def Func(arg_0,
                arg_1,
                arg_2,
                arg_3,
                arg_4=None,
                arg_5=True):
    """
    Attributes the performance of a returns stream to a set of risk factors.

    Preprocesses inputs, and then calls empyrical.Func. See
    empyrical.Func for more info.

    Performance attribution determines how much each risk factor, e.g.,
    momentum, the technology sector, etc., contributed to total returns, as
    well as the daily exposure to each of the risk factors. The returns that
    can be attributed to one of the given risk factors are the
    `common_returns`, and the returns that _cannot_ be attributed to a risk
    factor are the `specific_returns`, or the alpha. The common_returns and
    specific_returns summed together will always equal the total returns.

    Parameters
    ----------
    returns : pd.Series
        Returns for each day in the date range.
        - Example:
            2017-01-01   -0.017098
            2017-01-02    0.002683
            2017-01-03   -0.008669

    positions: pd.DataFrame
        Daily holdings (in dollars or percentages), indexed by date.
        Will be converted to percentages if positions are in dollars.
        Short positions show up as cash in the 'cash' column.
        - Examples:
                        AAPL  TLT  XOM  cash
            2017-01-01    34   58   10     0
            2017-01-02    22   77   18     0
            2017-01-03   -15   27   30    15

                            AAPL       TLT       XOM  cash
            2017-01-01  0.333333  0.568627  0.098039   0.0
            2017-01-02  0.188034  0.658120  0.153846   0.0
            2017-01-03  0.208333  0.375000  0.416667   0.0

    factor_returns : pd.DataFrame
        Returns by factor, with date as index and factors as columns
        - Example:
                        momentum  reversal
            2017-01-01  0.002779 -0.005453
            2017-01-02  0.001096  0.010290

    factor_loadings : pd.DataFrame
        Factor loadings for all days in the date range, with date and ticker as
        index, and factors as columns.
        - Example:
                               momentum  reversal
            dt         ticker
            2017-01-01 AAPL   -1.592914  0.852830
                       TLT     0.184864  0.895534
                       XOM     0.993160  1.149353
            2017-01-02 AAPL   -0.140009 -0.524952
                       TLT    -1.066978  0.185435
                       XOM    -1.798401  0.761549

    transactions : pd.DataFrame, optional
        Executed trade volumes and fill prices. Used to check the turnover of
        the algorithm. Default is None, in which case the turnover check is
        skipped.

        - One row per trade.
        - Trades on different names that occur at the
          same time will have identical indicies.
        - Example:
            index                  amount   price    symbol
            2004-01-09 12:18:01    483      324.12   'AAPL'
            2004-01-09 12:18:01    122      83.10    'MSFT'
            2004-01-13 14:12:23    -75      340.43   'AAPL'

    pos_in_dollars : bool
        Flag indicating whether `positions` are in dollars or percentages
        If True, positions are in dollars.

    Returns
    -------
    tuple of (risk_exposures_portfolio, Funcution)

    risk_exposures_portfolio : pd.DataFrame
        df indexed by datetime, with factors as columns
        - Example:
                        momentum  reversal
            dt
            2017-01-01 -0.238655  0.077123
            2017-01-02  0.821872  1.520515

    Funcution : pd.DataFrame
        df with factors, common returns, and specific returns as columns,
        and datetimes as index
        - Example:
                        momentum  reversal  common_returns  specific_returns
            dt
            2017-01-01  0.249087  0.935925        1.185012          1.185012
            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980
    """
    (arg_0,
     arg_1,
     arg_2,
     arg_3) = _align_and_warn(arg_0,
                                        arg_1,
                                        arg_2,
                                        arg_3,
                                        arg_4=arg_4,
                                        arg_5=arg_5)

    # Note that we convert positions to percentages *after* the checks
    # above, since get_turnover() expects positions in dollars.
    arg_1 = _stack_positions(arg_1, arg_5=arg_5)

    return ep.Func(arg_0, arg_1, arg_2, arg_3)


def Func(arg_0,
                           arg_1,
                           arg_2,
                           arg_3,
                           arg_4=None,
                           arg_5=True):
    """
    Calls `perf_attrib` using inputs, and displays outputs using
    `utils.print_table`.
    """
    arg_6, arg_7 = perf_attrib(
        arg_0,
        arg_1,
        arg_2,
        arg_3,
        arg_4,
        arg_5=arg_5,
    )

    arg_8, arg_9 =\
        create_perf_attrib_stats(arg_7, arg_6)

    arg_10 = '{:.2%}'.format
    arg_11 = '{:.2f}'.format

    arg_12 = arg_8.loc[['Annualized Specific Return',
                                           'Annualized Common Return',
                                           'Annualized Total Return',
                                           'Specific Sharpe Ratio']]

    # Format return rows in summary stats table as percentages.
    for arg_13 in (
        'Annualized Specific Return',
        'Annualized Common Return',
        'Annualized Total Return',
    ):
        arg_12[arg_13] = arg_10(arg_12[arg_13])

    # Display sharpe to two decimal places.
    arg_12['Specific Sharpe Ratio'] = arg_11(
        arg_12['Specific Sharpe Ratio']
    )

    print_table(arg_12, name='Summary Statistics')

    print_table(
        arg_9,
        name='Exposures Summary',
        # In exposures table, format exposure column to 2 decimal places, and
        # return columns  as percentages.
        formatters={
            'Average Risk Factor Exposure': arg_11,
            'Annualized Return': arg_10,
            'Cumulative Return': arg_10,
        },
    )


def Func(arg_0, arg_1=None, arg_2=None):
    """
    Plot total, specific, and common returns.

    Parameters
    ----------
    perf_attrib_data : pd.DataFrame
        df with factors, common returns, and specific returns as columns,
        and datetimes as index. Assumes the `total_returns` column is NOT
        cost adjusted.
        - Example:
                        momentum  reversal  common_returns  specific_returns
            dt
            2017-01-01  0.249087  0.935925        1.185012          1.185012
            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980

    cost : pd.Series, optional
        if present, gets subtracted from `perf_attrib_data['total_returns']`,
        and gets plotted separately

    ax :  matplotlib.axes.Axes
        axes on which plots are made. if None, current axes will be used

    Returns
    -------
    ax :  matplotlib.axes.Axes
    """

    if arg_2 is None:
        arg_2 = plt.gca()

    arg_3 = arg_0['total_returns']
    arg_4 = 'Total returns'

    arg_5 = _cumulative_returns_less_costs(
        arg_3,
        arg_1
    )
    if arg_1 is not None:
        arg_4 += ' (adjusted)'

    arg_6 = arg_0['specific_returns']
    arg_7 = arg_0['common_returns']

    arg_2.plot(arg_5, color='b',
            label=arg_4)
    arg_2.plot(ep.cum_returns(arg_6), color='g',
            label='Cumulative specific returns')
    arg_2.plot(ep.cum_returns(arg_7), color='r',
            label='Cumulative common returns')

    if arg_1 is not None:
        arg_2.plot(-ep.cum_returns(arg_1), color='k',
                label='Cumulative cost spent')

    arg_2.set_title('Time series of cumulative returns')
    arg_2.set_ylabel('Returns')

    configure_legend(arg_2)

    return arg_2


def Func(
        arg_0,
        arg_1=None,
        arg_2='Cumulative common returns attribution',
):
    """
    Plot each factor's contribution to performance.

    Parameters
    ----------
    perf_attrib_data : pd.DataFrame
        df with factors, common returns, and specific returns as columns,
        and datetimes as index
        - Example:
                        momentum  reversal  common_returns  specific_returns
            dt
            2017-01-01  0.249087  0.935925        1.185012          1.185012
            2017-01-02 -0.003194 -0.400786       -0.403980         -0.403980

    ax :  matplotlib.axes.Axes
        axes on which plots are made. if None, current axes will be used

    title : str, optional
        title of plot

    Returns
    -------
    ax :  matplotlib.axes.Axes
    """
    if arg_1 is None:
        arg_1 = plt.gca()

    arg_3 = arg_0.drop(
        ['total_returns', 'common_returns'], axis='columns', errors='ignore'
    )

    arg_4 = pd.DataFrame()
    for arg_5 in arg_3:
        arg_4[arg_5] = ep.cum_returns(arg_3[arg_5])

    for arg_6 in arg_4:
        arg_1.plot(arg_4[arg_6])

    arg_1.axhline(0, color='k')
    configure_legend(arg_1, change_colors=True)

    arg_1.set_ylabel('Cumulative returns by factor')
    arg_1.set_title(arg_2)

    return arg_1


def Func(arg_0, arg_1=True):
    """
    Convert positions to percentages if necessary, and change them
    to long format.

    Parameters
    ----------
    positions: pd.DataFrame
        Daily holdings (in dollars or percentages), indexed by date.
        Will be converted to percentages if positions are in dollars.
        Short positions show up as cash in the 'cash' column.

    pos_in_dollars : bool
        Flag indicating whether `positions` are in dollars or percentages
        If True, positions are in dollars.
    """
    if arg_1:
        # convert holdings to percentages
        arg_0 = get_percent_alloc(arg_0)

    # remove cash after normalizing positions
    arg_0 = arg_0.drop('cash', axis='columns')

    # convert positions to long format
    arg_0 = arg_0.stack()
    arg_0.index = arg_0.index.set_names(['dt', 'ticker'])

    return arg_0


def Func(arg_0, arg_1):
    """
    Compute cumulative returns, less costs.
    """
    if arg_1 is None:
        return ep.cum_returns(arg_0)
    return ep.cum_returns(arg_0 - arg_1)


def Func(arg_0):
    """
    If zipline asset objects are used, we want to print them out prettily
    within the tear sheet. This function should only be applied directly
    before displaying.
    """

    try:
        import zipline.assets
    except ImportError:
        return arg_0

    if isinstance(arg_0, zipline.assets.Asset):
        return arg_0.symbol
    else:
        return arg_0


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Logic for checking if a strategy is intraday and processing it.

    Parameters
    ----------
    estimate: boolean or str, optional
        Approximate returns for intraday strategies.
        See description in tears.create_full_tear_sheet.
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in create_full_tear_sheet.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in create_full_tear_sheet.

    Returns
    -------
    pd.DataFrame
        Daily net position values, adjusted for intraday movement.
    """

    if arg_0 == 'infer':
        if arg_2 is not None and arg_3 is not None:
            if detect_intraday(arg_2, arg_3):
                warnings.warn('Detected intraday strategy; inferring positi' +
                              'ons from transactions. Set estimate_intraday' +
                              '=False to disable.')
                return estimate_intraday(arg_1, arg_2, arg_3)
            else:
                return arg_2
        else:
            return arg_2

    elif arg_0:
        if arg_2 is not None and arg_3 is not None:
            return estimate_intraday(arg_1, arg_2, arg_3)
        else:
            raise ValueError('Positions and txns needed to estimate intraday')
    else:
        return arg_2


def Func(arg_0, arg_1, arg_2, arg_3=23):
    """
    Intraday strategies will often not hold positions at the day end.
    This attempts to find the point in the day that best represents
    the activity of the strategy on that day, and effectively resamples
    the end-of-day positions with the positions at this point of day.
    The point of day is found by detecting when our exposure in the
    market is at its maximum point. Note that this is an estimate.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in create_full_tear_sheet.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in create_full_tear_sheet.

    Returns
    -------
    pd.DataFrame
        Daily net position values, resampled for intraday behavior.
    """

    # Construct DataFrame of transaction amounts
    arg_4 = arg_2.copy()
    arg_4.index.names = ['date']
    arg_4['value'] = arg_4.amount * arg_4.price
    arg_4 = arg_4.reset_index().pivot_table(
        arg_5='date', values='value',
        arg_13='symbol').replace(np.nan, 0)

    # Cumulate transaction amounts each day
    arg_4['date'] = arg_4.index.date
    arg_4 = arg_4.groupby('date').cumsum()

    # Calculate exposure, then take peak of exposure every day
    arg_4['exposure'] = arg_4.abs().sum(axis=1)
    arg_7 = (arg_4['exposure'] == arg_4.groupby(
        pd.TimeGrouper('24H'))['exposure'].transform(max))
    arg_4 = arg_4[arg_7].drop('exposure', axis=1)

    # Compute cash delta
    arg_4['cash'] = -arg_4.sum(axis=1)

    # Shift EOD positions to positions at start of next trading day
    arg_8 = arg_1.copy().shift(1).fillna(0)
    arg_9 = arg_1.iloc[0].sum() / (1 + arg_0[0])
    arg_8.cash[0] = arg_9

    # Format and add start positions to intraday position changes
    arg_4.index = arg_4.index.normalize()
    arg_11 = arg_8.add(arg_4, fill_value=0)
    arg_11.index.name = 'period_close'
    arg_11.columns.name = 'sid'

    return arg_11


def Func(arg_0, arg_1):
    """
    Drop entries from rets so that the start and end dates of rets match those
    of benchmark_rets.

    Parameters
    ----------
    rets : pd.Series
        Daily returns of the strategy, noncumulative.
         - See pf.tears.create_full_tear_sheet for more details

    benchmark_rets : pd.Series
        Daily returns of the benchmark, noncumulative.

    Returns
    -------
    clipped_rets : pd.Series
        Daily noncumulative returns with index clipped to match that of
        benchmark returns.
    """

    if (arg_0.index[0] < arg_1.index[0]) \
            or (arg_0.index[-1] > arg_1.index[-1]):
        arg_2 = arg_0[arg_1.index]
    else:
        arg_2 = arg_0

    return arg_2


def Func(arg_0, arg_1=None, arg_2=None):
    """
    Calls the currently registered 'returns_func'

    Parameters
    ----------
    symbol : object
        An identifier for the asset whose return
        series is desired.
        e.g. ticker symbol or database ID
    start : date, optional
        Earliest date to fetch data for.
        Defaults to earliest date available.
    end : date, optional
        Latest date to fetch data for.
        Defaults to latest date available.

    Returns
    -------
    pandas.Series
        Returned by the current 'returns_func'
    """

    return SETTINGS['returns_func'](arg_0,
                                    arg_1=arg_1,
                                    arg_2=arg_2)


def Func(arg_0):
    """
    Decorator to set plotting context and axes style during function call.
    """
    @wraps(arg_0)
    def call_w_context(*arg_1, **arg_2):
        arg_3 = arg_2.pop('set_context', True)
        if arg_3:
            with plotting_context(), axes_style():
                return arg_0(*arg_1, **arg_2)
        else:
            return arg_0(*arg_1, **arg_2)
    return call_w_context


def Func(arg_0='darkgrid', arg_1=None):
    """
    Create pyfolio default axes style context.

    Under the hood, calls and returns seaborn.Func() with
    some custom settings. Usually you would use in a with-context.

    Parameters
    ----------
    style : str, optional
        Name of seaborn style.
    rc : dict, optional
        Config flags.

    Returns
    -------
    seaborn plotting context

    Example
    -------
    >>> with pyfolio.plotting.Func(style='whitegrid'):
    >>>    pyfolio.create_full_tear_sheet(..., set_context=False)

    See also
    --------
    For more information, see seaborn.plotting_context().

    """
    if arg_1 is None:
        arg_1 = {}

    arg_2 = {}

    # Add defaults if they do not exist
    for arg_3, arg_4 in arg_2.items():
        arg_1.setdefault(arg_3, arg_4)

    return sns.Func(arg_0=arg_0, arg_1=arg_1)


def Func(arg_0, arg_1=None, **arg_2):
    """
    Plots a heatmap of returns by month.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to seaborn plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_1 is None:
        arg_1 = plt.gca()

    arg_3 = ep.aggregate_returns(arg_0, 'monthly')
    arg_3 = arg_3.unstack().round(3)

    sns.heatmap(
        arg_3.fillna(0) *
        100.0,
        annot=True,
        annot_kws={"size": 9},
        alpha=1.0,
        center=0.0,
        cbar=False,
        cmap=matplotlib.cm.RdYlGn,
        arg_1=arg_1, **arg_2)
    arg_1.set_ylabel('Year')
    arg_1.set_xlabel('Month')
    arg_1.set_title("Monthly returns (%)")
    return arg_1


def Func(arg_0, arg_1=None, **arg_2):
    """
    Plots a distribution of monthly returns.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_1 is None:
        arg_1 = plt.gca()

    arg_3 = FuncFormatter(utils.percentage)
    arg_1.xaxis.set_major_formatter(FuncFormatter(arg_3))
    arg_1.tick_params(axis='x', which='major')

    arg_4 = ep.aggregate_returns(arg_0, 'monthly')

    arg_1.hist(
        100 * arg_4,
        color='orangered',
        alpha=0.80,
        bins=20,
        **arg_2)

    arg_1.axvline(
        100 * arg_4.mean(),
        color='gold',
        linestyle='--',
        lw=4,
        alpha=1.0)

    arg_1.axvline(0.0, color='black', linestyle='-', lw=3, alpha=0.75)
    arg_1.legend(['Mean'], frameon=True, framealpha=0.5)
    arg_1.set_ylabel('Number of months')
    arg_1.set_xlabel('Returns')
    arg_1.set_title("Distribution of monthly returns")
    return arg_1


def Func(arg_0, arg_1,
                             arg_2='upper left', arg_3=None, **arg_4):
    """
    Plots total amount of stocks with an active position, breaking out
    short and long into transparent filled regions.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    positions : pd.DataFrame, optional
        Daily net position values.
         - See full explanation in tears.create_full_tear_sheet.
    legend_loc : matplotlib.loc, optional
        The location of the legend on the plot.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.

    """

    if arg_3 is None:
        arg_3 = plt.gca()

    arg_1 = arg_1.drop('cash', axis='columns')
    arg_1 = arg_1.replace(0, np.nan)
    arg_5 = arg_1[arg_1 > 0].count(axis=1)
    arg_6 = arg_1[arg_1 < 0].count(axis=1)
    arg_7 = arg_3.fill_between(arg_5.index, 0, arg_5.values,
                         color='g', alpha=0.5, lw=2.0)
    arg_8 = arg_3.fill_between(arg_6.index, 0, arg_6.values,
                         color='r', alpha=0.5, lw=2.0)

    arg_9 = patches.Rectangle([0, 0], 1, 1, color='darkgoldenrod')
    arg_10 = arg_3.legend([arg_7, arg_8, arg_9],
                    ['Long (max: %s, min: %s)' % (arg_5.max(),
                                                  arg_5.min()),
                     'Short (max: %s, min: %s)' % (arg_6.max(),
                                                   arg_6.min()),
                     'Overlap'], loc=arg_2, frameon=True,
                    framealpha=0.5)
    arg_10.get_frame().set_edgecolor('black')

    arg_3.set_xlim((arg_0.index[0], arg_0.index[-1]))
    arg_3.set_title('Long and short holdings')
    arg_3.set_ylabel('Holdings')
    arg_3.set_xlabel('')
    return arg_3


def Func(arg_0, arg_1=10, arg_2=None, **arg_3):
    """
    Plots cumulative returns highlighting top drawdown periods.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    top : int, optional
        Amount of top drawdowns periods to plot (default 10).
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_2 is None:
        arg_2 = plt.gca()

    arg_4 = FuncFormatter(utils.two_dec_places)
    arg_2.yaxis.set_major_formatter(FuncFormatter(arg_4))

    arg_5 = ep.cum_returns(arg_0, starting_value=1.0)
    arg_6 = timeseries.gen_drawdown_table(arg_0, arg_1=arg_1)

    arg_5.plot(arg_2=arg_2, **arg_3)

    arg_7 = arg_2.get_ylim()
    arg_8 = sns.cubehelix_palette(len(arg_6))[::-1]
    for arg_9, (arg_10, arg_11) in arg_6[
            ['Peak date', 'Recovery date']].iterrows():
        if pd.isnull(arg_11):
            arg_11 = arg_0.index[-1]
        arg_2.fill_between((arg_10, arg_11),
                        arg_7[0],
                        arg_7[1],
                        alpha=.4,
                        color=arg_8[arg_9])
    arg_2.set_ylim(arg_7)
    arg_2.set_title('Top %i drawdown periods' % arg_1)
    arg_2.set_ylabel('Cumulative returns')
    arg_2.legend(['Portfolio'], loc='upper left',
              frameon=True, framealpha=0.5)
    arg_2.set_xlabel('')
    return arg_2


def Func(arg_0, arg_1=None, **arg_2):
    """
    Plots how far underwaterr returns are over time, or plots current
    drawdown vs. date.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_1 is None:
        arg_1 = plt.gca()

    arg_3 = FuncFormatter(utils.percentage)
    arg_1.yaxis.set_major_formatter(FuncFormatter(arg_3))

    arg_4 = ep.cum_returns(arg_0, starting_value=1.0)
    arg_5 = np.maximum.accumulate(arg_4)
    arg_6 = -100 * ((arg_5 - arg_4) / arg_5)
    (arg_6).plot(arg_1=arg_1, kind='area', color='coral', alpha=0.7, **arg_2)
    arg_1.set_ylabel('Drawdown')
    arg_1.set_title('Underwater plot')
    arg_1.set_xlabel('')
    return arg_1


def Func(arg_0,
                         arg_1=None,
                         arg_2=None,
                         arg_3=False,
                         arg_4=None,
                         arg_5='best',
                         arg_6=False,
                         arg_7=arg_8.forecast_cone_bootstrap,
                         arg_10=None, **arg_11):
    """
    Plots cumulative rolling returns versus some benchmarks'.

    Backtest returns are in green, and out-of-sample (live trading)
    returns are in red.

    Additionally, a non-parametric cone plot may be added to the
    out-of-sample returns region.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series, optional
        Daily noncumulative returns of the benchmark factor to which betas are
        computed. Usually a benchmark such as market returns.
         - This is in the same style as returns.
    live_start_date : datetime, optional
        The date when the strategy began live trading, after
        its backtest period. This date should be normalized.
    logy : bool, optional
        Whether to log-scale the y-axis.
    cone_std : float, or tuple, optional
        If float, The standard deviation to use for the cone plots.
        If tuple, Tuple of standard deviation values to use for the cone plots
         - See timeseries.forecast_cone_bounds for more details.
    legend_loc : matplotlib.loc, optional
        The location of the legend on the plot.
    volatility_match : bool, optional
        Whether to normalize the volatility of the returns to those of the
        benchmark returns. This helps compare strategies with different
        volatilities. Requires passing of benchmark_rets.
    cone_function : function, optional
        Function to use when generating forecast probability cone.
        The function signiture must follow the form:
        def cone(in_sample_returns (pd.Series),
                 days_to_project_forward (int),
                 cone_std= (float, or tuple),
                 starting_value= (int, or float))
        See timeseries.forecast_cone_bootstrap for an example.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_10 is None:
        arg_10 = plt.gca()

    arg_10.set_xlabel('')
    arg_10.set_ylabel('Cumulative returns')
    arg_10.set_yscale('log' if arg_3 else 'linear')

    if arg_6 and arg_1 is None:
        raise ValueError('volatility_match requires passing of '
                         'factor_returns.')
    elif arg_6 and arg_1 is not None:
        arg_12 = arg_1.loc[arg_0.index].std()
        arg_0 = (arg_0 / arg_0.std()) * arg_12

    arg_13 = ep.cum_returns(arg_0, 1.0)

    arg_14 = FuncFormatter(utils.two_dec_places)
    arg_10.yaxis.set_major_formatter(FuncFormatter(arg_14))

    if arg_1 is not None:
        arg_15 = ep.cum_returns(
            arg_1[arg_13.index], 1.0)
        arg_15.plot(lw=2, color='gray',
                                label=arg_1.name, alpha=0.60,
                                arg_10=arg_10, **arg_11)

    if arg_2 is not None:
        arg_2 = ep.utils.get_utc_timestamp(arg_2)
        arg_16 = arg_13.loc[arg_13.index < arg_2]
        arg_17 = arg_13.loc[arg_13.index >= arg_2]
    else:
        arg_16 = arg_13
        arg_17 = pd.Series([])

    arg_16.plot(lw=3, color='forestgreen', alpha=0.6,
                        label='Backtest', arg_10=arg_10, **arg_11)

    if len(arg_17) > 0:
        arg_17.plot(lw=4, color='red', alpha=0.6,
                             label='Live', arg_10=arg_10, **arg_11)

        if arg_4 is not None:
            if isinstance(arg_4, (float, int)):
                arg_4 = [arg_4]

            arg_18 = arg_0.loc[arg_0.index < arg_2]
            arg_19 = arg_7(
                arg_18,
                len(arg_17),
                arg_4=arg_4,
                starting_value=arg_16[-1])

            arg_19 = arg_19.set_index(arg_17.index)
            for arg_20 in arg_4:
                arg_10.fill_between(arg_19.index,
                                arg_19[float(arg_20)],
                                arg_19[float(-arg_20)],
                                color='steelblue', alpha=0.5)

    if arg_5 is not None:
        arg_10.legend(loc=arg_5, frameon=True, framealpha=0.5)
    arg_10.axhline(1.0, linestyle='--', color='black', lw=2)

    return arg_10


def Func(arg_0, arg_1, arg_2='best',
                      arg_3=None, **arg_4):
    """
    Plots the rolling 6-month and 12-month beta versus date.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series
        Daily noncumulative returns of the benchmark factor to which betas are
        computed. Usually a benchmark such as market returns.
         - This is in the same style as returns.
    legend_loc : matplotlib.loc, optional
        The location of the legend on the plot.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_3 is None:
        arg_3 = plt.gca()

    arg_5 = FuncFormatter(utils.two_dec_places)
    arg_3.yaxis.set_major_formatter(FuncFormatter(arg_5))

    arg_3.set_title("Rolling portfolio beta to " + str(arg_1.name))
    arg_3.set_ylabel('Beta')
    arg_6 = timeseries.rolling_beta(
        arg_0, arg_1, rolling_window=APPROX_BDAYS_PER_MONTH * 6)
    arg_6.plot(color='steelblue', lw=3, alpha=0.6, arg_3=arg_3, **arg_4)
    arg_7 = timeseries.rolling_beta(
        arg_0, arg_1, rolling_window=APPROX_BDAYS_PER_MONTH * 12)
    arg_7.plot(color='grey', lw=3, alpha=0.4, arg_3=arg_3, **arg_4)
    arg_3.axhline(arg_6.mean(), color='steelblue', linestyle='--', lw=3)
    arg_3.axhline(0.0, color='black', linestyle='-', lw=2)

    arg_3.set_xlabel('')
    arg_3.legend(['6-mo',
               '12-mo'],
              loc=arg_2, frameon=True, framealpha=0.5)
    arg_3.set_ylim((-1.0, 1.0))
    return arg_3


def Func(arg_0, arg_1=None,
                        arg_2=arg_3 * 6,
                        arg_4='best', arg_5=None, **arg_6):
    """
    Plots the rolling Sharpe ratio versus date.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series, optional
        Daily noncumulative returns of the benchmark factor for
        which the benchmark rolling Sharpe is computed. Usually
        a benchmark such as market returns.
         - This is in the same style as returns.
    rolling_window : int, optional
        The days window over which to compute the sharpe ratio.
    legend_loc : matplotlib.loc, optional
        The location of the legend on the plot.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_5 is None:
        arg_5 = plt.gca()

    arg_7 = FuncFormatter(utils.two_dec_places)
    arg_5.yaxis.set_major_formatter(FuncFormatter(arg_7))

    arg_8 = timeseries.rolling_sharpe(
        arg_0, arg_2)
    arg_8.plot(alpha=.7, lw=3, color='orangered', arg_5=arg_5,
                           **arg_6)

    if arg_1 is not None:
        arg_9 = timeseries.rolling_sharpe(
            arg_1, arg_2)
        arg_9.plot(alpha=.7, lw=3, color='grey', arg_5=arg_5,
                                      **arg_6)

    arg_5.set_title('Rolling Sharpe ratio (6-month)')
    arg_5.axhline(
        arg_8.mean(),
        color='steelblue',
        linestyle='--',
        lw=3)
    arg_5.axhline(0.0, color='black', linestyle='-', lw=3)

    arg_5.set_ylabel('Sharpe ratio')
    arg_5.set_xlabel('')
    if arg_1 is None:
        arg_5.legend(['Sharpe', 'Average'],
                  loc=arg_4, frameon=True, framealpha=0.5)
    else:
        arg_5.legend(['Sharpe', 'Benchmark Sharpe', 'Average'],
                  loc=arg_4, frameon=True, framealpha=0.5)

    return arg_5


def Func(arg_0, arg_1, arg_2=None, **arg_3):
    """
    Plots the sector exposures of the portfolio over time.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    sector_alloc : pd.DataFrame
        Portfolio allocation of positions. See pos.get_sector_alloc.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_2 is None:
        arg_2 = plt.gca()

    arg_1.plot(title='Sector allocation over time',
                      alpha=0.5, arg_2=arg_2, **arg_3)

    arg_4 = arg_2.get_position()
    arg_2.set_position([arg_4.x0, arg_4.y0 + arg_4.height * 0.1,
                     arg_4.width, arg_4.height * 0.9])

    # Put a legend below current axis
    arg_2.legend(loc='upper center', frameon=True, framealpha=0.5,
              bbox_to_anchor=(0.5, -0.14), ncol=5)

    arg_2.set_xlim((arg_1.index[0], arg_1.index[-1]))
    arg_2.set_ylabel('Exposure by sector')
    arg_2.set_xlabel('')

    return arg_2


def Func(arg_0, arg_1, arg_2,
                        arg_3=(3, 8, 10, 12, 15, 20, 50),
                        arg_4=None, **arg_5):
    """
    Plots equity curves at different per-dollar slippage assumptions.

    Parameters
    ----------
    returns : pd.Series
        Timeseries of portfolio returns to be adjusted for various
        degrees of slippage.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in tears.create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in tears.create_full_tear_sheet.
    slippage_params: tuple
        Slippage pameters to apply to the return time series (in
        basis points).
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to seaborn plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_4 is None:
        arg_4 = plt.gca()

    arg_6 = pd.DataFrame()
    for arg_7 in arg_3:
        arg_8 = txn.adjust_returns_for_slippage(arg_0, arg_1,
                                                      arg_2, arg_7)
        arg_9 = str(arg_7) + " bps"
        arg_6[arg_9] = ep.cum_returns(arg_8, 1)

    arg_6.plot(alpha=1.0, lw=0.5, arg_4=arg_4)

    arg_4.set_title('Cumulative returns given additional per-dollar slippage')
    arg_4.set_ylabel('')

    arg_4.legend(loc='center left', frameon=True, framealpha=0.5)

    return arg_4


def Func(arg_0, arg_1, arg_2=None, **arg_3):
    """
    Plots trading volume per day vs. date.

    Also displays all-time daily average.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in tears.create_full_tear_sheet.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_2 is None:
        arg_2 = plt.gca()
    arg_4 = txn.get_txn_vol(arg_1)
    arg_4.txn_shares.plot(alpha=1.0, lw=0.5, arg_2=arg_2, **arg_3)
    arg_2.axhline(arg_4.txn_shares.mean(), color='steelblue',
               linestyle='--', lw=3, alpha=1.0)
    arg_2.set_title('Daily trading volume')
    arg_2.set_xlim((arg_0.index[0], arg_0.index[-1]))
    arg_2.set_ylabel('Amount of shares traded')
    arg_2.set_xlabel('')
    return arg_2


def Func(arg_0, arg_1=5, arg_2='America/New_York',
                       arg_3=None, **arg_4):
    """
    Plots a histogram of transaction times, binning the times into
    buckets of a given duration.

    Parameters
    ----------
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in tears.create_full_tear_sheet.
    bin_minutes : float, optional
        Sizes of the bins in minutes, defaults to 5 minutes.
    tz : str, optional
        Time zone to plot against. Note that if the specified
        zone does not apply daylight savings, the distribution
        may be partially offset.
    ax : matplotlib.Axes, optional
        Axes upon which to plot.
    **kwargs, optional
        Passed to plotting function.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_3 is None:
        arg_3 = plt.gca()

    arg_5 = arg_0.copy()

    arg_5.index = arg_5.index.tz_convert(pytz.timezone(arg_2))
    arg_5.index = arg_5.index.map(lambda x: x.hour * 60 + x.minute)
    arg_5['trade_value'] = (arg_5.amount * arg_5.price).abs()
    arg_5 = arg_5.groupby(level=0).sum().reindex(arg_6=range(570, 961))
    arg_5.index = (arg_5.index / arg_1).astype(int) * arg_1
    arg_5 = arg_5.groupby(level=0).sum()

    arg_5['time_str'] = arg_5.index.map(lambda x:
                                              str(datetime.time(int(x / 60),
                                                                x % 60))[:-3])

    arg_7 = arg_5.trade_value.sum()
    arg_5.trade_value = arg_5.trade_value.fillna(0) / arg_7

    arg_3.bar(arg_5.index, arg_5.trade_value, width=arg_1, **arg_4)

    arg_3.set_xlim(570, 960)
    arg_3.set_xticks(arg_5.index[::int(30 / arg_1)])
    arg_3.set_xticklabels(arg_5.time_str[::int(30 / arg_1)])
    arg_3.set_title('Transaction time distribution')
    arg_3.set_ylabel('Proportion')
    arg_3.set_xlabel('')
    return arg_3


def Func(arg_0, arg_1=5):
    """
    Prints information about the worst drawdown periods.

    Prints peak dates, valley dates, recovery dates, and net
    drawdowns.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    top : int, optional
        Amount of top drawdowns periods to plot (default 5).
    """

    arg_2 = timeseries.gen_drawdown_table(arg_0, arg_1=arg_1)
    utils.print_table(
        arg_2.sort_values('Net drawdown in %', ascending=False),
        name='Worst drawdown periods',
        float_format='{0:.2f}'.format,
    )


def Func(arg_0, arg_1=16, arg_2=18, arg_3=None):
    """
    Plots timespans and directions of a sample of round trip trades.

    Parameters
    ----------
    round_trips : pd.DataFrame
        DataFrame with one row per round trip trade.
        - See full explanation in round_trips.extract_round_trips
    ax : matplotlib.Axes, optional
        Axes upon which to plot.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    if arg_3 is None:
        arg_3 = plt.subplot()

    arg_4 = arg_0.symbol.unique()
    np.random.seed(1)
    arg_5 = np.random.choice(arg_0.symbol.unique(), replace=False,
                              size=min(arg_1, len(arg_4)))
    arg_6 = arg_0[arg_0.symbol.isin(arg_5)]

    arg_7 = pd.Series(np.arange(len(arg_5)), index=arg_5)

    for arg_8, arg_9 in arg_6.groupby('symbol'):
        for arg_10, arg_11 in arg_9.iterrows():
            arg_12 = 'b' if arg_11.long else 'r'
            arg_13 = arg_7[arg_8] + 0.05
            arg_3.plot([arg_11['open_dt'], arg_11['close_dt']],
                    [arg_13, arg_13], color=arg_12,
                    linewidth=arg_2, solid_capstyle='butt')

    arg_3.set_yticks(range(arg_1))
    arg_3.set_yticklabels([utils.format_asset(arg_14) for arg_14 in arg_5])

    arg_3.set_ylim((-0.5, min(len(arg_5), arg_1) - 0.5))
    arg_15 = patches.Rectangle([0, 0], 1, 1, color='b', label='Long')
    arg_16 = patches.Rectangle([0, 0], 1, 1, color='r', label='Short')
    arg_17 = arg_3.legend(handles=[arg_15, arg_16], loc='lower left',
                    frameon=True, framealpha=0.5)
    arg_17.get_frame().set_edgecolor('black')
    arg_3.grid(False)

    return arg_3


def Func(arg_0):
    """
    Prints the share of total PnL contributed by each
    traded name.

    Parameters
    ----------
    round_trips : pd.DataFrame
        DataFrame with one row per round trip trade.
        - See full explanation in round_trips.extract_round_trips
    ax : matplotlib.Axes, optional
        Axes upon which to plot.

    Returns
    -------
    ax : matplotlib.Axes
        The axes that were plotted on.
    """

    arg_1 = arg_0['pnl'].sum()
    arg_2 = arg_0.groupby('symbol')['pnl'].sum() / arg_1
    arg_2.name = ''

    arg_2.index = arg_2.index.map(utils.format_asset)
    utils.print_table(
        arg_2.sort_values(
            inplace=False,
            ascending=False,
        ),
        arg_3='Profitability (PnL / PnL total) per name',
        float_format='{:.2%}'.format,
    )


def Func(arg_0, arg_1=0, arg_2=arg_3):
    """
    Determines the Sortino ratio of a strategy.

    Parameters
    ----------
    returns : pd.Series or pd.DataFrame
        Daily returns of the strategy, noncumulative.
        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.
    required_return: float / series
        minimum acceptable return
    period : str, optional
        Defines the periodicity of the 'returns' data for purposes of
        annualizing. Can be 'monthly', 'weekly', or 'daily'.
        - Defaults to 'daily'.

    Returns
    -------
    depends on input type
    series ==> float
    DataFrame ==> np.array

        Annualized Sortino ratio.
    """

    return ep.Func(arg_0, arg_1=arg_1)


def Func(arg_0, arg_1=0, arg_2=arg_3):
    """
    Determines the Sharpe ratio of a strategy.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
        - See full explanation in :func:`~pyfolio.timeseries.cum_returns`.
    risk_free : int, float
        Constant risk-free return throughout the period.
    period : str, optional
        Defines the periodicity of the 'returns' data for purposes of
        annualizing. Can be 'monthly', 'weekly', or 'daily'.
        - Defaults to 'daily'.

    Returns
    -------
    float
        Sharpe ratio.
    np.nan
        If insufficient length of returns or if if adjusted returns are 0.

    Note
    -----
    See https://en.wikipedia.org/wiki/Sharpe_ratio for more details.
    """

    return ep.Func(arg_0, arg_1=arg_1, arg_2=arg_2)


def Func(arg_0, arg_1,
                 arg_2=arg_3 * 6):
    """
    Determines the rolling beta of a strategy.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series or pd.DataFrame
        Daily noncumulative returns of the benchmark factor to which betas are
        computed. Usually a benchmark such as market returns.
         - If DataFrame is passed, computes rolling beta for each column.
         - This is in the same style as returns.
    rolling_window : int, optional
        The size of the rolling window, in days, over which to compute
        beta (default 6 months).

    Returns
    -------
    pd.Series
        Rolling beta.

    Note
    -----
    See https://en.wikipedia.org/wiki/Beta_(finance) for more details.
    """

    if arg_1.ndim > 1:
        # Apply column-wise
        return arg_1.apply(partial(Func, arg_0),
                                    arg_2=arg_2)
    else:
        arg_4 = pd.Series(index=arg_0.index)
        for arg_5, arg_6 in zip(arg_0.index[0:-arg_2],
                            arg_0.index[arg_2:]):
            arg_4.loc[arg_6] = ep.beta(
                arg_0.loc[arg_5:arg_6],
                arg_1.loc[arg_5:arg_6])

        return arg_4


def Func(arg_0):
    """
    Calculates the gross leverage of a strategy.

    Parameters
    ----------
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in tears.create_full_tear_sheet.

    Returns
    -------
    pd.Series
        Gross leverage.
    """

    arg_1 = arg_0.drop('cash', axis=1).abs().sum(axis=1)
    return arg_1 / arg_0.sum(axis=1)


def Func(arg_0, arg_1=None, arg_2=None,
               arg_3=None, arg_4='AGB'):
    """
    Calculates various performance metrics of a strategy, for use in
    plotting.show_Func.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    factor_returns : pd.Series, optional
        Daily noncumulative returns of the benchmark factor to which betas are
        computed. Usually a benchmark such as market returns.
         - This is in the same style as returns.
         - If None, do not compute alpha, beta, and information ratio.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in tears.create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
        - See full explanation in tears.create_full_tear_sheet.
    turnover_denom : str
        Either AGB or portfolio_value, default AGB.
        - See full explanation in txn.get_turnover.

    Returns
    -------
    pd.Series
        Performance metrics.
    """

    arg_5 = pd.Series()
    for arg_6 in SIMPLE_STAT_FUNCS:
        arg_5[arg_7[arg_6.__name__]] = arg_6(arg_0)

    if arg_2 is not None:
        arg_5['Gross leverage'] = gross_lev(arg_2).mean()
        if arg_3 is not None:
            arg_5['Daily turnover'] = get_turnover(arg_2,
                                                   arg_3,
                                                   arg_4).mean()
    if arg_1 is not None:
        for arg_6 in FACTOR_STAT_FUNCS:
            arg_9 = arg_6(arg_0, arg_1)
            arg_5[arg_7[arg_6.__name__]] = arg_9

    return arg_5


def Func(arg_0):
    """Calculate various summary statistics of data.

    Parameters
    ----------
    x : numpy.ndarray or pandas.Series
        Array to compute summary statistics for.

    Returns
    -------
    pandas.Series
        Series containing mean, median, std, as well as 5, 25, 75 and
        95 percentiles of passed in values.
    """

    return pd.Series({'mean': np.mean(arg_0),
                      'median': np.median(arg_0),
                      'std': np.std(arg_0),
                      '5%': np.percentile(arg_0, 5),
                      '25%': np.percentile(arg_0, 25),
                      '75%': np.percentile(arg_0, 75),
                      '95%': np.percentile(arg_0, 95),
                      'IQR': np.subtract.reduce(
                          np.percentile(arg_0, [75, 25])),
                      })


def Func(arg_0, arg_1=10):
    """
    Finds top drawdowns, sorted by drawdown amount.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in tears.create_full_tear_sheet.
    top : int, optional
        The amount of top drawdowns to find (default 10).

    Returns
    -------
    drawdowns : list
        List of drawdown peaks, valleys, and recoveries. See get_max_drawdown.
    """

    arg_0 = arg_0.copy()
    arg_2 = ep.cum_returns(arg_0, 1.0)
    arg_3 = np.maximum.accumulate(arg_2)
    arg_4 = arg_2 / arg_3 - 1

    arg_5 = []
    for arg_6 in range(arg_1):
        arg_7, arg_8, arg_9 = get_max_drawdown_underwater(arg_4)
        # Slice out draw-down period
        if not pd.isnull(arg_9):
            arg_4.drop(arg_4[arg_7: arg_9].index[1:-1],
                            inplace=True)
        else:
            # drawdown has not ended yet
            arg_4 = arg_4.loc[:arg_7]

        arg_5.append((arg_7, arg_8, arg_9))
        if (len(arg_0) == 0) or (len(arg_4) == 0):
            break

    return arg_5


def Func(arg_0, arg_1,
                   arg_2=1, arg_3=1000, arg_4=None):
    """
    Gnerate alternate paths using available values from in-sample returns.

    Parameters
    ----------
    is_returns : pandas.core.frame.DataFrame
        Non-cumulative in-sample returns.
    num_days : int
        Number of days to project the probability cone forward.
    starting_value : int or float
        Starting value of the out of sample period.
    num_samples : int
        Number of samples to draw from the in-sample daily returns.
        Each sample will be an array with length num_days.
        A higher number of samples will generate a more accurate
        bootstrap cone.
    random_seed : int
        Seed for the pseudorandom number generator used by the pandas
        sample method.

    Returns
    -------
    samples : numpy.ndarray
    """

    arg_5 = np.empty((arg_3, arg_1))
    arg_6 = np.random.RandomState(arg_6=arg_4)
    for arg_7 in range(arg_3):
        arg_5[arg_7, :] = arg_0.sample(arg_1, replace=True,
                                          random_state=arg_6)

    return arg_5


def Func(arg_0, arg_1=(1., 1.5, 2.), arg_2=1.):
    """
    Gnerate the upper and lower bounds of an n standard deviation
    cone of forecasted cumulative returns.

    Parameters
    ----------
    samples : numpy.ndarray
        Alternative paths, or series of possible outcomes.
    cone_std : list of int/float
        Number of standard devations to use in the boundaries of
        the cone. If multiple values are passed, cone bounds will
        be generated for each value.

    Returns
    -------
    samples : pandas.core.frame.DataFrame
    """

    arg_3 = ep.cum_returns(arg_0.T,
                                 arg_2=arg_2).T

    arg_4 = arg_3.mean(axis=0)
    arg_5 = arg_3.std(axis=0)

    if isinstance(arg_1, (arg_9, int)):
        arg_1 = [arg_1]

    arg_6 = pd.DataFrame(columns=pd.Float64Index([]))
    for arg_7 in arg_1:
        arg_6.loc[:, arg_9(arg_7)] = arg_4 + arg_5 * arg_7
        arg_6.loc[:, arg_9(-arg_7)] = arg_4 - arg_5 * arg_7

    return arg_6


def Func(arg_0, arg_1=None, arg_2=None):
    """
    Generate plot for stochastic volatility model.

    Parameters
    ----------
    data : pandas.Series
        Returns to model.
    trace : pymc3.sampling.BaseTrace object, optional
        trace as returned by model_stoch_vol
        If not passed, sample from model.
    ax : matplotlib.axes object, optional
        Plot into axes object

    Returns
    -------
    ax object

    See Also
    --------
    model_stoch_vol : run stochastic volatility model
    """

    if arg_1 is None:
        arg_1 = model_stoch_vol(arg_0)

    if arg_2 is None:
        arg_3, arg_2 = plt.subplots(figsize=(15, 8))

    arg_0.abs().plot(arg_2=arg_2)
    arg_2.plot(arg_0.index, np.exp(arg_1['s', ::30].T), 'r', alpha=.03)
    arg_2.set(title='Stochastic volatility', xlabel='Time', ylabel='Volatility')
    arg_2.legend(['Abs returns', 'Stochastic volatility process'],
              frameon=True, framealpha=0.5)

    return arg_2


def Func(arg_0, arg_1=1.):
    """
    Compute 5, 25, 75 and 95 percentiles of cumulative returns, used
    for the Bayesian cone.

    Parameters
    ----------
    preds : numpy.array
        Multiple (simulated) cumulative returns.
    starting_value : int (optional)
        Have cumulative returns start around this value.
        Default = 1.

    Returns
    -------
    dict of percentiles over time
        Dictionary mapping percentiles (5, 25, 75, 95) to a
        timeseries.
    """

    def scoreatpercentile(arg_2, arg_3):
        return [stats.scoreatpercentile(
            arg_4, arg_3) for arg_4 in arg_2.T]

    arg_2 = np.cumprod(arg_0 + 1, 1) * arg_1
    arg_5 = {arg_3: scoreatpercentile(arg_2, arg_3) for arg_3 in (5, 25, 75, 95)}

    return arg_5


def Func(arg_0, arg_1):
    """
    Compute Bayesian consistency score.

    Parameters
    ----------
    returns_test : pd.Series
        Observed cumulative returns.
    preds : numpy.array
        Multiple (simulated) cumulative returns.

    Returns
    -------
    Consistency score
        Score from 100 (returns_test perfectly on the median line of the
        Bayesian cone spanned by preds) to 0 (returns_test completely
        outside of Bayesian cone.)
    """

    arg_2 = cum_returns(arg_0, starting_value=1.)
    arg_3 = np.cumprod(arg_1 + 1, 1)

    arg_4 = [sp.stats.percentileofscore(arg_3[:, i],
                                    arg_2.iloc[i],
                                    kind='weak')
         for i in range(len(arg_2))]
    # normalize to be from 100 (perfect median line) to 0 (completely outside
    # of cone)
    return 100 - np.abs(50 - np.mean(arg_4)) / .5


def Func(arg_0, arg_1, arg_2,
                    arg_3=50, arg_4=None):
    """
    Generate cumulative returns plot with Bayesian cone.

    Parameters
    ----------
    returns_train : pd.Series
        Timeseries of simple returns
    returns_test : pd.Series
        Out-of-sample returns. Datetimes in returns_test will be added to
        returns_train as missing values and predictions will be generated
        for them.
    ppc : np.array
        Posterior predictive samples of shape samples x
        len(returns_test).
    plot_train_len : int (optional)
        How many data points to plot of returns_train. Useful to zoom in on
        the prediction if there is a long backtest period.
    ax : matplotlib.Axis (optional)
        Axes upon which to plot.

    Returns
    -------
    score : float
        Consistency score (see compute_consistency_score)
    trace : pymc3.sampling.BaseTrace
        A PyMC3 trace object that contains samples for each parameter
        of the posterior.
    """

    arg_5 = compute_consistency_score(arg_1,
                                      arg_2)

    arg_4 = _Func(
        arg_0,
        arg_1,
        arg_2,
        arg_3=arg_3,
        arg_4=arg_4)
    arg_4.text(
        0.40,
        0.90,
        'Consistency score: %.1f' %
        arg_5,
        verticalalignment='bottom',
        horizontalalignment='right',
        transform=arg_4.transAxes,
    )

    arg_4.set_ylabel('Cumulative returns')
    return arg_5


def Func(arg_0):
        """Defer the message.

        This message will remain in the queue but must be received
        specifically by its sequence number in order to be processed.

        :raises: ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
        :raises: ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
        :raises: ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
        :raises: ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.
        """
        arg_0._is_live('Func')
        try:
            arg_0.message.modify(True, True)
        except Exception as e:
            raise MessageSettleFailed("Func", e)


def Func(arg_0):
    """Guess Python Autorest options based on the spec path.

    Expected path:
    specification/compute/resource-manager/readme.md
    """
    arg_0 = arg_0.lower()
    arg_0 = arg_0[arg_0.index("specification"):] # Might raise and it's ok
    arg_1 = arg_0.split("/")

    arg_2 = arg_1[1]
    arg_3 = arg_1[2] == "resource-manager"

    return {
        "rp_name": arg_2,
        "is_arm": arg_3
    }


def Func(
            arg_0, arg_1, arg_2=None, arg_3=False, arg_4=True, **arg_5):
        """Deletes the managed application definition.

        :param application_definition_id: The fully qualified ID of the
         managed application definition, including the managed application name
         and the managed application definition resource type. Use the format,
         /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applicationDefinitions/{applicationDefinition-name}
        :type application_definition_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: The poller return type is ClientRawResponse, the
         direct response alongside the deserialized response
        :param polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :return: An instance of LROPoller that returns None or
         ClientRawResponse<None> if raw==True
        :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
        :raises:
         :class:`ErrorResponseException<azure.mgmt.resource.managedapplications.models.ErrorResponseException>`
        """
        arg_6 = arg_0._Func_initial(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=True,
            **arg_5
        )

        def get_long_running_output(arg_7):
            if arg_3:
                arg_8 = ClientRawResponse(None, arg_7)
                return arg_8

        arg_9 = arg_5.get(
            'long_running_operation_timeout',
            arg_0.config.long_running_operation_timeout)
        if arg_4 is True: arg_10 = ARMPolling(arg_9, **arg_5)
        elif arg_4 is False: arg_10 = NoPolling()
        else: arg_10 = arg_4
        return LROPoller(arg_0._client, arg_6, get_long_running_output, arg_10)


def Func(
            arg_0, arg_1, arg_2, arg_3=None, arg_4=False, arg_5=True, **arg_6):
        """Creates a new managed application definition.

        :param application_definition_id: The fully qualified ID of the
         managed application definition, including the managed application name
         and the managed application definition resource type. Use the format,
         /subscriptions/{guid}/resourceGroups/{resource-group-name}/Microsoft.Solutions/applicationDefinitions/{applicationDefinition-name}
        :type application_definition_id: str
        :param parameters: Parameters supplied to the create or update a
         managed application definition.
        :type parameters:
         ~azure.mgmt.resource.managedapplications.models.ApplicationDefinition
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: The poller return type is ClientRawResponse, the
         direct response alongside the deserialized response
        :param polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :return: An instance of LROPoller that returns ApplicationDefinition
         or ClientRawResponse<ApplicationDefinition> if raw==True
        :rtype:
         ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition]
         or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.resource.managedapplications.models.ApplicationDefinition]]
        :raises:
         :class:`ErrorResponseException<azure.mgmt.resource.managedapplications.models.ErrorResponseException>`
        """
        arg_7 = arg_0._Func_initial(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=True,
            **arg_6
        )

        def get_long_running_output(arg_8):
            arg_9 = arg_0._deserialize('ApplicationDefinition', arg_8)

            if arg_4:
                arg_10 = ClientRawResponse(arg_9, arg_8)
                return arg_10

            return arg_9

        arg_11 = arg_6.get(
            'long_running_operation_timeout',
            arg_0.config.long_running_operation_timeout)
        if arg_5 is True: arg_12 = ARMPolling(arg_11, **arg_6)
        elif arg_5 is False: arg_12 = NoPolling()
        else: arg_12 = arg_5
        return LROPoller(arg_0._client, arg_7, get_long_running_output, arg_12)


def Func(arg_0, arg_1):
        ''' Return the target uri for the request.'''
        arg_2 = arg_1.protocol_override \
            if arg_1.protocol_override else arg_0.protocol
        arg_2 = arg_2.lower()
        arg_3 = HTTP_PORT if arg_2 == 'http' else HTTPS_PORT
        return arg_2 + '://' + arg_1.host + ':' + str(arg_3) + arg_1.path


def Func(arg_0, arg_1):
        ''' Sends request to cloud service server and return the response. '''
        arg_2 = arg_0.get_connection(arg_1)
        try:
            arg_2.putrequest(arg_1.method, arg_1.path)

            arg_0.send_request_headers(arg_2, arg_1.headers)
            arg_0.send_request_body(arg_2, arg_1.body)

            if DEBUG_REQUESTS and arg_1.body:
                print('request:')
                try:
                    print(arg_1.body)
                except:  # pylint: disable=bare-except
                    pass

            arg_3 = arg_2.getresponse()
            arg_4 = int(arg_3.status)
            arg_5 = arg_3.reason
            arg_6 = arg_3.getheaders()

            # for consistency across platforms, make header names lowercase
            for arg_7, arg_8 in enumerate(arg_6):
                arg_6[arg_7] = (arg_8[0].lower(), arg_8[1])

            arg_9 = None
            if arg_3.length is None:
                arg_9 = arg_3.read()
            elif arg_3.length > 0:
                arg_9 = arg_3.read(arg_3.length)

            if DEBUG_RESPONSES and arg_9:
                print('response:')
                try:
                    print(arg_9)
                except:  # pylint: disable=bare-except
                    pass

            arg_10 = HTTPResponse(
                arg_4, arg_3.reason, arg_6, arg_9)
            if arg_4 == 307:
                arg_11 = urlparse(dict(arg_6)['location'])
                arg_1.host = arg_11.hostname
                arg_1.path = arg_11.path
                arg_1.path, arg_1.query = arg_0._update_request_uri_query(arg_1)
                return arg_0.Func(arg_1)
            if arg_4 >= 300:
                raise HTTPError(arg_4, arg_5, arg_6, arg_9)

            return arg_10
        finally:
            arg_2.close()


def Func(
            arg_0, arg_1, arg_2, arg_3, arg_4=None, arg_5=None, arg_6=False, arg_7=True, **arg_8):
        """Executes script actions on the specified HDInsight cluster.

        :param resource_group_name: The name of the resource group.
        :type resource_group_name: str
        :param cluster_name: The name of the cluster.
        :type cluster_name: str
        :param persist_on_success: Gets or sets if the scripts needs to be
         persisted.
        :type persist_on_success: bool
        :param script_actions: The list of run time script actions.
        :type script_actions:
         list[~azure.mgmt.hdinsight.models.RuntimeScriptAction]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: The poller return type is ClientRawResponse, the
         direct response alongside the deserialized response
        :param polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :return: An instance of LROPoller that returns None or
         ClientRawResponse<None> if raw==True
        :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
        :raises:
         :class:`ErrorResponseException<azure.mgmt.hdinsight.models.ErrorResponseException>`
        """
        arg_9 = arg_0._Func_initial(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=True,
            **arg_8
        )

        def get_long_running_output(arg_10):
            if arg_6:
                arg_11 = ClientRawResponse(None, arg_10)
                return arg_11

        arg_12 = arg_8.get(
            'long_running_operation_timeout',
            arg_0.config.long_running_operation_timeout)
        if arg_7 is True: arg_13 = ARMPolling(arg_12, **arg_8)
        elif arg_7 is False: arg_13 = NoPolling()
        else: arg_13 = arg_7
        return LROPoller(arg_0._client, arg_9, get_long_running_output, arg_13)


def Func(
            arg_0, arg_1, arg_2, arg_3=None, arg_4=False, **arg_5):
        """Check the availability of a Front Door resource name.

        :param name: The resource name to validate.
        :type name: str
        :param type: The type of the resource whose name is to be validated.
         Possible values include: 'Microsoft.Network/frontDoors',
         'Microsoft.Network/frontDoors/frontendEndpoints'
        :type type: str or ~azure.mgmt.frontdoor.models.ResourceType
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: CheckNameAvailabilityOutput or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.frontdoor.models.CheckNameAvailabilityOutput or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.frontdoor.models.ErrorResponseException>`
        """
        arg_6 = models.CheckNameAvailabilityInput(arg_1=arg_1, arg_2=arg_2)

        arg_7 = "2018-08-01"

        # Construct URL
        arg_8 = arg_0.Func.metadata['url']

        # Construct parameters
        arg_9 = {}
        arg_9['api-version'] = arg_0._serialize.query("api_version", arg_7, 'str')

        # Construct headers
        arg_10 = {}
        arg_10['Accept'] = 'application/json'
        arg_10['Content-Type'] = 'application/json; charset=utf-8'
        if arg_0.config.generate_client_request_id:
            arg_10['x-ms-client-request-id'] = str(uuid.uuid1())
        if arg_3:
            arg_10.update(arg_3)
        if arg_0.config.accept_language is not None:
            arg_10['accept-language'] = arg_0._serialize.header("self.config.accept_language", arg_0.config.accept_language, 'str')

        # Construct body
        arg_11 = arg_0._serialize.body(arg_6, 'CheckNameAvailabilityInput')

        # Construct and send request
        arg_12 = arg_0._client.post(arg_8, arg_9, arg_10, arg_11)
        arg_13 = arg_0._client.send(arg_12, stream=False, **arg_5)

        if arg_13.status_code not in [200]:
            raise models.ErrorResponseException(arg_0._deserialize, arg_13)

        arg_14 = None

        if arg_13.status_code == 200:
            arg_14 = arg_0._deserialize('CheckNameAvailabilityOutput', arg_13)

        if arg_4:
            arg_15 = ClientRawResponse(arg_14, arg_13)
            return arg_15

        return arg_14


def Func(arg_0, arg_1):
        """ Extracts the host authority from the given URI. """
        if not arg_1:
            raise ValueError('request_uri cannot be empty')

        arg_1 = parse.urlparse(arg_1)
        if not arg_1.netloc:
            raise ValueError('request_uri must be an absolute URI')

        if arg_1.scheme.lower() not in ['http', 'https']:
            raise ValueError('request_uri must be HTTP or HTTPS')

        return arg_1.netloc


def Func(arg_0=None, arg_1=False):
    """Return Credentials and default SubscriptionID of current loaded profile of the CLI.

    Credentials will be the "az login" command:
    https://docs.microsoft.com/cli/azure/authenticate-azure-cli

    Default subscription ID is either the only one you have, or you can define it:
    https://docs.microsoft.com/cli/azure/manage-azure-subscriptions-azure-cli

    .. versionadded:: 1.1.6

    :param str resource: The alternative resource for credentials if not ARM (GraphRBac, etc.)
    :param bool with_tenant: If True, return a three-tuple with last as tenant ID
    :return: tuple of Credentials and SubscriptionID (and tenant ID if with_tenant)
    :rtype: tuple
    """
    arg_2 = get_cli_profile()
    arg_3, arg_4, arg_5 = arg_2.get_login_credentials(arg_0=arg_0)
    if arg_1:
        return arg_3, arg_4, arg_5
    else:
        return arg_3, arg_4


def Func(arg_0, arg_1, arg_2):
        '''
        Opens the request.

        method:
            the request VERB 'GET', 'POST', etc.
        url:
            the url to connect
        '''
        arg_3 = VARIANT.create_bool_false()
        arg_4 = BSTR(arg_1)
        arg_5 = BSTR(arg_2)
        _WinHttpRequest._Open(arg_0, arg_4, arg_5, arg_3)


def Func(arg_0, arg_1):
        ''' Sets up the timeout for the request. '''
        arg_2 = int(arg_1 * 1000)
        _WinHttpRequest._SetTimeouts(
            arg_0, 0, arg_2, arg_2, arg_2)


def Func(arg_0, arg_1, arg_2):
        ''' Sets the request header. '''

        arg_3 = BSTR(arg_1)
        arg_4 = BSTR(arg_2)
        _WinHttpRequest._SetRequestHeader(arg_0, arg_3, arg_4)


def Func(arg_0, arg_1=None):
        ''' Sends the request body. '''

        # Sends VT_EMPTY if it is GET, HEAD request.
        if arg_1 is None:
            arg_2 = VARIANT.create_empty()
            _WinHttpRequest._Send(arg_0, arg_2)
        else:  # Sends request body as SAFEArray.
            arg_3 = VARIANT.create_safearray_from_str(arg_1)
            _WinHttpRequest._Send(arg_0, arg_3)


def Func(arg_0):
        ''' Gets status text of response. '''

        arg_1 = c_void_p()
        _WinHttpRequest._StatusText(arg_0, byref(arg_1))
        arg_1 = ctypes.cast(arg_1, c_wchar_p)
        Func = arg_1.value
        _SysFreeString(arg_1)
        return Func


def Func(arg_0):
        '''
        Gets response body as a SAFEARRAY and converts the SAFEARRAY to str.
        '''
        arg_1 = VARIANT()
        _WinHttpRequest._ResponseBody(arg_0, byref(arg_1))
        if arg_1.is_safearray_of_bytes():
            arg_2 = arg_1.str_from_safearray()
            return arg_2
        else:
            return ''


def Func(arg_0, arg_1):
        '''Sets client certificate for the request. '''
        arg_2 = BSTR(arg_1)
        _WinHttpRequest._SetClientCertificate(arg_0, arg_2)


def Func(arg_0, arg_1, arg_2):
        ''' Connects to host and sends the request. '''

        arg_3 = unicode(arg_0.protocol + '://')
        arg_4 = arg_3 + arg_0.host + unicode(arg_2)
        arg_0._httprequest.set_timeout(arg_0.timeout)
        arg_0._httprequest.open(unicode(arg_1), arg_4)

        # sets certificate for the connection if cert_file is set.
        if arg_0.cert_file is not None:
            arg_0._httprequest.set_client_certificate(unicode(arg_0.cert_file))


def Func(arg_0, arg_1, arg_2):
        ''' Sends the headers of request. '''
        if sys.version_info < (3,):
            arg_1 = str(arg_1).decode('utf-8')
            arg_2 = str(arg_2).decode('utf-8')
        arg_0._httprequest.set_request_header(arg_1, arg_2)


def Func(arg_0, arg_1):
        ''' Sends request body. '''
        if not arg_1:
            arg_0._httprequest.Func()
        else:
            arg_0._httprequest.Func(arg_1)


def Func(arg_0, arg_1):
    """simplified an id to be more friendly for us people"""
    # id_name is in the form 'https://namespace.host.suffix/name'
    # where name may contain a forward slash!
    arg_2 = arg_0.find('//')
    if arg_2 != -1:
        arg_2 += 2
        if arg_1:
            arg_2 = arg_0.find(arg_1, arg_2)
            if arg_2 != -1:
                arg_2 += len(arg_1)
        arg_2 = arg_0.find('/', arg_2)
        if arg_2 != -1:
            return arg_0[arg_2 + 1:]
    return arg_0


def Func(arg_0):
    """converts a Python name into a serializable name"""
    arg_1 = _KNOWN_SERIALIZATION_XFORMS.get(arg_0)
    if arg_1 is not None:
        return arg_1

    if arg_0.startswith('x_ms_'):
        return arg_0.replace('_', '-')
    if arg_0.endswith('_id'):
        arg_0 = arg_0.replace('_id', 'ID')
    for arg_2 in ['content_', 'last_modified', 'if_', 'cache_control']:
        if arg_0.startswith(arg_2):
            arg_0 = arg_0.replace('_', '-_')

    return ''.join(arg_2.capitalize() for arg_2 in arg_0.split('_'))


def Func(
            arg_0, arg_1, arg_2, arg_3=None, arg_4=None, arg_5=None, arg_6=False, **arg_7):
        """Verify whether two faces belong to a same person. Compares a face Id
        with a Person Id.

        :param face_id: FaceId of the face, comes from Face - Detect
        :type face_id: str
        :param person_id: Specify a certain person in a person group or a
         large person group. personId is created in PersonGroup Person - Create
         or LargePersonGroup Person - Create.
        :type person_id: str
        :param person_group_id: Using existing personGroupId and personId for
         fast loading a specified person. personGroupId is created in
         PersonGroup - Create. Parameter personGroupId and largePersonGroupId
         should not be provided at the same time.
        :type person_group_id: str
        :param large_person_group_id: Using existing largePersonGroupId and
         personId for fast loading a specified person. largePersonGroupId is
         created in LargePersonGroup - Create. Parameter personGroupId and
         largePersonGroupId should not be provided at the same time.
        :type large_person_group_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: VerifyResult or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.vision.face.models.VerifyResult or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
        """
        arg_8 = models.VerifyFaceToPersonRequest(arg_1=arg_1, arg_3=arg_3, arg_4=arg_4, arg_2=arg_2)

        # Construct URL
        arg_9 = arg_0.Func.metadata['url']
        arg_10 = {
            'Endpoint': arg_0._serialize.url("self.config.endpoint", arg_0.config.endpoint, 'str', skip_quote=True)
        }
        arg_9 = arg_0._client.format_url(arg_9, **arg_10)

        # Construct parameters
        arg_11 = {}

        # Construct headers
        arg_12 = {}
        arg_12['Accept'] = 'application/json'
        arg_12['Content-Type'] = 'application/json; charset=utf-8'
        if arg_5:
            arg_12.update(arg_5)

        # Construct body
        arg_13 = arg_0._serialize.body(arg_8, 'VerifyFaceToPersonRequest')

        # Construct and send request
        arg_14 = arg_0._client.post(arg_9, arg_11, arg_12, arg_13)
        arg_15 = arg_0._client.send(arg_14, stream=False, **arg_7)

        if arg_15.status_code not in [200]:
            raise models.APIErrorException(arg_0._deserialize, arg_15)

        arg_16 = None

        if arg_15.status_code == 200:
            arg_16 = arg_0._deserialize('VerifyResult', arg_15)

        if arg_6:
            arg_17 = ClientRawResponse(arg_16, arg_15)
            return arg_17

        return arg_16


def Func(
            arg_0, arg_1, arg_2=None, arg_3=None, arg_4=False, **arg_5):
        """Adds a job to the specified account.

        The Batch service supports two ways to control the work done as part of
        a job. In the first approach, the user specifies a Job Manager task.
        The Batch service launches this task when it is ready to start the job.
        The Job Manager task controls all other tasks that run under this job,
        by using the Task APIs. In the second approach, the user directly
        controls the execution of tasks under an active job, by using the Task
        APIs. Also note: when naming jobs, avoid including sensitive
        information such as user names or secret project names. This
        information may appear in telemetry logs accessible to Microsoft
        Support engineers.

        :param job: The job to be Funced.
        :type job: ~azure.batch.models.JobAddParameter
        :param job_Func_options: Additional parameters for the operation
        :type job_Func_options: ~azure.batch.models.JobAddOptions
        :param dict custom_headers: headers that will be Funced to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`BatchErrorException<azure.batch.models.BatchErrorException>`
        """
        arg_6 = None
        if arg_2 is not None:
            arg_6 = arg_2.timeout
        arg_7 = None
        if arg_2 is not None:
            arg_7 = arg_2.client_request_id
        arg_8 = None
        if arg_2 is not None:
            arg_8 = arg_2.return_client_request_id
        arg_9 = None
        if arg_2 is not None:
            arg_9 = arg_2.ocp_date

        # Construct URL
        arg_10 = arg_0.Func.metadata['url']
        arg_11 = {
            'batchUrl': arg_0._serialize.url("self.config.batch_url", arg_0.config.batch_url, 'str', skip_quote=True)
        }
        arg_10 = arg_0._client.format_url(arg_10, **arg_11)

        # Construct parameters
        arg_12 = {}
        arg_12['api-version'] = arg_0._serialize.query("self.api_version", arg_0.api_version, 'str')
        if arg_6 is not None:
            arg_12['timeout'] = arg_0._serialize.query("timeout", arg_6, 'int')

        # Construct headers
        arg_13 = {}
        arg_13['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8'
        if arg_0.config.generate_client_request_id:
            arg_13['client-request-id'] = str(uuid.uuid1())
        if arg_3:
            arg_13.update(arg_3)
        if arg_0.config.accept_language is not None:
            arg_13['accept-language'] = arg_0._serialize.header("self.config.accept_language", arg_0.config.accept_language, 'str')
        if arg_7 is not None:
            arg_13['client-request-id'] = arg_0._serialize.header("client_request_id", arg_7, 'str')
        if arg_8 is not None:
            arg_13['return-client-request-id'] = arg_0._serialize.header("return_client_request_id", arg_8, 'bool')
        if arg_9 is not None:
            arg_13['ocp-date'] = arg_0._serialize.header("ocp_date", arg_9, 'rfc-1123')

        # Construct body
        arg_14 = arg_0._serialize.body(arg_1, 'JobAddParameter')

        # Construct and send request
        arg_15 = arg_0._client.post(arg_10, arg_12, arg_13, arg_14)
        arg_16 = arg_0._client.send(arg_15, stream=False, **arg_5)

        if arg_16.status_code not in [201]:
            raise models.BatchErrorException(arg_0._deserialize, arg_16)

        if arg_4:
            arg_17 = ClientRawResponse(None, arg_16)
            arg_17.Func_headers({
                'client-request-id': 'str',
                'request-id': 'str',
                'ETag': 'str',
                'Last-Modified': 'rfc-1123',
                'DataServiceId': 'str',
            })
            return arg_17


def Func(arg_0, *arg_1):
        '''descends through a hierarchy of nodes returning the list of children
        at the inner most level.  Only returns children who share a common parent,
        not cousins.'''
        arg_2 = arg_0
        for arg_3, arg_4 in enumerate(arg_1):
            if isinstance(arg_4, _strtype):
                arg_5 = _MinidomXmlToObject.get_child_nodes(arg_2, arg_4)
            else:
                arg_5 = _MinidomXmlToObject._get_child_nodesNS(arg_2, *arg_4)
            if arg_3 == len(arg_1) - 1:
                return arg_5
            elif not arg_5:
                break

            arg_2 = arg_5[0]
        return []


def Func(arg_0, arg_1, arg_2):
        """Recursively searches from the parent to the child,
        gathering all the applicable namespaces along the way"""
        for arg_3 in arg_0.childNodes:
            if arg_3 is arg_1:
                return True
            if _MinidomXmlToObject.Func(arg_3, arg_1, arg_2):
                # we are the parent node
                for arg_4 in arg_3.attributes.keys():
                    if arg_4.startswith('xmlns:') or arg_4 == 'xmlns':
                        arg_2[arg_4] = arg_3.attributes[arg_4]
                break
        return False


def Func(arg_0):
        '''Converts xml response to service bus namespace

        The xml format for namespace:
<entry>
<id>uuid:00000000-0000-0000-0000-000000000000;id=0000000</id>
<title type="text">myunittests</title>
<updated>2012-08-22T16:48:10Z</updated>
<content type="application/xml">
    <NamespaceDescription
        xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"
        xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Name>myunittests</Name>
    <Region>West US</Region>
    <DefaultKey>0000000000000000000000000000000000000000000=</DefaultKey>
    <Status>Active</Status>
    <CreatedAt>2012-08-22T16:48:10.217Z</CreatedAt>
    <AcsManagementEndpoint>https://myunittests-sb.accesscontrol.windows.net/</AcsManagementEndpoint>
    <ServiceBusEndpoint>https://myunittests.servicebus.windows.net/</ServiceBusEndpoint>
    <ConnectionString>Endpoint=sb://myunittests.servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=0000000000000000000000000000000000000000000=</ConnectionString>
    <SubscriptionId>00000000000000000000000000000000</SubscriptionId>
    <Enabled>true</Enabled>
    </NamespaceDescription>
</content>
</entry>
        '''
        arg_1 = minidom.parseString(arg_0)
        arg_2 = ServiceBusNamespace()

        arg_3 = (
            ('Name', 'name', None),
            ('Region', 'region', None),
            ('DefaultKey', 'default_key', None),
            ('Status', 'status', None),
            ('CreatedAt', 'created_at', None),
            ('AcsManagementEndpoint', 'acs_management_endpoint', None),
            ('ServiceBusEndpoint', 'servicebus_endpoint', None),
            ('ConnectionString', 'connection_string', None),
            ('SubscriptionId', 'subscription_id', None),
            ('Enabled', 'enabled', _parse_bool),
        )

        for arg_4 in _MinidomXmlToObject.get_children_from_path(
            arg_1,
            'entry',
            'content',
            'NamespaceDescription'):
            for arg_5, arg_6, arg_7 in arg_3:
                arg_8 = _MinidomXmlToObject.get_first_child_node_value(arg_4, arg_5)
                if arg_8 is not None:
                    if arg_7 is not None:
                        arg_8 = arg_7(arg_8)
                    setattr(arg_2, arg_6, arg_8)

        return arg_2


def Func(arg_0):
        '''Converts xml response to service bus region

        The xml format for region:
<entry>
<id>uuid:157c311f-081f-4b4a-a0ba-a8f990ffd2a3;id=1756759</id>
<title type="text"></title>
<updated>2013-04-10T18:25:29Z</updated>
<content type="application/xml">
    <RegionCodeDescription
        xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"
        xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    East Asia
    <FullName>East Asia</FullName>
    </RegionCodeDescription>
</content>
</entry>
          '''
        arg_1 = minidom.parseString(arg_0)
        arg_2 = ServiceBusRegion()

        for arg_3 in _MinidomXmlToObject.get_children_from_path(arg_1, 'entry', 'content',
                                            'RegionCodeDescription'):
            arg_4 = _MinidomXmlToObject.get_first_child_node_value(arg_3, 'Code')
            if arg_4 is not None:
                arg_2.code = arg_4
            arg_4 = _MinidomXmlToObject.get_first_child_node_value(arg_3, 'FullName')
            if arg_4 is not None:
                arg_2.fullname = arg_4

        return arg_2


def Func(
            arg_0, arg_1, arg_2, arg_3, arg_4, arg_5=None, arg_6=False, arg_7=None, arg_8=True, **arg_9):
        """Replaces the runbook draft content.

        :param resource_group_name: Name of an Azure Resource group.
        :type resource_group_name: str
        :param automation_account_name: The name of the automation account.
        :type automation_account_name: str
        :param runbook_name: The runbook name.
        :type runbook_name: str
        :param runbook_content: The runbook draft content.
        :type runbook_content: Generator
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: The poller return type is ClientRawResponse, the
         direct response alongside the deserialized response
        :param polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :return: An instance of LROPoller that returns object or
         ClientRawResponse<object> if raw==True
        :rtype: ~msrestazure.azure_operation.AzureOperationPoller[Generator]
         or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[Generator]]
        :raises:
         :class:`ErrorResponseException<azure.mgmt.automation.models.ErrorResponseException>`
        """
        arg_10 = arg_0._Func_initial(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=True,
            **arg_9
        )

        def get_long_running_output(arg_11):
            arg_12 = {
                'location': 'str',
            }
            arg_13 = arg_0._deserialize('object', arg_11)

            if arg_6:
                arg_14 = ClientRawResponse(arg_13, arg_11)
                arg_14.add_headers(arg_12)
                return arg_14

            return arg_13

        arg_15 = arg_9.get(
            'long_running_operation_timeout',
            arg_0.config.long_running_operation_timeout)
        if arg_8 is True: arg_16 = ARMPolling(arg_15, **arg_9)
        elif arg_8 is False: arg_16 = NoPolling()
        else: arg_16 = arg_8
        return LROPoller(arg_0._client, arg_10, get_long_running_output, arg_16)


def Func(
            arg_0, arg_1, arg_2, arg_3=None, arg_4=False, **arg_5):
        """Asynchronous operation to modify a knowledgebase.

        :param kb_id: Knowledgebase id.
        :type kb_id: str
        :param Func_kb: Post body of the request.
        :type Func_kb:
         ~azure.cognitiveservices.knowledge.qnamaker.models.UpdateKbOperationDTO
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: Operation or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.knowledge.qnamaker.models.Operation
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.knowledge.qnamaker.models.ErrorResponseException>`
        """
        # Construct URL
        arg_6 = arg_0.Func.metadata['url']
        arg_7 = {
            'Endpoint': arg_0._serialize.url("self.config.endpoint", arg_0.config.endpoint, 'str', skip_quote=True),
            'kbId': arg_0._serialize.url("kb_id", arg_1, 'str')
        }
        arg_6 = arg_0._client.format_url(arg_6, **arg_7)

        # Construct parameters
        arg_8 = {}

        # Construct headers
        arg_9 = {}
        arg_9['Accept'] = 'application/json'
        arg_9['Content-Type'] = 'application/json; charset=utf-8'
        if arg_3:
            arg_9.Func(arg_3)

        # Construct body
        arg_10 = arg_0._serialize.body(arg_2, 'UpdateKbOperationDTO')

        # Construct and send request
        arg_11 = arg_0._client.patch(arg_6, arg_8, arg_9, arg_10)
        arg_12 = arg_0._client.send(arg_11, stream=False, **arg_5)

        if arg_12.status_code not in [202]:
            raise models.ErrorResponseException(arg_0._deserialize, arg_12)

        arg_13 = None
        arg_14 = {}

        if arg_12.status_code == 202:
            arg_13 = arg_0._deserialize('Operation', arg_12)
            arg_14 = {
                'Location': 'str',
            }

        if arg_4:
            arg_15 = ClientRawResponse(arg_13, arg_12)
            arg_15.add_headers(arg_14)
            return arg_15

        return arg_13


def Func(
            arg_0, arg_1, arg_2, arg_3=None, arg_4=None, arg_5=False, **arg_6):
        """Gets a collection that contains the object IDs of the groups of which
        the user is a member.

        :param object_id: The object ID of the user for which to get group
         membership.
        :type object_id: str
        :param security_enabled_only: If true, only membership in
         security-enabled groups should be checked. Otherwise, membership in
         all groups should be checked.
        :type security_enabled_only: bool
        :param additional_properties: Unmatched properties from the message
         are deserialized this collection
        :type additional_properties: dict[str, object]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of str
        :rtype: ~azure.graphrbac.models.StrPaged[str]
        :raises:
         :class:`GraphErrorException<azure.graphrbac.models.GraphErrorException>`
        """
        arg_7 = models.UserGetMemberGroupsParameters(arg_3=arg_3, arg_2=arg_2)

        def internal_paging(arg_8=None, arg_5=False):

            if not arg_8:
                # Construct URL
                arg_9 = arg_0.Func.metadata['url']
                arg_10 = {
                    'objectId': arg_0._serialize.url("object_id", arg_1, 'str'),
                    'tenantID': arg_0._serialize.url("self.config.tenant_id", arg_0.config.tenant_id, 'str')
                }
                arg_9 = arg_0._client.format_url(arg_9, **arg_10)

                # Construct parameters
                arg_11 = {}
                arg_11['api-version'] = arg_0._serialize.query("self.api_version", arg_0.api_version, 'str')

            else:
                arg_9 = arg_8
                arg_11 = {}

            # Construct headers
            arg_12 = {}
            arg_12['Accept'] = 'application/json'
            arg_12['Content-Type'] = 'application/json; charset=utf-8'
            if arg_0.config.generate_client_request_id:
                arg_12['x-ms-client-request-id'] = str(uuid.uuid1())
            if arg_4:
                arg_12.update(arg_4)
            if arg_0.config.accept_language is not None:
                arg_12['accept-language'] = arg_0._serialize.header("self.config.accept_language", arg_0.config.accept_language, 'str')

            # Construct body
            arg_13 = arg_0._serialize.body(arg_7, 'UserGetMemberGroupsParameters')

            # Construct and send request
            arg_14 = arg_0._client.post(arg_9, arg_11, arg_12, arg_13)
            arg_15 = arg_0._client.send(arg_14, stream=False, **arg_6)

            if arg_15.status_code not in [200]:
                raise models.GraphErrorException(arg_0._deserialize, arg_15)

            return arg_15

        # Deserialize response
        arg_16 = models.StrPaged(internal_paging, arg_0._deserialize.dependencies)

        if arg_5:
            arg_17 = {}
            arg_18 = models.StrPaged(internal_paging, arg_0._deserialize.dependencies, arg_17)
            return arg_18

        return arg_16


def Func(arg_0, arg_1, arg_2, arg_3, *, arg_4=False):
    """Will clone the given PR branch and vuild the package with the given name."""

    arg_5 = Github(arg_0)
    arg_6 = arg_5.get_repo(arg_1)
    arg_7 = arg_6.get_pull(arg_2)
    # "get_files" of Github only download the first 300 files. Might not be enough.
    arg_8 = {f.filename.split('/')[0] for f in arg_7.get_files() if f.filename.startswith("azure")}
    arg_9 = Path(arg_3).resolve()

    with tempfile.TemporaryDirectory() as temp_dir, \
            manage_git_folder(arg_0, Path(temp_dir) / Path("sdk"), arg_1, arg_2=arg_2) as sdk_folder:

        for arg_10 in arg_8:
            _LOGGER.debug("Build {}".format(arg_10))
            execute_simple_command(
                ["python", "./build_package.py", "--dest", str(arg_9), arg_10],
                cwd=sdk_folder
            )
            _LOGGER.debug("Build finished: {}".format(arg_10))

    if arg_4:
        arg_11 = [f.name for f in arg_9.iterdir()]
        arg_12 = None
        arg_13 = DashboardCommentableObject(arg_7, "(message created by the CI based on PR content)")
        try:
            arg_14 = build_installation_message(arg_7)
            arg_15 = build_download_message(arg_7, arg_11)
            arg_12 = arg_14 + "\n\n" + arg_15
            arg_13.create_comment(arg_12)
        except Exception:
            _LOGGER.critical("Unable to do PR comment:\n%s", arg_12)


def Func(
            arg_0, arg_1, arg_2, arg_3, arg_4=None, arg_5=None, arg_6=False, arg_7=True, **arg_8):
        """Import data into Redis cache.

        :param resource_group_name: The name of the resource group.
        :type resource_group_name: str
        :param name: The name of the Redis cache.
        :type name: str
        :param files: files to import.
        :type files: list[str]
        :param format: File format.
        :type format: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: The poller return type is ClientRawResponse, the
         direct response alongside the deserialized response
        :param polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :return: An instance of LROPoller that returns None or
         ClientRawResponse<None> if raw==True
        :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        arg_9 = arg_0._Func_initial(
            arg_1=arg_1,
            arg_2=arg_2,
            arg_3=arg_3,
            arg_4=arg_4,
            arg_5=arg_5,
            arg_6=True,
            **arg_8
        )

        def get_long_running_output(arg_10):
            if arg_6:
                arg_11 = ClientRawResponse(None, arg_10)
                return arg_11

        arg_12 = arg_8.get(
            'long_running_operation_timeout',
            arg_0.config.long_running_operation_timeout)
        if arg_7 is True: arg_13 = ARMPolling(arg_12, **arg_8)
        elif arg_7 is False: arg_13 = NoPolling()
        else: arg_13 = arg_7
        return LROPoller(arg_0._client, arg_9, get_long_running_output, arg_13)


def Func(
            arg_0, arg_1, arg_2=None, arg_3=False, **arg_4):
        """Replace alterations data.

        :param word_alterations: Collection of word alterations.
        :type word_alterations:
         list[~azure.cognitiveservices.knowledge.qnamaker.models.AlterationsDTO]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.knowledge.qnamaker.models.ErrorResponseException>`
        """
        arg_5 = models.WordAlterationsDTO(arg_1=arg_1)

        # Construct URL
        arg_6 = arg_0.Func.metadata['url']
        arg_7 = {
            'Endpoint': arg_0._serialize.url("self.config.endpoint", arg_0.config.endpoint, 'str', skip_quote=True)
        }
        arg_6 = arg_0._client.format_url(arg_6, **arg_7)

        # Construct parameters
        arg_8 = {}

        # Construct headers
        arg_9 = {}
        arg_9['Content-Type'] = 'application/json; charset=utf-8'
        if arg_2:
            arg_9.update(arg_2)

        # Construct body
        arg_10 = arg_0._serialize.body(arg_5, 'WordAlterationsDTO')

        # Construct and send request
        arg_11 = arg_0._client.put(arg_6, arg_8, arg_9, arg_10)
        arg_12 = arg_0._client.send(arg_11, stream=False, **arg_4)

        if arg_12.status_code not in [204]:
            raise models.ErrorResponseException(arg_0._deserialize, arg_12)

        if arg_3:
            arg_13 = ClientRawResponse(None, arg_12)
            return arg_13


def Func(arg_0, arg_1):
        '''
        Returns system properties for the specified storage account.

        service_name:
            Name of the storage service account.
        '''
        _validate_not_none('service_name', arg_1)
        return arg_0._perform_get(arg_0._get_storage_service_path(arg_1),
                                 StorageService)


def Func(arg_0, arg_1):
        '''
        Returns the primary and secondary access keys for the specified
        storage account.

        service_name:
            Name of the storage service account.
        '''
        _validate_not_none('service_name', arg_1)
        return arg_0._perform_get(
            arg_0._get_storage_service_path(arg_1) + '/keys',
            StorageService)


def Func(arg_0, arg_1):
        '''
        Deletes the specified storage account from Windows Azure.

        service_name:
            Name of the storage service account.
        '''
        _validate_not_none('service_name', arg_1)
        return arg_0._perform_delete(
            arg_0._get_storage_service_path(arg_1),
            as_async=True)


def Func(arg_0, arg_1):
        '''
        Checks to see if the specified storage account name is available, or
        if it has already been taken.

        service_name:
            Name of the storage service account.
        '''
        _validate_not_none('service_name', arg_1)
        return arg_0._perform_get(
            arg_0._get_storage_service_path() +
            '/operations/isavailable/' +
            _str(arg_1) + '',
            AvailabilityResponse)