text:
"""Sandwich covariance estimators

Created on Sun Nov 27 14:10:57 2011

Author: Josef Perktold
Author: Skipper Seabold for HCxxx in linear_model.RegressionResults
License: BSD-3

Notes
-----

for calculating it, we have two versions

version 1: use pinv
pinv(x) scale pinv(x)   used currently in linear_model, with scale is
1d (or diagonal matrix)
(x'x)^(-1) x' scale x (x'x)^(-1),  scale in general is (nobs, nobs) so
pretty large
general formulas for scale in cluster case are in
http://pubs.amstat.org/doi/abstract/10.1198/jbes.2010.07136 which also
has the second version

version 2:
(x'x)^(-1) S (x'x)^(-1)    with S = x' scale x,    S is (kvar,kvars),
(x'x)^(-1) is available as normalized_covparams.

S = sum (x*u) dot (x*u)' = sum x*u*u'*x'  where sum here can aggregate
over observations or groups. u is regression residual.

x is (nobs, k_var)
u is (nobs, 1)
x*u is (nobs, k_var)

For cluster robust standard errors, we first sum (x*w) over other groups
(including time) and then take the dot product (sum of outer products)

S = sum_g(x*u)' dot sum_g(x*u)
For HAC by clusters, we first sum over groups for each time period, and then
use HAC on the group sums of (x*w).
If we have several groups, we have to sum first over all relevant groups, and
then take the outer product sum. This can be done by summing using indicator
functions or matrices or with explicit loops. Alternatively we calculate
separate covariance matrices for each group, sum them and subtract the
duplicate counted intersection.

Not checked in details yet: degrees of freedom or small sample correction
factors, see (two) references (?)

This is the general case for MLE and GMM also

in MLE     hessian H, outerproduct of jacobian S,   cov_hjjh = HJJH,
which reduces to the above in the linear case, but can be used
generally, e.g. in discrete, and is misnomed in GenericLikelihoodModel

in GMM it's similar but I would have to look up the details, (it comes
out in sandwich form by default, it's in the sandbox), standard Newey
West or similar are on the covariance matrix of the moment conditions

quasi-MLE: MLE with mis-specified model where parameter estimates are
fine (consistent ?) but cov_params needs to be adjusted similar or
same as in sandwiches. (I didn't go through any details yet.)

TODO
----
* small sample correction factors, Done for cluster, not yet for HAC
* automatic lag-length selection for Newey-West HAC,
  -> added: nlag = floor[4(T/100)^(2/9)]  Reference: xtscc paper, Newey-West
     note this will not be optimal in the panel context, see Peterson
* HAC should maybe return the chosen nlags
* get consistent notation, varies by paper, S, scale, sigma?
* replace diag(hat_matrix) calculations in cov_hc2, cov_hc3

References
----------
John C. Driscoll and Aart C. Kraay, "Consistent Covariance Matrix Estimation
with Spatially Dependent Panel Data," Review of Economics and Statistics 80,
no. 4 (1998): 549-560.

Daniel Hoechle, "Robust Standard Errors for Panel Regressions with
Cross-Sectional Dependence", The Stata Journal

Mitchell A. Petersen, "Estimating Standard Errors in Finance Panel Data
Sets: Comparing Approaches," Review of Financial Studies 22, no. 1
(January 1, 2009): 435 -480.

A. Colin Cameron, Jonah B. Gelbach, and Douglas L. Miller, "Robust Inference
With Multiway Clustering," Journal of Business and Economic Statistics 29
(April 2011): 238-249.

not used yet:
A.C. Cameron, J.B. Gelbach, and D.L. Miller, "Bootstrap-based improvements
for inference with clustered errors," The Review of Economics and
Statistics 90, no. 3 (2008): 414–427.

"""
from statsmodels.compat.python import range
import pandas as pd
import numpy as np

from statsmodels.tools.grouputils import Group
from statsmodels.stats.moment_helpers import se_cov

__all__ = ['cov_cluster', 'cov_cluster_2groups', 'cov_hac', 'cov_nw_panel',
           'cov_white_simple',
           'cov_hc0', 'cov_hc1', 'cov_hc2', 'cov_hc3',
           'se_cov', 'weights_bartlett', 'weights_uniform']

#----------- from linear_model.RegressionResults
'''
    HC0_se
        White's (1980) heteroskedasticity robust standard errors.
        Defined as sqrt(diag(X.T X)^(-1)X.T diag(e_i^(2)) X(X.T X)^(-1)
        where e_i = resid[i]
        HC0_se is a property.  It is not evaluated until it is called.
        When it is called the RegressionResults instance will then have
        another attribute cov_HC0, which is the full heteroskedasticity
        consistent covariance matrix and also `het_scale`, which is in
        this case just resid**2.  HCCM matrices are only appropriate for OLS.
    HC1_se
        MacKinnon and White's (1985) alternative heteroskedasticity robust
        standard errors.
        Defined as sqrt(diag(n/(n-p)*HC_0)
        HC1_se is a property.  It is not evaluated until it is called.
        When it is called the RegressionResults instance will then have
        another attribute cov_HC1, which is the full HCCM and also `het_scale`,
        which is in this case n/(n-p)*resid**2.  HCCM matrices are only
        appropriate for OLS.
    HC2_se
        MacKinnon and White's (1985) alternative heteroskedasticity robust
        standard errors.
        Defined as (X.T X)^(-1)X.T diag(e_i^(2)/(1-h_ii)) X(X.T X)^(-1)
        where h_ii = x_i(X.T X)^(-1)x_i.T
        HC2_se is a property.  It is not evaluated until it is called.
        When it is called the RegressionResults instance will then have
        another attribute cov_HC2, which is the full HCCM and also `het_scale`,
        which is in this case is resid^(2)/(1-h_ii).  HCCM matrices are only
        appropriate for OLS.
    HC3_se
        MacKinnon and White's (1985) alternative heteroskedasticity robust
        standard errors.
        Defined as (X.T X)^(-1)X.T diag(e_i^(2)/(1-h_ii)^(2)) X(X.T X)^(-1)
        where h_ii = x_i(X.T X)^(-1)x_i.T
        HC3_se is a property.  It is not evaluated until it is called.
        When it is called the RegressionResults instance will then have
        another attribute cov_HC3, which is the full HCCM and also `het_scale`,
        which is in this case is resid^(2)/(1-h_ii)^(2).  HCCM matrices are
        only appropriate for OLS.

'''

def _HCCM(results, scale):
    '''
    sandwich with pinv(x) * diag(scale) * pinv(x).T

    where pinv(x) = (X'X)^(-1) X
    and scale is (nobs,)
    '''
    H = np.dot(results.model.pinv_wexog,
        scale[:,None]*results.model.pinv_wexog.T)
    return H

def cov_hc0(results):
    """
    See statsmodels.RegressionResults
    """

    het_scale = results.resid**2 # or whitened residuals? only OLS?
    cov_hc0 = _HCCM(results, het_scale)

    return cov_hc0

def cov_hc1(results):
    """
    See statsmodels.RegressionResults
    """

    het_scale = results.nobs/(results.df_resid)*(results.resid**2)
    cov_hc1 = _HCCM(results, het_scale)
    return cov_hc1

def cov_hc2(results):
    """
    See statsmodels.RegressionResults
    """

    # probably could be optimized
    h = np.diag(np.dot(results.model.exog,
                          np.dot(results.normalized_cov_params,
                          results.model.exog.T)))
    het_scale = results.resid**2/(1-h)
    cov_hc2_ = _HCCM(results, het_scale)
    return cov_hc2_

def cov_hc3(results):
    """
    See statsmodels.RegressionResults
    """

    # above probably could be optimized to only calc the diag
    h = np.diag(np.dot(results.model.exog,
                          np.dot(results.normalized_cov_params,
                          results.model.exog.T)))
    het_scale=(results.resid/(1-h))**2
    cov_hc3_ = _HCCM(results, het_scale)
    return cov_hc3_

#---------------------------------------

def _get_sandwich_arrays(results):
    """Helper function to get scores from results

    Parameters

    """

    if isinstance(results, tuple):
        # assume we have jac and hessian_inv
        jac, hessian_inv = results
        jac = np.asarray(jac)
        hessian_inv = np.asarray(hessian_inv)
    elif hasattr(results, 'model'):
        if hasattr(results, '_results'):
            # remove wrapper
            results = results._results
        # assume we have a results instance
        if hasattr(results.model, 'jac'):
            xu = results.model.jac(results.params)
            hessian_inv = np.linalg.inv(results.model.hessian(results.params))
        elif hasattr(results.model, 'score_obs'):
            xu = results.model.score_obs(results.params)
            hessian_inv = np.linalg.inv(results.model.hessian(results.params))
        else:
            xu = results.model.wexog * results.wresid[:, None]

            hessian_inv = np.asarray(results.normalized_cov_params)

        # experimental support for freq_weights
        if hasattr(results.model, 'freq_weights'):
            # we don't want to square the weights in the covariance calculations
            # assumes that freq_weights are incorporated in score_obs or equivalent
            # assumes xu/score_obs is 2D
            # temporary asarray
            xu /= np.sqrt(np.asarray(results.model.freq_weights)[:, None])

    else:
        raise ValueError('need either tuple of (jac, hessian_inv) or results' +
                         'instance')

    return xu, hessian_inv

def _HCCM1(results, scale):
    '''
    sandwich with pinv(x) * scale * pinv(x).T

    where pinv(x) = (X'X)^(-1) X
    and scale is (nobs, nobs), or (nobs,) with diagonal matrix diag(scale)

    Parameters
    ----------
    results : result instance
       need to contain regression results, uses results.model.pinv_wexog
    scale : ndarray (nobs,) or (nobs, nobs)
       scale matrix, treated as diagonal matrix if scale is one-dimensional

    Returns
    -------
    H : ndarray (k_vars, k_vars)
        robust covariance matrix for the parameter estimates

    '''
    if scale.ndim == 1:
        H = np.dot(results.model.pinv_wexog,
                   scale[:,None]*results.model.pinv_wexog.T)
    else:
        H = np.dot(results.model.pinv_wexog,
                   np.dot(scale, results.model.pinv_wexog.T))
    return H

def _HCCM2(hessian_inv, scale):
    '''
    sandwich with (X'X)^(-1) * scale * (X'X)^(-1)

    scale is (kvars, kvars)
    this uses results.normalized_cov_params for (X'X)^(-1)

    Parameters
    ----------
    results : result instance
       need to contain regression results, uses results.normalized_cov_params
    scale : ndarray (k_vars, k_vars)
       scale matrix

    Returns
    -------
    H : ndarray (k_vars, k_vars)
        robust covariance matrix for the parameter estimates

    '''
    if scale.ndim == 1:
        scale = scale[:,None]

    xxi = hessian_inv
    H = np.dot(np.dot(xxi, scale), xxi.T)
    return H

#TODO: other kernels, move ?
def weights_bartlett(nlags):
    '''Bartlett weights for HAC

    this will be moved to another module

    Parameters
    ----------
    nlags : int
       highest lag in the kernel window, this does not include the zero lag

    Returns
    -------
    kernel : ndarray, (nlags+1,)
        weights for Bartlett kernel

    '''

    #with lag zero
    return 1 - np.arange(nlags+1)/(nlags+1.)

def weights_uniform(nlags):
    '''uniform weights for HAC

    this will be moved to another module

    Parameters
    ----------
    nlags : int
       highest lag in the kernel window, this does not include the zero lag

    Returns
    -------
    kernel : ndarray, (nlags+1,)
        weights for uniform kernel

    '''

    #with lag zero
    return np.ones(nlags+1)

def S_hac_simple(x, nlags=None, weights_func=weights_bartlett):
    '''inner covariance matrix for HAC (Newey, West) sandwich

    assumes we have a single time series with zero axis consecutive, equal
    spaced time periods

    Parameters
    ----------
    x : ndarray (nobs,) or (nobs, k_var)
        data, for HAC this is array of x_i * u_i
    nlags : int or None
        highest lag to include in kernel window. If None, then
        nlags = floor(4(T/100)^(2/9)) is used.
    weights_func : callable
        weights_func is called with nlags as argument to get the kernel
        weights. default are Bartlett weights

    Returns
    -------
    S : ndarray, (k_vars, k_vars)
        inner covariance matrix for sandwich

    Notes
    -----
    used by cov_hac_simple

    options might change when other kernels besides Bartlett are available.

    '''

    if x.ndim == 1:
        x = x[:,None]
    n_periods = x.shape[0]
    if nlags is None:
        nlags = int(np.floor(4 * (n_periods / 100.)**(2./9.)))

    weights = weights_func(nlags)

    S = weights[0] * np.dot(x.T, x)  #weights[0] just for completeness, is 1

    for lag in range(1, nlags+1):
        s = np.dot(x[lag:].T, x[:-lag])
        S += weights[lag] * (s + s.T)

    return S

def S_white_simple(x):
    '''inner covariance matrix for White heteroscedastistity sandwich

    Parameters
    ----------
    x : ndarray (nobs,) or (nobs, k_var)
        data, for HAC this is array of x_i * u_i

    Returns
    -------
    S : ndarray, (k_vars, k_vars)
        inner covariance matrix for sandwich

    Notes
    -----
    this is just dot(X.T, X)

    '''
    if x.ndim == 1:
        x = x[:,None]

    return np.dot(x.T, x)

def group_sums(x, group):
    '''sum x for each group, simple bincount version, again

    group : array, integer
        assumed to be consecutive integers

    no dtype checking because I want to raise in that case

    uses loop over columns of x

    #TODO: remove this, already copied to tools/grouputils
    '''

    #TODO: transpose return in group_sum, need test coverage first

    # re-label groups or bincount takes too much memory
    if np.max(group) > 2 * x.shape[0]:
        group = pd.factorize(group)[0]

    return np.array([np.bincount(group, weights=x[:, col])
                            for col in range(x.shape[1])])

def S_hac_groupsum(x, time, nlags=None, weights_func=weights_bartlett):
    '''inner covariance matrix for HAC over group sums sandwich

    This assumes we have complete equal spaced time periods.
    The number of time periods per group need not be the same, but we need
    at least one observation for each time period

    For a single categorical group only, or a everything else but time
    dimension. This first aggregates x over groups for each time period, then
    applies HAC on the sum per period.

    Parameters
    ----------
    x : ndarray (nobs,) or (nobs, k_var)
        data, for HAC this is array of x_i * u_i
    time : ndarray, (nobs,)
        timeindes, assumed to be integers range(n_periods)
    nlags : int or None
        highest lag to include in kernel window. If None, then
        nlags = floor[4(T/100)^(2/9)] is used.
    weights_func : callable
        weights_func is called with nlags as argument to get the kernel
        weights. default are Bartlett weights

    Returns
    -------
    S : ndarray, (k_vars, k_vars)
        inner covariance matrix for sandwich

    References
    ----------
    Daniel Hoechle, xtscc paper
    Driscoll and Kraay

    '''
    #needs groupsums

    x_group_sums = group_sums(x, time).T #TODO: transpose return in grou_sum

    return S_hac_simple(x_group_sums, nlags=nlags, weights_func=weights_func)

def S_crosssection(x, group):
    '''inner covariance matrix for White on group sums sandwich

    I guess for a single categorical group only,
    categorical group, can also be the product/intersection of groups

    This is used by cov_cluster and indirectly verified

    '''
    x_group_sums = group_sums(x, group).T  #TODO: why transposed

    return S_white_simple(x_group_sums)

def cov_crosssection_0(results, group):
    '''this one is still wrong, use cov_cluster instead'''

    #TODO: currently used version of groupsums requires 2d resid
    scale = S_crosssection(results.resid[:,None], group)
    scale = np.squeeze(scale)
    cov = _HCCM1(results, scale)
    return cov

def cov_cluster(results, group, use_correction=True):
    '''cluster robust covariance matrix

    Calculates sandwich covariance matrix for a single cluster, i.e. grouped
    variables.

    Parameters
    ----------
    results : result instance
       result of a regression, uses results.model.exog and results.resid
       TODO: this should use wexog instead
    use_correction : bool
       If true (default), then the small sample correction factor is used.

    Returns
    -------
    cov : ndarray, (k_vars, k_vars)
        cluster robust covariance matrix for parameter estimates

    Notes
    -----
    same result as Stata in UCLA example and same as Peterson

    '''
    #TODO: currently used version of groupsums requires 2d resid
    xu, hessian_inv = _get_sandwich_arrays(results)

    if not hasattr(group, 'dtype') or group.dtype != np.dtype('int'):
        clusters, group = np.unique(group, return_inverse=True)
    else:
        clusters = np.unique(group)

    scale = S_crosssection(xu, group)

    nobs, k_params = xu.shape
    n_groups = len(clusters) #replace with stored group attributes if available

    cov_c = _HCCM2(hessian_inv, scale)

    if use_correction:
        cov_c *= (n_groups / (n_groups - 1.) *
                  ((nobs-1.) / float(nobs - k_params)))

    return cov_c

def cov_cluster_2groups(results, group, group2=None, use_correction=True):
    '''cluster robust covariance matrix for two groups/clusters

    Parameters
    ----------
    results : result instance
       result of a regression, uses results.model.exog and results.resid
       TODO: this should use wexog instead
    use_correction : bool
       If true (default), then the small sample correction factor is used.

    Returns
    -------
    cov_both : ndarray, (k_vars, k_vars)
        cluster robust covariance matrix for parameter estimates, for both
        clusters
    cov_0 : ndarray, (k_vars, k_vars)
        cluster robust covariance matrix for parameter estimates for first
        cluster
    cov_1 : ndarray, (k_vars, k_vars)
        cluster robust covariance matrix for parameter estimates for second
        cluster

    Notes
    -----

    verified against Peterson's table, (4 decimal print precision)
    '''

    if group2 is None:
        if group.ndim !=2 or group.shape[1] != 2:
            raise ValueError('if group2 is not given, then groups needs to be ' +
                             'an array with two columns')
        group0 = group[:, 0]
        group1 = group[:, 1]
    else:
        group0 = group
        group1 = group2
        group = (group0, group1)

    cov0 = cov_cluster(results, group0, use_correction=use_correction)
    #[0] because we get still also returns bse
    cov1 = cov_cluster(results, group1, use_correction=use_correction)

    group_intersection = Group(group)
    #cov of cluster formed by intersection of two groups
    cov01 = cov_cluster(results,
                        group_intersection.group_int,
                        use_correction=use_correction)

    #robust cov matrix for union of groups
    cov_both = cov0 + cov1 - cov01

    #return all three (for now?)
    return cov_both, cov0, cov1

def cov_white_simple(results, use_correction=True):
    '''
    heteroscedasticity robust covariance matrix (White)

    Parameters
    ----------
    results : result instance
       result of a regression, uses results.model.exog and results.resid
       TODO: this should use wexog instead

    Returns
    -------
    cov : ndarray, (k_vars, k_vars)
        heteroscedasticity robust covariance matrix for parameter estimates

    Notes
    -----
    This produces the same result as cov_hc0, and does not include any small
    sample correction.

    verified (against LinearRegressionResults and Peterson)

    See Also
    --------
    cov_hc1, cov_hc2, cov_hc3 : heteroscedasticity robust covariance matrices
        with small sample corrections

    '''
    xu, hessian_inv = _get_sandwich_arrays(results)
    sigma = S_white_simple(xu)

    cov_w = _HCCM2(hessian_inv, sigma)  #add bread to sandwich

    if use_correction:
        nobs, k_params = xu.shape
        cov_w *= nobs / float(nobs - k_params)

    return cov_w

def cov_hac_simple(results, nlags=None, weights_func=weights_bartlett,
                   use_correction=True):
    '''
    heteroscedasticity and autocorrelation robust covariance matrix (Newey-West)

    Assumes we have a single time series with zero axis consecutive, equal
    spaced time periods

    Parameters
    ----------
    results : result instance
       result of a regression, uses results.model.exog and results.resid
       TODO: this should use wexog instead
    nlags : int or None
        highest lag to include in kernel window. If None, then
        nlags = floor[4(T/100)^(2/9)] is used.
    weights_func : callable
        weights_func is called with nlags as argument to get the kernel
        weights. default are Bartlett weights

    Returns
    -------
    cov : ndarray, (k_vars, k_vars)
        HAC robust covariance matrix for parameter estimates

    Notes
    -----
    verified only for nlags=0, which is just White
    just guessing on correction factor, need reference

    options might change when other kernels besides Bartlett are available.

    '''
    xu, hessian_inv = _get_sandwich_arrays(results)
    sigma = S_hac_simple(xu, nlags=nlags, weights_func=weights_func)

    cov_hac = _HCCM2(hessian_inv, sigma)

    if use_correction:
        nobs, k_params = xu.shape
        cov_hac *= nobs / float(nobs - k_params)

    return cov_hac

cov_hac = cov_hac_simple   #alias for users

#---------------------- use time lags corrected for groups
#the following were copied from a different experimental script,
#groupidx is tuple, observations assumed to be stacked by group member and
#sorted by time, equal number of periods is not required, but equal spacing is.
#I think this is pure within group HAC: apply HAC to each group member
#separately

def lagged_groups(x, lag, groupidx):
    '''
    assumes sorted by time, groupidx is tuple of start and end values
    not optimized, just to get a working version, loop over groups
    '''
    out0 = []
    out_lagged = []
    for l,u in groupidx:
        if l+lag < u: #group is longer than lag
            out0.append(x[l+lag:u])
            out_lagged.append(x[l:u-lag])

    if out0 == []:
        raise ValueError('all groups are empty taking lags')
    #return out0, out_lagged
    return np.vstack(out0), np.vstack(out_lagged)

def S_nw_panel(xw, weights, groupidx):
    '''inner covariance matrix for HAC for panel data

    no denominator nobs used

    no reference for this, just accounting for time indices
    '''
    nlags = len(weights)-1

    S = weights[0] * np.dot(xw.T, xw)  #weights just for completeness
    for lag in range(1, nlags+1):
        xw0, xwlag = lagged_groups(xw, lag, groupidx)
        s = np.dot(xw0.T, xwlag)
        S += weights[lag] * (s + s.T)
    return S

def cov_nw_panel(results, nlags, groupidx, weights_func=weights_bartlett,
                 use_correction='hac'):
    '''Panel HAC robust covariance matrix

    Assumes we have a panel of time series with consecutive, equal spaced time
    periods. Data is assumed to be in long format with time series of each
    individual stacked into one array. Panel can be unbalanced.

    Parameters
    ----------
    results : result instance
       result of a regression, uses results.model.exog and results.resid
       TODO: this should use wexog instead
    nlags : int or None
        Highest lag to include in kernel window. Currently, no default
        because the optimal length will depend on the number of observations
        per cross-sectional unit.
    groupidx : list of tuple
        each tuple should contain the start and end index for an individual.
        (groupidx might change in future).
    weights_func : callable
        weights_func is called with nlags as argument to get the kernel
        weights. default are Bartlett weights
    use_correction : 'cluster' or 'hac' or False
        If False, then no small sample correction is used.
        If 'cluster' (default), then the same correction as in cov_cluster is
        used.
        If 'hac', then the same correction as in single time series, cov_hac
        is used.

    Returns
    -------
    cov : ndarray, (k_vars, k_vars)
        HAC robust covariance matrix for parameter estimates

    Notes
    -----
    For nlags=0, this is just White covariance, cov_white.
    If kernel is uniform, `weights_uniform`, with nlags equal to the number
    of observations per unit in a balance panel, then cov_cluster and
    cov_hac_panel are identical.

    Tested against STATA `newey` command with same defaults.

    Options might change when other kernels besides Bartlett and uniform are
    available.

    '''
    if nlags == 0: #so we can reproduce HC0 White
        weights = [1, 0]  #to avoid the scalar check in hac_nw
    else:
        weights = weights_func(nlags)

    xu, hessian_inv = _get_sandwich_arrays(results)

    S_hac = S_nw_panel(xu, weights, groupidx)
    cov_hac = _HCCM2(hessian_inv, S_hac)
    if use_correction:
        nobs, k_params = xu.shape
        if use_correction == 'hac':
            cov_hac *= nobs / float(nobs - k_params)
        elif use_correction in ['c', 'clu', 'cluster']:
            n_groups = len(groupidx)
            cov_hac *= n_groups / (n_groups - 1.)
            cov_hac *= ((nobs-1.) / float(nobs - k_params))

    return cov_hac

def cov_nw_groupsum(results, nlags, time, weights_func=weights_bartlett,
                 use_correction=0):
    '''Driscoll and Kraay Panel robust covariance matrix

    Robust covariance matrix for panel data of Driscoll and Kraay.

    Assumes we have a panel of time series where the time index is available.
    The time index is assumed to represent equal spaced periods. At least one
    observation per period is required.

    Parameters
    ----------
    results : result instance
       result of a regression, uses results.model.exog and results.resid
       TODO: this should use wexog instead
    nlags : int or None
        Highest lag to include in kernel window. Currently, no default
        because the optimal length will depend on the number of observations
        per cross-sectional unit.
    time : ndarray of int
        this should contain the coding for the time period of each observation.
        time periods should be integers in range(maxT) where maxT is obs of i
    weights_func : callable
        weights_func is called with nlags as argument to get the kernel
        weights. default are Bartlett weights
    use_correction : 'cluster' or 'hac' or False
        If False, then no small sample correction is used.
        If 'hac' (default), then the same correction as in single time series, cov_hac
        is used.
        If 'cluster', then the same correction as in cov_cluster is
        used.

    Returns
    -------
    cov : ndarray, (k_vars, k_vars)
        HAC robust covariance matrix for parameter estimates

    Notes
    -----
    Tested against STATA xtscc package, which uses no small sample correction

    This first averages relevant variables for each time period over all
    individuals/groups, and then applies the same kernel weighted averaging
    over time as in HAC.

    Warning:
    In the example with a short panel (few time periods and many individuals)
    with mainly across individual variation this estimator did not produce
    reasonable results.

    Options might change when other kernels besides Bartlett and uniform are
    available.

    References
    ----------
    Daniel Hoechle, xtscc paper
    Driscoll and Kraay

    '''

    xu, hessian_inv = _get_sandwich_arrays(results)

    #S_hac = S_nw_panel(xw, weights, groupidx)
    S_hac = S_hac_groupsum(xu, time, nlags=nlags, weights_func=weights_func)
    cov_hac = _HCCM2(hessian_inv, S_hac)
    if use_correction:
        nobs, k_params = xu.shape
        if use_correction == 'hac':
            cov_hac *= nobs / float(nobs - k_params)
        elif use_correction in ['c', 'cluster']:
            n_groups = len(np.unique(time))
            cov_hac *= n_groups / (n_groups - 1.)
            cov_hac *= ((nobs-1.) / float(nobs - k_params))

    return cov_hac


text:
@implementation UAFilterableResultsController (UICollectionViewDataSource)

#pragma mark - UITableViewDataSource Methods

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    // The table is never loaded until we have data
    if (self.UAData == nil)
        return 0;

    // we have data!
    self.tableViewHasLoaded = YES;

    NSArray *data = self.filteredData ?: self.UAData;

    // let the delegate know if we're about to display no rows
    if (data.count == 0)
    {
        id<UAFilterableResultsControllerDelegate> delegate = self.delegate;
        if (delegate != nil && [delegate respondsToSelector:@selector(filterableResultsController:hasNoDataForLoadingCollectionView:)]) {
            [delegate filterableResultsController:self hasNoDataForLoadingCollectionView:collectionView];
        }
    }

    return [self isArrayTwoDimensional:data] ? (NSInteger)data.count : 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSArray *data = self.filteredData ?: self.UAData;
    if ([self isArrayTwoDimensional:data]) {
        NSArray * rows = data[section];
        return (NSInteger)rows.count;
    } else {
        return (NSInteger)data.count;
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    id<UAFilterableResultsControllerDelegate> delegate = self.delegate;
    NSAssert(delegate != nil, @"Filterable Results Controller delegate cannot be nil.");
    NSAssert([delegate respondsToSelector:@selector(filterableResultsController:viewForSupplementaryElementOfKind:atIndexPath:)],
             @"Your delegate must implement -filterableResultsController:viewForSupplementaryElementOfKind:atIndexPath: if you have a header, footer or other supplementary view with a size greater than CGSizeZero.");
    return [delegate filterableResultsController:self viewForSupplementaryElementOfKind:kind atIndexPath:indexPath];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    id<UAFilterableResultsControllerDelegate> delegate = self.delegate;
    NSAssert(delegate != nil, @"Filterable Results Controller delegate cannot be nil.");

    // we need to find the object in the correct 2D Array
    NSArray *data = self.filteredData ?: self.UAData;
    id object = nil;
    if ([self isArrayTwoDimensional:data])
    {
        NSArray *section = data[indexPath.section];
        object = section[indexPath.row];

        // 1D Array
    } else {
        object = data[indexPath.row];
    }

    return [delegate filterableResultsController:self cellForItemWithObject:object atIndexPath:indexPath];
}
@end

redpajama_set_name: RedPajamaGithub


text:
/***************************** Include Files *******************************/
#include "AXI_DPTI.h"
#include "xparameters.h"
#include "stdio.h"
#include "xil_io.h"

/************************** Constant Definitions ***************************/
#define READ_WRITE_MUL_FACTOR 0x10

/************************** Function Definitions ***************************/
/**
 *
 * Run a self-test on the driver/device. Note this may be a destructive test if
 * resets of the device are performed.
 *
 * If the hardware system is not built correctly, this function may never
 * return to the caller.
 *
 * @param   baseaddr_p is the base address of the AXI_DPTIinstance to be worked on.
 *
 * @return
 *
 *    - XST_SUCCESS   if all self-test code passed
 *    - XST_FAILURE   if any self-test code failed
 *
 * @note    Caching must be turned off for this function to work.
 * @note    Self test may fail if data memory and device are not on the same bus.
 *
 */
XStatus AXI_DPTI_Reg_SelfTest(u32 baseaddr)
{
	u32 StsReg, flag_0, flag_16;
	int write_loop_index;
	int read_loop_index;
	int Index;

	xil_printf("******************************\n\r");
	xil_printf("* User Peripheral Self Test\n\r");
	xil_printf("******************************\n\n\r");

	/*
	 * Write to user logic slave module register(s) and read back
	 */
	xil_printf("User logic slave module test...\n\r");

	StsReg = Xil_In32 (baseaddr + STATUS_REG_OFFSET);
	flag_0 = (StsReg & 0x01);
	flag_16 = (StsReg >> 0x10 ) & 0x01;

	if(flag_0 == 0 || flag_16 == 0)
	{
		xil_printf ("Error reading register value at address %x\n", (int)baseaddr + STATUS_REG_OFFSET);
	    return XST_FAILURE;
	}

	xil_printf("   - slave register write/read passed\n\n\r");

	return XST_SUCCESS;
}


text:
<?php

namespace ApiGen\Parser\Reflection\Extractors;

use ApiGen\Contracts\Parser\Reflection\ClassReflectionInterface;
use ApiGen\Contracts\Parser\Reflection\Extractors\AnnotationMethodExtractorInterface;
use ApiGen\Parser\Reflection\ReflectionClass;
use ApiGen\Parser\Reflection\ReflectionMethodMagic;
use ApiGen\Parser\Reflection\TokenReflection\ReflectionFactory;

class AnnotationMethodExtractor implements AnnotationMethodExtractorInterface
{

    const PATTERN_METHOD
        = '~^(?:(static)\\s+)?(?:([\\w\\\\]+(?:\\|[\\w\\\\]+)*)\\s+)?(&)?\\s*(\\w+)\\s*\\(\\s*(.*)\\s*\\)\\s*(.*|$)~s';
    const PATTERN_PARAMETER = '~^(?:([\\w\\\\]+(?:\\|[\\w\\\\]+)*)\\s+)?(&)?\\s*\\$(\\w+)(?:\\s*=\\s*(.*))?($)~s';

    /**
     * @var ReflectionFactory
     */
    private $reflectionFactory;

    /**
     * @var ReflectionClass
     */
    private $reflectionClass;

    public function __construct(ReflectionFactory $reflectionFactory)
    {
        $this->reflectionFactory = $reflectionFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function extractFromReflection(ClassReflectionInterface $reflectionClass)
    {
        $this->reflectionClass = $reflectionClass;

        $methods = [];
        if ($reflectionClass->hasAnnotation('method')) {
            foreach ($reflectionClass->getAnnotation('method') as $annotation) {
                $methods += $this->processMagicMethodAnnotation($annotation);
            };
        }

        return $methods;
    }

    /**
     * @param string $annotation
     * @return ReflectionMethodMagic[]|array
     */
    private function processMagicMethodAnnotation($annotation)
    {
        if (! preg_match(self::PATTERN_METHOD, $annotation, $matches)) {
            return [];
        }

        list(, $static, $returnTypeHint, $returnsReference, $name, $args, $shortDescription) = $matches;

        $startLine = $this->getStartLine($annotation);
        $endLine = $startLine + substr_count($annotation, "\n");

        $methods = [];
        $methods[$name] = $method = $this->reflectionFactory->createMethodMagic([
            'name' => $name,
            'shortDescription' => str_replace("\n", ' ', $shortDescription),
            'startLine' => $startLine,
            'endLine' => $endLine,
            'returnsReference' => ($returnsReference === '&'),
            'declaringClass' => $this->reflectionClass,
            'annotations' => ['return' => [0 => $returnTypeHint]],
            'static' => ($static === 'static')
        ]);
        $this->attachMethodParameters($method, $args);
        return $methods;
    }

    /**
     * @param string $annotation
     * @return int
     */
    private function getStartLine($annotation)
    {
        $doc = $this->reflectionClass->getDocComment();
        $tmp = $annotation;
        if ($delimiter = strpos($annotation, "\n")) {
            $tmp = substr($annotation, 0, $delimiter);
        }
        return $this->reflectionClass->getStartLine() + substr_count(substr($doc, 0, strpos($doc, $tmp)), "\n");
    }

    /**
     * @param ReflectionMethodMagic $method
     * @param string $args
     */
    private function attachMethodParameters(ReflectionMethodMagic $method, $args)
    {
        $parameters = [];
        foreach (array_filter(preg_split('~\\s*,\\s*~', $args)) as $position => $arg) {
            if (! preg_match(self::PATTERN_PARAMETER, $arg, $matches)) {
                // Wrong annotation format
                continue;
            }

            list(, $typeHint, $passedByReference, $name, $defaultValueDefinition) = $matches;

            $parameters[$name] = $this->reflectionFactory->createParameterMagic([
                'name' => $name,
                'position' => $position,
                'typeHint' => $typeHint,
                'defaultValueDefinition' => $defaultValueDefinition,
                'unlimited' => false,
                'passedByReference' => ($passedByReference === '&'),
                'declaringFunction' => $method
            ]);
            $method->addAnnotation('param', ltrim(sprintf('%s $%s', $typeHint, $name)));
        }
        $method->setParameters($parameters);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>Import Addressbook Help Guide</title>
<META http-equiv=Content-Type content="text/html; charset=utf-8">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<LINK href="javascript/stylehelp.css" rel=stylesheet type=text/css>
Import Addressbook Help Guide [ Language/help/file.html">Индекс справки ]

Information found here will assist you in importing an existing address book into your WebMail account.

Selecting Import options

Selecting corresponding fields

 Selecting Import options

  To import an address book you will need the date to be in CSV file format. CSV stands for Comma Separated Values, and would look similar to:

First Name,Last Name,Name,E-mail Address,Home Street,Home City,....

If your importing your address book from another email client such as Outlook, you can export your address data to CSV within this program.

For example if you would like to import an address book from Outlook Express, you would take the following steps.

1: In Outlook, visit File --> Export --> Address Book.

2: You will then have the option to select what sort of format you would like the export to convert to.

Select "Text File (Comma Separated Values)"

3: You will then have the option to store the CSV file somewhere on your computer. Select the browser button to find a suitable place and name the file.

4: You can now select which data from your address book you would like to import into your WebMail. Click "Finish" when your done.

5: Your address book CSV should now be successfully completed. Now return to the WebMail interface.

Visit the Address Book function and select the below button "Import". Fill in the necessary information.

First row contains CSV column description: Most CSV files, including files created via Outlook, contain the column descriptions. If your not sure, you can check if your CSV contains the headings by opening the file in Notepad.

Click on the "browse" button from the Address Import book and select the CSV file you created. Then click "Import File" and your almost there!

 Selecting corresponding fields [top]

 Here you can select which fields from your CSV match with the WebMail address book fields.

WebMail will try to find the best match, however if its not correct you can change it via each fields drop down menu.

If there is a field with "Select" it means that WebMail was unable to find data for this field. This may be because it was not included in your CSV. It won't affect the export or cause any problems, as long as the EMail address field is correctly linked up.

Once your done, click "Export".

If successful you will be notified of the number of new contacts, then be directed to your newly updated Address book.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Globalization;
using System.Data;
using System.Data.OleDb;
using System.Threading;

using HSoft.SQL;
using HSoft.ClientManager.Web;

using SisoDb.Sql2012;
using SisoDb.Configurations;

using CTCT;
using CTCT.Components;
using CTCT.Components.Contacts;
using CTCT.Components.AccountService;
using CTCT.Components.EmailCampaigns;
using CTCT.Exceptions;

using Obout.Interface;

public partial class CC_EmailLists : System.Web.UI.Page
{

    private static String ssql = String.Empty;

    public ConstantContact _constantContact = null;
    private string _apiKey = string.Empty;
    private string _accessToken = string.Empty;

    SortedList<int, ContactList> CCNoLead = new SortedList<int, ContactList>();
    SortedList<int, ContactList> CCUnSubscribed = new SortedList<int, ContactList>();

    string sCCNoLead = "";
    string sCCUnSubscribed = "";

    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (Session["wx"] == null) { Session["wx"] = Request.QueryString["wx"]; }
        if (Session["wy"] == null) { Session["wy"] = Request.QueryString["wy"]; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

            Tools.devlogincheat();
            HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
            if (Session["ghirarchy"] == null) { Session["ghirarchy"] = String.Format("{0},", Session["guser"]); }

            _apiKey = ConfigurationManager.AppSettings["APIKey"];
            _accessToken = ConfigurationManager.AppSettings["AccessToken"];
            if (_accessToken.Length != new Guid().ToString().Length)
            {
                byte[] decryptedB = Convert.FromBase64String(ConfigurationManager.AppSettings["AccessToken"]);
                _accessToken = System.Text.Encoding.UTF8.GetString(decryptedB).Replace("\0", "");
            }
            _constantContact = new ConstantContact(_apiKey, _accessToken);

            IList<ContactList> _rscl = _constantContact.GetLists(null);

            foreach (ContactList _cl in _rscl)
            {
                if (_cl.Name.StartsWith("No Lead Group") == true)
                {
                    CCNoLead.Add(int.Parse(_cl.Name.Split(' ')[3]), _cl);
                    sCCNoLead = String.Format("{0}'{1}',", sCCNoLead, _cl.Id);
                }
                if (_cl.Name.StartsWith("Unsubscribed Group") == true)
                {
                    CCUnSubscribed.Add(int.Parse(_cl.Name.Split(' ')[2]), _cl);
                    sCCUnSubscribed = String.Format("{0}'{1}',", CCUnSubscribed, _cl.Id);
                }
            }
            sCCNoLead = String.Format("{0}'{1}'", sCCNoLead, "XXX");
            sCCUnSubscribed = String.Format("{0}'{1}'", CCUnSubscribed, "XXX");

            foreach (KeyValuePair<int, ContactList> kvList in CCNoLead)
            {
                HtmlTableRow _row = new HtmlTableRow();
                HtmlTableCell _cell1 = new HtmlTableCell();
                HtmlTableCell _cell2 = new HtmlTableCell();

                _cell1.Controls.Add(new LiteralControl(kvList.Value.Name));
                _cell2.Controls.Add(new LiteralControl(kvList.Value.ContactCount.ToString()));

                _row.Cells.Add(_cell1);
                _row.Cells.Add(_cell2);

                list.Rows.Add(_row);

            }

            foreach (KeyValuePair<int, ContactList> kvList in CCUnSubscribed)
            {
                HtmlTableRow _row = new HtmlTableRow();
                HtmlTableCell _cell1 = new HtmlTableCell();
                HtmlTableCell _cell2 = new HtmlTableCell();

                _cell1.Controls.Add(new LiteralControl(kvList.Value.Name));
                _cell2.Controls.Add(new LiteralControl(kvList.Value.ContactCount.ToString()));

                _row.Cells.Add(_cell1);
                _row.Cells.Add(_cell2);

                list.Rows.Add(_row);

            }

            _sql.Close();

    }

    protected void CreateList_Lead_500()
    {
        ConstantContact _constantContact = null;
        string _apiKey = string.Empty;
        string _accessToken = string.Empty;

        _apiKey = ConfigurationManager.AppSettings["APIKey"];
        _accessToken = ConfigurationManager.AppSettings["AccessToken"];
        if (_accessToken.Length != new Guid().ToString().Length)
        {
            byte[] decryptedB = Convert.FromBase64String(ConfigurationManager.AppSettings["AccessToken"]);
            _accessToken = System.Text.Encoding.UTF8.GetString(decryptedB).Replace("\0", "");
        }
        _constantContact = new ConstantContact(_apiKey, _accessToken);
        SisoDb.ISisoDatabase _siso = ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString.CreateSql2012Db();

        HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString);
        foreach (KeyValuePair<int, ContactList> kvList in CCNoLead)
        {
            if (kvList.Value.ContactCount<500)
            {

                ssql = String.Format("SELECT a.StructureId , a.Value Date,b.Value eMail, c.Value Id, e.Value Status " +
                                     "  FROM [dbo].[ContactStrings] a " +
                                     "   LEFT JOIN [dbo].[ContactStrings] b ON a.StructureId =b.StructureId AND b.MemberPath = 'EmailAddresses.EmailAddr' " +
                                     "   LEFT JOIN [dbo].[ContactStrings] c ON a.StructureId =c.StructureId AND c.MemberPath = 'Id' " +
                                     "   LEFT JOIN [dbo].[ContactStrings] e ON a.StructureId =e.StructureId AND e.MemberPath = 'Status' " +
                                     "   LEFT OUTER JOIN Lead_Flat lf ON lf.ConstantContactID =  c.Value " +
                                     " WHERE a.MemberPath = 'DateCreated' " +
                                     "   AND COALESCE(lf.Priority,'CCOnly') NOT IN ('Not Right','Sold','Spam','Black List','Discarded') " +
                                     "   AND 0 = (SELECT COUNT(*) FROM  [dbo].[ContactStrings] x WHERE a.StructureId = x.StructureId AND x.MemberPath = 'Lists.Id' AND x.Value IN ({0})) " +
                                     "   AND e.Value = 'ACTIVE' " +
                                     "   AND 0 = (SELECT COUNT(*) FROM Lead_Flat WHERE c.Value = ConstantContactID) " +
                                     " ORDER BY a.Value DESC ", sCCNoLead);
                DataTable _Leads = _sql.GetTable(ssql);
                int icount = kvList.Value.ContactCount;
                foreach (DataRow dr in _Leads.Rows)
                {
                    Thread.Sleep(250);
                    CTCT.Components.Contacts.Contact _ct = null;
                    try
                    {
                        _ct = _constantContact.GetContact(dr["Id"].ToString());
                    }
                    catch (Exception ex)
                    {
                        ssql = String.Format("INSERT INTO _auditt([Table], [Field], [Key], OldValue, NewValue, createdby) " +
                                             "VALUES ('{0}','{1}','{4}','{2}','{3}','{4}') ", "No Lead Group", "READ", dr["Id"].ToString(), ex.Message.Replace("'", "''"), Guid.Parse("D0F06FCC-B87E-4F33-A3D3-D64354863F39"));
                        _sql.Execute(ssql);
                        continue;
                    }
                    if (_ct.EmailAddresses.Count == 0) { continue; }
                    _ct.Lists.Add(kvList.Value);
                    try
                    {
                        _ct = _constantContact.UpdateContact(_ct, false);
                        icount++;
                    }
                    catch (Exception ex)
                    {
                        ssql = String.Format("INSERT INTO _auditt([Table], [Field], [Key], OldValue, NewValue, createdby) " +
                                             "VALUES ('{0}','{1}','{4}','{2}','{3}','{4}') ", "No Lead Group", "ADD", _ct.ToJSON().Replace("'", "''"), ex.Message.Replace("'", "''"), Guid.Parse("D0F06FCC-B87E-4F33-A3D3-D64354863F39"));
                        _sql.Execute(ssql);
                        continue;
                    }
                    using (var session = _siso.BeginSession())
                    {
                        session.DeleteById<CTCT.Components.Contacts.Contact>(_ct.Id);
                        session.Insert(_ct);
                    }
                    if (icount >= 500) { break; }
                }
                break;
            }
        }
        _sql.Close();

    }

    protected void Btn_Command(object sender, CommandEventArgs e)
    {
        CC_Command(e.CommandName);
    }

    protected void CC_Command(string scmd)
    {
        switch (scmd)
        {
            case "CC_Lead_500":
                {
                    CreateList_Lead_500();
                }
                break;
            case "CC_Unsubscribed_500":
                {
                }
                break;
        }
        Response.Redirect("/Pages/CC_EmailLists.aspx");
    }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.management.SubResource;
import com.azure.resourcemanager.network.models.IpAllocationMethod;
import com.azure.resourcemanager.network.models.ProvisioningState;
import com.fasterxml.jackson.annotation.JsonProperty;

/** IpConfigurations. */
@Fluent
public final class HubIpConfigurationInner extends SubResource {
    /*
     * The properties of the Virtual Hub IPConfigurations.
     */
    @JsonProperty(value = "properties")
    private HubIpConfigurationPropertiesFormatInner innerProperties;

    /*
     * Name of the Ip Configuration.
     */
    @JsonProperty(value = "name")
    private String name;

    /*
     * A unique read-only string that changes whenever the resource is updated.
     */
    @JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY)
    private String etag;

    /*
     * Ipconfiguration type.
     */
    @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY)
    private String type;

    /** Creates an instance of HubIpConfigurationInner class. */
    public HubIpConfigurationInner() {
    }

    /**
     * Get the innerProperties property: The properties of the Virtual Hub IPConfigurations.
     *
     * @return the innerProperties value.
     */
    private HubIpConfigurationPropertiesFormatInner innerProperties() {
        return this.innerProperties;
    }

    /**
     * Get the name property: Name of the Ip Configuration.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: Name of the Ip Configuration.
     *
     * @param name the name value to set.
     * @return the HubIpConfigurationInner object itself.
     */
    public HubIpConfigurationInner withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the etag property: A unique read-only string that changes whenever the resource is updated.
     *
     * @return the etag value.
     */
    public String etag() {
        return this.etag;
    }

    /**
     * Get the type property: Ipconfiguration type.
     *
     * @return the type value.
     */
    public String type() {
        return this.type;
    }

    /** {@inheritDoc} */
    @Override
    public HubIpConfigurationInner withId(String id) {
        super.withId(id);
        return this;
    }

    /**
     * Get the privateIpAddress property: The private IP address of the IP configuration.
     *
     * @return the privateIpAddress value.
     */
    public String privateIpAddress() {
        return this.innerProperties() == null ? null : this.innerProperties().privateIpAddress();
    }

    /**
     * Set the privateIpAddress property: The private IP address of the IP configuration.
     *
     * @param privateIpAddress the privateIpAddress value to set.
     * @return the HubIpConfigurationInner object itself.
     */
    public HubIpConfigurationInner withPrivateIpAddress(String privateIpAddress) {
        if (this.innerProperties() == null) {
            this.innerProperties = new HubIpConfigurationPropertiesFormatInner();
        }
        this.innerProperties().withPrivateIpAddress(privateIpAddress);
        return this;
    }

    /**
     * Get the privateIpAllocationMethod property: The private IP address allocation method.
     *
     * @return the privateIpAllocationMethod value.
     */
    public IpAllocationMethod privateIpAllocationMethod() {
        return this.innerProperties() == null ? null : this.innerProperties().privateIpAllocationMethod();
    }

    /**
     * Set the privateIpAllocationMethod property: The private IP address allocation method.
     *
     * @param privateIpAllocationMethod the privateIpAllocationMethod value to set.
     * @return the HubIpConfigurationInner object itself.
     */
    public HubIpConfigurationInner withPrivateIpAllocationMethod(IpAllocationMethod privateIpAllocationMethod) {
        if (this.innerProperties() == null) {
            this.innerProperties = new HubIpConfigurationPropertiesFormatInner();
        }
        this.innerProperties().withPrivateIpAllocationMethod(privateIpAllocationMethod);
        return this;
    }

    /**
     * Get the subnet property: The reference to the subnet resource.
     *
     * @return the subnet value.
     */
    public SubnetInner subnet() {
        return this.innerProperties() == null ? null : this.innerProperties().subnet();
    }

    /**
     * Set the subnet property: The reference to the subnet resource.
     *
     * @param subnet the subnet value to set.
     * @return the HubIpConfigurationInner object itself.
     */
    public HubIpConfigurationInner withSubnet(SubnetInner subnet) {
        if (this.innerProperties() == null) {
            this.innerProperties = new HubIpConfigurationPropertiesFormatInner();
        }
        this.innerProperties().withSubnet(subnet);
        return this;
    }

    /**
     * Get the publicIpAddress property: The reference to the public IP resource.
     *
     * @return the publicIpAddress value.
     */
    public PublicIpAddressInner publicIpAddress() {
        return this.innerProperties() == null ? null : this.innerProperties().publicIpAddress();
    }

    /**
     * Set the publicIpAddress property: The reference to the public IP resource.
     *
     * @param publicIpAddress the publicIpAddress value to set.
     * @return the HubIpConfigurationInner object itself.
     */
    public HubIpConfigurationInner withPublicIpAddress(PublicIpAddressInner publicIpAddress) {
        if (this.innerProperties() == null) {
            this.innerProperties = new HubIpConfigurationPropertiesFormatInner();
        }
        this.innerProperties().withPublicIpAddress(publicIpAddress);
        return this;
    }

    /**
     * Get the provisioningState property: The provisioning state of the IP configuration resource.
     *
     * @return the provisioningState value.
     */
    public ProvisioningState provisioningState() {
        return this.innerProperties() == null ? null : this.innerProperties().provisioningState();
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (innerProperties() != null) {
            innerProperties().validate();
        }
    }
}


text:
module Coinsimple
  class Invoice

    def initialize opts = {}
      @options = opts
    end

    def set_name recipient
      @options[:name] = recipient
      self
    end

    def set_email email
      @options[:email] = email
      self
    end

    def set_processor processor
      @options[:processor] = processor
      self
    end

    def set_rate rate
      @options[:rate] = rate
      self
    end

    def set_currency currency
      @options[:currency] = currency
      self
    end

    def set_notes notes
      @options[:notes] = notes
      self
    end

    def set_precent precent
      @options[:precent] = precent
      self
    end
    alias_method :set_discount , :set_precent

    def set_custom custom
      @options[:custom] = custom
      self
    end

    def set_callback_url callback_url
      @options[:callback_url] = callback_url
      self
    end

    def set_redirect_url redirect_url
      @options[:redirect_url] = redirect_url
      self
    end

    def set_recurring_times recurring_times
      @options[:recurring_times] = recurring_times
      self
    end
    alias_method :set_stop_after , :set_recurring_times

    def recur_by_days num_days
      @options[:invoice_type] = 'days'
      @options[:interval] = num_days
      self
    end

    def recur_by_date day_of_month
      @options[:invoice_type] = 'date'
      @options[:interval] = day_of_month
      self
    end

    def add_item item
      @options[:items] = [] unless @options.has_key?(:items)
      @options[:items] << item
      self
    end

    def data
      @options
    end

  end
end


text:
#region Copyright and License
// Copyright 2010..2015 Alexander Reinert
//
// This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.com/)
//
// 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.
#endregion

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;

namespace MailTester.ARSoft.Tools.Net.Dns.DnsRecord
{
	/// <summary>
	///   <para>Location information</para>
	///   <para>
	///     Defined in
	///     <see cref="!:http://tools.ietf.org/html/rfc1876">RFC 1876</see>
	///   </para>
	/// </summary>
	public class LocRecord : DnsRecordBase
	{
		private static Regex _parserRegex = new Regex(@"^(?<latd>\d{1,2})( (?<latm>\d{1,2})( (?<lats>\d{1,2})(\.(?<latms>\d{1,3}))?)?)? (?<lat>(N|S)) (?<longd>\d{1,2})( (?<longm>\d{1,2})( (?<longs>\d{1,2})(\.(?<longms>\d{1,3}))?)?)? (?<long>(W|E)) (?<alt>-?\d{1,2}(\.\d+)?)m?( (?<size>\d+(\.\d+)?)m?( (?<hp>\d+(\.\d+)?)m?( (?<vp>\d+(\.\d+)?)m?)?)?)?$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled);

		/// <summary>
		///   Represents a geopgraphical degree
		/// </summary>
		public class Degree
		{
			/// <summary>
			///   Is negative value
			/// </summary>
			public bool IsNegative { get; private set; }

			/// <summary>
			///   Number of full degrees
			/// </summary>
			public int Degrees { get; private set; }

			/// <summary>
			///   Number of minutes
			/// </summary>
			public int Minutes { get; private set; }

			/// <summary>
			///   Number of seconds
			/// </summary>
			public int Seconds { get; private set; }

			/// <summary>
			///   Number of Milliseconds
			/// </summary>
			public int Milliseconds { get; private set; }

			/// <summary>
			///   Returns the decimal representation of the Degree instance
			/// </summary>
			public double DecimalDegrees
			{
				get { return (IsNegative ? -1d : 1d) * (Degrees + (double) Minutes / 6000 * 100 + (Seconds + (double) Milliseconds / 1000) / 360000 * 100); }
			}

			/// <summary>
			///   Creates a new instance of the Degree class
			/// </summary>
			/// <param name="isNegative"> Is negative value </param>
			/// <param name="degrees"> Number of full degrees </param>
			/// <param name="minutes"> Number of minutes </param>
			/// <param name="seconds"> Number of seconds </param>
			/// <param name="milliseconds"> Number of Milliseconds </param>
			public Degree(bool isNegative, int degrees, int minutes, int seconds, int milliseconds)
			{
				IsNegative = isNegative;
				Degrees = degrees;
				Minutes = minutes;
				Seconds = seconds;
				Milliseconds = milliseconds;
			}

			internal Degree(bool isNegative, string degrees, string minutes, string seconds, string milliseconds)
			{
				IsNegative = isNegative;

				Degrees = Int32.Parse(degrees);
				Minutes = Int32.Parse(minutes.PadLeft(1, '0'));
				Seconds = Int32.Parse(seconds.PadLeft(1, '0'));
				Milliseconds = Int32.Parse(milliseconds.PadRight(3, '0'));
			}

			/// <summary>
			///   Creates a new instance of the Degree class
			/// </summary>
			/// <param name="decimalDegrees"> Decimal representation of the Degree </param>
			public Degree(double decimalDegrees)
			{
				if (decimalDegrees < 0)
				{
					IsNegative = true;
					decimalDegrees = -decimalDegrees;
				}

				Degrees = (int) decimalDegrees;
				decimalDegrees -= Degrees;
				decimalDegrees *= 60;
				Minutes = (int) decimalDegrees;
				decimalDegrees -= Minutes;
				decimalDegrees *= 60;
				Seconds = (int) decimalDegrees;
				decimalDegrees -= Seconds;
				decimalDegrees *= 1000;
				Milliseconds = (int) decimalDegrees;
			}

			private string ToDegreeString()
			{
				string res = String.Empty;

				if (Milliseconds != 0)
					res = "." + Milliseconds.ToString().PadLeft(3, '0').TrimEnd('0');

				if ((res.Length > 0) || (Seconds != 0))
					res = " " + Seconds + res;

				if ((res.Length > 0) || (Minutes != 0))
					res = " " + Minutes + res;

				res = Degrees + res;

				return res;
			}

			internal string ToLatitudeString()
			{
				return ToDegreeString() + " " + (IsNegative ? "S" : "N");
			}

			internal string ToLongitudeString()
			{
				return ToDegreeString() + " " + (IsNegative ? "W" : "E");
			}
		}

		/// <summary>
		///   Version number of representation
		/// </summary>
		public byte Version { get; private set; }

		/// <summary>
		///   Size of location in centimeters
		/// </summary>
		public double Size { get; private set; }

		/// <summary>
		///   Horizontal precision in centimeters
		/// </summary>
		public double HorizontalPrecision { get; private set; }

		/// <summary>
		///   Vertical precision in centimeters
		/// </summary>
		public double VerticalPrecision { get; private set; }

		/// <summary>
		///   Latitude of the geographical position
		/// </summary>
		public Degree Latitude { get; private set; }

		/// <summary>
		///   Longitude of the geographical position
		/// </summary>
		public Degree Longitude { get; private set; }

		/// <summary>
		///   Altitude of the geographical position
		/// </summary>
		public double Altitude { get; private set; }

		internal LocRecord() {}

		/// <summary>
		///   Creates a new instance of the LocRecord class
		/// </summary>
		/// <param name="name"> Name of the record </param>
		/// <param name="timeToLive"> Seconds the record should be cached at most </param>
		/// <param name="version"> Version number of representation </param>
		/// <param name="size"> Size of location in centimeters </param>
		/// <param name="horizontalPrecision"> Horizontal precision in centimeters </param>
		/// <param name="verticalPrecision"> Vertical precision in centimeters </param>
		/// <param name="latitude"> Latitude of the geographical position </param>
		/// <param name="longitude"> Longitude of the geographical position </param>
		/// <param name="altitude"> Altitude of the geographical position </param>
		public LocRecord(string name, int timeToLive, byte version, double size, double horizontalPrecision, double verticalPrecision, Degree latitude, Degree longitude, double altitude)
			: base(name, RecordType.Loc, RecordClass.INet, timeToLive)
		{
			Version = version;
			Size = size;
			HorizontalPrecision = horizontalPrecision;
			VerticalPrecision = verticalPrecision;
			Latitude = latitude;
			Longitude = longitude;
			Altitude = altitude;
		}

		internal override void ParseRecordData(byte[] resultData, int currentPosition, int length)
		{
			Version = resultData[currentPosition++];
			Size = ConvertPrecision(resultData[currentPosition++]);
			HorizontalPrecision = ConvertPrecision(resultData[currentPosition++]);
			VerticalPrecision = ConvertPrecision(resultData[currentPosition++]);
			Latitude = ConvertDegree(DnsMessageBase.ParseInt(resultData, ref currentPosition));
			Longitude = ConvertDegree(DnsMessageBase.ParseInt(resultData, ref currentPosition));
			Altitude = ConvertAltitude(DnsMessageBase.ParseInt(resultData, ref currentPosition));
		}

		internal override void ParseRecordData(string origin, string[] stringRepresentation)
		{
			var groups = _parserRegex
				.Match(String.Join(" ", stringRepresentation))
				.Groups;

			bool latNegative = groups["lat"].Value.Equals("S", StringComparison.InvariantCultureIgnoreCase);
			Latitude = new Degree(latNegative, groups["latd"].Value, groups["latm"].Value, groups["lats"].Value, groups["latms"].Value);

			bool longNegative = groups["long"].Value.Equals("W", StringComparison.InvariantCultureIgnoreCase);
			Longitude = new Degree(longNegative, groups["longd"].Value, groups["longm"].Value, groups["longs"].Value, groups["longms"].Value);

			Altitude = Double.Parse(groups["alt"].Value, CultureInfo.InvariantCulture);
			Size = String.IsNullOrEmpty(groups["size"].Value) ? 1 : Double.Parse(groups["size"].Value, CultureInfo.InvariantCulture);
			HorizontalPrecision = String.IsNullOrEmpty(groups["hp"].Value) ? 10000 : Double.Parse(groups["hp"].Value, CultureInfo.InvariantCulture);
			VerticalPrecision = String.IsNullOrEmpty(groups["vp"].Value) ? 10 : Double.Parse(groups["vp"].Value, CultureInfo.InvariantCulture);
		}

		internal override string RecordDataToString()
		{
			return Latitude.ToLatitudeString()
			       + " "
			       + Longitude.ToLongitudeString()
			       + " " + Altitude.ToString(CultureInfo.InvariantCulture) + "m"
			       + (((Size != 1) || (HorizontalPrecision != 10000) || (VerticalPrecision != 10)) ? " " + Size + "m" : "")
			       + (((HorizontalPrecision != 10000) || (VerticalPrecision != 10)) ? " " + HorizontalPrecision + "m" : "")
			       + ((VerticalPrecision != 10) ? " " + VerticalPrecision + "m" : "");
		}

		protected internal override int MaximumRecordDataLength
		{
			get { return 16; }
		}

		protected internal override void EncodeRecordData(byte[] messageData, int offset, ref int currentPosition, Dictionary<string, ushort> domainNames)
		{
			messageData[currentPosition++] = Version;
			messageData[currentPosition++] = ConvertPrecision(Size);
			messageData[currentPosition++] = ConvertPrecision(HorizontalPrecision);
			messageData[currentPosition++] = ConvertPrecision(VerticalPrecision);
			DnsMessageBase.EncodeInt(messageData, ref currentPosition, ConvertDegree(Latitude));
			DnsMessageBase.EncodeInt(messageData, ref currentPosition, ConvertDegree(Longitude));
			DnsMessageBase.EncodeInt(messageData, ref currentPosition, ConvertAltitude(Altitude));
		}

		#region Convert Precision
		private static readonly int[] _POWER_OFTEN = new int[] { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };

		private static double ConvertPrecision(byte precision)
		{
			int mantissa = ((precision >> 4) & 0x0f) % 10;
			int exponent = (precision & 0x0f) % 10;
			return mantissa * (double) _POWER_OFTEN[exponent] / 100;
		}

		private static byte ConvertPrecision(double precision)
		{
			double centimeters = (precision * 100);

			int exponent;
			for (exponent = 0; exponent < 9; exponent++)
			{
				if (centimeters < _POWER_OFTEN[exponent + 1])
					break;
			}

			int mantissa = (int) (centimeters / _POWER_OFTEN[exponent]);
			if (mantissa > 9)
				mantissa = 9;

			return (byte) ((mantissa << 4) | exponent);
		}
		#endregion

		#region Convert Degree
		private static Degree ConvertDegree(int degrees)
		{
			degrees -= (1 << 31);

			bool isNegative;
			if (degrees < 0)
			{
				isNegative = true;
				degrees = -degrees;
			}
			else
			{
				isNegative = false;
			}

			int milliseconds = degrees % 1000;
			degrees /= 1000;
			int seconds = degrees % 60;
			degrees /= 60;
			int minutes = degrees % 60;
			degrees /= 60;

			return new Degree(isNegative, degrees, minutes, seconds, milliseconds);
		}

		private static int ConvertDegree(Degree degrees)
		{
			int res = degrees.Degrees * 3600000 + degrees.Minutes * 60000 + degrees.Seconds * 1000 + degrees.Milliseconds;

			if (degrees.IsNegative)
				res = -res;

			return res + (1 << 31);
		}
		#endregion

		#region Convert Altitude
		private const int _ALTITUDE_REFERENCE = 10000000;

		private static double ConvertAltitude(int altitude)
		{
			return ((altitude < _ALTITUDE_REFERENCE) ? ((_ALTITUDE_REFERENCE - altitude) * -1) : (altitude - _ALTITUDE_REFERENCE)) / 100d;
		}

		private static int ConvertAltitude(double altitude)
		{
			int centimeter = (int) (altitude * 100);
			return ((centimeter > 0) ? (_ALTITUDE_REFERENCE + centimeter) : (centimeter + _ALTITUDE_REFERENCE));
		}
		#endregion
	}
}


text:
<projectskin>
    <skin name="segment_skin_focus" value="segFocus"/>
    <skin name="imagegallery_skin_focus" value="galFocus"/>
    <skin name="combobox_skin_focus" value="No Skin"/>
    <skin name="segment_sec_skin_focus" value="segHeader"/>
    <skin name="himgstrip_skin_focus" value="hStripFocus"/>
    <skin name="datagrid_alternate_skin" value="dgRow"/>
    <skin name="android_form_title_skin" value="titleBar"/>
    <skin name="calendar_skin_focus" value="calFocus"/>
    <skin name="android_native_listbox_skin_focus" value="sknNativ"/>
    <skin name="textarea_skin" value="txtNormal"/>
    <skin name="textarea2_skin_focus" value="txt2Focus"/>
    <skin name="line_skin" value="lineNormal"/>
    <skin name="checkboxgroup_skin" value="sknCbxKonyThemeNormal"/>
    <skin name="textbox2_skin" value="sknTbxKonyThemeLogin"/>
    <skin name="winmob_slider_right_skin" value="sliderRight"/>
    <skin name="himgstrip_skin" value="hStripNormal"/>
    <skin name="textarea2_skin" value="txt2Normal"/>
    <skin name="winmob_slider_left_skin" value="sliderLeft"/>
    <skin name="imagegallery2_skin_focus" value="gal2Focus"/>
    <skin name="phone_skin_focus" value="phoneFocus"/>
    <skin name="popup_skin" value="sknPopupKonyThemeNormal"/>
    <skin name="textarea_skin_focus" value="txtFocus"/>
    <skin name="button_skin_focus" value="sknBtnKonyThemeFocus"/>
    <skin name="bb_slider_left_skin_key" value="sliderLeft"/>
    <skin name="textbox2_skin_focus" value="sknTbxKonyThemeLogin"/>
    <skin name="android_slider_left_skin" value="sliderLeft"/>
    <skin name="segment2_row_skin" value="seg2Normal"/>
    <skin name="android_slider_right_skin" value="sliderRight"/>
    <skin name="imagegallery_skin" value="galNormal"/>
    <skin name="android_native_listbox_skin" value="sknPlaceHolder"/>
    <skin name="segment2_secheader_skin" value="seg2Header"/>
    <skin name="form_skin" value="sknFrmKonyThemeNormal"/>
    <skin name="label_skin" value="sknLblKonyThemeNormal"/>
    <skin name="camera_skin_focus" value="camFocus"/>
    <skin name="button_skin" value="sknBtnKonyThemeNormal"/>
    <skin name="imagegallery2_skin" value="gal2Normal"/>
    <skin name="row_skin_focus" value="hbxWhite"/>
    <skin name="datagrid_row_skin_focus" value="dgFocus"/>
    <skin name="richtext_skin" value="richNormal"/>
    <skin name="datagrid_row_skin" value="dgRow"/>
    <skin name="segment_skin" value="segNormal"/>
    <skin name="row_skin" value="hbxWhite"/>
    <skin name="checkboxgroup_skin_focus" value="sknCbxKonyThemeFocus"/>
    <skin name="radiobuttongroup_skin" value="radioNormal"/>
    <skin name="tabpane_active_focus_skin" value="tabFocus"/>
    <skin name="calendar_skin" value="calNormal"/>
    <skin name="bb_form_title_skin" value="titleBar"/>
    <skin name="segment2_row_focus_skin" value="seg2Focus"/>
    <skin name="tabpane_active_skin" value="tabActive"/>
    <skin name="phone_skin" value="phoneNormal"/>
    <skin name="combobox_skin" value="cboxNormal"/>
    <skin name="himgstrip2_skin_focus" value="hStrip2Focus"/>
    <skin name="datagrid_header_skin" value="dgHead"/>
    <skin name="camera_skin" value="camNormal"/>
    <skin name="radiobuttongroup_skin_focus" value="radioFocus"/>
    <skin name="bb_slider_right_skin_key" value="sliderRight"/>
    <skin name="tabpane_inactive_skin" value="tabInactive"/>
    <skin name="listbox_skin" value="listboxNormal"/>
    <skin name="himgstrip2_skin" value="hStrip2Normal"/>
    <skin name="textfield_skin_focus" value="tbxFocus"/>
    <skin name="textfield_skin" value="tbxNormal"/>
    <skin name="listbox_skin_focus" value="listboxFocus"/>
    <skin name="android_placeholder_skin" value="sknPlaceHolderList"/>
</projectskin>


text:
<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Background</title>
  <script src="js/ijl.js" type="text/javascript"></script>

  <script src="js/config.js" type="text/javascript"></script>
  <script src="js/player.js" type="text/javascript"></script>
  <script src="js/notifier.js" type="text/javascript"></script>
  <script src="js/history.js" type="text/javascript"></script>
  <script src="js/report_fmt.js" type="text/javascript"></script>
  <script src="js/bean_fm.js" type="text/javascript"></script>

</head>
<body>
  <audio autoplay src='dummy.mp3' id="drhac-player"></audio>
  <script src="js/page_bg.js" type="text/javascript"></script>
</body>
</html>


text:
@class NSArray, NSString;

@interface ShakeTvHistoryView : MMUIView <IShakeTvHistoryMgrExt>
{
    NSArray *_arrTVItem;
    id <ShakeTvHistoryViewDelegate> delegate;
}

@property(nonatomic) __weak id <ShakeTvHistoryViewDelegate> delegate; // @synthesize delegate;
- (void).cxx_destruct;
- (void)onClcikIconBtn:(id)arg1;
- (void)layoutAllView;
- (unsigned int)getXOffset;
- (unsigned int)getBtnCnt;
- (unsigned int)getBtnWidth;
- (void)refreshData;
- (void)onShakeTvHistoryDataChange;
- (void)dealloc;
- (id)initWithFrame:(struct CGRect)arg1;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
package org.apache.coyote;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;

import org.apache.tomcat.util.net.SSLHostConfig;

/**
 * Abstract the protocol implementation, including threading, etc.
 *
 * This is the main interface to be implemented by a coyote protocol.
 * Adapter is the main interface to be implemented by a coyote servlet
 * container.
 *
 * @author Remy Maucherat
 * @author Costin Manolache
 * @see Adapter
 */
public interface ProtocolHandler {

    /**
     * Return the adapter associated with the protocol handler.
     * @return the adapter
     */
    public Adapter getAdapter();

    /**
     * The adapter, used to call the connector.
     *
     * @param adapter The adapter to associate
     */
    public void setAdapter(Adapter adapter);

    /**
     * The executor, provide access to the underlying thread pool.
     *
     * @return The executor used to process requests
     */
    public Executor getExecutor();

    /**
     * Set the optional executor that will be used by the connector.
     * @param executor the executor
     */
    public void setExecutor(Executor executor);

    /**
     * Get the utility executor that should be used by the protocol handler.
     * @return the executor
     */
    public ScheduledExecutorService getUtilityExecutor();

    /**
     * Set the utility executor that should be used by the protocol handler.
     * @param utilityExecutor the executor
     */
    public void setUtilityExecutor(ScheduledExecutorService utilityExecutor);

    /**
     * Initialise the protocol.
     *
     * @throws Exception If the protocol handler fails to initialise
     */
    public void init() throws Exception;

    /**
     * Start the protocol.
     *
     * @throws Exception If the protocol handler fails to start
     */
    public void start() throws Exception;

    /**
     * Pause the protocol (optional).
     *
     * @throws Exception If the protocol handler fails to pause
     */
    public void pause() throws Exception;

    /**
     * Resume the protocol (optional).
     *
     * @throws Exception If the protocol handler fails to resume
     */
    public void resume() throws Exception;

    /**
     * Stop the protocol.
     *
     * @throws Exception If the protocol handler fails to stop
     */
    public void stop() throws Exception;

    /**
     * Destroy the protocol (optional).
     *
     * @throws Exception If the protocol handler fails to destroy
     */
    public void destroy() throws Exception;

    /**
     * Close the server socket (to prevent further connections) if the server
     * socket was bound on {@link #start()} (rather than on {@link #init()}
     * but do not perform any further shutdown.
     */
    public void closeServerSocketGraceful();

    /**
     * Wait for the client connections to the server to close gracefully. The
     * method will return when all of the client connections have closed or the
     * method has been waiting for {@code waitTimeMillis}.
     *
     * @param waitMillis    The maximum time to wait in milliseconds for the
     *                      client connections to close.
     *
     * @return The wait time, if any remaining when the method returned
     */
    public long awaitConnectionsClose(long waitMillis);

    /**
     * Does this ProtocolHandler support sendfile?
     *
     * @return true if this Protocol Handler supports sendfile,
     *         otherwise false
     */
    public boolean isSendfileSupported();

    /**
     * Add a new SSL configuration for a virtual host.
     * @param sslHostConfig the configuration
     */
    public void addSslHostConfig(SSLHostConfig sslHostConfig);

    /**
     * Find all configured SSL virtual host configurations which will be used
     * by SNI.
     * @return the configurations
     */
    public SSLHostConfig[] findSslHostConfigs();

    /**
     * Add a new protocol for used by HTTP/1.1 upgrade or ALPN.
     * @param upgradeProtocol the protocol
     */
    public void addUpgradeProtocol(UpgradeProtocol upgradeProtocol);

    /**
     * Return all configured upgrade protocols.
     * @return the protocols
     */
    public UpgradeProtocol[] findUpgradeProtocols();

    /**
     * Some protocols, like AJP, have a packet length that
     * shouldn't be exceeded, and this can be used to adjust the buffering
     * used by the application layer.
     * @return the desired buffer size, or -1 if not relevant
     */
    public default int getDesiredBufferSize() {
        return -1;
    }

    /**
     * The default behavior is to identify connectors uniquely with address
     * and port. However, certain connectors are not using that and need
     * some other identifier, which then can be used as a replacement.
     * @return the id
     */
    public default String getId() {
        return null;
    }

    /**
     * Create a new ProtocolHandler for the given protocol.
     * @param protocol the protocol
     * @return the newly instantiated protocol handler
     * @throws ClassNotFoundException Specified protocol was not found
     * @throws InstantiationException Specified protocol could not be instantiated
     * @throws IllegalAccessException Exception occurred
     * @throws IllegalArgumentException Exception occurred
     * @throws InvocationTargetException Exception occurred
     * @throws NoSuchMethodException Exception occurred
     * @throws SecurityException Exception occurred
     */
    public static ProtocolHandler create(String protocol)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
        if (protocol == null || "HTTP/1.1".equals(protocol)
                || org.apache.coyote.http11.Http11NioProtocol.class.getName().equals(protocol)) {
            return new org.apache.coyote.http11.Http11NioProtocol();
        } else if ("AJP/1.3".equals(protocol)
                || org.apache.coyote.ajp.AjpNioProtocol.class.getName().equals(protocol)) {
            return new org.apache.coyote.ajp.AjpNioProtocol();
        } else {
            // Instantiate protocol handler
            Class<?> clazz = Class.forName(protocol);
            return (ProtocolHandler) clazz.getConstructor().newInstance();
        }
    }

}


text:
module YhsdApi

  class Product < YhsdApi::Base

    def self.all(token, params = nil)
      path = "products#{handle_query_string(params)}"
      uri = URI.join(YhsdApi.configuration.api_url, YhsdApi.configuration.api_version, path)
      YhsdApi::HTTP::get(uri, build_header(token))
    end

    def self.count(token)
      path = "products/count"
      uri = URI.join(YhsdApi.configuration.api_url, YhsdApi.configuration.api_version, path)
      YhsdApi::HTTP::get(uri, build_header(token))
    end

    def self.find(token, id, params = nil)
      path = "products/#{id}#{handle_query_string(params)}"
      uri = URI.join(YhsdApi.configuration.api_url, YhsdApi.configuration.api_version, path)
      YhsdApi::HTTP::get(uri, build_header(token))
    end

    def self.create(token, params)
      path = "products"
      uri = URI.join(YhsdApi.configuration.api_url, YhsdApi.configuration.api_version, path)
      YhsdApi::HTTP::post(uri, params.to_json, build_header(token))
    end

    def self.update(token, id, params)
      path = "products/#{id}"
      uri = URI.join(YhsdApi.configuration.api_url, YhsdApi.configuration.api_version, path)
      YhsdApi::HTTP::put(uri, params.to_json, build_header(token))
    end

    def self.delete(token, id)
      path = "products/#{id}"
      uri = URI.join(YhsdApi.configuration.api_url, YhsdApi.configuration.api_version, path)
      YhsdApi::HTTP::delete(uri, build_header(token))
    end

  end

end


text:
"use strict";

var path = require("path");
var ABN  = require(path.resolve(__dirname, "../lib/abn-validator"));

var abn = process.argv.splice(2).join("");

if(!abn) {
	console.error("abn-validator <abn>");
	process.exit(1);
}

var valid = ABN(abn);

if(valid) {
	console.log("Valid ABN");
} else {
	console.log("Invalid ABN");
}


text:
namespace cr_fuchsia {

// Uses |navigation_controller| to load |url| with |load_url_params|. Returns
// after the load is completed. Returns true if the load was successful, false
// otherwise.
bool LoadUrlAndExpectResponse(
    fuchsia::web::NavigationController* navigation_controller,
    fuchsia::web::LoadUrlParams load_url_params,
    base::StringPiece url);

// Executes |script| in the context of |frame|'s top-level document.
// Returns an un-set |base::Optional<>| on failure.
base::Optional<base::Value> ExecuteJavaScript(fuchsia::web::Frame* frame,
                                              base::StringPiece script);

// Creates and returns a LoadUrlParams with was_user_activated set to true.
// This allows user actions to propagate to the frame, allowing features such as
// autoplay to be used, which is used by many media tests.
fuchsia::web::LoadUrlParams CreateLoadUrlParamsWithUserActivation();

}  // namespace cr_fuchsia

#endif  // FUCHSIA_BASE_FRAME_TEST_UTIL_H_


text:
#pragma once
#include <aws/iam/IAM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/iam/model/PolicySourceType.h>
#include <aws/iam/model/Position.h>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace IAM
{
namespace Model
{
  /*
    $shape.documentation
  */
  class AWS_IAM_API Statement
  {
  public:
    Statement();
    Statement(const Aws::Utils::Xml::XmlNode& xmlNode);
    Statement& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    inline const Aws::String& GetSourcePolicyId() const{ return m_sourcePolicyId; }

    inline void SetSourcePolicyId(const Aws::String& value) { m_sourcePolicyIdHasBeenSet = true; m_sourcePolicyId = value; }

    inline void SetSourcePolicyId(Aws::String&& value) { m_sourcePolicyIdHasBeenSet = true; m_sourcePolicyId = value; }

    inline void SetSourcePolicyId(const char* value) { m_sourcePolicyIdHasBeenSet = true; m_sourcePolicyId.assign(value); }

    inline Statement& WithSourcePolicyId(const Aws::String& value) { SetSourcePolicyId(value); return *this;}

    inline Statement& WithSourcePolicyId(Aws::String&& value) { SetSourcePolicyId(value); return *this;}

    inline Statement& WithSourcePolicyId(const char* value) { SetSourcePolicyId(value); return *this;}

    inline const PolicySourceType& GetSourcePolicyType() const{ return m_sourcePolicyType; }

    inline void SetSourcePolicyType(const PolicySourceType& value) { m_sourcePolicyTypeHasBeenSet = true; m_sourcePolicyType = value; }

    inline void SetSourcePolicyType(PolicySourceType&& value) { m_sourcePolicyTypeHasBeenSet = true; m_sourcePolicyType = value; }

    inline Statement& WithSourcePolicyType(const PolicySourceType& value) { SetSourcePolicyType(value); return *this;}

    inline Statement& WithSourcePolicyType(PolicySourceType&& value) { SetSourcePolicyType(value); return *this;}

    inline const Position& GetStartPosition() const{ return m_startPosition; }

    inline void SetStartPosition(const Position& value) { m_startPositionHasBeenSet = true; m_startPosition = value; }

    inline void SetStartPosition(Position&& value) { m_startPositionHasBeenSet = true; m_startPosition = value; }

    inline Statement& WithStartPosition(const Position& value) { SetStartPosition(value); return *this;}

    inline Statement& WithStartPosition(Position&& value) { SetStartPosition(value); return *this;}

    inline const Position& GetEndPosition() const{ return m_endPosition; }

    inline void SetEndPosition(const Position& value) { m_endPositionHasBeenSet = true; m_endPosition = value; }

    inline void SetEndPosition(Position&& value) { m_endPositionHasBeenSet = true; m_endPosition = value; }

    inline Statement& WithEndPosition(const Position& value) { SetEndPosition(value); return *this;}

    inline Statement& WithEndPosition(Position&& value) { SetEndPosition(value); return *this;}

  private:
    Aws::String m_sourcePolicyId;
    bool m_sourcePolicyIdHasBeenSet;
    PolicySourceType m_sourcePolicyType;
    bool m_sourcePolicyTypeHasBeenSet;
    Position m_startPosition;
    bool m_startPositionHasBeenSet;
    Position m_endPosition;
    bool m_endPositionHasBeenSet;
  };

} // namespace Model
} // namespace IAM
} // namespace Aws


text:
<?php
declare(strict_types = 1);

namespace Tests\Innmind\TimeContinuum\Earth\Timezone\America\Argentina;

use Innmind\TimeContinuum\{
    Earth\Timezone\America\Argentina\Mendoza,
    Timezone,
};
use PHPUnit\Framework\TestCase;

class MendozaTest extends TestCase
{
    public function testInterface()
    {
        $zone = new Mendoza;

        $this->assertInstanceOf(Timezone::class, $zone);
    }
}


text:
<?php
// You can use your own mailing methods.

$url = 'https://api.sendgrid.com/';
$user = '';                             //Your username
$pass = '';                             //Your password
$params = array(
    'api_user'  => $user,
    'api_key'   => $pass,
    'to'        => $email_to,
    'subject'   => $subject_to,
    'html'      => $message_to,
    'from'      => 'info@hashtagofficial.in',
  );

$request =  $url.'api/mail.send.json';

// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

// obtain response
$response = curl_exec($session);
curl_close($session);

// print everything out
$email_success=3;

?>


text:
package org.andengine.entity.modifier;

import org.andengine.util.modifier.ease.EaseLinear;
import org.andengine.util.modifier.ease.IEaseFunction;

/**
 * (c) 2010 Nicolas Gramlich
 * (c) 2011 Zynga Inc.
 *
 * @author Nicolas Gramlich
 * @since 19:03:12 - 08.06.2010
 */
public class FadeInModifier extends AlphaModifier {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	// ===========================================================
	// Constructors
	// ===========================================================

	public FadeInModifier(final float pDuration) {
		super(pDuration, 0.0f, 1.0f, EaseLinear.getInstance());
	}

	public FadeInModifier(final float pDuration, final IEaseFunction pEaseFunction) {
		super(pDuration, 0.0f, 1.0f, pEaseFunction);
	}

	public FadeInModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener) {
		super(pDuration, 0.0f, 1.0f, pEntityModifierListener, EaseLinear.getInstance());
	}

	public FadeInModifier(final float pDuration, final IEntityModifierListener pEntityModifierListener, final IEaseFunction pEaseFunction) {
		super(pDuration, 0.0f, 1.0f, pEntityModifierListener, pEaseFunction);
	}

	protected FadeInModifier(final FadeInModifier pFadeInModifier) {
		super(pFadeInModifier);
	}

	@Override
	public FadeInModifier deepCopy() {
		return new FadeInModifier(this);
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lostessence.client.component;

import com.artemis.Component;
import com.lostessence.client.graphics.SpriteAnimation;

/**
 *
 * @author simplyianm
 */
public class CSpriteAnimationComponent extends Component {
    private SpriteAnimation animation;

    public CSpriteAnimationComponent(SpriteAnimation animation) {
        this.animation = animation;
    }

    /**
     * @return the animation
     */
    public SpriteAnimation getAnimation() {
        return animation;
    }

    /**
     * @param animation the animation to set
     */
    public void setAnimation(SpriteAnimation animation) {
        this.animation = animation;
    }
}


text:
package com.hsj.common.utils;

import android.content.Context;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.util.TypedValue;

import com.hsj.common.annotations.NetType;

/**
 * @Author:HSJ
 * @E-mail:shengjunhu@foxmail.com
 * @Date:2017/5/27 16:41
 * @Class:PhoneManager
 * @Description:手机相关工具类
 */
public class PhoneManager {

    //////////////////////////////////////////////////////////////
    // PhoneManager 缓存功能如下:
    //      1、获取设备品牌:android.os.Build.BRAND;
    //      2、设备的唯一标识:android.os.Build.FINGERPRINT;
    //      3、获取设备型号:android.os.Build.MODEL
    //      4、获取设备制造厂商:android.os.Build.MANUFACTURER
    //      5、获取系统版本号:android.os.Build.VERSION.SDK_INT
    //////////////////////////////////////////////////////////////

    private PhoneManager() {
    }

    /**
     * dp转px
     *
     * @param context
     * @param dpValue
     * @return
     */
    public static float dp2px(@NonNull Context context, float dpValue) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpValue, context.getResources().getDisplayMetrics());
    }

    /**
     * sp转px
     *
     * @param context
     * @param spValue
     * @return
     */
    public static float sp2px(@NonNull Context context, float spValue) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spValue, context.getResources().getDisplayMetrics());
    }

    /**
     * px转dp
     *
     * @param context
     * @param pxValue
     * @return
     */
    public static float px2dp(@NonNull Context context, float pxValue) {
        return (pxValue / context.getResources().getDisplayMetrics().density);
    }

    /**
     * px转sp
     *
     * @param context
     * @param pxValue
     * @return
     */
    public static float px2sp(Context context, float pxValue) {
        return (pxValue / context.getResources().getDisplayMetrics().scaledDensity);
    }

    /**
     * 获取设备分辨率( 内容显示分辨率)
     *
     * @param context
     */
    public static int[] getResolution(@NonNull Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int resolution[] = new int[2];
        resolution[0] = dm.widthPixels;
        resolution[1] = dm.heightPixels;
        return resolution;
    }

    /**
     * 获取设备分辨率(屏幕分辨率)
     *
     * @param context
     */
    public static int[] getScreenResolution(@NonNull Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int resolution[] = new int[2];
        resolution[0] = dm.widthPixels;
        resolution[1] = dm.heightPixels + getNavigationBarHeight(context);
        return resolution;
    }

    /**
     * 获取设备顶部状态栏高度
     *
     * @param context
     */
    public static int getStatusBarHeight(@NonNull Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        return resources.getDimensionPixelSize(resourceId);
    }

    /**
     * 获取设备底部导航栏高度
     *
     * @param context
     */
    public static int getNavigationBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        return resources.getDimensionPixelSize(resourceId);
    }

    /**
     * 获取网络状态
     *
     * @return 0为网络不可用、1为移动网络、2为Wifi网络
     */
    public int getNetworkType(@NonNull Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return NetType.NETWORK_CLOSE;
        } else {
            NetworkInfo mNetworkInfo = cm.getActiveNetworkInfo();
            if (mNetworkInfo == null) {
                return NetType.NETWORK_UNAVAILABLE;
            } else if (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                return NetType.NETWORK_WIFI;
            } else if (mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                return NetType.NETWORK_MOBILE;
            } else {
                return NetType.NETWORK_UNAVAILABLE;
            }
        }
    }

}


text:
package com.waimai.da.shockwave.web.service;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by jsong on 2017/8/29.
 */
public class ConfigServiceTest {

    private ConfigService service1;
    private ConfigService service2;

    @Before
    public void init() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        service1 = (ConfigService) context.getBean("configService");
        service2 = (ConfigService) context.getBean("configService");
    }

}


text:
<?php declare(strict_types=1);

namespace CodeManager\Entity\Abstractions\Traits\Number\Whole;

use Doctrine\ORM\Mapping\Column;

trait FieldInt {

    /**
     * @var int
     * @Column(name="int0", type="integer", nullable=false, unique=false)
     */
    protected $int0;

    /**
     * @return int
     */
    public function getInt0(): int {
        return $this->int0;
    }

    /**
     * @param int $int0
     * @return self
     */
    public function setInt0(int $int0): self {
        $this->int0 = $int0;
        return $this;
    }

    /**
     * @param int $n
     * @return bool
     */
    public function isInt0EqualTo(int $n): bool {
        return $this->int0 === $n;
    }

}


text:
/**
 * Módulo de bloqueio do sistema com tela de loading
 */
angular.module('flex4angular.loading', [])

/**
 * Factory para auxiliar o show é o hide da camada de bloqueio da tela
 */
.factory('$faLoading', ['$rootScope',
	function($rootScope) {
		$rootScope.loading = 0;
		return {
			start: function() {
				$rootScope.loading += 1;
			},
			stop: function() {
				$rootScope.loading -= 1;
			}
		};
	}
])

/**
 * Diretiva que coloca uma camada de bloqueio na tela
 * Obs. O show e hide deve ser inserido manualmente
 * EX:
 *		<fa-loading></fa-loading>
 *
 */
.directive('faLoadingView', ['$rootScope', '$window',
	function($rootScope, $window) {
		return {
			scope: {},
			restrict: 'E',
			transclude: true,
			template: '

',
			link: function($scope) {
				$scope.preventFunc = function(e) {
					e.preventDefault();
				};
				$rootScope.$watch('loading', function(newValue, oldValue, scope) {
					$scope.loading = newValue > 0;
					if (!oldValue && newValue > 0) {
						angular.element($window).bind('keydown keypress', $scope.preventFunc);
					}
					if (oldValue > 0 && !newValue) {
						angular.element($window).unbind('keydown keypress', $scope.preventFunc);
					}
				});
			}
		};
	}
]);