text:
import re
import logging

logging.basicConfig(level=logging.INFO)

import warnings
import multiprocess as mp
from functools import partial

import numpy as np
import pandas as pd
import cooler
from skimage.filters import threshold_li, threshold_otsu

from ..lib._query import CSRSelector
from ..lib import peaks, numutils

from ..lib.checks import is_compatible_viewframe, is_cooler_balanced
from ..lib.common import make_cooler_view

def get_n_pixels(bad_bin_mask, window=10, ignore_diags=2):
    """
    Calculate the number of "good" pixels in a diamond at each bin.

    """
    N = len(bad_bin_mask)
    n_pixels = np.zeros(N)
    loc_bad_bin_mask = np.zeros(N, dtype=bool)
    for i_shift in range(0, window):
        for j_shift in range(0, window):
            if i_shift + j_shift < ignore_diags:
                continue

            loc_bad_bin_mask[:] = False
            if i_shift == 0:
                loc_bad_bin_mask |= bad_bin_mask
            else:
                loc_bad_bin_mask[i_shift:] |= bad_bin_mask[:-i_shift]
            if j_shift == 0:
                loc_bad_bin_mask |= bad_bin_mask
            else:
                loc_bad_bin_mask[:-j_shift] |= bad_bin_mask[j_shift:]

            n_pixels[i_shift : (-j_shift if j_shift else None)] += (
                1 - loc_bad_bin_mask[i_shift : (-j_shift if j_shift else None)]
            )
    return n_pixels

def insul_diamond(
    pixel_query,
    bins,
    window=10,
    ignore_diags=2,
    norm_by_median=True,
    clr_weight_name="weight",
):
    """
    Calculates the insulation score of a Hi-C interaction matrix.

    Parameters
    ----------
    pixel_query : RangeQuery object <TODO:update description>
        A table of Hi-C interactions. Must follow the Cooler columnar format:
        bin1_id, bin2_id, count, balanced (optional)).
    bins : pandas.DataFrame
        A table of bins, is used to determine the span of the matrix
        and the locations of bad bins.
    window : int
        The width (in bins) of the diamond window to calculate the insulation
        score.
    ignore_diags : int
        If > 0, the interactions at separations < `ignore_diags` are ignored
        when calculating the insulation score. Typically, a few first diagonals
        of the Hi-C map should be ignored due to contamination with Hi-C
        artifacts.
    norm_by_median : bool
        If True, normalize the insulation score by its NaN-median.
    clr_weight_name : str or None
        Name of balancing weight column from the cooler to use.
        Using raw unbalanced data is not supported for insulation.
    """
    lo_bin_id = bins.index.min()
    hi_bin_id = bins.index.max() + 1
    N = hi_bin_id - lo_bin_id
    sum_counts = np.zeros(N)
    sum_balanced = np.zeros(N)

    if clr_weight_name is None:
        # define n_pixels
        n_pixels = get_n_pixels(
            np.repeat(False, len(bins)), window=window, ignore_diags=ignore_diags
        )
    else:
        # calculate n_pixels
        n_pixels = get_n_pixels(
            bins[clr_weight_name].isnull().values,
            window=window,
            ignore_diags=ignore_diags,
        )
        # define transform - balanced and raw ('count') for now
        weight1 = clr_weight_name + "1"
        weight2 = clr_weight_name + "2"
        transform = lambda p: p["count"] * p[weight1] * p[weight2]

    for chunk_dict in pixel_query.read_chunked():
        chunk = pd.DataFrame(chunk_dict, columns=["bin1_id", "bin2_id", "count"])
        diag_pixels = chunk[chunk.bin2_id - chunk.bin1_id <= (window - 1) * 2]

        if clr_weight_name:
            diag_pixels = cooler.annotate(diag_pixels, bins[[clr_weight_name]])
            diag_pixels["balanced"] = transform(diag_pixels)
            valid_pixel_mask = ~diag_pixels["balanced"].isnull().values

        i = diag_pixels.bin1_id.values - lo_bin_id
        j = diag_pixels.bin2_id.values - lo_bin_id

        for i_shift in range(0, window):
            for j_shift in range(0, window):
                if i_shift + j_shift < ignore_diags:
                    continue

                mask = (
                    (i + i_shift == j - j_shift)
                    & (i + i_shift < N)
                    & (j - j_shift >= 0)
                )

                sum_counts += np.bincount(
                    i[mask] + i_shift, diag_pixels["count"].values[mask], minlength=N
                )

                if clr_weight_name:
                    sum_balanced += np.bincount(
                        i[mask & valid_pixel_mask] + i_shift,
                        diag_pixels["balanced"].values[mask & valid_pixel_mask],
                        minlength=N,
                    )

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")

        if clr_weight_name:
            score = sum_balanced / n_pixels
        else:
            score = sum_counts / n_pixels

        if norm_by_median:
            score /= np.nanmedian(score)

    return score, n_pixels, sum_balanced, sum_counts

def calculate_insulation_score(
    clr,
    window_bp,
    view_df=None,
    ignore_diags=None,
    min_dist_bad_bin=0,
    is_bad_bin_key="is_bad_bin",
    append_raw_scores=False,
    chunksize=20000000,
    clr_weight_name="weight",
    verbose=False,
    nproc=1,
):
    """Calculate the diamond insulation scores for all bins in a cooler.

    Parameters
    ----------
    clr : cooler.Cooler
        A cooler with balanced Hi-C data.
    window_bp : int or list of integers
        The size of the sliding diamond window used to calculate the insulation
        score. If a list is provided, then a insulation score if calculated for each
        value of window_bp.
    view_df : bioframe.viewframe or None
        Viewframe for independent calculation of insulation scores for regions
    ignore_diags : int | None
        The number of diagonals to ignore. If None, equals the number of
        diagonals ignored during IC balancing.
    min_dist_bad_bin : int
        The minimal allowed distance to a bad bin to report insulation score.
        Fills bins that have a bad bin closer than this distance by nans.
    is_bad_bin_key : str
        Name of the output column to store bad bins
    append_raw_scores : bool
        If True, append columns with raw scores (sum_counts, sum_balanced, n_pixels)
        to the output table.
    clr_weight_name : str or None
        Name of the column in the bin table with weight.
        Using unbalanced data with `None` will avoid masking "bad" pixels.
    verbose : bool
        If True, report real-time progress.
    nproc : int, optional
        How many processes to use for calculation

    Returns
    -------
    ins_table : pandas.DataFrame
        A table containing the insulation scores of the genomic bins
    """

    if view_df is None:
        view_df = make_cooler_view(clr)
    else:
        # Make sure view_df is a proper viewframe
        try:
            _ = is_compatible_viewframe(
                view_df,
                clr,
                check_sorting=True,
                raise_errors=True,
            )
        except Exception as e:
            raise ValueError("view_df is not a valid viewframe or incompatible") from e

    # check if cooler is balanced
    if clr_weight_name:
        try:
            _ = is_cooler_balanced(clr, clr_weight_name, raise_errors=True)
        except Exception as e:
            raise ValueError(
                f"provided cooler is not balanced or {clr_weight_name} is missing"
            ) from e

    bin_size = clr.info["bin-size"]
    # check if ignore_diags is valid
    if ignore_diags is None:
        try:
            ignore_diags = clr._load_attrs(
                clr.root.rstrip("/") + f"/bins/{clr_weight_name}"
            )["ignore_diags"]
        except:
            raise ValueError(
                f"ignore_diags not provided, and not found in cooler balancing weights {clr_weight_name}"
            )
    elif isinstance(ignore_diags, int):
        pass  # keep it as is
    else:
        raise ValueError(f"ignore_diags must be int or None, got {ignore_diags}")

    if np.isscalar(window_bp):
        window_bp = [window_bp]
    window_bp = np.array(window_bp, dtype=int)

    bad_win_sizes = window_bp % bin_size != 0
    if np.any(bad_win_sizes):
        raise ValueError(
            f"The window sizes {window_bp[bad_win_sizes]} has to be a multiple of the bin size {bin_size}"
        )

    # Calculate insulation score for each region separately.
    # Define mapper depending on requested number of threads:
    if nproc > 1:
        pool = mp.Pool(nproc)
        map_ = pool.map
    else:
        map_ = map

    # Using try-clause to close mp.Pool properly
    try:
        # Apply get_region_insulation:
        job = partial(
            _get_region_insulation,
            clr,
            is_bad_bin_key,
            clr_weight_name,
            chunksize,
            window_bp,
            min_dist_bad_bin,
            ignore_diags,
            append_raw_scores,
            verbose,
        )
        ins_region_tables = map_(job, view_df[["chrom", "start", "end", "name"]].values)

    finally:
        if nproc > 1:
            pool.close()

    ins_table = pd.concat(ins_region_tables)
    return ins_table

def _get_region_insulation(
    clr,
    is_bad_bin_key,
    clr_weight_name,
    chunksize,
    window_bp,
    min_dist_bad_bin,
    ignore_diags,
    append_raw_scores,
    verbose,
    region,
):
    """
    Auxilary function to make calculate_insulation_score parallel.
    """

    # XXX -- Use a delayed query executor
    nbins = len(clr.bins())
    selector = CSRSelector(
        clr.open("r"), shape=(nbins, nbins), field="count", chunksize=chunksize
    )

    # Convert window sizes to bins:
    bin_size = clr.info["bin-size"]
    window_bins = window_bp // bin_size

    # Parse region and set up insulation table for the region:
    chrom, start, end, name = region
    region = [chrom, start, end]
    region_bins = clr.bins().fetch(region)
    ins_region = region_bins[["chrom", "start", "end"]].copy()
    ins_region.loc[:, "region"] = name
    ins_region[is_bad_bin_key] = (
        region_bins[clr_weight_name].isnull() if clr_weight_name else False
    )

    if verbose:
        logging.info(f"Processing region {name}")

    if min_dist_bad_bin:
        ins_region = ins_region.assign(
            dist_bad_bin=numutils.dist_to_mask(ins_region[is_bad_bin_key])
        )

    # XXX --- Create a delayed selection
    c0, c1 = clr.extent(region)
    region_query = selector[c0:c1, c0:c1]

    for j, win_bin in enumerate(window_bins):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", RuntimeWarning)
            # XXX -- updated insul_diamond
            ins_track, n_pixels, sum_balanced, sum_counts = insul_diamond(
                region_query,
                region_bins,
                window=win_bin,
                ignore_diags=ignore_diags,
                clr_weight_name=clr_weight_name,
            )
            ins_track[ins_track == 0] = np.nan
            ins_track = np.log2(ins_track)

        ins_track[~np.isfinite(ins_track)] = np.nan

        ins_region[f"log2_insulation_score_{window_bp[j]}"] = ins_track
        ins_region[f"n_valid_pixels_{window_bp[j]}"] = n_pixels

        if min_dist_bad_bin:
            mask_bad = ins_region.dist_bad_bin.values < min_dist_bad_bin
            ins_region.loc[mask_bad, f"log2_insulation_score_{window_bp[j]}"] = np.nan

        if append_raw_scores:
            ins_region[f"sum_counts_{window_bp[j]}"] = sum_counts
            ins_region[f"sum_balanced_{window_bp[j]}"] = sum_balanced

    return ins_region

def find_boundaries(
    ins_table,
    min_frac_valid_pixels=0.66,
    min_dist_bad_bin=0,
    log2_ins_key="log2_insulation_score_{WINDOW}",
    n_valid_pixels_key="n_valid_pixels_{WINDOW}",
    is_bad_bin_key="is_bad_bin",
):
    """Call insulating boundaries.

    Find all local minima of the log2(insulation score) and calculate their
    chromosome-wide topographic prominence.

    Parameters
    ----------
    ins_table : pandas.DataFrame
        A bin table with columns containing log2(insulation score),
        annotation of regions (required),
        the number of valid pixels per diamond and (optionally) the mask
        of bad bins. Normally, this should be an output of calculate_insulation_score.
    view_df : bioframe.viewframe or None
        Viewframe for independent boundary calls for regions
    min_frac_valid_pixels : float
        The minimal fraction of valid pixels in a diamond to be used in
        boundary picking and prominence calculation.
    min_dist_bad_bin : int
        The minimal allowed distance to a bad bin to be used in boundary picking.
        Ignore bins that have a bad bin closer than this distance.
    log2_ins_key, n_valid_pixels_key : str
        The names of the columns containing log2_insulation_score and
        the number of valid pixels per diamond. When a template
        containing `{WINDOW}` is provided, the calculation is repeated
        for all pairs of columns matching the template.

    Returns
    -------
    ins_table : pandas.DataFrame
        A bin table with appended columns with boundary prominences.
    """

    if min_dist_bad_bin:
        ins_table = pd.concat(
            [
                df.assign(dist_bad_bin=numutils.dist_to_mask(df[is_bad_bin_key]))
                for region, df in ins_table.groupby("region")
            ]
        )

    if "{WINDOW}" in log2_ins_key:
        windows = set()
        for col in ins_table.columns:
            m = re.match(log2_ins_key.format(WINDOW=r"(\d+)"), col)
            if m:
                windows.add(int(m.groups()[0]))
    else:
        windows = set([None])

    min_valid_pixels = {
        win: ins_table[n_valid_pixels_key.format(WINDOW=win)].max()
        * min_frac_valid_pixels
        for win in windows
    }

    dfs = []
    index_name = ins_table.index.name  # Store the name of the index and soring order
    sorting_order = ins_table.index.values
    ins_table.index.name = "sorting_index"
    ins_table.reset_index(drop=False, inplace=True)
    for region, df in ins_table.groupby("region"):
        df = df.sort_values(["start"])  # Force sorting by the bin start coordinate
        for win in windows:
            mask = (
                df[n_valid_pixels_key.format(WINDOW=win)].values
                >= min_valid_pixels[win]
            )

            if min_dist_bad_bin:
                mask &= df.dist_bad_bin.values >= min_dist_bad_bin

            ins_track = df[log2_ins_key.format(WINDOW=win)].values[mask]
            poss, proms = peaks.find_peak_prominence(-ins_track)
            ins_prom_track = np.zeros_like(ins_track) * np.nan
            ins_prom_track[poss] = proms

            if win is not None:
                bs_key = f"boundary_strength_{win}"
            else:
                bs_key = "boundary_strength"

            df[bs_key] = np.nan
            df.loc[mask, bs_key] = ins_prom_track

        dfs.append(df)

    df = pd.concat(dfs)
    df = df.set_index("sorting_index")  # Restore original sorting order and name
    df.index.name = index_name
    df = df.loc[sorting_order, :]
    return df

def _insul_diamond_dense(mat, window=10, ignore_diags=2, norm_by_median=True):
    """
    Calculates the insulation score of a Hi-C interaction matrix.

    Parameters
    ----------
    mat : numpy.array
        A dense square matrix of Hi-C interaction frequencies.
        May contain nans, e.g. in rows/columns excluded from the analysis.

    window : int
        The width of the window to calculate the insulation score.

    ignore_diags : int
        If > 0, the interactions at separations < `ignore_diags` are ignored
        when calculating the insulation score. Typically, a few first diagonals
        of the Hi-C map should be ignored due to contamination with Hi-C
        artifacts.

    norm_by_median : bool
        If True, normalize the insulation score by its NaN-median.

    Returns
    -------
    score : ndarray
        an array with normalized insulation scores for provided matrix
    """
    if ignore_diags:
        mat = mat.copy()
        for i in range(-ignore_diags + 1, ignore_diags):
            numutils.set_diag(mat, np.nan, i)

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")

        N = mat.shape[0]
        score = np.nan * np.ones(N)
        for i in range(0, N):
            lo = max(0, i + 1 - window)
            hi = min(i + window, N)
            # nanmean of interactions to reduce the effect of bad bins
            score[i] = np.nanmean(mat[lo : i + 1, i:hi])
        if norm_by_median:
            score /= np.nanmedian(score)
    return score

def _find_insulating_boundaries_dense(
    clr,
    window_bp=100000,
    view_df=None,
    clr_weight_name="weight",
    min_dist_bad_bin=2,
    ignore_diags=None,
):
    """Calculate the diamond insulation scores and call insulating boundaries.

    Parameters
    ----------
    clr : cooler.Cooler
        A cooler with balanced Hi-C data. Balancing weights are required
        for the detection of bad_bins.
    window_bp : int
        The size of the sliding diamond window used to calculate the insulation
        score.
    view_df : bioframe.viewframe or None
        Viewframe for independent calculation of insulation scores for regions
    clr_weight_name : str
        Name of the column in bin table that stores the balancing weights.
    min_dist_bad_bin : int
        The minimal allowed distance to a bad bin. Do not calculate insulation
        scores for bins having a bad bin closer than this distance.
    ignore_diags : int
        The number of diagonals to ignore. If None, equals the number of
        diagonals ignored during IC balancing.

    Returns
    -------
    ins_table : pandas.DataFrame
        A table containing the insulation scores of the genomic bins and
        the insulating boundary strengths.
    """

    if view_df is None:
        view_df = make_cooler_view(clr)
    else:
        # Make sure view_df is a proper viewframe
        try:
            _ = is_compatible_viewframe(
                view_df,
                clr,
                check_sorting=True,
                raise_errors=True,
            )
        except Exception as e:
            raise ValueError("view_df is not a valid viewframe or incompatible") from e

    bin_size = clr.info["bin-size"]

    # check if cooler is balanced
    if clr_weight_name:
        try:
            _ = is_cooler_balanced(clr, clr_weight_name, raise_errors=True)
        except Exception as e:
            raise ValueError(
                f"provided cooler is not balanced or {clr_weight_name} is missing"
            ) from e

    # check if ignore_diags is valid
    if ignore_diags is None:
        ignore_diags = clr._load_attrs(
            clr.root.rstrip("/") + f"/bins/{clr_weight_name}"
        )["ignore_diags"]
    elif isinstance(ignore_diags, int):
        pass  # keep it as is
    else:
        raise ValueError(f"provided ignore_diags {ignore_diags} is not int or None")

    window_bins = window_bp // bin_size

    if window_bp % bin_size != 0:
        raise ValueError(
            f"The window size ({window_bp}) has to be a multiple of the bin size {bin_size}"
        )

    ins_region_tables = []
    for chrom, start, end, name in view_df[["chrom", "start", "end", "name"]].values:
        region = [chrom, start, end]
        ins_region = clr.bins().fetch(region)[["chrom", "start", "end"]]
        is_bad_bin = np.isnan(clr.bins().fetch(region)[clr_weight_name].values)
        # extract dense Hi-C heatmap for a given "region"
        m = clr.matrix(balance=clr_weight_name).fetch(region)

        with warnings.catch_warnings():
            warnings.simplefilter("ignore", RuntimeWarning)
            ins_track = _insul_diamond_dense(m, window_bins, ignore_diags)
            ins_track[ins_track == 0] = np.nan
            ins_track = np.log2(ins_track)

        bad_bin_neighbor = np.zeros_like(is_bad_bin)
        for i in range(0, min_dist_bad_bin):
            if i == 0:
                bad_bin_neighbor = bad_bin_neighbor | is_bad_bin
            else:
                bad_bin_neighbor = bad_bin_neighbor | np.r_[[True] * i, is_bad_bin[:-i]]
                bad_bin_neighbor = bad_bin_neighbor | np.r_[is_bad_bin[i:], [True] * i]

        ins_track[bad_bin_neighbor] = np.nan
        ins_region["bad_bin_masked"] = bad_bin_neighbor

        ins_track[~np.isfinite(ins_track)] = np.nan

        ins_region[f"log2_insulation_score_{window_bp}"] = ins_track

        poss, proms = peaks.find_peak_prominence(-ins_track)
        ins_prom_track = np.zeros_like(ins_track) * np.nan
        ins_prom_track[poss] = proms
        ins_region[f"boundary_strength_{window_bp}"] = ins_prom_track
        ins_region[f"boundary_strength_{window_bp}"] = ins_prom_track

        ins_region_tables.append(ins_region)

    ins_table = pd.concat(ins_region_tables)
    return ins_table

def insulation(
    clr,
    window_bp,
    view_df=None,
    ignore_diags=None,
    clr_weight_name="weight",
    min_frac_valid_pixels=0.66,
    min_dist_bad_bin=0,
    threshold="Li",
    append_raw_scores=False,
    chunksize=20000000,
    verbose=False,
    nproc=1,
):
    """Find insulating boundaries in a contact map via the diamond insulation score.

    For a given cooler, this function (a) calculates the diamond insulation score track,
    (b) detects all insulating boundaries, and (c) removes weak boundaries via an automated
    thresholding algorithm.

    Parameters
    ----------
    clr : cooler.Cooler
        A cooler with balanced Hi-C data.
    window_bp : int or list of integers
        The size of the sliding diamond window used to calculate the insulation
        score. If a list is provided, then a insulation score if done for each
        value of window_bp.
    view_df : bioframe.viewframe or None
        Viewframe for independent calculation of insulation scores for regions
    ignore_diags : int | None
        The number of diagonals to ignore. If None, equals the number of
        diagonals ignored during IC balancing.
    clr_weight_name : str
        Name of the column in the bin table with weight
    min_frac_valid_pixels : float
        The minimal fraction of valid pixels in a diamond to be used in
        boundary picking and prominence calculation.
    min_dist_bad_bin : int
        The minimal allowed distance to a bad bin to report insulation score.
        Fills bins that have a bad bin closer than this distance by nans.
    threshold : "Li", "Otsu" or float
        Rule used to threshold the histogram of boundary strengths to exclude weak
        boundaries. "Li" or "Otsu" use corresponding methods from skimage.thresholding.
        Providing a float value will filter by a fixed threshold
    append_raw_scores : bool
        If True, append columns with raw scores (sum_counts, sum_balanced, n_pixels)
        to the output table.
    verbose : bool
        If True, report real-time progress.
    nproc : int, optional
        How many processes to use for calculation

    Returns
    -------
    ins_table : pandas.DataFrame
        A table containing the insulation scores of the genomic bins
    """
    # Create view:
    if view_df is None:
        # full chromosomes:
        view_df = make_cooler_view(clr)
    else:
        # Make sure view_df is a proper viewframe
        try:
            _ = is_compatible_viewframe(
                view_df,
                clr,
                # must be sorted for pairwise regions combinations
                # to be in the upper right of the heatmap
                check_sorting=True,
                raise_errors=True,
            )
        except Exception as e:
            raise ValueError("view_df is not a valid viewframe or incompatible") from e

    if threshold == "Li":
        thresholding_func = lambda x: x >= threshold_li(x)
    elif threshold == "Otsu":
        thresholding_func = lambda x: x >= threshold_otsu(x)
    else:
        try:
            thr = float(threshold)
            thresholding_func = lambda x: x >= thr
        except ValueError:
            raise ValueError(
                "Insulating boundary strength threshold can be Li, Otsu or a float"
            )
    # Calculate insulation score:
    ins_table = calculate_insulation_score(
        clr,
        view_df=view_df,
        window_bp=window_bp,
        ignore_diags=ignore_diags,
        min_dist_bad_bin=min_dist_bad_bin,
        append_raw_scores=append_raw_scores,
        clr_weight_name=clr_weight_name,
        chunksize=chunksize,
        verbose=verbose,
        nproc=nproc,
    )

    # Find boundaries:
    ins_table = find_boundaries(
        ins_table,
        min_frac_valid_pixels=min_frac_valid_pixels,
        min_dist_bad_bin=min_dist_bad_bin,
    )
    for win in window_bp:
        strong_boundaries = thresholding_func(
            ins_table[f"boundary_strength_{win}"].values
        )
        ins_table[f"is_boundary_{win}"] = strong_boundaries

    return ins_table


text:
package org.springframework.vault.authentication.event;

import org.springframework.context.ApplicationEvent;
import org.springframework.vault.support.VaultToken;

/**
 * Event published when dropping an expired {@link VaultToken login token}.
 *
 * @author Mark Paluch
 * @since 2.2
 * @see ApplicationEvent
 */
public class LoginTokenExpiredEvent extends AuthenticationEvent {

	private static final long serialVersionUID = 1L;

	/**
	 * Create a new {@link LoginTokenExpiredEvent} given {@link VaultToken}.
	 *
	 * @param source the {@link VaultToken} associated with this event, must not be
	 *     {@literal null}.
	 */
	public LoginTokenExpiredEvent(VaultToken source) {
		super(source);
	}
}

redpajama_set_name: RedPajamaGithub


text:
using FluentValidation;
using Nop.Admin.Models.Directory;
using Nop.Services.Localization;

namespace Nop.Admin.Validators.Directory
{
    public class CountryValidator : AbstractValidator<CountryModel>
    {
        public CountryValidator(ILocalizationService localizationService)
        {
            RuleFor(x => x.Name)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Admin.Configuration.Countries.Fields.Name.Required"));

            RuleFor(x => x.TwoLetterIsoCode)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Admin.Configuration.Countries.Fields.TwoLetterIsoCode.Required"));
            RuleFor(x => x.TwoLetterIsoCode)
                .Length(2)
                .WithMessage(localizationService.GetResource("Admin.Configuration.Countries.Fields.TwoLetterIsoCode.Length"));

            RuleFor(x => x.ThreeLetterIsoCode)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Admin.Configuration.Countries.Fields.ThreeLetterIsoCode.Required"));
            RuleFor(x => x.ThreeLetterIsoCode)
                .Length(3)
                .WithMessage(localizationService.GetResource("Admin.Configuration.Countries.Fields.ThreeLetterIsoCode.Length"));
        }
    }
}


text:
using std::string;
using std::map;

class cConfig
{
public:
	cConfig();
	virtual ~cConfig();

protected:
	bool Parse(const string &fileName);
	void UpdateParseData();
	void InitDefault();

public:
	map<string, string> m_options;
	int m_screenWidth;
	int m_screenHeight;
	int m_cameraWidth;
	int m_cameraHeight;
	int m_cameraIndex;
	int m_screen_BinaryThreshold;
	float m_screenMinimumAreaRate;
	int m_rotateSensitivity;
	int m_detectPointThreshold;
	float m_detectPointMinArea;
	float m_detectPointMaxArea;

	bool m_showCamera;
	bool m_showScreen;
	bool m_showDetectPoint;
	bool m_showDebug;

	// camera undistortion
	double m_cx;
	double m_cy;
	double m_fx;
	double m_fy;
	double m_k1;
	double m_k2;
	double m_k3;
	double m_p1;
	double m_p2;
	double m_skew_c;

	// screen contour
	bool m_screenDetectEnable;
	cv::Point m_screenContours[4];

	// shared memory
	string m_sharedMemroyName;

	// UDP Network
	bool m_udpCommunincationEnable;
	int m_udpPort;

	// Windows
	cv::Rect m_screenRect;
	cv::Rect m_cameraRect;
	cv::Rect m_screenBinRect;
	cv::Rect m_screenRecogRect;
	cv::Rect m_skewScreenRect;
	cv::Rect m_matchScreenRect;
	cv::Rect m_detectPointBinaryScreenRect;

	bool m_screenEnable;
	bool m_cameraEnable;
	bool m_screenBinEnable;
	bool m_screenRecogEnable;
	bool m_skewScreenEnable;
	bool m_matchScreenEnable;
	bool m_detectPointBinaryScreenEnable;

	bool m_matchScreenDrawBox;
};

extern cConfig g_config;


text:
#ifndef IVW_IMAGECLGL_H
#define IVW_IMAGECLGL_H

#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/datastructures/image/imagerepresentation.h>
#include <modules/opencl/inviwoopencl.h>
#include <modules/opencl/openclmoduledefine.h>
#include <modules/opencl/image/layerclgl.h>

namespace inviwo {

class IVW_MODULE_OPENCL_API ImageCLGL: public ImageRepresentation {

public:
    ImageCLGL();
    ImageCLGL(const ImageCLGL& other);
    virtual ~ImageCLGL();
    virtual ImageCLGL* clone() const;

    LayerCLGL* getLayerCL();
    const LayerCLGL* getLayerCL() const;

    virtual bool copyRepresentationsTo(DataRepresentation*) const override;

protected:
    virtual void update(bool);

    LayerCLGL* layerCLGL_;
};

} // namespace

namespace cl {

// Kernel argument specializations for ImageCLGL type
// Will set the color layer as argument.
// (enables calling cl::Queue::setArg with ImageCLGL)
template <>
IVW_MODULE_OPENCL_API cl_int Kernel::setArg(cl_uint index, const inviwo::ImageCLGL& value);

} // namespace cl

#endif // IVW_IMAGECLGL_H


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>Introductions List</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

      Trees

      Indices

        Toggle frames

[
 Identifiers
| Deprecations
| Introductions
]
Introductions List

Introductions in cocos.audio.SDL.sound.Sound_NewSampleFromMem

Not yet released in SDL_sound

Introductions in cocos.custom_clocks.AutotestClock.get_sleep_time

pyglet 1.1

Introductions in cocos.custom_clocks.AutotestClock_12dev.get_sleep_time

pyglet 1.1

Introductions in cocos.custom_clocks.AutotestClock_12dev.update_time

pyglet 1.2

Introductions in cocos.custom_clocks.ScreenReaderClock_12dev.get_sleep_time

pyglet 1.1

Introductions in cocos.custom_clocks.ScreenReaderClock_12dev.update_time

pyglet 1.2

Introductions in pyglet.clock.Clock.call_scheduled_functions

pyglet 1.2

Introductions in pyglet.clock.Clock.get_sleep_time

pyglet 1.1

Introductions in pyglet.clock.Clock.schedule_interval_soft

pyglet 1.1

Introductions in pyglet.clock.Clock.update_time

pyglet 1.2

      Trees

      Indices

        Toggle frames

    Generated by Epydoc 3.0beta1 on Sun Aug 12 20:39:16 2012

      http://epydoc.sourceforge.net


text:
package com.google.errorprone.refaster;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Flags;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for {@link UTemplater#createTemplate} against real compiled code.
 *
 * @author lowasser@google.com (Louis Wasserman)
 */
@RunWith(JUnit4.class)
public class TemplatingTest extends CompilerBasedTest {

  @Test
  public void arrayAccess() {
    compile(
        "class ArrayAccessExample {",
        "  public double example(double[] array) {",
        "    return array[5];",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of("array", UArrayType.create(UPrimitiveType.DOUBLE)),
                UArrayAccess.create(UFreeIdent.create("array"), ULiteral.intLit(5)),
                UPrimitiveType.DOUBLE));
  }

  @Test
  public void binary() {
    compile(
        "class BinaryExample {",
        "  public int example(int x, int y) {",
        "    return (x + y) / 2;",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of(
                    "x", UPrimitiveType.INT,
                    "y", UPrimitiveType.INT),
                UBinary.create(
                    Kind.DIVIDE,
                    UParens.create(
                        UBinary.create(Kind.PLUS, UFreeIdent.create("x"), UFreeIdent.create("y"))),
                    ULiteral.intLit(2)),
                UPrimitiveType.INT));
  }

  @Test
  public void conditional() {
    compile(
        "class ConditionalExample {",
        "  public String example(boolean foo) {",
        "    return foo ? null : \"bar\";",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of("foo", UPrimitiveType.BOOLEAN),
                UConditional.create(
                    UFreeIdent.create("foo"), ULiteral.nullLit(), ULiteral.stringLit("bar")),
                UClassType.create("java.lang.String")));
  }

  @Test
  public void whileLoop() {
    compile(
        "import java.util.Iterator;",
        "class WhileLoopExample {",
        "  public void example(Iterator<?> itr) {",
        "    while (itr.hasNext()) {",
        "      itr.next();",
        "    }",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            BlockTemplate.create(
                ImmutableMap.of(
                    "itr", UClassType.create("java.util.Iterator", UWildcardType.create())),
                UWhileLoop.create(
                    UParens.create(
                        UMethodInvocation.create(
                            UMemberSelect.create(
                                UFreeIdent.create("itr"),
                                "hasNext",
                                UMethodType.create(UPrimitiveType.BOOLEAN)))),
                    UBlock.create(
                        UExpressionStatement.create(
                            UMethodInvocation.create(
                                UMemberSelect.create(
                                    UFreeIdent.create("itr"),
                                    "next",
                                    UMethodType.create(UTypeVar.create("E")))))))));
  }

  @Test
  public void fullyQualifiedGlobalIdent() {
    compile(
        "class FullyQualifiedIdentExample {",
        "  public java.math.RoundingMode example() {",
        "    return java.math.RoundingMode.FLOOR;",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                UStaticIdent.create(
                    "java.math.RoundingMode", "FLOOR", UClassType.create("java.math.RoundingMode")),
                UClassType.create("java.math.RoundingMode")));
  }

  @Test
  public void qualifiedGlobalIdent() {
    compile(
        "import java.math.RoundingMode;",
        "class QualifiedIdentExample {",
        "  public RoundingMode example() {",
        "    return RoundingMode.FLOOR;",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                UStaticIdent.create(
                    "java.math.RoundingMode", "FLOOR", UClassType.create("java.math.RoundingMode")),
                UClassType.create("java.math.RoundingMode")));
  }

  @Test
  public void staticImportedGlobalIdent() {
    compile(
        "import java.math.RoundingMode;",
        "import static java.math.RoundingMode.FLOOR;",
        "class StaticImportedIdentExample {",
        "  public RoundingMode example() {",
        "    return FLOOR;",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                UStaticIdent.create(
                    "java.math.RoundingMode", "FLOOR", UClassType.create("java.math.RoundingMode")),
                UClassType.create("java.math.RoundingMode")));
  }

  @Test
  public void staticMethodInvocation() {
    compile(
        "import java.math.BigInteger;",
        "class StaticMethodExample {",
        "  public BigInteger example(int x) {",
        "    return BigInteger.valueOf(x);",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of("x", UPrimitiveType.INT),
                UMethodInvocation.create(
                    UStaticIdent.create(
                        "java.math.BigInteger",
                        "valueOf",
                        UMethodType.create(
                            UClassType.create("java.math.BigInteger"), UPrimitiveType.LONG)),
                    UFreeIdent.create("x")),
                UClassType.create("java.math.BigInteger")));
  }

  @Test
  public void instanceMethodInvocation() {
    compile(
        "class InstanceMethodExample {",
        "  public char example(String str) {",
        "    return str.charAt(5);",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of("str", UClassType.create("java.lang.String")),
                UMethodInvocation.create(
                    UMemberSelect.create(
                        UFreeIdent.create("str"),
                        "charAt",
                        UMethodType.create(UPrimitiveType.CHAR, UPrimitiveType.INT)),
                    ULiteral.intLit(5)),
                UPrimitiveType.CHAR));
  }

  @Test
  public void anyOf() {
    compile(
        "import com.google.errorprone.refaster.Refaster;",
        "class InstanceMethodExample {",
        "  public char example(String str) {",
        "    return str.charAt(Refaster.anyOf(1, 3, 5));",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of("str", UClassType.create("java.lang.String")),
                UMethodInvocation.create(
                    UMemberSelect.create(
                        UFreeIdent.create("str"),
                        "charAt",
                        UMethodType.create(UPrimitiveType.CHAR, UPrimitiveType.INT)),
                    UAnyOf.create(ULiteral.intLit(1), ULiteral.intLit(3), ULiteral.intLit(5))),
                UPrimitiveType.CHAR));
  }

  @Test
  public void unary() {
    compile(
        "import java.util.Arrays;",
        "class UnaryExample {",
        "  public int example(int[] array, int key) {",
        "    return ~Arrays.binarySearch(array, key);",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of(
                    "array", UArrayType.create(UPrimitiveType.INT), "key", UPrimitiveType.INT),
                UUnary.create(
                    Kind.BITWISE_COMPLEMENT,
                    UMethodInvocation.create(
                        UStaticIdent.create(
                            "java.util.Arrays",
                            "binarySearch",
                            UMethodType.create(
                                UPrimitiveType.INT,
                                UArrayType.create(UPrimitiveType.INT),
                                UPrimitiveType.INT)),
                        UFreeIdent.create("array"),
                        UFreeIdent.create("key"))),
                UPrimitiveType.INT));
  }

  @Test
  public void genericTemplate() {
    compile(
        "import java.util.List;",
        "class GenericTemplateExample {",
        "  public <E> E example(List<E> list) {",
        "    return list.get(0);",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableClassToInstanceMap.of(),
                ImmutableList.of(UTypeVar.create("E")),
                ImmutableMap.of("list", UClassType.create("java.util.List", UTypeVar.create("E"))),
                UMethodInvocation.create(
                    UMemberSelect.create(
                        UFreeIdent.create("list"),
                        "get",
                        UMethodType.create(UTypeVar.create("E"), UPrimitiveType.INT)),
                    ULiteral.intLit(0)),
                UTypeVar.create("E")));
  }

  @Test
  public void genericMethodInvocation() {
    compile(
        "import java.util.Collections;",
        "import java.util.List;",
        "class GenericTemplateExample {",
        "  public <E> List<E> example(List<E> list) {",
        "    return Collections.unmodifiableList(list);",
        "  }",
        "}");
    UTypeVar tVar = UTypeVar.create("T");
    UTypeVar eVar = UTypeVar.create("E");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableClassToInstanceMap.of(),
                ImmutableList.of(eVar),
                ImmutableMap.of("list", UClassType.create("java.util.List", eVar)),
                UMethodInvocation.create(
                    UStaticIdent.create(
                        "java.util.Collections",
                        "unmodifiableList",
                        UForAll.create(
                            ImmutableList.of(tVar),
                            UMethodType.create(
                                UClassType.create("java.util.List", tVar),
                                UClassType.create(
                                    "java.util.List",
                                    UWildcardType.create(BoundKind.EXTENDS, tVar))))),
                    UFreeIdent.create("list")),
                UClassType.create("java.util.List", eVar)));
  }

  @Test
  public void doWhile() {
    compile(
        "class DoWhileExample {",
        "  public void example(String str) {",
        "    int old = 0;",
        "    do {",
        "      old = str.indexOf(' ', old + 1);",
        "    } while (old != -1);",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            BlockTemplate.create(
                ImmutableMap.of("str", UClassType.create("java.lang.String")),
                UVariableDecl.create("old", UPrimitiveTypeTree.INT, ULiteral.intLit(0)),
                UDoWhileLoop.create(
                    UBlock.create(
                        UExpressionStatement.create(
                            UAssign.create(
                                ULocalVarIdent.create("old"),
                                UMethodInvocation.create(
                                    UMemberSelect.create(
                                        UFreeIdent.create("str"),
                                        "indexOf",
                                        UMethodType.create(
                                            UPrimitiveType.INT,
                                            UPrimitiveType.INT,
                                            UPrimitiveType.INT)),
                                    ULiteral.charLit(' '),
                                    UBinary.create(
                                        Kind.PLUS,
                                        ULocalVarIdent.create("old"),
                                        ULiteral.intLit(1)))))),
                    UParens.create(
                        UBinary.create(
                            Kind.NOT_EQUAL_TO,
                            ULocalVarIdent.create("old"),
                            ULiteral.intLit(-1))))));
  }

  @Test
  public void voidReturn() {
    compile(
        "import java.security.MessageDigest;",
        "class VoidExample {",
        "  public void example(MessageDigest md, byte[] bytes) {",
        "    md.update(bytes);",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            BlockTemplate.create(
                ImmutableMap.of(
                    "md", UClassType.create("java.security.MessageDigest"),
                    "bytes", UArrayType.create(UPrimitiveType.BYTE)),
                UExpressionStatement.create(
                    UMethodInvocation.create(
                        UMemberSelect.create(
                            UFreeIdent.create("md"),
                            "update",
                            UMethodType.create(
                                UPrimitiveType.VOID, UArrayType.create(UPrimitiveType.BYTE))),
                        UFreeIdent.create("bytes")))));
  }

  @Test
  public void arrayCast() {
    compile(
        "class ArrayCastExample {",
        "  public String[] example(Object o) {",
        "    return (String[]) o;",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of("o", UClassType.create("java.lang.Object")),
                UTypeCast.create(
                    UArrayTypeTree.create(UClassIdent.create("java.lang.String")),
                    UFreeIdent.create("o")),
                UArrayType.create(UClassType.create("java.lang.String"))));
  }

  @Test
  public void primitiveCast() {
    compile(
        "class PrimitiveCastExample {",
        "  public char example(int x) {",
        "    return (char) x;",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of("x", UPrimitiveType.INT),
                UTypeCast.create(UPrimitiveTypeTree.CHAR, UFreeIdent.create("x")),
                UPrimitiveType.CHAR));
  }

  @Test
  public void objectCast() {
    compile(
        "class ObjectCastExample {",
        "  public String example(Object o) {",
        "    return (String) o;",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of("o", UClassType.create("java.lang.Object")),
                UTypeCast.create(UClassIdent.create("java.lang.String"), UFreeIdent.create("o")),
                UClassType.create("java.lang.String")));
  }

  @Test
  public void constructor() {
    compile(
        "import java.util.ArrayList;",
        "class ConstructorExample {",
        "  public String example() {",
        "    return new String(\"foo\");",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                UNewClass.create(UClassIdent.create("java.lang.String"), ULiteral.stringLit("foo")),
                UClassType.create("java.lang.String")));
  }

  @Test
  public void forLoop() {
    compile(
        "class ForLoopExample {",
        "  public void example(int from, int to) {",
        "     for (int i = from; i < to; i++) {",
        "     }",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            BlockTemplate.create(
                ImmutableMap.of(
                    "from", UPrimitiveType.INT,
                    "to", UPrimitiveType.INT),
                UForLoop.create(
                    ImmutableList.of(
                        UVariableDecl.create(
                            "i", UPrimitiveTypeTree.INT, UFreeIdent.create("from"))),
                    UBinary.create(
                        Kind.LESS_THAN, ULocalVarIdent.create("i"), UFreeIdent.create("to")),
                    ImmutableList.of(
                        UExpressionStatement.create(
                            UUnary.create(Kind.POSTFIX_INCREMENT, ULocalVarIdent.create("i")))),
                    UBlock.create())));
  }

  @Test
  public void forLoopNoStep() {
    compile(
        "class ForLoopExample {",
        "  public void example(int from, int to) {",
        "     for (int i = from; i < to;) {",
        "     }",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            BlockTemplate.create(
                ImmutableMap.of(
                    "from", UPrimitiveType.INT,
                    "to", UPrimitiveType.INT),
                UForLoop.create(
                    ImmutableList.of(
                        UVariableDecl.create(
                            "i", UPrimitiveTypeTree.INT, UFreeIdent.create("from"))),
                    UBinary.create(
                        Kind.LESS_THAN, ULocalVarIdent.create("i"), UFreeIdent.create("to")),
                    ImmutableList.<UExpressionStatement>of(),
                    UBlock.create())));
  }

  @Test
  public void forLoopNoCondition() {
    compile(
        "class ForLoopExample {",
        "  public void example(int from, int to) {",
        "     for (int i = from; ; i++) {",
        "     }",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            BlockTemplate.create(
                ImmutableMap.of(
                    "from", UPrimitiveType.INT,
                    "to", UPrimitiveType.INT),
                UForLoop.create(
                    ImmutableList.of(
                        UVariableDecl.create(
                            "i", UPrimitiveTypeTree.INT, UFreeIdent.create("from"))),
                    null,
                    ImmutableList.of(
                        UExpressionStatement.create(
                            UUnary.create(Kind.POSTFIX_INCREMENT, ULocalVarIdent.create("i")))),
                    UBlock.create())));
  }

  @Test
  public void forLoopNoStart() {
    compile(
        "class ForLoopExample {",
        "  public void example(int from, int to) {",
        "     for (; from < to; from++) {",
        "     }",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            BlockTemplate.create(
                ImmutableMap.of(
                    "from", UPrimitiveType.INT,
                    "to", UPrimitiveType.INT),
                UForLoop.create(
                    ImmutableList.<UStatement>of(),
                    UBinary.create(
                        Kind.LESS_THAN, UFreeIdent.create("from"), UFreeIdent.create("to")),
                    ImmutableList.of(
                        UExpressionStatement.create(
                            UUnary.create(Kind.POSTFIX_INCREMENT, UFreeIdent.create("from")))),
                    UBlock.create())));
  }

  @Test
  public void parameterizedCast() {
    compile(
        "import java.util.Collection;",
        "import java.util.List;",
        "class ParameterizedCastExample {",
        "  public List<String> example(Collection<String> elements) {",
        "    return (List<String>) elements;",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of(
                    "elements",
                    UClassType.create(
                        "java.util.Collection", UClassType.create("java.lang.String"))),
                UTypeCast.create(
                    UTypeApply.create(
                        UClassIdent.create("java.util.List"),
                        UClassIdent.create("java.lang.String")),
                    UFreeIdent.create("elements")),
                UClassType.create("java.util.List", UClassType.create("java.lang.String"))));
  }

  @Test
  public void instanceOf() {
    compile(
        "class InstanceOfExample {",
        "  public boolean example(Object foo) {",
        "    return foo instanceof CharSequence;",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of("foo", UClassType.create("java.lang.Object")),
                UInstanceOf.create(
                    UFreeIdent.create("foo"), UClassIdent.create("java.lang.CharSequence")),
                UPrimitiveType.BOOLEAN));
  }

  @Test
  public void assignment() {
    compile(
        "class AssignmentExample {",
        "  public String example(String foo) {",
        "    return foo = \"bar\";",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableMap.of("foo", UClassType.create("java.lang.String")),
                UAssign.create(UFreeIdent.create("foo"), ULiteral.stringLit("bar")),
                UClassType.create("java.lang.String")));
  }

  @Test
  public void recursiveTypes() {
    compile(
        "class RecursiveTypeExample {",
        "  public <E extends Enum<E>> E example(E e) {",
        "    return e;",
        "  }",
        "}");
    Template<?> template = UTemplater.createTemplate(context, getMethodDeclaration("example"));
    UTypeVar eVar = Iterables.getOnlyElement(template.templateTypeVariables());
    assertThat(template)
        .isEqualTo(
            ExpressionTemplate.create(
                ImmutableClassToInstanceMap.of(),
                ImmutableList.of(UTypeVar.create("E", UClassType.create("java.lang.Enum", eVar))),
                ImmutableMap.of("e", eVar),
                UFreeIdent.create("e"),
                eVar));
  }

  @Test
  public void localVariable() {
    compile(
        "import java.util.ArrayList;",
        "import java.util.Comparator;",
        "import java.util.Collection;",
        "import java.util.Collections;",
        "import java.util.List;",
        "class LocalVariableExample {",
        "  public <E> void example(Collection<E> collection, Comparator<? super E> comparator) {",
        "    List<E> list = new ArrayList<E>(collection);",
        "    Collections.sort(list, comparator);",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            BlockTemplate.create(
                ImmutableList.of(UTypeVar.create("E")),
                ImmutableMap.of(
                    "collection", UClassType.create("java.util.Collection", UTypeVar.create("E")),
                    "comparator",
                        UClassType.create(
                            "java.util.Comparator",
                            UWildcardType.create(BoundKind.SUPER, UTypeVar.create("E")))),
                UVariableDecl.create(
                    "list",
                    UTypeApply.create("java.util.List", UTypeVarIdent.create("E")),
                    UNewClass.create(
                        UTypeApply.create("java.util.ArrayList", UTypeVarIdent.create("E")),
                        UFreeIdent.create("collection"))),
                UExpressionStatement.create(
                    UMethodInvocation.create(
                        UStaticIdent.create(
                            "java.util.Collections",
                            "sort",
                            UForAll.create(
                                ImmutableList.of(UTypeVar.create("T")),
                                UMethodType.create(
                                    UPrimitiveType.VOID,
                                    UClassType.create("java.util.List", UTypeVar.create("T")),
                                    UClassType.create(
                                        "java.util.Comparator",
                                        UWildcardType.create(
                                            BoundKind.SUPER, UTypeVar.create("T")))))),
                        ULocalVarIdent.create("list"),
                        UFreeIdent.create("comparator")))));
  }

  @Test
  public void throwException() {
    compile(
        "class ThrowExceptionExample {",
        "  public void example() {",
        "    throw new IllegalArgumentException();",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            BlockTemplate.create(
                UThrow.create(
                    UNewClass.create(UClassIdent.create("java.lang.IllegalArgumentException")))));
  }

  @Test
  public void forEach() {
    compile(
        "class ForEachExample {",
        "  public void example(int[] array) {",
        "    int sum = 0;",
        "    for (int value : array) {",
        "      sum += value;",
        "    }",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            BlockTemplate.create(
                ImmutableMap.of("array", UArrayType.create(UPrimitiveType.INT)),
                UVariableDecl.create("sum", UPrimitiveTypeTree.INT, ULiteral.intLit(0)),
                UEnhancedForLoop.create(
                    UVariableDecl.create("value", UPrimitiveTypeTree.INT),
                    UFreeIdent.create("array"),
                    UBlock.create(
                        UExpressionStatement.create(
                            UAssignOp.create(
                                ULocalVarIdent.create("sum"),
                                Kind.PLUS_ASSIGNMENT,
                                ULocalVarIdent.create("value")))))));
  }

  @Test
  public void synchronizd() {
    compile(
        "class SynchronizedExample {",
        "  public void example(int[] array) {",
        "    int sum = 0;",
        "    synchronized (array) {",
        "      for (int value : array) {",
        "        sum += value;",
        "      }",
        "    }",
        "  }",
        "}");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            BlockTemplate.create(
                ImmutableMap.of("array", UArrayType.create(UPrimitiveType.INT)),
                UVariableDecl.create("sum", UPrimitiveTypeTree.INT, ULiteral.intLit(0)),
                USynchronized.create(
                    UParens.create(UFreeIdent.create("array")),
                    UBlock.create(
                        UEnhancedForLoop.create(
                            UVariableDecl.create("value", UPrimitiveTypeTree.INT),
                            UFreeIdent.create("array"),
                            UBlock.create(
                                UExpressionStatement.create(
                                    UAssignOp.create(
                                        ULocalVarIdent.create("sum"),
                                        Kind.PLUS_ASSIGNMENT,
                                        ULocalVarIdent.create("value")))))))));
  }

  @Test
  public void anonymousClass() {
    compile(
        "import java.util.Collections;",
        "import java.util.Comparator;",
        "import java.util.List;",
        "class AnonymousClassExample {",
        "  public void example(List<String> list) {",
        "    Collections.sort(list, new Comparator<String>() {",
        "      @Override public int compare(String a, String b) {",
        "        return a.compareTo(b);",
        "      }",
        "    });",
        "  }",
        "}");
    UTypeVar tVar = UTypeVar.create("T");
    assertThat(UTemplater.createTemplate(context, getMethodDeclaration("example")))
        .isEqualTo(
            BlockTemplate.create(
                ImmutableMap.of(
                    "list",
                    UClassType.create("java.util.List", UClassType.create("java.lang.String"))),
                UExpressionStatement.create(
                    UMethodInvocation.create(
                        UStaticIdent.create(
                            "java.util.Collections",
                            "sort",
                            UForAll.create(
                                ImmutableList.of(tVar),
                                UMethodType.create(
                                    UPrimitiveType.VOID,
                                    UClassType.create("java.util.List", tVar),
                                    UClassType.create(
                                        "java.util.Comparator",
                                        UWildcardType.create(BoundKind.SUPER, tVar))))),
                        UFreeIdent.create("list"),
                        UNewClass.create(
                            null,
                            ImmutableList.<UExpression>of(),
                            UTypeApply.create(
                                "java.util.Comparator", UClassIdent.create("java.lang.String")),
                            ImmutableList.<UExpression>of(),
                            UClassDecl.create(
                                UMethodDecl.create(
                                    UModifiers.create(
                                        Flags.PUBLIC,
                                        UAnnotation.create(
                                            UClassIdent.create("java.lang.Override"))),
                                    "compare",
                                    UPrimitiveTypeTree.INT,
                                    ImmutableList.of(
                                        UVariableDecl.create(
                                            "a", UClassIdent.create("java.lang.String")),
                                        UVariableDecl.create(
                                            "b", UClassIdent.create("java.lang.String"))),
                                    ImmutableList.<UExpression>of(),
                                    UBlock.create(
                                        UReturn.create(
                                            UMethodInvocation.create(
                                                UMemberSelect.create(
                                                    ULocalVarIdent.create("a"),
                                                    "compareTo",
                                                    UMethodType.create(
                                                        UPrimitiveType.INT,
                                                        UClassType.create("java.lang.String"))),
                                                ULocalVarIdent.create("b")))))))))));
  }
}


text:
"use strict";

var moment = require("moment");

function parseCommit(badges, commit, callback) {
    try {
        var commitDate = new Date(commit.date);
        var day = commitDate.getDay();
        var startTime = moment("4:00am", "h:mma").utc();
        var endTime = moment("0:00am", "h:mma").utc();
        var theTime = moment(moment(commit.date).utc().format("h:mma"), "h:mma").utc();
        var isOutOfHours = theTime.isBefore(startTime) && theTime.isAfter(endTime);
        var isWeekday = (day < 6) && (day > 0);
        if (isWeekday && isOutOfHours && commit.author.user) {
            badges.push({
                "badge_img": "./img/after-midnight.jpg",
                "title": "The Witching Hour",
                "subtitle": "Beware after hours coding.",
                "description": "Awarded to developers working into the wee hours of the morning.",
                "recipient": [
                    {
                        "avatar": "https://bitbucket.org/account/" + commit.author.user.username + "/avatar/32/",
                        "username": commit.author.user.display_name,
                        "date": moment(commit.date).utc().format("LLLL")
                    }
                ]
            });
        }
        callback();
    } catch (error) {
        console.log(error);
    }
}

module.exports = {
    parseCommit: parseCommit
};


text:
package shapeless

import poly._

/**
 * Heterogenous map with type-level key/value associations that are fixed by an arbitrary
 * relation `R`.
 *
 * `HMap`s extend `Poly` and hence are also polymorphic function values with type-specific
 * cases corresponding to the map's type-level key/value associations.
 */
class HMap[R[_, _]](underlying : Map[Any, Any] = Map.empty) extends Poly1 {
  def get[K, V](k : K)(implicit ev : R[K, V]) : Option[V] = underlying.get(k).asInstanceOf[Option[V]]

  def +[K, V](kv : (K, V))(implicit ev : R[K, V]) : HMap[R] = new HMap[R](underlying+kv)
  def -[K](k : K) : HMap[R] = new HMap[R](underlying-k)

  implicit def caseRel[K, V](implicit ev : R[K, V]) = Case1[this.type, K, V](get(_).get)
}

object HMap {
  def apply[R[_, _]] = new HMapBuilder[R]

  def empty[R[_, _]] = new HMap[R]
  def empty[R[_, _]](underlying : Map[Any, Any]) = new HMap[R](underlying)
}

/**
 * Type class witnessing the existence of a natural transformation between `K[_]` and `V[_]`.
 *
 * Use this trait to represent an `HMap` relation of the form `K[T]` maps to `V[T]`.
 *
 * @author Miles Sabin
 */
class ~?>[K[_], V[_]] extends Serializable {
  class λ[K, V] extends Serializable
}

object ~?> {
  implicit def rel[K[_], V[_]] : K ~?> V = new (K ~?> V)

  implicit def witness[K[_], V[_], T](implicit rel : K ~?> V) : rel.λ[K[T], V[T]] = new rel.λ[K[T], V[T]]

  implicit def idKeyWitness[V[_], T](implicit rel : Id ~?> V) : rel.λ[T, V[T]] = new rel.λ[Id[T], V[T]]
  implicit def idValueWitness[K[_], T](implicit rel : K ~?> Id) : rel.λ[K[T], T] = new rel.λ[K[T], Id[T]]
}


text:
layout: post
title: FooBar Refactor
published: true
---

Those who have been programming for awhile are probably familiar with the classic FooBar or FizzBuzz problem. A slight varient on this problem is the final quiz item for the pre-work for [The Firehose Project](https://www.thefirehoseproject.com).

The main varient introducted is that the user specifies the number to be output. So if the user enters 7 then the program should execute the foo bar program up to and including 7. For those who need a refresher or are curious about what this problem entailed, check it out here: [Pre-work Lesson 32] (http://www.thefirehoseproject.com/prework/32).

### My original answer

Now don't laugh, but here is my original (and technically functional) answer from exactly 4 weeks ago:

    def foo_bar(num)
        if num % 3 == 0 && num % 5 == 0
            "foobar"
        elsif num % 3 == 0
            "foo"
        elsif num % 5 == 0
            "bar"
        else
            num
        end
    end

    puts "How many items do you want to see?"
    items_seen = gets.chomp.to_i + 1

    if items_seen <= 0
        puts "You can't see zero or negative numbers"
    end

    array = []

    items_seen.times do |num|
        array << foo_bar(num)
    end

    array.delete_at(0)
    puts array

### Refactor Number 1

Since I had just finished up my Blur 2 challenge problem (and was putting off Blur 3) I decided to try to refine my FooBar answer from 4 weeks ago into something a bit cleaner:

    puts "How many items do you want to see?"
    items = gets.chomp.to_i

    (1..items).each do |num|
    	if num % 15 == 0
    		puts 'foobar'
    	elsif num % 3 == 0
    		puts 'foo'
    	elsif num % 5 == 0
    		puts 'bar'
    	else
    		puts num
    	end
    end

### Refactor Number 2

That was quite a bit nicer than the first version but since this is a pretty simple problem wouldn't it be cool to get this down to just a couple of lines of code?

    puts "How many items do you want to see?"
    items = gets.chomp.to_i

    1.upto(items){|n| p "#{'fizz' if n%3==0}#{'buzz' if n%5==0}#{n if n%3!=0 && n%5!=0}"}

### Conclusion

Considering how much I struggled with this problem the first time through (took about 3 days) it's pretty amazing to me that only 4 weeks later I'm hacking it down to 3 lines of code and wondering if I can get it down to 1 line of code.

I'm pretty excited to see how much my problem solving skills improve in the next month.


text:
<?php
/**
 * Created by PhpStorm.
 * User: Kurraz
 */

namespace app\modules\game\models\game_data\locations;

use app\modules\game\models\game_data\base\BaseLocation;

class WhiteCityLocation extends BaseLocation
{
    public function serializableParams()
    {
        return [];
    }

    public static function getRoute()
    {
        return ['/game/white-city/index'];
    }
}


text:
@implementation TGSchema

+ (NSObject *)makeMutable:(NSObject *)object
{
    return object;
}

+ (NSString *)stringFromObject:(id)object
{
    if (object == nil)
        return nil;
    if ([object isKindOfClass:[NSString class]])
        return (NSString *)object;
    else if ([object isKindOfClass:[NSNumber class]])
        return [(NSNumber *)object stringValue];
    else if ([object isKindOfClass:[NSNull class]])
        return nil;

    TGLog(@"Warning: stringFromObject couldn't convert object");

    return nil;
}

+ (bool)canCreateStringFromObject:(id)object
{
    if ([object isKindOfClass:[NSString class]])
        return true;
    else if ([object isKindOfClass:[NSNumber class]])
        return true;
    else if ([object isKindOfClass:[NSNull class]])
        return false;

    return false;
}

+ (int)intFromObject:(id)object
{
    if ([object isKindOfClass:[NSNumber class]])
        return [(NSNumber *)object intValue];
    else if ([object isKindOfClass:[NSString class]])
        return [(NSString *)object intValue];
    else if ([object isKindOfClass:[NSNull class]])
        return 0;

    TGLog(@"Warning: intFromObject couldn't convert object");

    return 0;
}

+ (bool)canCreateIntFromObject:(id)object
{
    if ([object isKindOfClass:[NSNumber class]])
        return true;
    else if ([object isKindOfClass:[NSString class]])
        return true;
    else if ([object isKindOfClass:[NSNull class]])
        return false;

    return false;
}

+ (bool)boolFromObject:(id)object
{
    if ([object isKindOfClass:[NSNumber class]])
        return [(NSNumber *)object boolValue];
    else if ([object isKindOfClass:[NSString class]])
        return [(NSString *)object boolValue];
    else if ([object isKindOfClass:[NSNull class]])
        return false;

    TGLog(@"Warning: boolFromObject couldn't convert object");

    return false;
}

+ (bool)canCreateBoolFromObject:(id)object
{
    if ([object isKindOfClass:[NSNumber class]])
        return true;
    else if ([object isKindOfClass:[NSString class]])
        return true;
    else if ([object isKindOfClass:[NSNull class]])
        return false;

    return false;
}

+ (double)doubleFromObject:(id)object
{
    if ([object isKindOfClass:[NSNumber class]])
        return [(NSNumber *)object doubleValue];
    else if ([object isKindOfClass:[NSString class]])
        return [(NSString *)object doubleValue];
    else if ([object isKindOfClass:[NSNull class]])
        return 0;

    TGLog(@"Warning: doubleFromObject couldn't convert object");

    return 0;
}

+ (bool)canCreateDoubleFromObject:(id)object
{
    if ([object isKindOfClass:[NSNumber class]])
        return true;
    else if ([object isKindOfClass:[NSString class]])
        return true;
    else if ([object isKindOfClass:[NSNull class]])
        return false;

    return false;
}

+ (NSArray *)arrayFromObject:(id)object
{
    if ([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *arrayDescription = (NSDictionary *)object;
        int count = [self intFromObject:[arrayDescription objectForKey:@"count"]];
        NSArray *items = [arrayDescription objectForKey:@"items"];
        if (items != nil && [items isKindOfClass:[NSArray class]])
        {
            if (items.count != (NSUInteger)count)
            {
                TGLog(@"Warning: arrayFromObject: array.count != count");
            }
            return items;
        }
    }
    else if ([object isKindOfClass:[NSArray class]])
    {
        return object;
    }

    return nil;
}

+ (bool)canCreateArrayFromObject:(id)object
{
    if ([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *arrayDescription = (NSDictionary *)object;
        int count = [self intFromObject:[arrayDescription objectForKey:@"count"]];
        NSArray *items = [arrayDescription objectForKey:@"items"];
        if (items != nil && [items isKindOfClass:[NSArray class]])
        {
            if ((int)items.count != count)
            {
                return false;
            }
            return true;
        }
    }
    else if ([object isKindOfClass:[NSArray class]])
    {
        return true;
    }

    return false;
}

+ (NSObject *)checkSchema:(NSObject *)__unused object
{
    TGLog(@"Error: TGSchema::checkSchema: no default implementation provided");
    return nil;
}

@end


text:
<template>
    <lightning-layout>
        <lightning-layout-item size="12" class="slds-p-left_small">
            <lightning-layout>
                <template if:true={isAllocations}>
                    <lightning-layout-item size="12">
                        {uiTitle}

{CUSTOM_LABELS.commonGeneralAccountUnit}

{CUSTOM_LABELS.commonAmount}

{CUSTOM_LABELS.commonPercent}

                    </lightning-layout-item>
                </template>
                <template if:true={isTokenizeCard}>
                    <lightning-layout-item size="12">

                            {CUSTOM_LABELS.geTextFieldBundlePaymentMethod }

                    </lightning-layout-item>
                </template>
            </lightning-layout>
        </lightning-layout-item>
    </lightning-layout>
</template>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using ZuoraMagic.Entities;
using ZuoraMagic.ORM.BaseRequestTemplates;

namespace ZuoraMagic.SoapApi.RequestTemplates
{
    [Serializable]
    public class BasicCrudTemplate
    {
        [XmlIgnore]
        public IEnumerable<ZObject> ZObjects { get; set; }

        [XmlElement("zObjects", Namespace = ZuoraNamespaces.Request)]
        public List<ZObject> Items
        {
            get
            {
                return ZObjects.ToList();
            }
        }
    }
}


text:
django-pushall - это приложение для поддержки системы Push-уведомлений PushAll для фреймворка Django.
Подробное описание системы PushAll на [официальном сайте](https://pushall.ru)

Поддерживает версии Django>=1.8, Python 2.7, 3.4, 3.5

#Установка
Установка

    pip install django-pushall

Добавить приложение в _INSTALLED_APPS_

    INSTALLED_APPS = [
        ...
        'django_pushall',
        ...
    ]

Выполнить команду

    python manage.py makemigrations django_pushall

    python manage.py migrate django_pushall

для создания таблиц моделей

Если вы будете использовать [Callback](https://pushall.ru/blog/api) для определения подписавшихся пользователей,
то необходимо добавить в _urls.py_

    urlpatterns = [
        ...
        url(r'^pushall/', include('django_pushall.urls')),
        ...
    ]

Укажите настройки канала в _settings.py_

    PUSHALL_CANAL_ID = 1234
    PUSHALL_API_KEY = 'e789ed7bea3cbd86e951e4b268b45ed8'

_PUSHALL_CANAL_ID_ - идентификатор канала. _PUSHALL_API_KEY_ - ключ API канала на [Pushall.ru](Pushall.ru)
Вы получите эти настройки при создании канала на сайте

Если вы планируете отправлять уведомления самому себе, то укажите в _settings.py_

    PUSHALL_USER_ID = 01234
    PUSHALL_USER_KEY = '3c2f2dc68c59b65ba9c789fd3a3fb4f6'

_PUSHALL_USER_ID_ - идентификатор вашей учетной записи на сайте [Pushall.ru](Pushall.ru).
_PUSHALL_USER_KEY_ - ключ API вашей учетной записи
Получить эти настройки можно в личном кабинете на сайте _Pushall.ru -> Администрирование -> API общее_

#Отправка уведомлений
##Отправка самому себе

    from django_pushall import Pushall

    Pushall.self('Заголовок', 'Текст сообщения')  # простое уведомление
    Pushall.self('Заголовок', 'Текст сообщения', url='http://site.ru')  # уведомление со ссылкой
    Pushall.self('Заголовок', 'Текст сообщения', icon='http://site.ru/icon.png')  # уведомление со своей иконкой
    Pushall.self('Заголовок', 'Текст сообщения', ttl=2160000)  # уведомление со временем жизни в секундах

Метод _Pushall.self_ возвращает идентификатор уведомления

##Отправка всех пользователям канала

    from django_pushall import Pushall

    Pushall.broadcast('Заголовок', 'Текст сообщения')

Возвращает идентификатор уведомления.

##Отправка подписчику канала

    from django_pushall import Pushall

    Pushall.unicast(12345, 'Заголовок', 'Текст сообщения') #отправка уведомления подписчику с идентификатором 12345

Возвращает идентификатор уведомления

##Отправка нескольким подписчикам канала

    from django_pushall import Pushall

    Pushall.milticast([12345, 12346, 12347], 'Заголовок', 'Текст сообщения') #отправка уведомления подписчикам с идентификаторами 12345, 12346, 12347

Возвращает идентификатор уведомления

##Дополнительные параметры отправки уведомлений

Указание ссылки для переходе по клику на уведомление

    Pushall.broadcast('Заголовок', 'Текст сообщения', url='http://site.ru')

Указание своей иконки уведомления

    Pushall.broadcast('Заголовок', 'Текст сообщения', icon='http://site.ru/icon.png')

Время жизни уведомления в секундах

    Pushall.broadcast('Заголовок', 'Текст сообщения', ttl=2160000)

Скрытие уведомлений из истории канала

    Pushall.broadcast('Заголовок', 'Текст сообщения', hidden=PushallAPI.HIDDEN_ALL) #скрыть уведомление из истории пользователей после отправки
    Pushall.broadcast('Заголовок', 'Текст сообщения', hidden=PushallAPI.HIDDEN_FEED) #скрыть уведомление из истории канала

Приоритет уведомления

    Pushall.broadcast('Заголовок', 'Текст сообщения', priority=PushallAPI.PRIORITY_DEFAULT) #приоритет по-умолчанию
    Pushall.broadcast('Заголовок', 'Текст сообщения', priority=PushallAPI.PRIORITY_LOW) #низкий приоритет. Не будит мобильные устройства
    Pushall.broadcast('Заголовок', 'Текст сообщения', priority=PushallAPI.PRIORITY_HIGH) #высокий приоритет. Будит мобильные устройства

Включение и отключение пользовательской фильтрации уведомлений

    Pushall.broadcast('Заголовок', 'Текст сообщения', filter=PushallAPI.FILTER_DISABLE) #принудительно отключить фильтрацию
    Pushall.unicast(12345, 'Заголовок', 'Текст сообщения', filter=PushallAPI.FILTER_ENABLE) #принудительно включить фильтрацию

##Просмотр состояния ленты канала

    from django_pushall import Pushall

    print(Pushall.show_list()) #вывод на экран состояния ленты канала
    print(Pushall.show_list(lid=1000)) #вывод на экран состояния уведомления c идентификатором 1000

##Просмотр списка подписчиков канала

    from django_pushall import Pushall

    print(Pushall.show_users()) #вывод на экран списка подписчиков
    print(Pushall.show_users(uid=12345)) #вывод на экран информации о подписчике с идентификатором 12345

#Сбор подписчиков
Чтобы приложение знало какие пользователи подписались на ваш канал необходимо использовать Callback подписки.
Для этого необходимо добавить в _urls.py_

    urlpatterns = [
        ...
        url(r'^pushall/', include('django_pushall.urls')),
        ...
    ]

и указать в настройках канала на сайте Pushall.ru **Callback-адрес для получения ID**

    http://ваш-url/pushall/callback

После подписки пользователь будет переходить по этому адресу. Приложение получит его UID в системе и далее перенаправит на главную страницу вашего сайта
Изменить адрес редиректа можно в _setting.py_

    PUSHALL_CALLBACK_REDIRECT = 'адрес редиректа'

Все подписчики привязываются к пользователям сайта.
Получить список подписчиков можно так

    from django_pushall.models import PushUser

    subscribers = PushUser.objects.all()

##Отправить уведомление подписчику

    from django_pushall.models import PushUser

    subscriber = PushUser.objects.get(uid=12345)
    subscriber.notice('Заголовок', 'Текст')

Можно использовать параметры дополнительные параметры уведомлений

##Отправить уведомление пользователю сайта

    from django.contrib.auth.models import User
    from django_pushall.models import PushUser

    user = User.objects.get(id=1)
    PushUser.notice_to_user(user, 'Заголовок', 'Текст')

Можно использовать параметры дополнительные параметры уведомлений


text:
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
////////////////////////////////////////////////////////////////////////////////

package com.puppycrawl.tools.checkstyle.checks.coding;

import static com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryParenthesesCheck.MSG_ASSIGN;
import static com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryParenthesesCheck.MSG_EXPR;
import static com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryParenthesesCheck.MSG_IDENT;
import static com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryParenthesesCheck.MSG_LITERAL;
import static com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryParenthesesCheck.MSG_RETURN;
import static com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryParenthesesCheck.MSG_STRING;

import java.io.File;

import org.apache.commons.lang3.ArrayUtils;
import org.junit.Assert;
import org.junit.Test;

import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;

/**
 * Test fixture for the UnnecessaryParenthesesCheck.
 *
 * @author  Eric K. Roe
 */
public class UnnecessaryParenthesesCheckTest extends BaseCheckTestSupport {
    private static final String TEST_FILE = "coding" + File.separator
        + "InputUnnecessaryParentheses.java";

    @Test
    public void testDefault() throws Exception {
        final DefaultConfiguration checkConfig =
            createCheckConfig(UnnecessaryParenthesesCheck.class);

        final String[] expected = {
            "5:22: " + getCheckMessage(MSG_ASSIGN),
            "5:29: " + getCheckMessage(MSG_EXPR),
            "5:31: " + getCheckMessage(MSG_IDENT, "i"),
            "5:46: " + getCheckMessage(MSG_ASSIGN),
            "6:15: " + getCheckMessage(MSG_ASSIGN),
            "7:14: " + getCheckMessage(MSG_IDENT, "x"),
            "7:17: " + getCheckMessage(MSG_ASSIGN),
            "8:15: " + getCheckMessage(MSG_ASSIGN),
            "9:14: " + getCheckMessage(MSG_IDENT, "x"),
            "9:17: " + getCheckMessage(MSG_ASSIGN),
            "12:22: " + getCheckMessage(MSG_ASSIGN),
            "12:30: " + getCheckMessage(MSG_IDENT, "i"),
            "12:46: " + getCheckMessage(MSG_ASSIGN),
            "16:17: " + getCheckMessage(MSG_LITERAL, "0"),
            "26:11: " + getCheckMessage(MSG_ASSIGN),
            "30:11: " + getCheckMessage(MSG_ASSIGN),
            "32:11: " + getCheckMessage(MSG_ASSIGN),
            "34:11: " + getCheckMessage(MSG_ASSIGN),
            "35:16: " + getCheckMessage(MSG_IDENT, "a"),
            "36:14: " + getCheckMessage(MSG_IDENT, "a"),
            "36:20: " + getCheckMessage(MSG_IDENT, "b"),
            "36:26: " + getCheckMessage(MSG_LITERAL, "600"),
            "36:40: " + getCheckMessage(MSG_LITERAL, "12.5f"),
            "36:56: " + getCheckMessage(MSG_IDENT, "arg2"),
            "37:14: " + getCheckMessage(MSG_STRING, "\"this\""),
            "37:25: " + getCheckMessage(MSG_STRING, "\"that\""),
            "38:11: " + getCheckMessage(MSG_ASSIGN),
            "38:14: " + getCheckMessage(MSG_STRING, "\"this is a really, really...\""),
            "40:16: " + getCheckMessage(MSG_RETURN),
            "44:21: " + getCheckMessage(MSG_LITERAL, "1"),
            "44:26: " + getCheckMessage(MSG_LITERAL, "13.5"),
            "45:22: " + getCheckMessage(MSG_LITERAL, "true"),
            "46:17: " + getCheckMessage(MSG_IDENT, "b"),
            "50:17: " + getCheckMessage(MSG_ASSIGN),
            "52:11: " + getCheckMessage(MSG_ASSIGN),
            "54:16: " + getCheckMessage(MSG_RETURN),
            "64:13: " + getCheckMessage(MSG_EXPR),
            "68:16: " + getCheckMessage(MSG_EXPR),
            "73:19: " + getCheckMessage(MSG_EXPR),
            "74:23: " + getCheckMessage(MSG_LITERAL, "4000"),
            "79:19: " + getCheckMessage(MSG_ASSIGN),
            "81:11: " + getCheckMessage(MSG_ASSIGN),
            "81:16: " + getCheckMessage(MSG_LITERAL, "3"),
            "82:27: " + getCheckMessage(MSG_ASSIGN),
        };

        verify(checkConfig, getPath(TEST_FILE), expected);
    }

    @Test
    public void test15Extensions() throws Exception {
        final DefaultConfiguration checkConfig = createCheckConfig(UnnecessaryParenthesesCheck.class);
        final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY;
        verify(checkConfig, getPath("Input15Extensions.java"), expected);
    }

    @Test
    public void testTokensNotNull() {
        UnnecessaryParenthesesCheck check = new UnnecessaryParenthesesCheck();
        Assert.assertNotNull(check.getDefaultTokens());
        Assert.assertNotNull(check.getAcceptableTokens());
        Assert.assertNotNull(check.getRequiredTokens());
    }
}


text:
<?php
/*
 * Programmer: Ben Matson
 * Date create: October 27, 2015
 * Purpose: This model retreives information on seller listings in the listings table
*/

class Listing_model extends CI_Model{
	public function __construct(){
		$this->load->database();
	}

// CREATE methods
	// the seller wants to create a new listing
	public function createListing($values){
		date_default_timezone_get("America/Denver");
		// Escape all values passed to the function
		$sID = $values['sellerID'];
		$title = $this->db->escape($values['title']);
		$description = $this->db->escape($values['description']);
		$pickup = $this->db->escape($values['pickup']);
		$price = $this->db->escape($values['price']);
		$inventory = $this->db->escape($values['inventory']);
		$private = $this->db->escape($values['private']);

		// Perform the insertion now
		$query = $this->db->query("insert into Listings (sellerID,title,description,pickup,
									price,status,start,rating,inventory,private) values(
									".$sID.",
									".$title.",
									".$description.",
									".$pickup.",
									".$price.",
									0, NOW(), 0,
									".$inventory.",
									".$private.");");

		$result = $this->db->insert_id();

		return $result;

	}

// READ methods
	// Functions to access different aspects of the listings table
	public function getListingsByArea($area){
		if(! empty($area)){
			$area = $this->db->escape($area);
			$query = $this->db->query("select u.fname, u.lname, u.userID, u.email, s.sellerID, s.breeds, s.eggrate, s.feed, s.city, s.lat, s.lng, s.xroad, l.price, l.inventory, l.listID, l.start, l.title, l.description, l.pickup from Users u join Sellers s on u.sellerID = s.sellerID join Listings l on s.sellerID = l.sellerID where s.city=".$area." and finish is null and private=0");
			$result = $query->result_array();
			return $result;
		}
	}

	// locate a public or private listing from a seller
	public function getSellerListing($sellerID, $private=0){
		$result = -1;
		if(!empty($sellerID)){
			$query = $this->db->query("select l.title, l.description, l.price, l.inventory, l.listID, l.sellerID, l.price, l.pickup, l.status, l.finish, l.rating, l.private, s.street, s.city, s.pcode, s.state, s.xroad from Listings l join Sellers s on l.sellerID = s.sellerID where l.sellerID=".$this->db->escape($sellerID)." and l.private=".$this->db->escape($private)." and l.finish is null");
			if(!empty($query)){
				$result = $query->result_array();
			}
		}

		if(empty($result)){
			return null;
		}else{
			return $result[0];
		}
	}

	// locate an individual listing by its ID
	public function getListing($lID){
		$result = -1;
		if(!empty($lID)){
			$query = $this->db->query("select u.fname, u.lname, u.userID, u.email, s.sellerID, s.breeds, s.eggrate, s.feed, s.city, s.lat, s.lng, s.xroad, l.price, l.inventory, l.listID, l.start, l.title, l.description, l.pickup from Users u join Sellers s on u.sellerID = s.sellerID join Listings l on s.sellerID = l.sellerID where finish is null and private=0 and listID=".$this->db->escape($lID));
			if(!empty($query)){
				$result = $query->result_array();
			}
		}

		return $result[0];
	}

	// Based upon the filters given, search for listings matching this criteria
	public function getFilteredListings($filters){
		$query = $this->db->query("select u.fname, u.lname, u.userID, s.sellerID, s.breeds, s.eggrate, s.feed, s.city, s.lat, s.lng, s.xroad, l.price, l.inventory, l.listID  from Users u join Sellers s on u.sellerID = s.sellerID join Listings l on s.sellerID = l.sellerID where finish is null and private=0");
		$listResult = $query->result_array();

		$result = $this->filter($listResult, $filters['breeds'], "breeds");
		$result = $this->filter($result, $filters['feed'], "feed");
		$result = $this->rangeFilter($result, $filters['inventory'], "inventory");
		$result = $this->rangeFilter($result, $filters['price'], "price");
		return $result;
	}

// UPDATE methods
	// Given a set of parameters, update an entry in the database
	public function updateListing($values){
		$title = $this->db->escape($values['title']);
		$description = $this->db->escape($values['description']);
		$pickup = $this->db->escape($values['pickup']);
		$inventory = $this->db->escape($values['inventory']);
		$price = $this->db->escape($values['price']);

		$query = $this->db->query("update Listings set title=".$title.
									", description=".$description.
									", pickup=".$pickup.
									", price=".$price.
									", inventory=".$inventory.
									" where listID=".$values['lID']);
		return $query;

	}

// DELETE methods
	// The seller no longer wants a listing displayed
	public function removeListing($lID){
		$query = $this->db->query("delete from Listings where listID=".$lID);
	}

// MISC methods
	private function filter($list, $filter, $type){
		$result = [];

		// check to make sure there is a filter to apply to
		if(!empty($filter)){
			// filter out the requested entries in the listing
			foreach($list as $key=>$listing){
				$found = FALSE;		// determines if an entry met the requirements

				// if there is more than one requirement, break it down and test each one
				foreach(explode(",", $filter) as $req){
					if(stristr($listing[$type], $req) != FALSE){
						// an entry matched the requirement, keep it
						$found = TRUE;
						break;
					}
				}

				// Add an entry to the result if the req was found
				// This is so that the entry doesn't appear more than once if multiple
				// requirements were met
				if($found == TRUE){
					array_push($result, $listing);
				}

			}
		}else{
			$result = $list;
		}

		return $result;
	}

	private function rangeFilter($list, $filter, $type){
		$result = [];

		// check to make sure there is a filter to apply to
		if(!empty($filter)){
			// filter out the requested entries in the listing
			foreach($list as $key=>$listing){
				$range = explode(",", $filter);		// break down the range so that it can be checked
				if($listing[$type] >= $range[0] and $listing[$type] <= $range[1]){
					// the entry met the criteria
					array_push($result, $listing);
				}
			}
		}else{
			$result = $list;
		}

		return $result;
	}
}// End of the Model Class


text:
with year_total as (
 select c_customer_id customer_id
       ,c_first_name customer_first_name
       ,c_last_name customer_last_name
       ,d_year as year
       --,stddev_samp(ss_net_paid) year_total
       ,cast(stddev_samp(ss_net_paid) as int) year_total
       ,'s' sale_type
 from customer
     ,store_sales
     ,date_dim
 where c_customer_sk = ss_customer_sk
   --removed Cloudera cheat
   --and ss_sold_date_sk between 2451545 and 2452275
   and ss_sold_date_sk = d_date_sk
   and d_year in (2000,2000+1)
 group by c_customer_id
         ,c_first_name
         ,c_last_name
         ,d_year
 union all
 select c_customer_id customer_id
       ,c_first_name customer_first_name
       ,c_last_name customer_last_name
       ,d_year as year
       ,cast(stddev_samp(ws_net_paid) as int) year_total
       ,'w' sale_type
 from customer
     ,web_sales
     ,date_dim
 where c_customer_sk = ws_bill_customer_sk
   --removed Cloudera cheat
   --and ws_sold_date_sk between 2451545 and 2452275
   and ws_sold_date_sk = d_date_sk
   and d_year in (2000,2000+1)
 group by c_customer_id
         ,c_first_name
         ,c_last_name
         ,d_year
         )
 select
        t_s_secyear.customer_id col1, t_s_secyear.customer_first_name col2, t_s_secyear.customer_last_name col3 from year_total t_s_firstyear
     ,year_total t_s_secyear
     ,year_total t_w_firstyear
     ,year_total t_w_secyear
 where t_s_secyear.customer_id = t_s_firstyear.customer_id
         and t_s_firstyear.customer_id = t_w_secyear.customer_id
         and t_s_firstyear.customer_id = t_w_firstyear.customer_id
         and t_s_firstyear.sale_type = 's'
         and t_w_firstyear.sale_type = 'w'
         and t_s_secyear.sale_type = 's'
         and t_w_secyear.sale_type = 'w'
         and t_s_firstyear.year = 2000
         and t_s_secyear.year = 2000+1
         and t_w_firstyear.year = 2000
         and t_w_secyear.year = 2000+1
         and t_s_firstyear.year_total > 0
         and t_w_firstyear.year_total > 0
         and case when t_w_firstyear.year_total > 0 then t_w_secyear.year_total / t_w_firstyear.year_total else null end
           > case when t_s_firstyear.year_total > 0 then t_s_secyear.year_total / t_s_firstyear.year_total else null end
 order by 1,3,2
 limit 100;
-- end query 74 in stream 0 using template query74.tpl