text:
"""
Notes
-----
Code written using below textbook as a reference.
Results are checked against the expected outcomes in the text book.

Properties:
Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and
practice. OTexts, 2014.

Author: Terence L van Zyl
Modified: Kevin Sheppard
"""
from statsmodels.compat.python import string_types

import numpy as np
import pandas as pd
from scipy.optimize import basinhopping, brute, minimize
from scipy.spatial.distance import sqeuclidean
from scipy.special import inv_boxcox
from scipy.stats import boxcox

from statsmodels.base.model import Results
from statsmodels.base.wrapper import populate_wrapper, union_dicts, ResultsWrapper
from statsmodels.tsa.base.tsa_model import TimeSeriesModel
from statsmodels.tsa.tsatools import freq_to_period
import statsmodels.tsa._exponential_smoothers as smoothers

def _holt_init(x, xi, p, y, l, b):
    """Initialization for the Holt Models"""
    p[xi.astype(np.bool)] = x
    alpha, beta, _, l0, b0, phi = p[:6]
    alphac = 1 - alpha
    betac = 1 - beta
    y_alpha = alpha * y
    l[:] = 0
    b[:] = 0
    l[0] = l0
    b[0] = b0
    return alpha, beta, phi, alphac, betac, y_alpha

def _holt__(x, xi, p, y, l, b, s, m, n, max_seen):
    """
    Simple Exponential Smoothing
    Minimization Function
    (,)
    """
    alpha, beta, phi, alphac, betac, y_alpha = _holt_init(x, xi, p, y, l, b)
    for i in range(1, n):
        l[i] = (y_alpha[i - 1]) + (alphac * (l[i - 1]))
    return sqeuclidean(l, y)

def _holt_mul_dam(x, xi, p, y, l, b, s, m, n, max_seen):
    """
    Multiplicative and Multiplicative Damped
    Minimization Function
    (M,) & (Md,)
    """
    alpha, beta, phi, alphac, betac, y_alpha = _holt_init(x, xi, p, y, l, b)
    if alpha == 0.0:
        return max_seen
    if beta > alpha:
        return max_seen
    for i in range(1, n):
        l[i] = (y_alpha[i - 1]) + (alphac * (l[i - 1] * b[i - 1]**phi))
        b[i] = (beta * (l[i] / l[i - 1])) + (betac * b[i - 1]**phi)
    return sqeuclidean(l * b**phi, y)

def _holt_add_dam(x, xi, p, y, l, b, s, m, n, max_seen):
    """
    Additive and Additive Damped
    Minimization Function
    (A,) & (Ad,)
    """
    alpha, beta, phi, alphac, betac, y_alpha = _holt_init(x, xi, p, y, l, b)
    if alpha == 0.0:
        return max_seen
    if beta > alpha:
        return max_seen
    for i in range(1, n):
        l[i] = (y_alpha[i - 1]) + (alphac * (l[i - 1] + phi * b[i - 1]))
        b[i] = (beta * (l[i] - l[i - 1])) + (betac * phi * b[i - 1])
    return sqeuclidean(l + phi * b, y)

def _holt_win_init(x, xi, p, y, l, b, s, m):
    """Initialization for the Holt Winters Seasonal Models"""
    p[xi.astype(np.bool)] = x
    alpha, beta, gamma, l0, b0, phi = p[:6]
    s0 = p[6:]
    alphac = 1 - alpha
    betac = 1 - beta
    gammac = 1 - gamma
    y_alpha = alpha * y
    y_gamma = gamma * y
    l[:] = 0
    b[:] = 0
    s[:] = 0
    l[0] = l0
    b[0] = b0
    s[:m] = s0
    return alpha, beta, gamma, phi, alphac, betac, gammac, y_alpha, y_gamma

def _holt_win__mul(x, xi, p, y, l, b, s, m, n, max_seen):
    """
    Multiplicative Seasonal
    Minimization Function
    (,M)
    """
    alpha, beta, gamma, phi, alphac, betac, gammac, y_alpha, y_gamma = _holt_win_init(
        x, xi, p, y, l, b, s, m)
    if alpha == 0.0:
        return max_seen
    if gamma > 1 - alpha:
        return max_seen
    for i in range(1, n):
        l[i] = (y_alpha[i - 1] / s[i - 1]) + (alphac * (l[i - 1]))
        s[i + m - 1] = (y_gamma[i - 1] / (l[i - 1])) + (gammac * s[i - 1])
    return sqeuclidean(l * s[:-(m - 1)], y)

def _holt_win__add(x, xi, p, y, l, b, s, m, n, max_seen):
    """
    Additive Seasonal
    Minimization Function
    (,A)
    """
    alpha, beta, gamma, phi, alphac, betac, gammac, y_alpha, y_gamma = _holt_win_init(
        x, xi, p, y, l, b, s, m)
    if alpha == 0.0:
        return max_seen
    if gamma > 1 - alpha:
        return max_seen
    for i in range(1, n):
        l[i] = (y_alpha[i - 1]) - (alpha * s[i - 1]) + (alphac * (l[i - 1]))
        s[i + m - 1] = y_gamma[i - 1] - (gamma * (l[i - 1])) + (gammac * s[i - 1])
    return sqeuclidean(l + s[:-(m - 1)], y)

def _holt_win_add_mul_dam(x, xi, p, y, l, b, s, m, n, max_seen):
    """
    Additive and Additive Damped with Multiplicative Seasonal
    Minimization Function
    (A,M) & (Ad,M)
    """
    alpha, beta, gamma, phi, alphac, betac, gammac, y_alpha, y_gamma = _holt_win_init(
        x, xi, p, y, l, b, s, m)
    if alpha * beta == 0.0:
        return max_seen
    if beta > alpha or gamma > 1 - alpha:
        return max_seen
    for i in range(1, n):
        l[i] = (y_alpha[i - 1] / s[i - 1]) + \
               (alphac * (l[i - 1] + phi * b[i - 1]))
        b[i] = (beta * (l[i] - l[i - 1])) + (betac * phi * b[i - 1])
        s[i + m - 1] = (y_gamma[i - 1] / (l[i - 1] + phi *
                                          b[i - 1])) + (gammac * s[i - 1])
    return sqeuclidean((l + phi * b) * s[:-(m - 1)], y)

def _holt_win_mul_mul_dam(x, xi, p, y, l, b, s, m, n, max_seen):
    """
    Multiplicative and Multiplicative Damped with Multiplicative Seasonal
    Minimization Function
    (M,M) & (Md,M)
    """
    alpha, beta, gamma, phi, alphac, betac, gammac, y_alpha, y_gamma = _holt_win_init(
        x, xi, p, y, l, b, s, m)
    if alpha * beta == 0.0:
        return max_seen
    if beta > alpha or gamma > 1 - alpha:
        return max_seen
    for i in range(1, n):
        l[i] = (y_alpha[i - 1] / s[i - 1]) + \
               (alphac * (l[i - 1] * b[i - 1]**phi))
        b[i] = (beta * (l[i] / l[i - 1])) + (betac * b[i - 1]**phi)
        s[i + m - 1] = (y_gamma[i - 1] / (l[i - 1] *
                                          b[i - 1]**phi)) + (gammac * s[i - 1])
    return sqeuclidean((l * b**phi) * s[:-(m - 1)], y)

def _holt_win_add_add_dam(x, xi, p, y, l, b, s, m, n, max_seen):
    """
    Additive and Additive Damped with Additive Seasonal
    Minimization Function
    (A,A) & (Ad,A)
    """
    alpha, beta, gamma, phi, alphac, betac, gammac, y_alpha, y_gamma = _holt_win_init(
        x, xi, p, y, l, b, s, m)
    if alpha * beta == 0.0:
        return max_seen
    if beta > alpha or gamma > 1 - alpha:
        return max_seen
    for i in range(1, n):
        l[i] = (y_alpha[i - 1]) - (alpha * s[i - 1]) + \
               (alphac * (l[i - 1] + phi * b[i - 1]))
        b[i] = (beta * (l[i] - l[i - 1])) + (betac * phi * b[i - 1])
        s[i + m - 1] = y_gamma[i - 1] - (gamma * (l[i - 1] + phi * b[i - 1])) + (gammac * s[i - 1])
    return sqeuclidean((l + phi * b) + s[:-(m - 1)], y)

def _holt_win_mul_add_dam(x, xi, p, y, l, b, s, m, n, max_seen):
    """
    Multiplicative and Multiplicative Damped with Additive Seasonal
    Minimization Function
    (M,A) & (M,Ad)
    """
    alpha, beta, gamma, phi, alphac, betac, gammac, y_alpha, y_gamma = _holt_win_init(
        x, xi, p, y, l, b, s, m)
    if alpha * beta == 0.0:
        return max_seen
    if beta > alpha or gamma > 1 - alpha:
        return max_seen
    for i in range(1, n):
        l[i] = (y_alpha[i - 1]) - (alpha * s[i - 1]) + \
               (alphac * (l[i - 1] * b[i - 1]**phi))
        b[i] = (beta * (l[i] / l[i - 1])) + (betac * b[i - 1]**phi)
        s[i + m - 1] = y_gamma[i - 1] - \
            (gamma * (l[i - 1] * b[i - 1]**phi)) + (gammac * s[i - 1])
    return sqeuclidean((l * phi * b) + s[:-(m - 1)], y)

SMOOTHERS = {('mul', 'add'): smoothers._holt_win_add_mul_dam,
             ('mul', 'mul'): smoothers._holt_win_mul_mul_dam,
             ('mul', None): smoothers._holt_win__mul,
             ('add', 'add'): smoothers._holt_win_add_add_dam,
             ('add', 'mul'): smoothers._holt_win_mul_add_dam,
             ('add', None): smoothers._holt_win__add,
             (None, 'add'): smoothers._holt_add_dam,
             (None, 'mul'): smoothers._holt_mul_dam,
             (None, None): smoothers._holt__}

PY_SMOOTHERS = {('mul', 'add'): _holt_win_add_mul_dam,
                ('mul', 'mul'): _holt_win_mul_mul_dam,
                ('mul', None): _holt_win__mul,
                ('add', 'add'): _holt_win_add_add_dam,
                ('add', 'mul'): _holt_win_mul_add_dam,
                ('add', None): _holt_win__add,
                (None, 'add'): _holt_add_dam,
                (None, 'mul'): _holt_mul_dam,
                (None, None): _holt__}

class HoltWintersResults(Results):
    """
    Holt Winter's Exponential Smoothing Results

    Parameters
    ----------
    model : ExponentialSmoothing instance
        The fitted model instance
    params : dict
        All the parameters for the Exponential Smoothing model.

    Attributes
    ----------
    params: dict
        All the parameters for the Exponential Smoothing model.
    params_formatted: pd.DataFrame
        DataFrame containing all parameters, their short names and a flag
        indicating whether the parameter's value was optimized to fit the data.
    fittedfcast: array
        An array of both the fitted values and forecast values.
    fittedvalues: array
        An array of the fitted values. Fitted by the Exponential Smoothing
        model.
    fcastvalues: array
        An array of the forecast values forecast by the Exponential Smoothing
        model.
    sse: float
        The sum of squared errors
    level: array
        An array of the levels values that make up the fitted values.
    slope: array
        An array of the slope values that make up the fitted values.
    season: array
        An array of the seasonal values that make up the fitted values.
    aic: float
        The Akaike information criterion.
    bic: float
        The Bayesian information criterion.
    aicc: float
        AIC with a correction for finite sample sizes.
    resid: array
        An array of the residuals of the fittedvalues and actual values.
    k: int
        the k parameter used to remove the bias in AIC, BIC etc.
    optimized: bool
        Flag indicating whether the model parameters were optimized to fit
        the data.
    mle_retvals:  {None, scipy.optimize.optimize.OptimizeResult}
        Optimization results if the parameters were optimized to fit the data.

    Methods
    -------
    forecast
    predict
    summary
    """

    def __init__(self, model, params, **kwargs):
        self.data = model.data
        super(HoltWintersResults, self).__init__(model, params, **kwargs)

    def predict(self, start=None, end=None):
        """
        In-sample prediction and out-of-sample forecasting

        Parameters
        ----------
        start : int, str, or datetime, optional
            Zero-indexed observation number at which to start forecasting, ie.,
            the first forecast is start. Can also be a date string to
            parse or a datetime type. Default is the the zeroth observation.
        end : int, str, or datetime, optional
            Zero-indexed observation number at which to end forecasting, ie.,
            the first forecast is start. Can also be a date string to
            parse or a datetime type. However, if the dates index does not
            have a fixed frequency, end must be an integer index if you
            want out of sample prediction. Default is the last observation in
            the sample.

        Returns
        -------
        forecast : array
            Array of out of sample forecasts.
        """
        return self.model.predict(self.params, start, end)

    def forecast(self, steps=1):
        """
        Out-of-sample forecasts

        Parameters
        ----------
        steps : int
            The number of out of sample forecasts from the end of the
            sample.

        Returns
        -------
        forecast : array
            Array of out of sample forecasts
        """
        try:
            start = self.model._index[-1] + 1
            end = self.model._index[-1] + steps
            return self.model.predict(self.params, start=start, end=end)
        except ValueError:
            # May occur when the index doesn't have a freq
            return self.model._predict(h=steps, **self.params).fcastvalues

    def summary(self):
        """Summarize the Model

        Returns
        -------
        smry : Summary instance
            This holds the summary table and text, which can be printed or
            converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary.Summary
        """
        from statsmodels.iolib.summary import Summary
        from statsmodels.iolib.table import SimpleTable
        model = self.model
        title = model.__class__.__name__ + ' Model Results'

        dep_variable = 'endog'
        if isinstance(self.model.endog, pd.DataFrame):
            dep_variable = self.model.endog.columns[0]
        elif isinstance(self.model.endog, pd.Series):
            dep_variable = self.model.endog.name
        seasonal_periods = None if self.model.seasonal is None else self.model.seasonal_periods
        lookup = {'add': 'Additive', 'additive': 'Additive',
                  'mul': 'Multiplicative', 'multiplicative': 'Multiplicative', None: 'None'}
        transform = self.params['use_boxcox']
        box_cox_transform = True if transform else False
        box_cox_coeff = transform if isinstance(transform, string_types) else self.params['lamda']
        if isinstance(box_cox_coeff, float):
            box_cox_coeff = '{:>10.5f}'.format(box_cox_coeff)
        top_left = [('Dep. Variable:', [dep_variable]),
                    ('Model:', [model.__class__.__name__]),
                    ('Optimized:', [str(np.any(self.optimized))]),
                    ('Trend:', [lookup[self.model.trend]]),
                    ('Seasonal:', [lookup[self.model.seasonal]]),
                    ('Seasonal Periods:', [str(seasonal_periods)]),
                    ('Box-Cox:', [str(box_cox_transform)]),
                    ('Box-Cox Coeff.:', [str(box_cox_coeff)])]

        top_right = [
            ('No. Observations:', [str(len(self.model.endog))]),
            ('SSE', ['{:5.3f}'.format(self.sse)]),
            ('AIC', ['{:5.3f}'.format(self.aic)]),
            ('BIC', ['{:5.3f}'.format(self.bic)]),
            ('AICC', ['{:5.3f}'.format(self.aicc)]),
            ('Date:', None),
            ('Time:', None)]

        smry = Summary()
        smry.add_table_2cols(self, gleft=top_left, gright=top_right,
                             title=title)
        formatted = self.params_formatted  # type: pd.DataFrame

        def _fmt(x):
            abs_x = np.abs(x)
            scale = 1
            if abs_x != 0:
                scale = int(np.log10(abs_x))
            if scale > 4 or scale < -3:
                return '{:>20.5g}'.format(x)
            dec = min(7 - scale, 7)
            fmt = '{{:>20.{0}f}}'.format(dec)
            return fmt.format(x)

        tab = []
        for _, vals in formatted.iterrows():
            tab.append([_fmt(vals.iloc[1]),
                        '{0:>20}'.format(vals.iloc[0]),
                        '{0:>20}'.format(str(bool(vals.iloc[2])))])
        params_table = SimpleTable(tab, headers=['coeff', 'code', 'optimized'],
                                   title="",
                                   stubs=list(formatted.index))

        smry.tables.append(params_table)

        return smry

class HoltWintersResultsWrapper(ResultsWrapper):
    _attrs = {'fittedvalues': 'rows',
              'level': 'rows',
              'resid': 'rows',
              'season': 'rows',
              'slope': 'rows'}
    _wrap_attrs = union_dicts(ResultsWrapper._wrap_attrs, _attrs)
    _methods = {'predict': 'dates',
                'forecast': 'dates'}
    _wrap_methods = union_dicts(ResultsWrapper._wrap_methods, _methods)

populate_wrapper(HoltWintersResultsWrapper, HoltWintersResults)

class ExponentialSmoothing(TimeSeriesModel):
    """
    Holt Winter's Exponential Smoothing

    Parameters
    ----------
    endog : array-like
        Time series
    trend : {"add", "mul", "additive", "multiplicative", None}, optional
        Type of trend component.
    damped : bool, optional
        Should the trend component be damped.
    seasonal : {"add", "mul", "additive", "multiplicative", None}, optional
        Type of seasonal component.
    seasonal_periods : int, optional
        The number of seasons to consider for the holt winters.

    Returns
    -------
    results : ExponentialSmoothing class

    Notes
    -----
    This is a full implementation of the holt winters exponential smoothing as
    per [1]. This includes all the unstable methods as well as the stable
    methods. The implementation of the library covers the functionality of the
    R library as much as possible whilst still being Pythonic.

    References
    ----------
    [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles
        and practice. OTexts, 2014.
    """

    def __init__(self, endog, trend=None, damped=False, seasonal=None,
                 seasonal_periods=None, dates=None, freq=None, missing='none'):
        super(ExponentialSmoothing, self).__init__(
            endog, None, dates, freq, missing=missing)
        if trend in ['additive', 'multiplicative']:
            trend = {'additive': 'add', 'multiplicative': 'mul'}[trend]
        self.trend = trend
        self.damped = damped
        if seasonal in ['additive', 'multiplicative']:
            seasonal = {'additive': 'add', 'multiplicative': 'mul'}[seasonal]
        self.seasonal = seasonal
        self.trending = trend in ['mul', 'add']
        self.seasoning = seasonal in ['mul', 'add']
        if (self.trend == 'mul' or self.seasonal == 'mul') and np.any(endog <= 0.0):
            raise ValueError('endog must be strictly positive when using multiplicative '
                             'trend or seasonal components.')
        if self.damped and not self.trending:
            raise ValueError('Can only dampen the trend component')
        if self.seasoning:
            self.seasonal_periods = seasonal_periods
            if seasonal_periods is None:
                self.seasonal_periods = freq_to_period(self._index_freq)
            if self.seasonal_periods <= 1:
                raise ValueError('seasonal_periods must be larger than 1.')
        else:
            self.seasonal_periods = 0
        self.nobs = len(self.endog)

    def predict(self, params, start=None, end=None):
        """
        Returns in-sample and out-of-sample prediction.

        Parameters
        ----------
        params : array
            The fitted model parameters.
        start : int, str, or datetime
            Zero-indexed observation number at which to start forecasting, ie.,
            the first forecast is start. Can also be a date string to
            parse or a datetime type.
        end : int, str, or datetime
            Zero-indexed observation number at which to end forecasting, ie.,
            the first forecast is start. Can also be a date string to
            parse or a datetime type.

        Returns
        -------
        predicted values : array
        """
        if start is None:
            start = self._index[-1] + 1
        start, end, out_of_sample, prediction_index = self._get_prediction_index(
            start=start, end=end)
        if out_of_sample > 0:
            res = self._predict(h=out_of_sample, **params)
        else:
            res = self._predict(h=0, **params)
        return res.fittedfcast[start:end + out_of_sample + 1]

    def fit(self, smoothing_level=None, smoothing_slope=None, smoothing_seasonal=None,
            damping_slope=None, optimized=True, use_boxcox=False, remove_bias=False,
            use_basinhopping=False, start_params=None, initial_level=None, initial_slope=None,
            use_brute=True):
        """
        Fit the model

        Parameters
        ----------
        smoothing_level : float, optional
            The alpha value of the simple exponential smoothing, if the value
            is set then this value will be used as the value.
        smoothing_slope :  float, optional
            The beta value of the Holt's trend method, if the value is
            set then this value will be used as the value.
        smoothing_seasonal : float, optional
            The gamma value of the holt winters seasonal method, if the value
            is set then this value will be used as the value.
        damping_slope : float, optional
            The phi value of the damped method, if the value is
            set then this value will be used as the value.
        optimized : bool, optional
            Estimate model parameters by maximizing the log-likelihood
        use_boxcox : {True, False, 'log', float}, optional
            Should the Box-Cox transform be applied to the data first? If 'log'
            then apply the log. If float then use lambda equal to float.
        remove_bias : bool, optional
            Remove bias from forecast values and fitted values by enforcing
            that the average residual is equal to zero.
        use_basinhopping : bool, optional
            Using Basin Hopping optimizer to find optimal values
        start_params: array, optional
            Starting values to used when optimizing the fit.  If not provided,
            starting values are determined using a combination of grid search
            and reasonable values based on the initial values of the data
        initial_level: float, optional
            Value to use when initializing the fitted level.
        initial_slope: float, optional
            Value to use when initializing the fitted slope.
        use_brute: bool, optional
            Search for good starting values using a brute force (grid)
            optimizer. If False, a naive set of starting values is used.

        Returns
        -------
        results : HoltWintersResults class
            See statsmodels.tsa.holtwinters.HoltWintersResults

        Notes
        -----
        This is a full implementation of the holt winters exponential smoothing
        as per [1]. This includes all the unstable methods as well as the
        stable methods. The implementation of the library covers the
        functionality of the R library as much as possible whilst still
        being Pythonic.

        References
        ----------
        [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles
            and practice. OTexts, 2014.
        """
        # Variable renames to alpha,beta, etc as this helps with following the
        # mathematical notation in general
        alpha = smoothing_level
        beta = smoothing_slope
        gamma = smoothing_seasonal
        phi = damping_slope
        l0 = self._l0 = initial_level
        b0 = self._b0 = initial_slope

        data = self.endog
        damped = self.damped
        seasoning = self.seasoning
        trending = self.trending
        trend = self.trend
        seasonal = self.seasonal
        m = self.seasonal_periods
        opt = None
        phi = phi if damped else 1.0
        if use_boxcox == 'log':
            lamda = 0.0
            y = boxcox(data, lamda)
        elif isinstance(use_boxcox, float):
            lamda = use_boxcox
            y = boxcox(data, lamda)
        elif use_boxcox:
            y, lamda = boxcox(data)
        else:
            lamda = None
            y = data.squeeze()
        if np.ndim(y) != 1:
            raise ValueError('Only 1 dimensional data supported')
        self._y = y
        l = np.zeros(self.nobs)
        b = np.zeros(self.nobs)
        s = np.zeros(self.nobs + m - 1)
        p = np.zeros(6 + m)
        max_seen = np.finfo(np.double).max
        l0, b0, s0 = self.initial_values()

        xi = np.zeros_like(p, dtype=np.bool)
        if optimized:
            init_alpha = alpha if alpha is not None else 0.5 / max(m, 1)
            init_beta = beta if beta is not None else 0.1 * init_alpha if trending else beta
            init_gamma = None
            init_phi = phi if phi is not None else 0.99
            # Selection of functions to optimize for appropriate parameters
            if seasoning:
                init_gamma = gamma if gamma is not None else 0.05 * \
                                                             (1 - init_alpha)
                xi = np.array([alpha is None, trending and beta is None, gamma is None,
                               initial_level is None, trending and initial_slope is None,
                               phi is None and damped] + [True] * m)
                func = SMOOTHERS[(seasonal, trend)]
            elif trending:
                xi = np.array([alpha is None, beta is None, False,
                               initial_level is None, initial_slope is None,
                               phi is None and damped] + [False] * m)
                func = SMOOTHERS[(None, trend)]
            else:
                xi = np.array([alpha is None, False, False,
                               initial_level is None, False, False] + [False] * m)
                func = SMOOTHERS[(None, None)]
            p[:] = [init_alpha, init_beta, init_gamma, l0, b0, init_phi] + s0
            if np.any(xi):
                # txi [alpha, beta, gamma, l0, b0, phi, s0,..,s_(m-1)]
                # Have a quick look in the region for a good starting place for alpha etc.
                # using guesstimates for the levels
                txi = xi & np.array([True, True, True, False, False, True] + [False] * m)
                txi = txi.astype(np.bool)
                bounds = np.array([(0.0, 1.0), (0.0, 1.0), (0.0, 1.0),
                                   (0.0, None), (0.0, None), (0.0, 1.0)] + [(None, None), ] * m)
                args = (txi.astype(np.uint8), p, y, l, b, s, m, self.nobs, max_seen)
                if start_params is None and np.any(txi) and use_brute:
                    res = brute(func, bounds[txi], args, Ns=20, full_output=True, finish=None)
                    p[txi], max_seen, _, _ = res
                else:
                    if start_params is not None:
                        start_params = np.atleast_1d(np.squeeze(start_params))
                        if len(start_params) != xi.sum():
                            raise ValueError('start_params must have {0} values but '
                                             'has {1} instead'.format(len(xi), len(start_params)))
                        p[xi] = start_params
                    args = (xi.astype(np.uint8), p, y, l, b, s, m, self.nobs, max_seen)
                    max_seen = func(np.ascontiguousarray(p[xi]), *args)
                # alpha, beta, gamma, l0, b0, phi = p[:6]
                # s0 = p[6:]
                # bounds = np.array([(0.0,1.0),(0.0,1.0),(0.0,1.0),(0.0,None),
                # (0.0,None),(0.8,1.0)] + [(None,None),]*m)
                args = (xi.astype(np.uint8), p, y, l, b, s, m, self.nobs, max_seen)
                if use_basinhopping:
                    # Take a deeper look in the local minimum we are in to find the best
                    # solution to parameters, maybe hop around to try escape the local
                    # minimum we may be in.
                    res = basinhopping(func, p[xi],
                                       minimizer_kwargs={'args': args, 'bounds': bounds[xi]},
                                       stepsize=0.01)
                    success = res.lowest_optimization_result.success
                else:
                    # Take a deeper look in the local minimum we are in to find the best
                    # solution to parameters
                    res = minimize(func, p[xi], args=args, bounds=bounds[xi])
                    success = res.success

                if not success:
                    from warnings import warn
                    from statsmodels.tools.sm_exceptions import ConvergenceWarning
                    warn("Optimization failed to converge. Check mle_retvals.",
                         ConvergenceWarning)
                p[xi] = res.x
                opt = res
            else:
                from warnings import warn
                from statsmodels.tools.sm_exceptions import EstimationWarning
                message = "Model has no free parameters to estimate. Set " \
                          "optimized=False to suppress this warning"
                warn(message, EstimationWarning)

            [alpha, beta, gamma, l0, b0, phi] = p[:6]
            s0 = p[6:]

        hwfit = self._predict(h=0, smoothing_level=alpha, smoothing_slope=beta,
                              smoothing_seasonal=gamma, damping_slope=phi,
                              initial_level=l0, initial_slope=b0, initial_seasons=s0,
                              use_boxcox=use_boxcox, remove_bias=remove_bias, is_optimized=xi)
        hwfit._results.mle_retvals = opt
        return hwfit

    def initial_values(self):
        """
        Compute initial values used in the exponential smoothing recursions

        Returns
        -------
        initial_level : float
            The initial value used for the level component
        initial_slope : {float, None}
            The initial value used for the trend component
        initial_seasons : list
            The initial values used for the seasonal components

        Notes
        -----
        Convenience function the exposes the values used to initialize the
        recursions. When optimizing parameters these are used as starting
        values.

        Method used to compute the initial value depends on when components
        are included in the model.  In a simple exponential smoothing model
        without trend or a seasonal components, the initial value is set to the
        first observation. When a trend is added, the trend is initialized
        either using y[1]/y[0], if multiplicative, or y[1]-y[0]. When the
        seasonal component is added the initialization adapts to account for
        the modified structure.
        """
        y = self._y
        trend = self.trend
        seasonal = self.seasonal
        seasoning = self.seasoning
        trending = self.trending
        m = self.seasonal_periods
        l0 = self._l0
        b0 = self._b0
        if seasoning:
            l0 = y[np.arange(self.nobs) % m == 0].mean() if l0 is None else l0
            if b0 is None and trending:
                lead, lag = y[m:m + m], y[:m]
                if trend == 'mul':
                    b0 = np.exp((np.log(lead.mean()) - np.log(lag.mean())) / m)
                else:
                    b0 = ((lead - lag) / m).mean()
            s0 = list(y[:m] / l0) if seasonal == 'mul' else list(y[:m] - l0)
        elif trending:
            l0 = y[0] if l0 is None else l0
            if b0 is None:
                b0 = y[1] / y[0] if trend == 'mul' else y[1] - y[0]
            s0 = []
        else:
            if l0 is None:
                l0 = y[0]
            b0 = None
            s0 = []

        return l0, b0, s0

    def _predict(self, h=None, smoothing_level=None, smoothing_slope=None,
                 smoothing_seasonal=None, initial_level=None, initial_slope=None,
                 damping_slope=None, initial_seasons=None, use_boxcox=None, lamda=None,
                 remove_bias=None, is_optimized=None):
        """
        Helper prediction function

        Parameters
        ----------
        h : int, optional
            The number of time steps to forecast ahead.
        """
        # Variable renames to alpha, beta, etc as this helps with following the
        # mathematical notation in general
        alpha = smoothing_level
        beta = smoothing_slope
        gamma = smoothing_seasonal
        phi = damping_slope

        # Start in sample and out of sample predictions
        data = self.endog
        damped = self.damped
        seasoning = self.seasoning
        trending = self.trending
        trend = self.trend
        seasonal = self.seasonal
        m = self.seasonal_periods
        phi = phi if damped else 1.0
        if use_boxcox == 'log':
            lamda = 0.0
            y = boxcox(data, 0.0)
        elif isinstance(use_boxcox, float):
            lamda = use_boxcox
            y = boxcox(data, lamda)
        elif use_boxcox:
            y, lamda = boxcox(data)
        else:
            lamda = None
            y = data.squeeze()
            if np.ndim(y) != 1:
                raise NotImplementedError('Only 1 dimensional data supported')
        y_alpha = np.zeros((self.nobs,))
        y_gamma = np.zeros((self.nobs,))
        alphac = 1 - alpha
        y_alpha[:] = alpha * y
        if trending:
            betac = 1 - beta
        if seasoning:
            gammac = 1 - gamma
            y_gamma[:] = gamma * y
        l = np.zeros((self.nobs + h + 1,))
        b = np.zeros((self.nobs + h + 1,))
        s = np.zeros((self.nobs + h + m + 1,))
        l[0] = initial_level
        b[0] = initial_slope
        s[:m] = initial_seasons
        phi_h = np.cumsum(np.repeat(phi, h + 1)**np.arange(1, h + 1 + 1)
                          ) if damped else np.arange(1, h + 1 + 1)
        trended = {'mul': np.multiply,
                   'add': np.add,
                   None: lambda l, b: l
                   }[trend]
        detrend = {'mul': np.divide,
                   'add': np.subtract,
                   None: lambda l, b: 0
                   }[trend]
        dampen = {'mul': np.power,
                  'add': np.multiply,
                  None: lambda b, phi: 0
                  }[trend]
        nobs = self.nobs
        if seasonal == 'mul':
            for i in range(1, nobs + 1):
                l[i] = y_alpha[i - 1] / s[i - 1] + \
                       (alphac * trended(l[i - 1], dampen(b[i - 1], phi)))
                if trending:
                    b[i] = (beta * detrend(l[i], l[i - 1])) + \
                           (betac * dampen(b[i - 1], phi))
                s[i + m - 1] = y_gamma[i - 1] / trended(l[i - 1], dampen(b[i - 1], phi)) + \
                    (gammac * s[i - 1])
            slope = b[1:nobs + 1].copy()
            season = s[m:nobs + m].copy()
            l[nobs:] = l[nobs]
            if trending:
                b[:nobs] = dampen(b[:nobs], phi)
                b[nobs:] = dampen(b[nobs], phi_h)
            trend = trended(l, b)
            s[nobs + m - 1:] = [s[(nobs - 1) + j % m] for j in range(h + 1 + 1)]
            fitted = trend * s[:-m]
        elif seasonal == 'add':
            for i in range(1, nobs + 1):
                l[i] = y_alpha[i - 1] - (alpha * s[i - 1]) + \
                       (alphac * trended(l[i - 1], dampen(b[i - 1], phi)))
                if trending:
                    b[i] = (beta * detrend(l[i], l[i - 1])) + \
                           (betac * dampen(b[i - 1], phi))
                s[i + m - 1] = y_gamma[i - 1] - \
                    (gamma * trended(l[i - 1], dampen(b[i - 1], phi))) + \
                    (gammac * s[i - 1])
            slope = b[1:nobs + 1].copy()
            season = s[m:nobs + m].copy()
            l[nobs:] = l[nobs]
            if trending:
                b[:nobs] = dampen(b[:nobs], phi)
                b[nobs:] = dampen(b[nobs], phi_h)
            trend = trended(l, b)
            s[nobs + m - 1:] = [s[(nobs - 1) + j % m] for j in range(h + 1 + 1)]
            fitted = trend + s[:-m]
        else:
            for i in range(1, nobs + 1):
                l[i] = y_alpha[i - 1] + \
                       (alphac * trended(l[i - 1], dampen(b[i - 1], phi)))
                if trending:
                    b[i] = (beta * detrend(l[i], l[i - 1])) + \
                           (betac * dampen(b[i - 1], phi))
            slope = b[1:nobs + 1].copy()
            season = s[m:nobs + m].copy()
            l[nobs:] = l[nobs]
            if trending:
                b[:nobs] = dampen(b[:nobs], phi)
                b[nobs:] = dampen(b[nobs], phi_h)
            trend = trended(l, b)
            fitted = trend
        level = l[1:nobs + 1].copy()
        if use_boxcox or use_boxcox == 'log' or isinstance(use_boxcox, float):
            fitted = inv_boxcox(fitted, lamda)
            level = inv_boxcox(level, lamda)
            slope = detrend(trend[:nobs], level)
            if seasonal == 'add':
                season = (fitted - inv_boxcox(trend, lamda))[:nobs]
            else:  # seasonal == 'mul':
                season = (fitted / inv_boxcox(trend, lamda))[:nobs]
        sse = sqeuclidean(fitted[:-h - 1], data)
        # (s0 + gamma) + (b0 + beta) + (l0 + alpha) + phi
        k = m * seasoning + 2 * trending + 2 + 1 * damped
        aic = self.nobs * np.log(sse / self.nobs) + k * 2
        if self.nobs - k - 3 > 0:
            aicc_penalty = (2 * (k + 2) * (k + 3)) / (self.nobs - k - 3)
        else:
            aicc_penalty = np.inf
        aicc = aic + aicc_penalty
        bic = self.nobs * np.log(sse / self.nobs) + k * np.log(self.nobs)
        resid = data - fitted[:-h - 1]
        if remove_bias:
            fitted += resid.mean()
        if not damped:
            phi = np.NaN
        self.params = {'smoothing_level': alpha,
                       'smoothing_slope': beta,
                       'smoothing_seasonal': gamma,
                       'damping_slope': phi,
                       'initial_level': l[0],
                       'initial_slope': b[0],
                       'initial_seasons': s[:m],
                       'use_boxcox': use_boxcox,
                       'lamda': lamda,
                       'remove_bias': remove_bias}

        # Format parameters into a DataFrame
        codes = ['alpha', 'beta', 'gamma', 'l.0', 'b.0', 'phi']
        codes += ['s.{0}'.format(i) for i in range(m)]
        idx = ['smoothing_level', 'smoothing_slope', 'smoothing_seasonal',
               'initial_level', 'initial_slope', 'damping_slope']
        idx += ['initial_seasons.{0}'.format(i) for i in range(m)]

        formatted = [alpha, beta, gamma, l[0], b[0], phi]
        formatted += s[:m].tolist()
        formatted = list(map(lambda v: np.nan if v is None else v, formatted))
        formatted = np.array(formatted)
        if is_optimized is None:
            optimized = np.zeros(len(codes), dtype=np.bool)
        else:
            optimized = is_optimized.astype(np.bool)
        included = [True, trending, seasoning, True, trending, damped]
        included += [True] * m
        formatted = pd.DataFrame([[c, f, o] for c, f, o in zip(codes, formatted, optimized)],
                                 columns=['name', 'param', 'optimized'],
                                 index=idx)
        formatted = formatted.loc[included]

        hwfit = HoltWintersResults(self, self.params, fittedfcast=fitted,
                                   fittedvalues=fitted[:-h - 1], fcastvalues=fitted[-h - 1:],
                                   sse=sse, level=level, slope=slope, season=season, aic=aic,
                                   bic=bic, aicc=aicc, resid=resid, k=k,
                                   params_formatted=formatted, optimized=optimized)
        return HoltWintersResultsWrapper(hwfit)

class SimpleExpSmoothing(ExponentialSmoothing):
    """
    Simple Exponential Smoothing

    Parameters
    ----------
    endog : array-like
        Time series

    Returns
    -------
    results : SimpleExpSmoothing class

    Notes
    -----
    This is a full implementation of the simple exponential smoothing as
    per [1].  `SimpleExpSmoothing` is a restricted version of
    :class:`ExponentialSmoothing`.

    See Also
    ---------
    ExponentialSmoothing
    Holt

    References
    ----------
    [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles
        and practice. OTexts, 2014.
    """

    def __init__(self, endog):
        super(SimpleExpSmoothing, self).__init__(endog)

    def fit(self, smoothing_level=None, optimized=True, start_params=None,
            initial_level=None, use_brute=True):
        """
        Fit the model

        Parameters
        ----------
        smoothing_level : float, optional
            The smoothing_level value of the simple exponential smoothing, if
            the value is set then this value will be used as the value.
        optimized : bool, optional
            Estimate model parameters by maximizing the log-likelihood
        start_params: array, optional
            Starting values to used when optimizing the fit.  If not provided,
            starting values are determined using a combination of grid search
            and reasonable values based on the initial values of the data
        initial_level: float, optional
            Value to use when initializing the fitted level.
        use_brute: bool, optional
            Search for good starting values using a brute force (grid)
            optimizer. If False, a naive set of starting values is used.

        Returns
        -------
        results : HoltWintersResults class
            See statsmodels.tsa.holtwinters.HoltWintersResults

        Notes
        -----
        This is a full implementation of the simple exponential smoothing as
        per [1].

        References
        ----------
        [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles
            and practice. OTexts, 2014.
        """
        return super(SimpleExpSmoothing, self).fit(smoothing_level=smoothing_level,
                                                   optimized=optimized, start_params=start_params,
                                                   initial_level=initial_level,
                                                   use_brute=use_brute)

class Holt(ExponentialSmoothing):
    """
    Holt's Exponential Smoothing

    Parameters
    ----------
    endog : array-like
        Time series
    exponential : bool, optional
        Type of trend component.
    damped : bool, optional
        Should the trend component be damped.

    Returns
    -------
    results : Holt class

    Notes
    -----
    This is a full implementation of the Holt's exponential smoothing as
    per [1]. `Holt` is a restricted version of :class:`ExponentialSmoothing`.

    See Also
    ---------
    ExponentialSmoothing
    SimpleExpSmoothing

    References
    ----------
    [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles
        and practice. OTexts, 2014.
    """

    def __init__(self, endog, exponential=False, damped=False):
        trend = 'mul' if exponential else 'add'
        super(Holt, self).__init__(endog, trend=trend, damped=damped)

    def fit(self, smoothing_level=None, smoothing_slope=None, damping_slope=None,
            optimized=True, start_params=None, initial_level=None,
            initial_slope=None, use_brute=True):
        """
        Fit the model

        Parameters
        ----------
        smoothing_level : float, optional
            The alpha value of the simple exponential smoothing, if the value
            is set then this value will be used as the value.
        smoothing_slope :  float, optional
            The beta value of the Holt's trend method, if the value is
            set then this value will be used as the value.
        damping_slope : float, optional
            The phi value of the damped method, if the value is
            set then this value will be used as the value.
        optimized : bool, optional
            Estimate model parameters by maximizing the log-likelihood
        start_params: array, optional
            Starting values to used when optimizing the fit.  If not provided,
            starting values are determined using a combination of grid search
            and reasonable values based on the initial values of the data
        initial_level: float, optional
            Value to use when initializing the fitted level.
        initial_slope: float, optional
            Value to use when initializing the fitted slope.
        use_brute: bool, optional
            Search for good starting values using a brute force (grid)
            optimizer. If False, a naive set of starting values is used.

        Returns
        -------
        results : HoltWintersResults class
            See statsmodels.tsa.holtwinters.HoltWintersResults

        Notes
        -----
        This is a full implementation of the Holt's exponential smoothing as
        per [1].

        References
        ----------
        [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles
            and practice. OTexts, 2014.
        """
        return super(Holt, self).fit(smoothing_level=smoothing_level,
                                     smoothing_slope=smoothing_slope, damping_slope=damping_slope,
                                     optimized=optimized, start_params=start_params,
                                     initial_level=None, initial_slope=None, use_brute=use_brute)


text:
"""Log parsing functions for logs related to the network.

Functions:
  + on_parse_packet: it happens when an RTPS message is parsed.
  + on_udpv4_send: it happens when sending an RTPS packet via UDPv4.
  + on_udpv4_receive: it happens when receiving an RTPS packet via UDPv4.
  + on_shmem_send: it happens when sending an RTPS packet via SharedMemory.
  + on_shmem_receive: it happens when receiving an RTPS packet via SharedMemory
  + on_error_unreachable_network: it happens when the network is unreachable.
  + on_error_no_transport_available: it happens when there isn't transport.
  + on_unregister_not_asserted_entity: it happens unregistering the entity.
  + on_schedule_data: it happens when a data is asynchronously scheduled.
  + on_send_data: it happens when a DATA message is sent.
  + on_resend_data: it happens when the writer resend a DATA message.
  + on_send_gap: it happens when the writer send a GAP message.
  + on_send_preemptive_gap: it happens when sending a preemptive GAP message.
  + on_send_preemptive_hb: it happens when sending a preemptive HB message.
  + on_send_piggyback_hb: it happens when sending a piggyback HB message.
  + on_send_piggyback_hb_syncrepair: it happens for piggyback HB at repair.
  + on_send_hb_response: it happens when sending a HB response.
  + on_receive_ack: it happens when receiving an ACK message.
  + on_instance_not_found: it happens when the instance is not found.
  + on_send_from_deleted_writer: it happens when the writer is deleted.
  + on_fail_serialize: it happens when the serialization fails.
  + on_drop_unregister_no_ack_instance: it happens when there is missing ACK.
  + on_writer_exceed_max_entries: it happens when resource limits are exceeded.
  + on_writer_batching_exceed_max_entries: it happens for batching limits.
  + on_reader_exceed_max_entries: it happens when resource limits are exceeded.
  + on_write_max_blocking_time_expired: it happens when blocking time expired.
  + on_batch_serialize_failure: it happens when the batch serialization fails.
  + on_receive_data: it happens when the reader receives data.
  + on_receive_out_order_data: it happens when SequenceNumber isn't contiguous.
  + on_accept_data: it happens when the reader accepts data.
  + on_rejected_data: it happens when the reader rejects data.
  + on_receive_hb: it happens when receiving a HB.
  + on_send_ack: it happens when a ACK message is sent.
  + on_send_nack: it happens when a NACK message is sent.
  + on_sample_received_from_deleted_writer: it happens when no remote writer.
  + on_deserialize_failure: it happens when deserialization fails.
  + on_shmem_queue_full: it happens when the SharedMemory queue is full.
"""
from __future__ import absolute_import
from logparser.utils import (add_statistics_bandwidth, add_statistics_packet,
                             get_data_packet_name, get_locator, get_oid,
                             get_participant, get_port_name, get_port_number,
                             hex2ip, is_builtin_entity, parse_guid, parse_sn)

# Disable warnings about unused arguments
# pylint: disable=W0613

# --------------------------------------------------------------------------- #
# -- Parser entity                                                         -- #
# --------------------------------------------------------------------------- #
def on_parse_packet(match, state, logger):
    """It happens when an RTPS message is parsed."""
    addr = parse_guid(state, match[1], match[2])
    logger.recv(addr, "", "Received %s packet" % match[0], 2)
    add_statistics_packet(addr, 'receive', match[0], state)

# --------------------------------------------------------------------------- #
# -- Transport layer                                                       -- #
# --------------------------------------------------------------------------- #
def on_udpv4_send(match, state, logger):
    """It happens when sending an RTPS packet through UDPv4."""
    qty = int(match[0])
    addr = get_participant(hex2ip(match[1], True), state)
    port = get_port_name(int(match[2]))
    addr += ":(%s)" % port
    logger.send(addr, "", "Sent %s bytes" % qty, 2)
    add_statistics_bandwidth(addr, 'send', qty, state)

def on_udpv4_receive(match, state, logger):
    """It happens when receiving an RTPS packet through UDPv4."""
    qty = int(match[0])
    addr = get_participant(hex2ip(match[1], True), state)
    port = get_port_number(match[2], state)
    addr += ":" + port.zfill(5)
    logger.recv(addr, "", "Received %d bytes" % qty, 2)
    add_statistics_bandwidth(addr, 'receive', qty, state)

def on_shmem_send(match, state, logger):
    """It happens when sending an RTPS packet through SharedMemory."""
    addr = "SHMEM:(%s)" % get_port_name(int(match[0], 16))
    logger.send(addr, "", "Sent data", 2)

def on_shmem_receive(match, state, logger):
    """It happens when receiving an RTPS packet through SharedMemory."""
    qty = int(match[0])
    logger.recv("SHMEM", "", "Received %d bytes" % qty, 2)
    add_statistics_bandwidth("SHMEM", 'receive', qty, state)

def on_error_unreachable_network(match, state, logger):
    """It happens when the network is unreachable."""
    logger.warning("Unreachable network for previous send", 1)

def on_error_no_transport_available(match, state, logger):
    """It happens when there isn't transport."""
    loc = get_locator(match[0], state)
    logger.warning("[LP-12] No transport available to reach locator %s" % loc,
                   1)

# --------------------------------------------------------------------------- #
# -- Participant entity                                                    -- #
# --------------------------------------------------------------------------- #
def on_unregister_not_asserted_entity(entity):
    """It happens unregistering the entity."""
    def on_unregister_given_not_asserted_entity(match, state, logger):
        """Internal function for the specific entity."""
        remote_part = parse_guid(state, match[0], match[1], match[2])
        remote_oid = get_oid(match[3])
        logger.warning("%s %s is unregistering " % (remote_part, remote_oid) +
                       "remote %s not previously asserted" % entity,
                       2)
    return on_unregister_given_not_asserted_entity

def on_send_participant_announcement(match, state, logger):
    """It happens when sending participant announcements."""
    addr = parse_guid(state, match[0], match[1], match[2])
    part_oid = get_oid(match[3])
    logger.send("", part_oid, "Sent participant announcement for %s" % addr, 1)

# --------------------------------------------------------------------------- #
# -- Write entity                                                          -- #
# --------------------------------------------------------------------------- #
def on_schedule_data(match, state, logger):
    """It happens when a data is asynchronously scheduled."""
    writer_oid = get_oid(match[0])
    seqnum = parse_sn(match[1])
    logger.process("", writer_oid, "Scheduled DATA [%d]" % seqnum)

    if 'packets_lost' not in state:
        state['packets_lost'] = []
    key = writer_oid + "-" + str(seqnum)
    if key in state['packets_lost']:
        state['packets_lost'].remove(key)
    else:
        state['packets_lost'].append(key)

def on_send_data(match, state, logger):
    """It happens when a DATA packet is sent."""
    writer_oid = get_oid(match[0])
    seqnum = parse_sn(match[1])
    logger.send("", writer_oid, "Sent DATA [%d]" % seqnum)
    add_statistics_packet(writer_oid, "send", "DATA", state)

    key = writer_oid + "-" + str(seqnum)
    if 'packets_lost' in state and key in state['packets_lost']:
        state['packets_lost'].remove(key)

def on_resend_data(match, state, logger):
    """It happens when the writer resend a DATA message."""
    writer_oid = get_oid(match[0])
    packet_name = get_data_packet_name(match[0])
    remote_part = parse_guid(state, match[1], match[2], match[3])
    remote_oid = get_oid(match[4])
    seqnum = parse_sn(match[5])
    verb = 1 if is_builtin_entity(match[0]) else 0
    logger.send(remote_part, writer_oid,
                "Resent %s [%d] to reader %s"
                % (packet_name, seqnum, remote_oid),
                verb)

def on_send_periodic_data(match, state, logger):
    """It happens when writing periodic data."""
    seqnum = int(match[0])
    key = match[1]
    local_part = parse_guid(state, key[0:8], key[8:16], key[16:24])
    oid = get_oid(key[24:32])
    data_name = get_data_packet_name(key[24:32])
    verb = 1 if is_builtin_entity(key[24:32]) else 0
    logger.send("", oid,
                "Sent periodic %s [%d] for %s" %
                (data_name, seqnum, local_part),
                verb)

def on_send_gap(match, state, logger):
    """It happens when the writer send a GAP message."""
    writer_oid = get_oid(match[0])
    remote_part = parse_guid(state, match[1], match[2], match[3])
    reader_oid = get_oid(match[4])
    sn_start = parse_sn(match[5])
    sn_end = parse_sn(match[6]) - 1
    verb = 1 if is_builtin_entity(match[0]) else 0
    logger.send(remote_part, writer_oid,
                "Sent GAP to reader %s for samples in [%d, %d]" %
                (reader_oid, sn_start, sn_end), verb)
    add_statistics_packet(writer_oid, 'send', 'GAP', state)

    # Check for large sequence number issues.
    if sn_end - sn_start >= (1 << 31):
        logger.warning("[LP-1] Large Sequence Number difference in GAP")

    # Check for reliable packet lost
    if 'packets_lost' not in state:
        return
    losts = []
    for k in state['packets_lost']:
        info = k.split("-")
        oid = info[0]
        seqnum = int(info[1])
        if oid == writer_oid and seqnum >= sn_start and seqnum < sn_end:
            logger.warning("DATA [%d] may have been lost" % seqnum)
            losts.append(k)
    for k in losts:
        state['packets_lost'].remove(k)

def on_send_preemptive_gap(match, state, logger):
    """It happens when sending a preemptive GAP message."""
    writer_oid = get_oid(match[0])
    reader_addr = parse_guid(state, match[1], match[2], match[3])
    reader_oid = get_oid(match[4])
    verb = 1 if is_builtin_entity(match[0]) else 0
    logger.send(reader_addr, writer_oid,
                "Sent preemptive GAP to volatile reader %s" % (reader_oid),
                verb)

def on_send_preemptive_hb(match, state, logger):
    """It happens when sending a preemptive HB message."""
    writer_oid = get_oid(match[0])
    sn_start = parse_sn(match[1])
    sn_end = parse_sn(match[2])
    verb = 1 if is_builtin_entity(match[0]) else 0
    logger.send("",
                writer_oid,
                "Sent preemptive HB to let know about samples in [%d, %d]" %
                (sn_start, sn_end),
                verb)

def on_send_periodic_hb(match, state, logger):
    """It happens when sending a periodic HB message."""
    writer_oid = get_oid(match[0])
    sn_start = parse_sn(match[1])
    sn_end = parse_sn(match[2])
    epoch = int(match[3])
    verb = 1 if is_builtin_entity(match[0]) else 0
    logger.send("", writer_oid,
                "Sent periodic HB [%d] for samples in [%d, %d]" %
                (epoch, sn_start, sn_end),
                verb)

def on_send_piggyback_hb(match, state, logger):
    """It happens when sending a piggyback HB message."""
    writer_oid = get_oid(match[0])
    sn_first = parse_sn(match[1])
    sn_last = parse_sn(match[2])
    verb = 1 if is_builtin_entity(match[0]) else 0
    logger.send("", writer_oid,
                "Sent piggyback HB to acknowledge samples in [%d, %d]" %
                (sn_first, sn_last), verb)
    add_statistics_packet(writer_oid, "send", "PIGGYBACK HB", state)

def on_send_piggyback_hb_syncrepair(match, state, logger):
    """It happens when sending a piggyback HB message from repair."""
    writer_oid = get_oid(match[0])
    sn_first = parse_sn(match[1])
    sn_last = parse_sn(match[2])
    epoch = int(match[3])
    verb = 1 if is_builtin_entity(match[0]) else 0
    logger.send("",
                writer_oid,
                ("Sent piggyback HB [%d] from synchronous reparation"
                 % epoch) + " to acknowledge samples in [%d, %d]"
                % (sn_first, sn_last),
                verb)
    add_statistics_packet(writer_oid, "send", "PIGGYBACK HB", state)

def on_send_hb_response(match, state, logger):
    """It happens when sending a HB to verify GAP."""
    writer_oid = get_oid(match[0])
    sn_end = parse_sn(match[1])
    sn_start = parse_sn(match[2])
    epoch = int(match[3])
    verb = 1 if is_builtin_entity(match[0]) else 0
    logger.send("",
                writer_oid,
                "Sent HB [%d] to verify GAP for samples in [%d, %d]" %
                (epoch, sn_start, sn_end),
                verb)

def on_receive_ack(match, state, logger):
    """It happens when receiving an ACK message."""
    writer_oid = get_oid(match[0])
    remote = match[1].split('.')
    reader_addr = parse_guid(state, remote[0], remote[1], remote[2])
    reader_oid = get_oid(remote[3])
    seqnum = parse_sn(match[2])
    bitcount = int(match[3])
    epoch = int(match[4])
    verb = 1 if is_builtin_entity(match[0]) else 0
    logger.recv(reader_addr,
                writer_oid,
                "Received ACKNACK [%d] from reader %s for %d +%d" %
                (epoch, reader_oid, seqnum, bitcount),
                verb)

def on_instance_not_found(match, state, logger):
    """It happens when the instance is not found."""
    logger.error("[LP-3] Cannot write unregistered instance.")

def on_send_from_deleted_writer(match, state, logger):
    """It happens when the writer is deleted."""
    logger.error("[LP-14] Cannot write because DataWriter has been deleted")

def on_fail_serialize(match, state, logger):
    """It happens when the serialization fails."""
    logger.error("[LP-8] Cannot serialize sample")

def on_drop_unregister_no_ack_instance(match, state, logger):
    """It happens when unregistering fails because missing ACK."""
    logger.warning("[LP-9] Cannot drop unregistered instance, missing ACKs", 1)

def on_writer_exceed_max_entries(match, state, logger):
    """It happens when the writer resource limits are exceeded."""
    logger.warning("[LP-10] DataWriter exceeded resource limits")

def on_writer_batching_exceed_max_entries(match, state, logger):
    """It happens when the batching resource limits are exceeded."""
    logger.warning("[LP-10] DataWriter with batching exceeded resource limits")

def on_reader_exceed_max_entries(match, state, logger):
    """It happens when the reader resource limits are excceded."""
    logger.warning("[LP-11] DataReader exceeded resource limits")

def on_write_max_blocking_time_expired(match, state, logger):
    """It happens when the blocking time expired."""
    logger.error("[LP-13] Write maximum blocking time expired")

def on_batch_serialize_failure(match, state, logger):
    """It happens when the batch serialization fails."""
    logger.error("Cannot serialize batch sample")

def on_ignore_ack(match, state, logger):
    """It happens when the ACK is ignored."""
    logger.process("", "", "Ignored ACK")

# --------------------------------------------------------------------------- #
# -- Read entity                                                           -- #
# --------------------------------------------------------------------------- #
def on_receive_data(match, state, logger):
    """It happens when the reader receives data."""
    comm = "best-effort" if match[0] == "Be" else "reliable"
    reader_oid = get_oid(match[1])
    packet = match[2]
    seqnum = parse_sn(match[3], 16 if match[0] == "Be" else 10)
    remote = match[5].split('.')
    writer_addr = parse_guid(state, remote[0], remote[1], remote[2])
    writer_oid = get_oid(remote[3])
    packet = get_data_packet_name(remote[3]) if packet == "DATA" else packet

    # Sequece number check
    full_id = writer_addr + "." + writer_oid + ' to ' + reader_oid
    if 'last_sn' not in state:
        state['last_sn'] = {}
    if full_id in state['last_sn']:
        prev_seqnum = state['last_sn'][full_id]
        diff = seqnum - prev_seqnum
        # Add a warning message per missing packet to have a good count in
        # the warning summary.
        for _ in range(diff - 1):
            logger.warning("Missing sample from %s" % full_id)
    if full_id not in state['last_sn'] or state['last_sn'][full_id] < seqnum:
        state['last_sn'][full_id] = seqnum

    # Show the message after any possible warning.
    verb = 1 if is_builtin_entity(remote[3]) else 0
    logger.recv(writer_addr, reader_oid,
                "Received %s [%d] from writer %s (%s)" %
                (packet, seqnum, writer_oid, comm),
                verb)

def on_receive_fragment(match, state, logger):
    """It happens when a DATA fragment is received."""
    reader_oid = get_oid(match[0])
    frag_start = int(match[1])
    frag_end = int(match[2])
    seqnum = parse_sn(match[3])
    logger.recv("", reader_oid,
                "Received DATA fragments %d to %d for sample %d" %
                (frag_start, frag_end, seqnum))

def on_complete_fragment(match, state, logger):
    """It happens when the fragment is complete."""
    reader_oid = get_oid(match[0])
    seqnum = parse_sn(match[1])
    logger.process("", reader_oid,
                   "Fragmented sample %d is complete" % seqnum)

def on_receive_out_order_data(match, state, logger):
    """It happens when the received data sequence number isn't contiguous."""
    reader_oid = get_oid(match[0])
    kind = "old" if match[1] == "old" else "future"
    seqnum = parse_sn(match[2])
    remote = match[3].split('.')
    writer_addr = parse_guid(state, remote[0], remote[1], remote[2])
    writer_oid = get_oid(remote[3])
    packet_name = get_data_packet_name(remote[3])
    verb = 1 if is_builtin_entity(remote[3]) else 0
    logger.recv(writer_addr, reader_oid, "Received %s %s [%d] from writer %s" %
                (kind, packet_name, seqnum, writer_oid),
                verb)

def on_accept_data(match, state, logger):
    """It happens when the reader accepts data."""
    seqnum = parse_sn(match[0])
    logger.process("", "", "Reader accepted DATA (%d)" % seqnum, 1)

def on_rejected_data(match, state, logger):
    """It happens when the reader rejects data."""
    seqnum = parse_sn(match[0])
    logger.process("", "", "Reader rejected DATA (%d)" % seqnum)
    logger.warning("A DataReader rejected sample %d" % seqnum)

def on_receive_hb(match, state, logger):
    """It happens when the write receives a HB."""
    reader_oid = get_oid(match[0])
    packet = match[1]
    sn_start = parse_sn(match[2])
    sn_end = parse_sn(match[3])
    epoch = int(match[4])
    remote = match[5].split('.')
    writer_addr = parse_guid(state, remote[0], remote[1], remote[2])
    writer_oid = get_oid(remote[3])
    verb = 1 if is_builtin_entity(remote[3]) else 0
    logger.recv(writer_addr,
                reader_oid,
                "Received %s [%d] from writer %s for samples in [%d, %d]" %
                (packet, epoch, writer_oid, sn_start, sn_end),
                verb)

def on_received_gap(match, state, logger):
    """It happens when the reader receives a GAP."""
    reader_oid = get_oid(match[0])
    seqnum = parse_sn(match[1])
    lead = parse_sn(match[2])
    bitcount = int(match[3])
    remote = match[4].split('.')
    writer_addr = parse_guid(state, remote[0], remote[1], remote[2])
    writer_oid = get_oid(remote[3])
    verb = 1 if is_builtin_entity(remote[3]) else 0
    logger.recv(writer_addr,
                reader_oid,
                "Received GAP from writer %s for [%d, %d] (+%d)" %
                (writer_oid, seqnum, lead, bitcount),
                verb)

def on_send_ack(match, state, logger):
    """It happens when a ACK message is sent."""
    reader_oid = get_oid(match[0])
    lead = parse_sn(match[1])
    bitcount = int(match[2])
    epoch = int(match[3])
    remote = match[4].split('.')
    writer_addr = parse_guid(state, remote[0], remote[1], remote[2])
    writer_oid = get_oid(remote[3])
    verb = 1 if is_builtin_entity(remote[3]) else 0
    logger.send(writer_addr,
                reader_oid,
                "Sent ACK [%d] to writer %s for %d count %d" %
                (epoch, writer_oid, lead, bitcount),
                verb)

def on_send_nack(match, state, logger):
    """It happens when a NACK message is sent."""
    reader_oid = get_oid(match[0])
    lead = parse_sn(match[1])
    bitcount = int(match[2])
    epoch = int(match[3])
    remote = match[4].split('.')
    writer_addr = parse_guid(state, remote[0], remote[1], remote[2])
    writer_oid = get_oid(remote[3])
    verb = 1 if is_builtin_entity(remote[3]) else 0
    logger.send(writer_addr,
                reader_oid,
                "Sent NACK [%d] to writer %s for %d count %d" %
                (epoch, writer_oid, lead, bitcount),
                verb)

def on_send_nack_frag(match, state, logger):
    """It happens when sending a NACK_FRAG."""
    reader_oid = get_oid(match[0])
    seqnum = parse_sn(match[1])
    verb = 1 if is_builtin_entity(match[0]) else 0
    logger.send("", reader_oid,
                "Sent NACK_FRAG for sample %d" % seqnum,
                verb)

def on_suppress_hb(match, state, logger):
    """It happens when the HB is suppressed."""
    reader_oid = get_oid(match[0])
    verb = 1 if is_builtin_entity(match[0]) else 0
    logger.process("", reader_oid,
                   "Ignored HB due to heartbeat_suppression_duration QoS",
                   verb)

def on_sample_received_from_deleted_writer(match, state, logger):
    """It happens when the remote writer is deleted."""
    logger.warning("Sample received from an already gone remote DataWriter", 1)

def on_deserialize_failure(match, state, logger):
    """It happens when the reader is not able to deserialize a sample."""
    kind = "keyed" if match[0] == "CstReaderCollator" else "unkeyed"
    logger.error("[LP-17] Cannot deserialize %s sample" % kind)

def on_shmem_queue_full(match, state, logger):
    """It happens when the SharedMemory queue is full and data is dropped."""
    port = get_port_number(match[0], state)
    port_name = get_port_name(int(match[0], 16))
    count_max = match[1]
    max_size = match[2]
    logger.cfg("SharedMemory limits for queue " +
               "%s (%s) are: max_num=%s, max_size=%s"
               % (port, port_name, count_max, max_size))
    logger.error("[LP-19] Sample dropped because SharedMemory queue %s is full"
                 % port)

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
in Smith & Soweby, Engl. Bot. 30: tab. 2129 (1810)

#### Original name
Lichen daedaleus Sm.

### Remarks
null


text:
'use strict';

import React, {Component, PropTypes} from 'react';
import {
	StyleSheet,
	View,
	Text,
	Image,
	Dimensions,
	PixelRatio,
	PanResponder
} from 'react-native';

class PickerAndroidItem extends Component{

	static propTypes = {
		value: PropTypes.any,
		label: PropTypes.any
	};

	constructor(props, context){
		super(props, context);
	}

	render() {
		return null;
	}

};

export default class PickerAndroid extends Component{

	static Item = PickerAndroidItem;

	static propTypes = {
		//picker's style
		pickerStyle: View.propTypes.style,
		//picker item's style
		itemStyle: Text.propTypes.style,
		//picked value changed then call this function
		onValueChange: PropTypes.func,
		//default to be selected value
		selectedValue: PropTypes.any
	};

	constructor(props, context){
		super(props, context);
		this.state = this._stateFromProps(this.props);
	}

	componentWillReceiveProps(nextProps){
		this.setState(this._stateFromProps(nextProps));
	}

	shouldComponentUpdate(nextProps, nextState, context){
		return JSON.stringify([{
			selectedIndex: nextState.selectedIndex,
			items: nextState.items,
			pickerStyle: nextState.pickerStyle,
			itemStyle: nextState.itemStyle,
			onValueChange: nextState.onValueChange
		}, context]) !== JSON.stringify([{
			selectedIndex: this.state.selectedIndex,
			items: this.state.items,
			pickerStyle: this.state.pickerStyle,
			itemStyle: this.state.itemStyle,
			onValueChange: this.state.onValueChange
		}, this.context]);
	}

	_stateFromProps(props){
		let selectedIndex = 0;
		let items = [];
		let pickerStyle = props.pickerStyle;
		let itemStyle = props.itemStyle;
		let onValueChange = props.onValueChange;
		React.Children.forEach(props.children, (child, index) => {
			child.props.value === props.selectedValue && ( selectedIndex = index );
			items.push({value: child.props.value, label: child.props.label});
		});
		return {
			selectedIndex,
			items,
			pickerStyle,
			itemStyle,
			onValueChange
		};
	}

	_move(dy){
		let index = this.index;
		this.middleHeight = Math.abs(-index * 40 + dy);
		this.up && this.up.setNativeProps({
			style: {
				marginTop: (3 - index) * 30 + dy * .75,
			},
		});
		this.middle && this.middle.setNativeProps({
			style: {
				marginTop: -index * 40 + dy,
			},
		});
		this.down && this.down.setNativeProps({
			style: {
				marginTop: (-index - 1) * 30 + dy * .75,
			},
		});
	}

	_moveTo(index){
		let _index = this.index;
		let diff = _index - index;
		let marginValue;
		let that = this;
		if(diff && !this.isMoving) {
			marginValue = diff * 40;
			this._move(marginValue);
			this.index = index;
			this._onValueChange();
		}
	}
	//cascade mode will reset the wheel position
	moveTo(index){
		this._moveTo(index);
	}

	moveUp(){
		this._moveTo(Math.max(this.state.items.index - 1, 0));
	}

	moveDown() {
		this._moveTo(Math.min(this.index + 1, this.state.items.length - 1));
	}

	_handlePanResponderMove(evt, gestureState){
		let dy = gestureState.dy;
		if(this.isMoving) {
			return;
		}
		// turn down
		if(dy > 0) {
			this._move(dy > this.index * 40 ? this.index * 40 : dy);
		}else{
			this._move(dy < (this.index - this.state.items.length + 1) * 40 ? (this.index - this.state.items.length + 1) * 40 : dy);
		}
	}

	_handlePanResponderRelease(evt, gestureState){
		let middleHeight = this.middleHeight;
		this.index = middleHeight % 40 >= 20 ? Math.ceil(middleHeight / 40) : Math.floor(middleHeight / 40);
		this._move(0);
		this._onValueChange();
	}

	componentWillMount(){
		this._panResponder = PanResponder.create({
			onMoveShouldSetPanResponder: (evt, gestureState) => true,
			onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
			onPanResponderRelease: this._handlePanResponderRelease.bind(this),
			onPanResponderMove: this._handlePanResponderMove.bind(this)
		});
		this.isMoving = false;
		this.index = this.state.selectedIndex;
	}

	componentWillUnmount(){
		this.timer && clearInterval(this.timer);
	}

	_renderItems(items){
		//value was used to watch the change of picker
		//label was used to display
		let upItems = [], middleItems = [], downItems = [];
		items.forEach((item, index) => {

			upItems[index] = <Text
								key={'up'+index}
								style={[styles.upText, this.state.itemStyle]}
								onPress={() => {
									this._moveTo(index);
								}} >
								{item.label}
							</Text>;

			middleItems[index] = <Text
									key={'mid'+index}
									style={[styles.middleText, this.state.itemStyle]}>{item.label}
								</Text>;

			downItems[index] = <Text
									key={'down'+index}
									style={[styles.downText, this.state.itemStyle]}
									onPress={() => {
										this._moveTo(index);
									}} >
									{item.label}
								</Text>;

		});
		return { upItems, middleItems, downItems, };
	}

	_onValueChange(){
		//the current picked label was more expected to be passed,
		//but PickerIOS only passed value, so we set label to be the second argument
		//add by zooble @2015-12-10
		var curItem = this.state.items[this.index];
		this.state.onValueChange && this.state.onValueChange(curItem.value, curItem.label);
	}

	render(){
		let index = this.state.selectedIndex;
		let length = this.state.items.length;
		let items = this._renderItems(this.state.items);

		let upViewStyle = {
			marginTop: (3 - index) * 30,
			height: length * 30,
		};
		let middleViewStyle = {
			marginTop:  -index * 40,
		};
		let downViewStyle = {
			marginTop: (-index - 1) * 30,
			height:  length * 30,
		};

		return (
			//total to be 90*2+40=220 height
			<View style={[styles.container, this.state.pickerStyle]} {...this._panResponder.panHandlers}>

				<View style={styles.up}>
					<View style={[styles.upView, upViewStyle]} ref={(up) => { this.up = up }} >
						{ items.upItems }
					</View>
				</View>

				<View style={styles.middle}>
					<View style={[styles.middleView, middleViewStyle]} ref={(middle) => { this.middle = middle }} >
						{ items.middleItems }
					</View>
				</View>

				<View style={styles.down}>
					<View style={[styles.downView, downViewStyle]} ref={(down) => { this.down = down }} >
						{ items.downItems }
					</View>
				</View>

			</View>
		);
	}

};

let width = Dimensions.get('window').width;
let height = Dimensions.get('window').height;
let ratio = PixelRatio.get();
let styles = StyleSheet.create({

	container: {
		flex: 1,
		justifyContent: 'center',
		alignItems: 'center',
		//this is very important
		backgroundColor: null
	},
	up: {
		height: 90,
		overflow: 'hidden'
	},
	upView: {
		justifyContent: 'flex-start',
		alignItems: 'center'
	},
	upText: {
		paddingTop: 0,
		height: 30,
		fontSize: 20,
		color: '#000',
		opacity: .5,
		paddingBottom: 0,
		marginTop: 0,
		marginBottom: 0
	},
	middle: {
		height: 40,
		width: width,
		overflow: 'hidden',
		borderColor: '#aaa',
		borderTopWidth: 1/ratio,
		borderBottomWidth: 1/ratio
	},
	middleView: {
		height: 40,
		justifyContent: 'flex-start',
		alignItems: 'center'
	},
	middleText: {
		paddingTop: 0,
		height: 40,
		color: '#000',
		fontSize: 28,
		paddingBottom: 0,
		marginTop: 0,
		marginBottom: 0
	},
	down: {
		height: 90,
		overflow: 'hidden'
	},
	downView: {
		overflow: 'hidden',
		justifyContent: 'flex-start',
		alignItems: 'center'
	},
	downText: {
		paddingTop: 0,
		height: 30,
		fontSize: 16,
		color: '#000',
		opacity: .5,
		paddingBottom: 0,
		marginTop: 0,
		marginBottom: 0
	}

});


text:
class AccountTransactionsController < ApplicationController
  layout 'accounting'
  # GET /account_transactions
  # GET /account_transactions.xml
  def index
    @account_transactions = user_default_branch.current_accounting_period.account_transactions.all(:include => [:account_transaction_items])

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @account_transactions }
    end
  end

  # GET /account_transactions/1
  # GET /account_transactions/1.xml
  def show
    @account_transaction = user_default_branch.current_accounting_period.account_transactions.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @account_transaction }
    end
  end

  # GET /account_transactions/new
  # GET /account_transactions/new.xml
  def new
    @account_transaction = user_default_branch.current_accounting_period.account_transactions.build
    5.times do
      @account_transaction.account_transaction_items << AccountTransactionItem.new
    end
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @account_transaction }
    end
  end

  # GET /account_transactions/1/edit
  def edit
    @account_transaction = user_default_branch.current_accounting_period.account_transactions.find(params[:id])
  end

  # POST /account_transactions
  # POST /account_transactions.xml
  def create
    @account_transaction = user_default_branch.current_accounting_period.account_transactions.build(params[:account_transaction])

    respond_to do |format|
      if @account_transaction.save
        flash[:notice] = 'AccountTransaction was successfully created.'
        format.html { redirect_to(@account_transaction) }
        format.xml  { render :xml => @account_transaction, :status => :created, :location => @account_transaction }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @account_transaction.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /account_transactions/1
  # PUT /account_transactions/1.xml
  def update
    @account_transaction = user_default_branch.current_accounting_period.account_transactions.find(params[:id])

    respond_to do |format|
      if @account_transaction.update_attributes(params[:account_transaction])
        flash[:notice] = 'AccountTransaction was successfully updated.'
        format.html { redirect_to(@account_transaction) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @account_transaction.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /account_transactions/1
  # DELETE /account_transactions/1.xml
  def destroy
    @account_transaction = user_default_branch.current_accounting_period.account_transactions.find(params[:id])
    @account_transaction.destroy

    respond_to do |format|
      format.html { redirect_to(account_transactions_url) }
      format.xml  { head :ok }
    end
  end
end


text:
require 'buckaroo_client/configuration'

describe BuckarooClient::Configuration do
  RSpec.shared_examples 'getter/setter' do |name|
    it "defines `#{name}' getter and setter" do
      subject.public_send("#{name}=", 'bla')
      expect(subject.public_send(name)).to eq 'bla'
    end
  end

  describe '#initialize' do
    it 'defaults to ENV values if no arguments given' do
      stub_const('ENV', {
        'BUCKAROO_CLIENT_WEBSITEKEY' => 'a',
        'BUCKAROO_CLIENT_SECRET' => 'b',
        'BUCKAROO_CLIENT_ENVIRONMENT' => 'c'
      })
      c = described_class.new
      expect(c.websitekey).to eq 'a'
      expect(c.secret).to eq 'b'
      expect(c.environment).to eq 'c'
    end
  end

  describe '#websitekey' do
    include_examples 'getter/setter', 'websitekey'
  end

  describe '#secret' do
    include_examples 'getter/setter', 'secret'
  end

  describe '#environment' do
    include_examples 'getter/setter', 'environment'

    it 'defaults to \'test\'' do
      expect(subject.environment).to eq 'test'
    end
  end

end


text:
<?php

// autoload_namespaces.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Trello' => array($vendorDir . '/trello/trello'),
);


text:
<!--
  Copyright 2013 The Android Open Source Project

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawablePadding="2dp"
    android:background="@drawable/activate_background_indicator"
    android:gravity="center_vertical"
    android:minHeight="56dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp" />


text:
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/layout_margin_medium"
    app:cardBackgroundColor="@android:color/white"
    app:cardCornerRadius="@dimen/card_corner_radius"
    app:cardElevation="@dimen/layout_margin_none"
    android:foreground="?android:attr/selectableItemBackground"
    android:background="@android:color/white">

    <LinearLayout
        android:layout_width="@dimen/item_image_view_extra_large"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="@dimen/item_image_view_160dp"
            android:scaleType="centerCrop"
            android:background="@color/shimmer_background"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_marginTop="@dimen/layout_margin_medium"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <View
                android:layout_width="@dimen/card_width_45dp"
                android:layout_height="@dimen/item_image_view"
                android:background="@color/shimmer_background"
                android:layout_marginEnd="@dimen/padding_large"
                android:layout_marginRight="@dimen/padding_large"
                android:gravity="center_horizontal"
                android:orientation="vertical"
                android:layout_marginTop="@dimen/padding_medium">
            </View>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:paddingBottom="@dimen/padding_large"
                android:paddingTop="@dimen/padding_medium">

                <View
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/view_height_25dp"
                    android:layout_marginBottom="@dimen/layout_margin_small"
                    android:background="@color/shimmer_background"/>

                <View
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/view_height_25dp"
                    android:background="@color/shimmer_background"/>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</androidx.cardview.widget.CardView>


text:
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.yangtypes import YANGDynClass
from pyangbind.lib.yangtypes import ReferenceType
from pyangbind.lib.base import PybindBase
from collections import OrderedDict
from decimal import Decimal
from bitarray import bitarray
import six

# PY3 support of some PY2 keywords (needs improved)
if six.PY3:
    import builtins as __builtin__

    long = int
elif six.PY2:
    import __builtin__

from . import state

class unconstrained_lsp(PybindBase):
    """
  This class was auto-generated by the PythonClass plugin for PYANG
  from YANG module openconfig-network-instance - based on the path /network-instances/network-instance/protocols/protocol/isis/levels/level/link-state-database/lsp/tlvs/tlv/mt-isn/neighbors/neighbor/subTLVs/subTLVs/unconstrained-lsp. Each member element of
  the container is represented as a class variable - with a specific
  YANG type.

  YANG Description: This container defines sub-TLV 23.
  """
    __slots__ = ("_path_helper", "_extmethods", "__state")

    _yang_name = "unconstrained-lsp"

    _pybind_generated_by = "container"

    def __init__(self, *args, **kwargs):

        self._path_helper = False

        self._extmethods = False
        self.__state = YANGDynClass(
            base=state.state,
            is_container="container",
            yang_name="state",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/network-instance",
            defining_module="openconfig-network-instance",
            yang_type="container",
            is_config=False,
        )

        load = kwargs.pop("load", None)
        if args:
            if len(args) > 1:
                raise TypeError("cannot create a YANG container with >1 argument")
            all_attr = True
            for e in self._pyangbind_elements:
                if not hasattr(args[0], e):
                    all_attr = False
                    break
            if not all_attr:
                raise ValueError("Supplied object did not have the correct attributes")
            for e in self._pyangbind_elements:
                nobj = getattr(args[0], e)
                if nobj._changed() is False:
                    continue
                setmethod = getattr(self, "_set_%s" % e)
                if load is None:
                    setmethod(getattr(args[0], e))
                else:
                    setmethod(getattr(args[0], e), load=load)

    def _path(self):
        if hasattr(self, "_parent"):
            return self._parent._path() + [self._yang_name]
        else:
            return [
                "network-instances",
                "network-instance",
                "protocols",
                "protocol",
                "isis",
                "levels",
                "level",
                "link-state-database",
                "lsp",
                "tlvs",
                "tlv",
                "mt-isn",
                "neighbors",
                "neighbor",
                "subTLVs",
                "subTLVs",
                "unconstrained-lsp",
            ]

    def _get_state(self):
        """
    Getter method for state, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/mt_isn/neighbors/neighbor/subTLVs/subTLVs/unconstrained_lsp/state (container)

    YANG Description: State parameters of sub-TLV 23.
    """
        return self.__state

    def _set_state(self, v, load=False):
        """
    Setter method for state, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/mt_isn/neighbors/neighbor/subTLVs/subTLVs/unconstrained_lsp/state (container)
    If this variable is read-only (config: false) in the
    source YANG file, then _set_state is considered as a private
    method. Backends looking to populate this variable should
    do so via calling thisObj._set_state() directly.

    YANG Description: State parameters of sub-TLV 23.
    """
        if hasattr(v, "_utype"):
            v = v._utype(v)
        try:
            t = YANGDynClass(
                v,
                base=state.state,
                is_container="container",
                yang_name="state",
                parent=self,
                path_helper=self._path_helper,
                extmethods=self._extmethods,
                register_paths=True,
                extensions=None,
                namespace="http://openconfig.net/yang/network-instance",
                defining_module="openconfig-network-instance",
                yang_type="container",
                is_config=False,
            )
        except (TypeError, ValueError):
            raise ValueError(
                {
                    "error-string": """state must be of a type compatible with container""",
                    "defined-type": "container",
                    "generated-type": """YANGDynClass(base=state.state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)""",
                }
            )

        self.__state = t
        if hasattr(self, "_set"):
            self._set()

    def _unset_state(self):
        self.__state = YANGDynClass(
            base=state.state,
            is_container="container",
            yang_name="state",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/network-instance",
            defining_module="openconfig-network-instance",
            yang_type="container",
            is_config=False,
        )

    state = __builtin__.property(_get_state)

    _pyangbind_elements = OrderedDict([("state", state)])

from . import state

class unconstrained_lsp(PybindBase):
    """
  This class was auto-generated by the PythonClass plugin for PYANG
  from YANG module openconfig-network-instance-l2 - based on the path /network-instances/network-instance/protocols/protocol/isis/levels/level/link-state-database/lsp/tlvs/tlv/mt-isn/neighbors/neighbor/subTLVs/subTLVs/unconstrained-lsp. Each member element of
  the container is represented as a class variable - with a specific
  YANG type.

  YANG Description: This container defines sub-TLV 23.
  """
    __slots__ = ("_path_helper", "_extmethods", "__state")

    _yang_name = "unconstrained-lsp"

    _pybind_generated_by = "container"

    def __init__(self, *args, **kwargs):

        self._path_helper = False

        self._extmethods = False
        self.__state = YANGDynClass(
            base=state.state,
            is_container="container",
            yang_name="state",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/network-instance",
            defining_module="openconfig-network-instance",
            yang_type="container",
            is_config=False,
        )

        load = kwargs.pop("load", None)
        if args:
            if len(args) > 1:
                raise TypeError("cannot create a YANG container with >1 argument")
            all_attr = True
            for e in self._pyangbind_elements:
                if not hasattr(args[0], e):
                    all_attr = False
                    break
            if not all_attr:
                raise ValueError("Supplied object did not have the correct attributes")
            for e in self._pyangbind_elements:
                nobj = getattr(args[0], e)
                if nobj._changed() is False:
                    continue
                setmethod = getattr(self, "_set_%s" % e)
                if load is None:
                    setmethod(getattr(args[0], e))
                else:
                    setmethod(getattr(args[0], e), load=load)

    def _path(self):
        if hasattr(self, "_parent"):
            return self._parent._path() + [self._yang_name]
        else:
            return [
                "network-instances",
                "network-instance",
                "protocols",
                "protocol",
                "isis",
                "levels",
                "level",
                "link-state-database",
                "lsp",
                "tlvs",
                "tlv",
                "mt-isn",
                "neighbors",
                "neighbor",
                "subTLVs",
                "subTLVs",
                "unconstrained-lsp",
            ]

    def _get_state(self):
        """
    Getter method for state, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/mt_isn/neighbors/neighbor/subTLVs/subTLVs/unconstrained_lsp/state (container)

    YANG Description: State parameters of sub-TLV 23.
    """
        return self.__state

    def _set_state(self, v, load=False):
        """
    Setter method for state, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/mt_isn/neighbors/neighbor/subTLVs/subTLVs/unconstrained_lsp/state (container)
    If this variable is read-only (config: false) in the
    source YANG file, then _set_state is considered as a private
    method. Backends looking to populate this variable should
    do so via calling thisObj._set_state() directly.

    YANG Description: State parameters of sub-TLV 23.
    """
        if hasattr(v, "_utype"):
            v = v._utype(v)
        try:
            t = YANGDynClass(
                v,
                base=state.state,
                is_container="container",
                yang_name="state",
                parent=self,
                path_helper=self._path_helper,
                extmethods=self._extmethods,
                register_paths=True,
                extensions=None,
                namespace="http://openconfig.net/yang/network-instance",
                defining_module="openconfig-network-instance",
                yang_type="container",
                is_config=False,
            )
        except (TypeError, ValueError):
            raise ValueError(
                {
                    "error-string": """state must be of a type compatible with container""",
                    "defined-type": "container",
                    "generated-type": """YANGDynClass(base=state.state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='container', is_config=False)""",
                }
            )

        self.__state = t
        if hasattr(self, "_set"):
            self._set()

    def _unset_state(self):
        self.__state = YANGDynClass(
            base=state.state,
            is_container="container",
            yang_name="state",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/network-instance",
            defining_module="openconfig-network-instance",
            yang_type="container",
            is_config=False,
        )

    state = __builtin__.property(_get_state)

    _pyangbind_elements = OrderedDict([("state", state)])


text:
/*
 * removed cliboard functions as not supported yet on iot
 *
 */

using System;
using System.Xml;

namespace Pololu.Usc.Sequencer
{

    public class Frame
    {
        public string name;
        private ushort[] privateTargets;
        public ushort length_ms;

        /// <summary>
        /// Gets the target of the given channel.
        /// </summary>
        /// <remarks>
        /// By retreiving targets this way, we protect the application against
        /// any kind of case where the Frame object might have fewer targets
        /// than expected.
        /// </remarks>
        [System.Runtime.CompilerServices.IndexerName("target")]
        public ushort this[int channel]
        {
            get
            {
                if (privateTargets == null || channel >= privateTargets.Length)
                {
                    return 0;
                }

                return privateTargets[channel];
            }
        }

        public ushort[] targets
        {
            set
            {
                privateTargets = value;
            }
            get
            {
                return privateTargets;
            }
        }

        /// <summary>
        /// Returns a string with all the servo positions, separated by spaces,
        /// e.g. "0 0 4000 0 1000 0 0".
        /// </summary>
        /// <returns></returns>
        public string getTargetsString()
        {
            string targetsString = "";
            for (int i = 0; i < privateTargets.Length; i++)
            {
                if (i != 0)
                {
                    targetsString += " ";
                }

                targetsString += privateTargets[i].ToString();
            }
            return targetsString;
        }

        /// <summary>
        /// Returns a string the name, duration, and all servo positions, separated by tabs.
        /// e.g. "Frame 1   500 0   0   0   4000    8000"
        /// </summary>
        /// <returns></returns>
        private string getTabSeparatedString()
        {
            string tabString = name + "\t" + length_ms;
            foreach (ushort target in privateTargets)
            {
                tabString += "\t" + target;
            }
            return tabString;
        }

        /// <summary>
        /// Take a (potentially malformed) string with target numbers separated by spaces
        /// and use it to set the targets.
        /// </summary>
        /// <param name="targetsString"></param>
        /// <param name="servoCount"></param>
        public void setTargetsFromString(string targetsString, byte servoCount)
        {
            ushort[] tmpTargets = new ushort[servoCount];

            string[] targetStrings = targetsString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < targetStrings.Length && i < servoCount; i++)
            {
                try
                {
                    tmpTargets[i] = ushort.Parse(targetStrings[i]);
                }
                catch { }
            }
            this.targets = tmpTargets;
        }

        public void writeXml(XmlWriter writer)
        {
            writer.WriteStartElement("Frame");
            writer.WriteAttributeString("name", name);
            writer.WriteAttributeString("duration", length_ms.ToString());
            writer.WriteString(getTargetsString());
            writer.WriteEndElement();
        }

    }
}


text:
import { connect } from 'react-redux';

import WorkExperiencesForm from '../../components/ShareExperience/WorkExperiencesForm';

const mapStateToProps = () => ({});

const mapDispatchToProps = () => ({});

export default connect(mapStateToProps, mapDispatchToProps)(WorkExperiencesForm);