text:
from __future__ import annotations

import functools
import operator
from collections import defaultdict
from contextlib import suppress
from typing import (
    TYPE_CHECKING,
    Any,
    Callable,
    Dict,
    Generic,
    Hashable,
    Iterable,
    Mapping,
    Tuple,
    Type,
    TypeVar,
    cast,
)

import numpy as np
import pandas as pd

from . import dtypes
from .common import DataWithCoords
from .indexes import Index, Indexes, PandasIndex, PandasMultiIndex, indexes_all_equal
from .utils import is_dict_like, is_full_slice, safe_cast_to_index
from .variable import Variable, as_compatible_data, calculate_dimensions

if TYPE_CHECKING:
    from .dataarray import DataArray
    from .dataset import Dataset
    from .types import JoinOptions, T_DataArray, T_DataArrayOrSet, T_Dataset

DataAlignable = TypeVar("DataAlignable", bound=DataWithCoords)

def reindex_variables(
    variables: Mapping[Any, Variable],
    dim_pos_indexers: Mapping[Any, Any],
    copy: bool = True,
    fill_value: Any = dtypes.NA,
    sparse: bool = False,
) -> dict[Hashable, Variable]:
    """Conform a dictionary of variables onto a new set of variables reindexed
    with dimension positional indexers and possibly filled with missing values.

    Not public API.

    """
    new_variables = {}
    dim_sizes = calculate_dimensions(variables)

    masked_dims = set()
    unchanged_dims = set()
    for dim, indxr in dim_pos_indexers.items():
        # Negative values in dim_pos_indexers mean values missing in the new index
        # See ``Index.reindex_like``.
        if (indxr < 0).any():
            masked_dims.add(dim)
        elif np.array_equal(indxr, np.arange(dim_sizes.get(dim, 0))):
            unchanged_dims.add(dim)

    for name, var in variables.items():
        if isinstance(fill_value, dict):
            fill_value_ = fill_value.get(name, dtypes.NA)
        else:
            fill_value_ = fill_value

        if sparse:
            var = var._as_sparse(fill_value=fill_value_)
        indxr = tuple(
            slice(None) if d in unchanged_dims else dim_pos_indexers.get(d, slice(None))
            for d in var.dims
        )
        needs_masking = any(d in masked_dims for d in var.dims)

        if needs_masking:
            new_var = var._getitem_with_mask(indxr, fill_value=fill_value_)
        elif all(is_full_slice(k) for k in indxr):
            # no reindexing necessary
            # here we need to manually deal with copying data, since
            # we neither created a new ndarray nor used fancy indexing
            new_var = var.copy(deep=copy)
        else:
            new_var = var[indxr]

        new_variables[name] = new_var

    return new_variables

CoordNamesAndDims = Tuple[Tuple[Hashable, Tuple[Hashable, ...]], ...]
MatchingIndexKey = Tuple[CoordNamesAndDims, Type[Index]]
NormalizedIndexes = Dict[MatchingIndexKey, Index]
NormalizedIndexVars = Dict[MatchingIndexKey, Dict[Hashable, Variable]]

class Aligner(Generic[DataAlignable]):
    """Implements all the complex logic for the re-indexing and alignment of Xarray
    objects.

    For internal use only, not public API.
    Usage:

    aligner = Aligner(*objects, **kwargs)
    aligner.align()
    aligned_objects = aligner.results

    """

    objects: tuple[DataAlignable, ...]
    results: tuple[DataAlignable, ...]
    objects_matching_indexes: tuple[dict[MatchingIndexKey, Index], ...]
    join: str
    exclude_dims: frozenset[Hashable]
    exclude_vars: frozenset[Hashable]
    copy: bool
    fill_value: Any
    sparse: bool
    indexes: dict[MatchingIndexKey, Index]
    index_vars: dict[MatchingIndexKey, dict[Hashable, Variable]]
    all_indexes: dict[MatchingIndexKey, list[Index]]
    all_index_vars: dict[MatchingIndexKey, list[dict[Hashable, Variable]]]
    aligned_indexes: dict[MatchingIndexKey, Index]
    aligned_index_vars: dict[MatchingIndexKey, dict[Hashable, Variable]]
    reindex: dict[MatchingIndexKey, bool]
    reindex_kwargs: dict[str, Any]
    unindexed_dim_sizes: dict[Hashable, set]
    new_indexes: Indexes[Index]

    def __init__(
        self,
        objects: Iterable[DataAlignable],
        join: str = "inner",
        indexes: Mapping[Any, Any] = None,
        exclude_dims: Iterable = frozenset(),
        exclude_vars: Iterable[Hashable] = frozenset(),
        method: str = None,
        tolerance: int | float | Iterable[int | float] | None = None,
        copy: bool = True,
        fill_value: Any = dtypes.NA,
        sparse: bool = False,
    ):
        self.objects = tuple(objects)
        self.objects_matching_indexes = ()

        if join not in ["inner", "outer", "override", "exact", "left", "right"]:
            raise ValueError(f"invalid value for join: {join}")
        self.join = join

        self.copy = copy
        self.fill_value = fill_value
        self.sparse = sparse

        if method is None and tolerance is None:
            self.reindex_kwargs = {}
        else:
            self.reindex_kwargs = {"method": method, "tolerance": tolerance}

        if isinstance(exclude_dims, str):
            exclude_dims = [exclude_dims]
        self.exclude_dims = frozenset(exclude_dims)
        self.exclude_vars = frozenset(exclude_vars)

        if indexes is None:
            indexes = {}
        self.indexes, self.index_vars = self._normalize_indexes(indexes)

        self.all_indexes = {}
        self.all_index_vars = {}
        self.unindexed_dim_sizes = {}

        self.aligned_indexes = {}
        self.aligned_index_vars = {}
        self.reindex = {}

        self.results = tuple()

    def _normalize_indexes(
        self,
        indexes: Mapping[Any, Any],
    ) -> tuple[NormalizedIndexes, NormalizedIndexVars]:
        """Normalize the indexes/indexers used for re-indexing or alignment.

        Return dictionaries of xarray Index objects and coordinate variables
        such that we can group matching indexes based on the dictionary keys.

        """
        if isinstance(indexes, Indexes):
            xr_variables = dict(indexes.variables)
        else:
            xr_variables = {}

        xr_indexes: dict[Hashable, Index] = {}
        for k, idx in indexes.items():
            if not isinstance(idx, Index):
                if getattr(idx, "dims", (k,)) != (k,):
                    raise ValueError(
                        f"Indexer has dimensions {idx.dims} that are different "
                        f"from that to be indexed along '{k}'"
                    )
                data = as_compatible_data(idx)
                pd_idx = safe_cast_to_index(data)
                pd_idx.name = k
                if isinstance(pd_idx, pd.MultiIndex):
                    idx = PandasMultiIndex(pd_idx, k)
                else:
                    idx = PandasIndex(pd_idx, k, coord_dtype=data.dtype)
                xr_variables.update(idx.create_variables())
            xr_indexes[k] = idx

        normalized_indexes = {}
        normalized_index_vars = {}
        for idx, index_vars in Indexes(xr_indexes, xr_variables).group_by_index():
            coord_names_and_dims = []
            all_dims: set[Hashable] = set()

            for name, var in index_vars.items():
                dims = var.dims
                coord_names_and_dims.append((name, dims))
                all_dims.update(dims)

            exclude_dims = all_dims & self.exclude_dims
            if exclude_dims == all_dims:
                continue
            elif exclude_dims:
                excl_dims_str = ", ".join(str(d) for d in exclude_dims)
                incl_dims_str = ", ".join(str(d) for d in all_dims - exclude_dims)
                raise ValueError(
                    f"cannot exclude dimension(s) {excl_dims_str} from alignment because "
                    "these are used by an index together with non-excluded dimensions "
                    f"{incl_dims_str}"
                )

            key = (tuple(coord_names_and_dims), type(idx))
            normalized_indexes[key] = idx
            normalized_index_vars[key] = index_vars

        return normalized_indexes, normalized_index_vars

    def find_matching_indexes(self) -> None:
        all_indexes: dict[MatchingIndexKey, list[Index]]
        all_index_vars: dict[MatchingIndexKey, list[dict[Hashable, Variable]]]
        all_indexes_dim_sizes: dict[MatchingIndexKey, dict[Hashable, set]]
        objects_matching_indexes: list[dict[MatchingIndexKey, Index]]

        all_indexes = defaultdict(list)
        all_index_vars = defaultdict(list)
        all_indexes_dim_sizes = defaultdict(lambda: defaultdict(set))
        objects_matching_indexes = []

        for obj in self.objects:
            obj_indexes, obj_index_vars = self._normalize_indexes(obj.xindexes)
            objects_matching_indexes.append(obj_indexes)
            for key, idx in obj_indexes.items():
                all_indexes[key].append(idx)
            for key, index_vars in obj_index_vars.items():
                all_index_vars[key].append(index_vars)
                for dim, size in calculate_dimensions(index_vars).items():
                    all_indexes_dim_sizes[key][dim].add(size)

        self.objects_matching_indexes = tuple(objects_matching_indexes)
        self.all_indexes = all_indexes
        self.all_index_vars = all_index_vars

        if self.join == "override":
            for dim_sizes in all_indexes_dim_sizes.values():
                for dim, sizes in dim_sizes.items():
                    if len(sizes) > 1:
                        raise ValueError(
                            "cannot align objects with join='override' with matching indexes "
                            f"along dimension {dim!r} that don't have the same size"
                        )

    def find_matching_unindexed_dims(self) -> None:
        unindexed_dim_sizes = defaultdict(set)

        for obj in self.objects:
            for dim in obj.dims:
                if dim not in self.exclude_dims and dim not in obj.xindexes.dims:
                    unindexed_dim_sizes[dim].add(obj.sizes[dim])

        self.unindexed_dim_sizes = unindexed_dim_sizes

    def assert_no_index_conflict(self) -> None:
        """Check for uniqueness of both coordinate and dimension names across all sets
        of matching indexes.

        We need to make sure that all indexes used for re-indexing or alignment
        are fully compatible and do not conflict each other.

        Note: perhaps we could choose less restrictive constraints and instead
        check for conflicts among the dimension (position) indexers returned by
        `Index.reindex_like()` for each matching pair of object index / aligned
        index?
        (ref: https://github.com/pydata/xarray/issues/1603#issuecomment-442965602)

        """
        matching_keys = set(self.all_indexes) | set(self.indexes)

        coord_count: dict[Hashable, int] = defaultdict(int)
        dim_count: dict[Hashable, int] = defaultdict(int)
        for coord_names_dims, _ in matching_keys:
            dims_set: set[Hashable] = set()
            for name, dims in coord_names_dims:
                coord_count[name] += 1
                dims_set.update(dims)
            for dim in dims_set:
                dim_count[dim] += 1

        for count, msg in [(coord_count, "coordinates"), (dim_count, "dimensions")]:
            dup = {k: v for k, v in count.items() if v > 1}
            if dup:
                items_msg = ", ".join(
                    f"{k!r} ({v} conflicting indexes)" for k, v in dup.items()
                )
                raise ValueError(
                    "cannot re-index or align objects with conflicting indexes found for "
                    f"the following {msg}: {items_msg}\n"
                    "Conflicting indexes may occur when\n"
                    "- they relate to different sets of coordinate and/or dimension names\n"
                    "- they don't have the same type\n"
                    "- they may be used to reindex data along common dimensions"
                )

    def _need_reindex(self, dims, cmp_indexes) -> bool:
        """Whether or not we need to reindex variables for a set of
        matching indexes.

        We don't reindex when all matching indexes are equal for two reasons:
        - It's faster for the usual case (already aligned objects).
        - It ensures it's possible to do operations that don't require alignment
          on indexes with duplicate values (which cannot be reindexed with
          pandas). This is useful, e.g., for overwriting such duplicate indexes.

        """
        has_unindexed_dims = any(dim in self.unindexed_dim_sizes for dim in dims)
        return not (indexes_all_equal(cmp_indexes)) or has_unindexed_dims

    def _get_index_joiner(self, index_cls) -> Callable:
        if self.join in ["outer", "inner"]:
            return functools.partial(
                functools.reduce,
                functools.partial(index_cls.join, how=self.join),
            )
        elif self.join == "left":
            return operator.itemgetter(0)
        elif self.join == "right":
            return operator.itemgetter(-1)
        elif self.join == "override":
            # We rewrite all indexes and then use join='left'
            return operator.itemgetter(0)
        else:
            # join='exact' return dummy lambda (error is raised)
            return lambda _: None

    def align_indexes(self) -> None:
        """Compute all aligned indexes and their corresponding coordinate variables."""

        aligned_indexes = {}
        aligned_index_vars = {}
        reindex = {}
        new_indexes = {}
        new_index_vars = {}

        for key, matching_indexes in self.all_indexes.items():
            matching_index_vars = self.all_index_vars[key]
            dims = {d for coord in matching_index_vars[0].values() for d in coord.dims}
            index_cls = key[1]

            if self.join == "override":
                joined_index = matching_indexes[0]
                joined_index_vars = matching_index_vars[0]
                need_reindex = False
            elif key in self.indexes:
                joined_index = self.indexes[key]
                joined_index_vars = self.index_vars[key]
                cmp_indexes = list(
                    zip(
                        [joined_index] + matching_indexes,
                        [joined_index_vars] + matching_index_vars,
                    )
                )
                need_reindex = self._need_reindex(dims, cmp_indexes)
            else:
                if len(matching_indexes) > 1:
                    need_reindex = self._need_reindex(
                        dims,
                        list(zip(matching_indexes, matching_index_vars)),
                    )
                else:
                    need_reindex = False
                if need_reindex:
                    if self.join == "exact":
                        raise ValueError(
                            "cannot align objects with join='exact' where "
                            "index/labels/sizes are not equal along "
                            "these coordinates (dimensions): "
                            + ", ".join(f"{name!r} {dims!r}" for name, dims in key[0])
                        )
                    joiner = self._get_index_joiner(index_cls)
                    joined_index = joiner(matching_indexes)
                    if self.join == "left":
                        joined_index_vars = matching_index_vars[0]
                    elif self.join == "right":
                        joined_index_vars = matching_index_vars[-1]
                    else:
                        joined_index_vars = joined_index.create_variables()
                else:
                    joined_index = matching_indexes[0]
                    joined_index_vars = matching_index_vars[0]

            reindex[key] = need_reindex
            aligned_indexes[key] = joined_index
            aligned_index_vars[key] = joined_index_vars

            for name, var in joined_index_vars.items():
                new_indexes[name] = joined_index
                new_index_vars[name] = var

        # Explicitly provided indexes that are not found in objects to align
        # may relate to unindexed dimensions so we add them too
        for key, idx in self.indexes.items():
            if key not in aligned_indexes:
                index_vars = self.index_vars[key]
                reindex[key] = False
                aligned_indexes[key] = idx
                aligned_index_vars[key] = index_vars
                for name, var in index_vars.items():
                    new_indexes[name] = idx
                    new_index_vars[name] = var

        self.aligned_indexes = aligned_indexes
        self.aligned_index_vars = aligned_index_vars
        self.reindex = reindex
        self.new_indexes = Indexes(new_indexes, new_index_vars)

    def assert_unindexed_dim_sizes_equal(self) -> None:
        for dim, sizes in self.unindexed_dim_sizes.items():
            index_size = self.new_indexes.dims.get(dim)
            if index_size is not None:
                sizes.add(index_size)
                add_err_msg = (
                    f" (note: an index is found along that dimension "
                    f"with size={index_size!r})"
                )
            else:
                add_err_msg = ""
            if len(sizes) > 1:
                raise ValueError(
                    f"cannot reindex or align along dimension {dim!r} "
                    f"because of conflicting dimension sizes: {sizes!r}" + add_err_msg
                )

    def override_indexes(self) -> None:
        objects = list(self.objects)

        for i, obj in enumerate(objects[1:]):
            new_indexes = {}
            new_variables = {}
            matching_indexes = self.objects_matching_indexes[i + 1]

            for key, aligned_idx in self.aligned_indexes.items():
                obj_idx = matching_indexes.get(key)
                if obj_idx is not None:
                    for name, var in self.aligned_index_vars[key].items():
                        new_indexes[name] = aligned_idx
                        new_variables[name] = var

            objects[i + 1] = obj._overwrite_indexes(new_indexes, new_variables)

        self.results = tuple(objects)

    def _get_dim_pos_indexers(
        self,
        matching_indexes: dict[MatchingIndexKey, Index],
    ) -> dict[Hashable, Any]:
        dim_pos_indexers = {}

        for key, aligned_idx in self.aligned_indexes.items():
            obj_idx = matching_indexes.get(key)
            if obj_idx is not None:
                if self.reindex[key]:
                    indexers = obj_idx.reindex_like(aligned_idx, **self.reindex_kwargs)  # type: ignore[call-arg]
                    dim_pos_indexers.update(indexers)

        return dim_pos_indexers

    def _get_indexes_and_vars(
        self,
        obj: DataAlignable,
        matching_indexes: dict[MatchingIndexKey, Index],
    ) -> tuple[dict[Hashable, Index], dict[Hashable, Variable]]:
        new_indexes = {}
        new_variables = {}

        for key, aligned_idx in self.aligned_indexes.items():
            index_vars = self.aligned_index_vars[key]
            obj_idx = matching_indexes.get(key)
            if obj_idx is None:
                # add the index if it relates to unindexed dimensions in obj
                index_vars_dims = {d for var in index_vars.values() for d in var.dims}
                if index_vars_dims <= set(obj.dims):
                    obj_idx = aligned_idx
            if obj_idx is not None:
                for name, var in index_vars.items():
                    new_indexes[name] = aligned_idx
                    new_variables[name] = var

        return new_indexes, new_variables

    def _reindex_one(
        self,
        obj: DataAlignable,
        matching_indexes: dict[MatchingIndexKey, Index],
    ) -> DataAlignable:
        new_indexes, new_variables = self._get_indexes_and_vars(obj, matching_indexes)
        dim_pos_indexers = self._get_dim_pos_indexers(matching_indexes)

        new_obj = obj._reindex_callback(
            self,
            dim_pos_indexers,
            new_variables,
            new_indexes,
            self.fill_value,
            self.exclude_dims,
            self.exclude_vars,
        )
        new_obj.encoding = obj.encoding
        return new_obj

    def reindex_all(self) -> None:
        self.results = tuple(
            self._reindex_one(obj, matching_indexes)
            for obj, matching_indexes in zip(
                self.objects, self.objects_matching_indexes
            )
        )

    def align(self) -> None:
        if not self.indexes and len(self.objects) == 1:
            # fast path for the trivial case
            (obj,) = self.objects
            self.results = (obj.copy(deep=self.copy),)

        self.find_matching_indexes()
        self.find_matching_unindexed_dims()
        self.assert_no_index_conflict()
        self.align_indexes()
        self.assert_unindexed_dim_sizes_equal()

        if self.join == "override":
            self.override_indexes()
        else:
            self.reindex_all()

def align(
    *objects: DataAlignable,
    join: JoinOptions = "inner",
    copy: bool = True,
    indexes=None,
    exclude=frozenset(),
    fill_value=dtypes.NA,
) -> tuple[DataAlignable, ...]:
    """
    Given any number of Dataset and/or DataArray objects, returns new
    objects with aligned indexes and dimension sizes.

    Array from the aligned objects are suitable as input to mathematical
    operators, because along each dimension they have the same index and size.

    Missing values (if ``join != 'inner'``) are filled with ``fill_value``.
    The default fill value is NaN.

    Parameters
    ----------
    *objects : Dataset or DataArray
        Objects to align.
    join : {"outer", "inner", "left", "right", "exact", "override"}, optional
        Method for joining the indexes of the passed objects along each
        dimension:

        - "outer": use the union of object indexes
        - "inner": use the intersection of object indexes
        - "left": use indexes from the first object with each dimension
        - "right": use indexes from the last object with each dimension
        - "exact": instead of aligning, raise `ValueError` when indexes to be
          aligned are not equal
        - "override": if indexes are of same size, rewrite indexes to be
          those of the first object with that dimension. Indexes for the same
          dimension must have the same size in all objects.

    copy : bool, default: True
        If ``copy=True``, data in the return values is always copied. If
        ``copy=False`` and reindexing is unnecessary, or can be performed with
        only slice operations, then the output may share memory with the input.
        In either case, new xarray objects are always returned.
    indexes : dict-like, optional
        Any indexes explicitly provided with the `indexes` argument should be
        used in preference to the aligned indexes.
    exclude : sequence of str, optional
        Dimensions that must be excluded from alignment
    fill_value : scalar or dict-like, optional
        Value to use for newly missing values. If a dict-like, maps
        variable names to fill values. Use a data array's name to
        refer to its values.

    Returns
    -------
    aligned : tuple of DataArray or Dataset
        Tuple of objects with the same type as `*objects` with aligned
        coordinates.

    Raises
    ------
    ValueError
        If any dimensions without labels on the arguments have different sizes,
        or a different size than the size of the aligned dimension labels.

    Examples
    --------
    >>> x = xr.DataArray(
    ...     [[25, 35], [10, 24]],
    ...     dims=("lat", "lon"),
    ...     coords={"lat": [35.0, 40.0], "lon": [100.0, 120.0]},
    ... )
    >>> y = xr.DataArray(
    ...     [[20, 5], [7, 13]],
    ...     dims=("lat", "lon"),
    ...     coords={"lat": [35.0, 42.0], "lon": [100.0, 120.0]},
    ... )

    >>> x
    <xarray.DataArray (lat: 2, lon: 2)>
    array([[25, 35],
           [10, 24]])
    Coordinates:
      * lat      (lat) float64 35.0 40.0
      * lon      (lon) float64 100.0 120.0

    >>> y
    <xarray.DataArray (lat: 2, lon: 2)>
    array([[20,  5],
           [ 7, 13]])
    Coordinates:
      * lat      (lat) float64 35.0 42.0
      * lon      (lon) float64 100.0 120.0

    >>> a, b = xr.align(x, y)
    >>> a
    <xarray.DataArray (lat: 1, lon: 2)>
    array([[25, 35]])
    Coordinates:
      * lat      (lat) float64 35.0
      * lon      (lon) float64 100.0 120.0
    >>> b
    <xarray.DataArray (lat: 1, lon: 2)>
    array([[20,  5]])
    Coordinates:
      * lat      (lat) float64 35.0
      * lon      (lon) float64 100.0 120.0

    >>> a, b = xr.align(x, y, join="outer")
    >>> a
    <xarray.DataArray (lat: 3, lon: 2)>
    array([[25., 35.],
           [10., 24.],
           [nan, nan]])
    Coordinates:
      * lat      (lat) float64 35.0 40.0 42.0
      * lon      (lon) float64 100.0 120.0
    >>> b
    <xarray.DataArray (lat: 3, lon: 2)>
    array([[20.,  5.],
           [nan, nan],
           [ 7., 13.]])
    Coordinates:
      * lat      (lat) float64 35.0 40.0 42.0
      * lon      (lon) float64 100.0 120.0

    >>> a, b = xr.align(x, y, join="outer", fill_value=-999)
    >>> a
    <xarray.DataArray (lat: 3, lon: 2)>
    array([[  25,   35],
           [  10,   24],
           [-999, -999]])
    Coordinates:
      * lat      (lat) float64 35.0 40.0 42.0
      * lon      (lon) float64 100.0 120.0
    >>> b
    <xarray.DataArray (lat: 3, lon: 2)>
    array([[  20,    5],
           [-999, -999],
           [   7,   13]])
    Coordinates:
      * lat      (lat) float64 35.0 40.0 42.0
      * lon      (lon) float64 100.0 120.0

    >>> a, b = xr.align(x, y, join="left")
    >>> a
    <xarray.DataArray (lat: 2, lon: 2)>
    array([[25, 35],
           [10, 24]])
    Coordinates:
      * lat      (lat) float64 35.0 40.0
      * lon      (lon) float64 100.0 120.0
    >>> b
    <xarray.DataArray (lat: 2, lon: 2)>
    array([[20.,  5.],
           [nan, nan]])
    Coordinates:
      * lat      (lat) float64 35.0 40.0
      * lon      (lon) float64 100.0 120.0

    >>> a, b = xr.align(x, y, join="right")
    >>> a
    <xarray.DataArray (lat: 2, lon: 2)>
    array([[25., 35.],
           [nan, nan]])
    Coordinates:
      * lat      (lat) float64 35.0 42.0
      * lon      (lon) float64 100.0 120.0
    >>> b
    <xarray.DataArray (lat: 2, lon: 2)>
    array([[20,  5],
           [ 7, 13]])
    Coordinates:
      * lat      (lat) float64 35.0 42.0
      * lon      (lon) float64 100.0 120.0

    >>> a, b = xr.align(x, y, join="exact")
    Traceback (most recent call last):
    ...
    ValueError: cannot align objects with join='exact' ...

    >>> a, b = xr.align(x, y, join="override")
    >>> a
    <xarray.DataArray (lat: 2, lon: 2)>
    array([[25, 35],
           [10, 24]])
    Coordinates:
      * lat      (lat) float64 35.0 40.0
      * lon      (lon) float64 100.0 120.0
    >>> b
    <xarray.DataArray (lat: 2, lon: 2)>
    array([[20,  5],
           [ 7, 13]])
    Coordinates:
      * lat      (lat) float64 35.0 40.0
      * lon      (lon) float64 100.0 120.0

    """
    aligner = Aligner(
        objects,
        join=join,
        copy=copy,
        indexes=indexes,
        exclude_dims=exclude,
        fill_value=fill_value,
    )
    aligner.align()
    return aligner.results

def deep_align(
    objects: Iterable[Any],
    join: JoinOptions = "inner",
    copy=True,
    indexes=None,
    exclude=frozenset(),
    raise_on_invalid=True,
    fill_value=dtypes.NA,
):
    """Align objects for merging, recursing into dictionary values.

    This function is not public API.
    """
    from .dataarray import DataArray
    from .dataset import Dataset

    if indexes is None:
        indexes = {}

    def is_alignable(obj):
        return isinstance(obj, (DataArray, Dataset))

    positions = []
    keys = []
    out = []
    targets = []
    no_key = object()
    not_replaced = object()
    for position, variables in enumerate(objects):
        if is_alignable(variables):
            positions.append(position)
            keys.append(no_key)
            targets.append(variables)
            out.append(not_replaced)
        elif is_dict_like(variables):
            current_out = {}
            for k, v in variables.items():
                if is_alignable(v) and k not in indexes:
                    # Skip variables in indexes for alignment, because these
                    # should to be overwritten instead:
                    # https://github.com/pydata/xarray/issues/725
                    # https://github.com/pydata/xarray/issues/3377
                    # TODO(shoyer): doing this here feels super-hacky -- can we
                    # move it explicitly into merge instead?
                    positions.append(position)
                    keys.append(k)
                    targets.append(v)
                    current_out[k] = not_replaced
                else:
                    current_out[k] = v
            out.append(current_out)
        elif raise_on_invalid:
            raise ValueError(
                "object to align is neither an xarray.Dataset, "
                "an xarray.DataArray nor a dictionary: {!r}".format(variables)
            )
        else:
            out.append(variables)

    aligned = align(
        *targets,
        join=join,
        copy=copy,
        indexes=indexes,
        exclude=exclude,
        fill_value=fill_value,
    )

    for position, key, aligned_obj in zip(positions, keys, aligned):
        if key is no_key:
            out[position] = aligned_obj
        else:
            out[position][key] = aligned_obj  # type: ignore[index]  # maybe someone can fix this?

    # something went wrong: we should have replaced all sentinel values
    for arg in out:
        assert arg is not not_replaced
        if is_dict_like(arg):
            assert all(value is not not_replaced for value in arg.values())

    return out

def reindex(
    obj: DataAlignable,
    indexers: Mapping[Any, Any],
    method: str = None,
    tolerance: int | float | Iterable[int | float] | None = None,
    copy: bool = True,
    fill_value: Any = dtypes.NA,
    sparse: bool = False,
    exclude_vars: Iterable[Hashable] = frozenset(),
) -> DataAlignable:
    """Re-index either a Dataset or a DataArray.

    Not public API.

    """

    # TODO: (benbovy - explicit indexes): uncomment?
    # --> from reindex docstrings: "any mis-matched dimension is simply ignored"
    # bad_keys = [k for k in indexers if k not in obj._indexes and k not in obj.dims]
    # if bad_keys:
    #     raise ValueError(
    #         f"indexer keys {bad_keys} do not correspond to any indexed coordinate "
    #         "or unindexed dimension in the object to reindex"
    #     )

    aligner = Aligner(
        (obj,),
        indexes=indexers,
        method=method,
        tolerance=tolerance,
        copy=copy,
        fill_value=fill_value,
        sparse=sparse,
        exclude_vars=exclude_vars,
    )
    aligner.align()
    return aligner.results[0]

def reindex_like(
    obj: DataAlignable,
    other: Dataset | DataArray,
    method: str = None,
    tolerance: int | float | Iterable[int | float] | None = None,
    copy: bool = True,
    fill_value: Any = dtypes.NA,
) -> DataAlignable:
    """Re-index either a Dataset or a DataArray like another Dataset/DataArray.

    Not public API.

    """
    if not other._indexes:
        # This check is not performed in Aligner.
        for dim in other.dims:
            if dim in obj.dims:
                other_size = other.sizes[dim]
                obj_size = obj.sizes[dim]
                if other_size != obj_size:
                    raise ValueError(
                        "different size for unlabeled "
                        f"dimension on argument {dim!r}: {other_size!r} vs {obj_size!r}"
                    )

    return reindex(
        obj,
        indexers=other.xindexes,
        method=method,
        tolerance=tolerance,
        copy=copy,
        fill_value=fill_value,
    )

def _get_broadcast_dims_map_common_coords(args, exclude):

    common_coords = {}
    dims_map = {}
    for arg in args:
        for dim in arg.dims:
            if dim not in common_coords and dim not in exclude:
                dims_map[dim] = arg.sizes[dim]
                if dim in arg._indexes:
                    common_coords.update(arg.xindexes.get_all_coords(dim))

    return dims_map, common_coords

def _broadcast_helper(
    arg: T_DataArrayOrSet, exclude, dims_map, common_coords
) -> T_DataArrayOrSet:

    from .dataarray import DataArray
    from .dataset import Dataset

    def _set_dims(var):
        # Add excluded dims to a copy of dims_map
        var_dims_map = dims_map.copy()
        for dim in exclude:
            with suppress(ValueError):
                # ignore dim not in var.dims
                var_dims_map[dim] = var.shape[var.dims.index(dim)]

        return var.set_dims(var_dims_map)

    def _broadcast_array(array: T_DataArray) -> T_DataArray:
        data = _set_dims(array.variable)
        coords = dict(array.coords)
        coords.update(common_coords)
        return array.__class__(
            data, coords, data.dims, name=array.name, attrs=array.attrs
        )

    def _broadcast_dataset(ds: T_Dataset) -> T_Dataset:
        data_vars = {k: _set_dims(ds.variables[k]) for k in ds.data_vars}
        coords = dict(ds.coords)
        coords.update(common_coords)
        return ds.__class__(data_vars, coords, ds.attrs)

    # remove casts once https://github.com/python/mypy/issues/12800 is resolved
    if isinstance(arg, DataArray):
        return cast("T_DataArrayOrSet", _broadcast_array(arg))
    elif isinstance(arg, Dataset):
        return cast("T_DataArrayOrSet", _broadcast_dataset(arg))
    else:
        raise ValueError("all input must be Dataset or DataArray objects")

def broadcast(*args, exclude=None):
    """Explicitly broadcast any number of DataArray or Dataset objects against
    one another.

    xarray objects automatically broadcast against each other in arithmetic
    operations, so this function should not be necessary for normal use.

    If no change is needed, the input data is returned to the output without
    being copied.

    Parameters
    ----------
    *args : DataArray or Dataset
        Arrays to broadcast against each other.
    exclude : sequence of str, optional
        Dimensions that must not be broadcasted

    Returns
    -------
    broadcast : tuple of DataArray or tuple of Dataset
        The same data as the input arrays, but with additional dimensions
        inserted so that all data arrays have the same dimensions and shape.

    Examples
    --------
    Broadcast two data arrays against one another to fill out their dimensions:

    >>> a = xr.DataArray([1, 2, 3], dims="x")
    >>> b = xr.DataArray([5, 6], dims="y")
    >>> a
    <xarray.DataArray (x: 3)>
    array([1, 2, 3])
    Dimensions without coordinates: x
    >>> b
    <xarray.DataArray (y: 2)>
    array([5, 6])
    Dimensions without coordinates: y
    >>> a2, b2 = xr.broadcast(a, b)
    >>> a2
    <xarray.DataArray (x: 3, y: 2)>
    array([[1, 1],
           [2, 2],
           [3, 3]])
    Dimensions without coordinates: x, y
    >>> b2
    <xarray.DataArray (x: 3, y: 2)>
    array([[5, 6],
           [5, 6],
           [5, 6]])
    Dimensions without coordinates: x, y

    Fill out the dimensions of all data variables in a dataset:

    >>> ds = xr.Dataset({"a": a, "b": b})
    >>> (ds2,) = xr.broadcast(ds)  # use tuple unpacking to extract one dataset
    >>> ds2
    <xarray.Dataset>
    Dimensions:  (x: 3, y: 2)
    Dimensions without coordinates: x, y
    Data variables:
        a        (x, y) int64 1 1 2 2 3 3
        b        (x, y) int64 5 6 5 6 5 6
    """

    if exclude is None:
        exclude = set()
    args = align(*args, join="outer", copy=False, exclude=exclude)

    dims_map, common_coords = _get_broadcast_dims_map_common_coords(args, exclude)
    result = [_broadcast_helper(arg, exclude, dims_map, common_coords) for arg in args]

    return tuple(result)


text:
import os
import sys
import commands
import shutil
from optparse import OptionParser
import urllib2
import re
from bs4 import BeautifulSoup
import platform

os.system("node -v")
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
crosswalk_test_suite = os.path.join(SCRIPT_PATH, "crosswalk-test-suite")
tmp = os.path.join(SCRIPT_PATH, "tmp")
apptools = os.path.join(crosswalk_test_suite, "apptools")
apptools_android_tests = os.path.join(tmp, "apptools-android-tests")
apptools_windows_tests = os.path.join(tmp, "apptools-windows-tests")
apptools_ios_tests = os.path.join(tmp, "apptools-ios-tests")

os.environ['CROSSWALK_APP_SRC'] = os.path.join(SCRIPT_PATH, "src") + "/"

returnCode = 0
if os.path.exists(crosswalk_test_suite):
    os.chdir(crosswalk_test_suite)
    cmd = 'git pull'
    returnCode = os.system(cmd)
    os.chdir(SCRIPT_PATH)
else:
    cmd = 'git clone https://github.com/crosswalk-project/crosswalk-test-suite'
    returnCode = os.system(cmd)
if returnCode == 1:
    sys.exit(1)

if os.path.exists(tmp):
    shutil.rmtree(tmp)

def crosswalk_version(channel, platform):
    htmlDoc = urllib2.urlopen(
        'https://download.01.org/crosswalk/releases/crosswalk/' + platform + '/' +
        channel +
        '/').read()
    soup = BeautifulSoup(htmlDoc)
    alist = soup.find_all('a')
    version = ''
    for  index in range(-1, -len(alist)-1, -1):
        aEle = alist[index]
        version = aEle['href'].strip('/')
        if re.search('[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*', version):
            break
    return version

def main():
    usage = "Usage: ./lint.py -p android"
    opts_parser = OptionParser(usage=usage)
    opts_parser.add_option(
        "-p",
        dest="platform",
        help="specify the testsuit platform, e.g. android, windows, ios")
    opts_parser.add_option(
        "-a",
        dest="arch",
        help="specify the packing apk bit, e.g. 32bit, 64bit")
    global BUILD_PARAMETERS
    (BUILD_PARAMETERS, args) = opts_parser.parse_args()
    if BUILD_PARAMETERS.platform == "android":
        os.environ['CROSSWALK_APP_TOOLS_CACHE_DIR'] = os.path.join(apptools_android_tests, "tools")
        x = []
        for i in list(os.popen('adb devices -l'))[1:]:
            if i.strip(os.linesep) != "" and i.strip(os.linesep).split(" ")[0] != "*":
                x.append(i.strip(os.linesep).split(" ")[0])
        if x:
            os.environ['DEVICE_ID'] = ",".join(x)
        os.environ['SKIP_EMULATOR'] = "True"
        android_crosswalk_version = crosswalk_version("stable", BUILD_PARAMETERS.platform)
        shutil.copytree(os.path.join(apptools, "apptools-android-tests"), apptools_android_tests)
        fp = open(apptools_android_tests + '/arch.txt', 'w+')
        fp.write("arm")
        fp.close()
        if platform.system() != "Linux":
            hp = open(apptools_android_tests + "/host.txt", 'w+')
            hp.write("Windows")
            hp.close()
        else:
            hp = open(apptools_android_tests + "/host.txt", 'w+')
            hp.write("Android")
            hp.close()
        if BUILD_PARAMETERS.arch == "64bit":
            vp_64 = open(apptools_android_tests + "/version.txt", 'w+')
            vp_64.write(android_crosswalk_version + " 64")
            vp_64.close()
            os.chdir(os.path.join(apptools_android_tests, "tools"))
            data = urllib2.urlopen("https://download.01.org/crosswalk/releases/crosswalk/" + BUILD_PARAMETERS.platform + "/stable/" + android_crosswalk_version + "/crosswalk-" + android_crosswalk_version + "-64bit.zip").read()
            with open("crosswalk-" + android_crosswalk_version + "-64bit.zip", 'wb') as f:
                f.write(data)
        else:
            vp_32 = open(apptools_android_tests + "/version.txt", 'w+')
            vp_32.write(android_crosswalk_version + " 32")
            vp_32.close()
            os.chdir(os.path.join(apptools_android_tests, "tools"))
            data = urllib2.urlopen("https://download.01.org/crosswalk/releases/crosswalk/" + BUILD_PARAMETERS.platform + "/stable/" + android_crosswalk_version + "/crosswalk-" + android_crosswalk_version + ".zip").read()
            with open("crosswalk-" + android_crosswalk_version + ".zip", 'wb') as f:
                f.write(data)
        os.chdir(os.path.join(os.path.join(apptools_android_tests, "apptools"), "CI"))
        if platform.system() != "Linux":
            retval = os.system("python -m unittest discover --pattern=crosswalk_pkg_basic.py > null")
        else:
            retval = os.system("python -m unittest discover --pattern=*.py")
    elif BUILD_PARAMETERS.platform == "windows":
        os.environ['CROSSWALK_APP_TOOLS_CACHE_DIR'] = os.path.join(apptools_windows_tests, "tools")
        shutil.copytree(os.path.join(apptools, "apptools-windows-tests"), apptools_windows_tests)
        os.chdir(os.path.join(apptools_windows_tests, "tools"))
        windows_crosswalk_version = crosswalk_version("canary", BUILD_PARAMETERS.platform)
        try:
            data = urllib2.urlopen("https://download.01.org/crosswalk/releases/crosswalk/" + BUILD_PARAMETERS.platform + "/canary/" + windows_crosswalk_version + "/crosswalk-" + windows_crosswalk_version + ".zip").read()
            with open("crosswalk-" + windows_crosswalk_version + ".zip", 'wb') as f:
                f.write(data)
        except Exception as e:
            data = urllib2.urlopen("https://download.01.org/crosswalk/releases/crosswalk/" + BUILD_PARAMETERS.platform + "/canary/" + windows_crosswalk_version + "/crosswalk64-" + windows_crosswalk_version + ".zip").read()
            with open("crosswalk64-" + windows_crosswalk_version + ".zip", 'wb') as f:
                f.write(data)
        os.chdir(os.path.join(os.path.join(apptools_windows_tests, "apptools"), "CI"))
        retval = os.system("python -m unittest discover --pattern=*.py > null")
    elif BUILD_PARAMETERS.platform == "ios":
        shutil.copytree(os.path.join(apptools, "apptools-ios-tests"), apptools_ios_tests)
        os.chdir(os.path.join(os.path.join(apptools_ios_tests, "apptools"), "CI"))
        retval = os.system("python -m unittest discover --pattern=*.py > null")
    return retval

if __name__ == "__main__":
    sys.exit(main())

redpajama_set_name: RedPajamaGithub


text:
package frostillicus.couchbase;

import java.io.IOException;
import java.io.Serializable;

import javax.faces.context.FacesContext;

import com.couchbase.client.CouchbaseClient;
import com.ibm.commons.util.io.json.JsonException;
import com.ibm.commons.util.io.json.JsonJavaFactory;
import com.ibm.commons.util.io.json.JsonJavaObject;
import com.ibm.commons.util.io.json.JsonParser;
import com.ibm.xsp.model.DataObject;

public class CouchbaseDocument implements Serializable, DataObject {
	private static final long serialVersionUID = -6401841857090580063L;

	private final String connectionName_;
	private final String key_;
	private final JsonJavaObject data_;

	public CouchbaseDocument(final String connectionName, final String key) throws IOException, JsonException {
		connectionName_ = connectionName;
		key_ = key;

		CouchbaseClient client = getClient();
		// Assume it's always a document
		String json = (String) client.get(key_);
		data_ = (JsonJavaObject) JsonParser.fromJson(JsonJavaFactory.instanceEx, json);
	}

	public Class<?> getType(final Object key) {
		return data_.get(String.valueOf(key)).getClass();
	}

	public Object getValue(final Object key) {
		return data_.get(String.valueOf(key));
	}

	public boolean isReadOnly(final Object key) {
		if ("documentId".equals(key)) {
			return true;
		}
		return false;
	}

	public void setValue(final Object key, final Object value) {
		if (key == null) {
			throw new IllegalArgumentException("Key cannot be null.");
		}
		if ("documentId".equals(key)) {
			throw new IllegalArgumentException("Document ID is immutable.");
		}
		data_.put(key.toString(), value);
	}

	public boolean save() throws IOException {
		CouchbaseClient client = getClient();
		client.set(key_, toString());
		return true;
	}

	@Override
	public String toString() {
		return data_.toString();
	}

	private CouchbaseClient getClient() throws IOException {
		FacesContext context = FacesContext.getCurrentInstance();
		XSPCouchbaseConnection conn = (XSPCouchbaseConnection) context.getApplication().getVariableResolver().resolveVariable(context, connectionName_);
		return conn.getClient();
	}
}


text:
#ifndef USERINTERFACE_H
#define USERINTERFACE_H

#include <QMainWindow>
#include <QMouseEvent>
#include <QString>
#include <string>
#include <Pump.h>

using namespace std;

namespace Ui {
class UserInterface;
}

class UserInterface : public QMainWindow
{
    Q_OBJECT

public:
    explicit UserInterface(QWidget *parent = 0);
    ~UserInterface();

    static const int INSULIN    = 1;
    static const int GLUCAGON   = 2;

    /**
     * Initiates the UI with the values from the config struct
     *
     * @param cfg - config scruct
     */
    void init(config cfg);

public slots:
    /**
     * Updates the Batteries power level in the Progressbar
     *
     * @param level - new battery power level
     */
    void batteryPowerLevelChanged(int level);
    /**
     * Updates the Batteries minimum power level in the spin box
     *
     * @param level - new battery power level
     */
    void minBatteryLevelChanged(int level);
    /**
     * Updates the Insulin amount in the Progressbar
     *
     * @param amount - new insulin amount
     */
    void insulinAmountInReservoirChanged(int amount);
    /**
     * Updates the Glucagon amount in the Progressbar
     *
     * @param amount - new glucagon amount
     */
    void glucagonAmountInReservoirChanged(int amount);
    /**
     * Updates the operation time in the Progressbar
     *
     * @param hours - new operation time in hours
     */
    void operationTimeChanged(int hours);
    /**
     * Updates the maximum operation time in the spin box
     *
     * @param hours - new maximum operation time in hours
     */
    void maxOperationTimeChanged(int hours);
    /**
     * Updates the control thread interval in the spin box
     *
     * @param seconds - new control thread interval in seconds
     */
    void controlThreadIntervalChanged(int seconds);
    /**
     * Updates the scheduler thread interval in the spin box
     *
     * @param seconds - new scheduler thread interval in seconds
     */
    void schedulerThreadIntervalChanged(int seconds);
    /**
     * Inserts the status message in to the QListWidgetItem
     *
     * @param message - string message to insert
     */
    void insertStatusLog(QString message);
    /**
     * Inserts the warning message in to the QListWidgetItem
     *
     * @param message - string message to insert
     */
    void insertWarningLog(QString message);
    /**
     * Inserts the critical message in to the QListWidgetItem
     *
     * @param message - string message to insert
     */
    void insertCriticalLog(QString message);

    /**
     * Updates the Bloodsugar in the UI
     *
     * @param amount - current bloodsugar
     */
    void updateBloodsugarLevel(int bloodsugarLevel);

    /**
     * Inserts a message into the QList witch containts the injected hormone and dose.
     *
     * @param hormone - injected hormone
     * @param amountInjected - the amount injected
     */
    void updateHormoneInjectionLog(int hormone, int amountInjected);

private slots:
    /**
     * Refill the Insulinreservoir in the Pump
     */
    void on_mInsulinRefillButton_clicked();
    /**
     * Refill the Glucagonreservoir in the Pump
     */
    void on_mGlucagonRefillButton_clicked();

    /**
     * Updates the Time in the UI
     */
    void updateClock();

    /**
     * Testing onBatteryButtonClicked
     *
     * Reads the value from the slider and calls the SIGNAL method setBatteryLevel().
     */
    void on_mTestingBatteryButton_clicked();

    /**
     * Testing onMinBatLoadButtonClicked
     *
     * Reads the value from the slider and calls the SIGNAL method setMinBatteryLevel().
     */
    void on_mMinBatLoadButton_clicked();

    /**
     * Testing onGlucagonButtonClicked
     *
     * Reads the value from the slider and calls the SIGNAL method setGlucagonReservoirLevel().
     */
    void on_mTestingGlucagonButton_clicked();

    /**
     * Testing onInsulinButtonClicked
     *
     * Reads the value from the slider and calls the SIGNAL method setInsulinReservoirLevel().
     */
    void on_mTestingInsulinButton_clicked();

    /**
     * Testing onOpTimeButtonClicked
     *
     * Reads the value from the slider and calls the SIGNAL method setOperationTime().
     */
    void on_mTestingOpTimeButton_clicked();

    /**
     * Testing onmMaxOpTimeButtonClicked
     *
     * Reads the value from the slider and calls the SIGNAL method setMaxOperationTime().
     */
    void on_mMaxOpTimeButton_clicked();

    /**
     * Testing onmContrIntButtonClicked
     *
     * Reads the value from the slider and calls the SIGNAL method setControlThreadInterval().
     */
    void on_mContrIntButton_clicked();

    /**
     * Testing onmSchedIntButtonClicked
     *
     * Reads the value from the slider and calls the SIGNAL method setSchedulerThreadInterval().
     */
    void on_mSchedIntButton_clicked();

    /**
     * Clear logs on right click
     */
    void mousePressEvent(QMouseEvent *event);

signals:
    /**
     * Notifys the Pump to refill the Insulin Reservoir
     */
    void refillInsulinInPump();

    /**
     * Notifys the Pump to refill the Glucagon Reservoir
     */
    void refillGlucagonInPump();

    /**
     * Notifys the SLOT method of the Pump class, which changes the battery level.
     *
     * @param level - new battery level
     */
    void setBatteryPowerLevel(int level);

    /**
     * Notifys the SLOT method of the ControlSystem class, which changes the min battery level.
     *
     * @param level - new minimum battery level
     */
    void setMinBatteryLevel(int level);

    /**
     * Notifys the SLOT method of the Pump class, which changes the glucagonreservoir fill level.
     *
     * @param level - new glucagonreservoir fill level
     */
    void setGlucagonReservoirLevel(int level);

    /**
     * Notifys the SLOT method of the Pump class, which changes the Insulinreservoir fill level.
     *
     * @param level - new insulinreservoir fill level
     */
    void setInsulinReservoirLevel(int level);

    /**
     * Notifys the SLOT method of the Scheduler class, which changes the operation time.
     *
     * @param hours - new operation time in hours
     */
    void setOperationTime(int hours);

    /**
     * Notifys the SLOT method of the Scheduler class, which changes the max operation time.
     *
     * @param hours - new maximum operation time in hours
     */
    void setMaxOperationTime(int hours);

    /**
     * Notifys the SLOT method of the Control System class, which changes the controller interval.
     *
     * @param hours - new control thread interval in seconds
     */
    void setControlThreadInterval(int seconds);

    /**
     * Notifys the SLOT method of the Scheduler class, which changes the scheduler interval.
     *
     * @param hours - new scheduler thread interval in seconds
     */
    void setSchedulerThreadInterval(int seconds);

private:
    Ui::UserInterface *ui;
    float upperLimit;
    float lowerLimit;
    int absMaxBSL;
    int resWarn;
    int resCrit;
    int battWarn;
    int battCrit;
};

#endif // USERINTERFACE_H


text:
<!DOCTYPE html>

    <title th:text="#{overview.title}"></title>

    <link rel="stylesheet" th:href="@{/css/overview.css}"/>

Page Heading

                <input id="fromDate" type="text" class="form-control">

to

                <input id="toDate" type="text" class="form-control">

Page Heading

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Delete Record

                    Do you really want to delete this record

                    <button type="button" class="btn btn-default" data-dismiss="modal" th:text="#{action.cancel}">Cancel</button>
                    <button id="recordDeleteBtn" type="button" class="btn btn-primary" th:text="#{action.delete}"></button>


text:
import { readFile as origReadFile, writeFile as origWriteFile } from 'fs';
import { graphql, GraphQLSchema, printSchema, lexicographicSortSchema } from 'graphql';
import * as GQL from 'graphql';
import { PostGraphileOptions } from '../../interfaces';
import { promisify } from 'util';

const introspectionQuery =
  typeof GQL.getIntrospectionQuery === 'function'
    ? GQL.getIntrospectionQuery()
    : (GQL as any).introspectionQuery;

const readFile = promisify(origReadFile);
const writeFile = promisify(origWriteFile);

async function writeFileIfDiffers(path: string, contents: string): Promise<void> {
  let oldContents: string | null = null;
  try {
    oldContents = await readFile(path, 'utf8');
  } catch (e) {
    /* noop */
  }
  if (oldContents !== contents) {
    await writeFile(path, contents);
  }
}

/**
 * Exports a PostGraphile schema by looking at a Postgres client.
 */
export default async function exportPostGraphileSchema(
  schema: GraphQLSchema,
  options: PostGraphileOptions = {},
): Promise<void> {
  const jsonPath =
    typeof options.exportJsonSchemaPath === 'string' ? options.exportJsonSchemaPath : null;
  const graphqlPath =
    typeof options.exportGqlSchemaPath === 'string' ? options.exportGqlSchemaPath : null;

  // Sort schema, if requested
  const finalSchema =
    options.sortExport && lexicographicSortSchema && (jsonPath || graphqlPath)
      ? lexicographicSortSchema(schema)
      : schema;

  // JSON version
  if (jsonPath) {
    const result = await graphql(finalSchema, introspectionQuery);
    await writeFileIfDiffers(jsonPath, JSON.stringify(result, null, 2));
  }

  // Schema language version
  if (graphqlPath) {
    await writeFileIfDiffers(graphqlPath, printSchema(finalSchema));
  }
}


text:
package com.github.mijicd.waes.domain

import com.github.mijicd.waes.TestSpec
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class DiffResultSpec extends TestSpec {
  "DiffResult.forEqual" should "create an instance with status 'EQUAL' " in {
    val instance = DiffResult.forEqual
    instance.status should be (Equal)
  }

  "DiffResult.forDifferentLengths" should "create an instance with status 'DIFFERENT_LENGTHS'" in {
    val instance = DiffResult.forDifferentLengths
    instance.status should be (DifferentLength)
  }

  "DiffResult.forDifferences(Seq(3))" should "create an instance with status 'DIFFERENT_AT' and a list of diffs" in {
    val instance = DiffResult.forDifferences(Seq(3))
    instance.status should be (DifferentAt)

    val diffs = instance.differences
    diffs.isDefined shouldBe true
    diffs.get should be (Seq(3))
  }
}


text:
namespace mirrage::renderer {

	// model components are intially loaded as Model_unloaded_comp, replaced by Model_loading_comp
	//   once the loading of the model data has begun and finally replaced by Model_comp afterwards.
	// Client code should only care about the Model_comp class as it represents an actually usable model.

	class Material_property_comp : public ecs::Component<Material_property_comp> {
	  public:
		static constexpr const char* name() { return "Material_property"; }

		Material_property_comp() = default;
		Material_property_comp(ecs::Entity_handle   owner,
		                       ecs::Entity_manager& em,
		                       glm::vec4            emissive_color = glm::vec4(1, 1, 1, 1000.f))
		  : Component(owner, em), emissive_color(emissive_color)
		{
		}

		glm::vec4 emissive_color = glm::vec4(1, 1, 1, 1000.f);
	};
	sf2_structDef(Material_property_comp, emissive_color);

	struct Material_override {
		Material_ptr material;
	};

	class Material_override_comp : public ecs::Component<Material_override_comp> {
	  public:
		static constexpr const char* name() { return "Material_override"; }
		friend void                  load_component(ecs::Deserializer& state, Material_override_comp&);
		friend void                  save_component(ecs::Serializer& state, const Material_override_comp&);

		Material_override_comp() = default;
		Material_override_comp(ecs::Entity_handle                              owner,
		                       ecs::Entity_manager&                            em,
		                       const util::small_vector<Material_override, 4>& material_overrides = {})
		  : Component(owner, em), material_overrides(material_overrides)
		{
		}

		util::small_vector<Material_override, 4> material_overrides;
	};

	class Model_comp : public ecs::Component<Model_comp> {
	  public:
		static constexpr const char* name() { return "Model_loaded"; }
		static constexpr const char* name_save_as() { return "Model"; }
		friend void                  load_component(ecs::Deserializer& state, Model_comp&);
		friend void                  save_component(ecs::Serializer& state, const Model_comp&);

		Model_comp() = default;
		Model_comp(ecs::Entity_handle   owner,
		           ecs::Entity_manager& em,
		           Model_ptr            model           = {},
		           const glm::mat4&     local_transform = glm::mat4(1.f))
		  : Component(owner, em)
		  , _model(std::move(model))
		  , _local_transform(local_transform)
		  , _bounding_sphere_offset(_model->bounding_sphere_offset())
		  , _bounding_sphere_radius(_model->bounding_sphere_radius())
		{
		}

		auto local_transform() const noexcept -> auto& { return _local_transform; }
		auto model_aid() const -> auto& { return _model.aid(); }
		auto model() const -> auto& { return _model; }
		void model(Model_ptr model) { _model = std::move(model); }

		auto bounding_sphere_radius() const noexcept { return _bounding_sphere_radius; }
		auto bounding_sphere_offset() const noexcept { return _bounding_sphere_offset; }

	  private:
		Model_ptr _model;
		glm::mat4 _local_transform = glm::mat4(1.f);
		glm::vec3 _bounding_sphere_offset;
		float     _bounding_sphere_radius;
	};

	class Model_unloaded_comp : public ecs::Component<Model_unloaded_comp> {
	  public:
		static constexpr const char* name() { return "Model"; }
		friend void                  load_component(ecs::Deserializer& state, Model_unloaded_comp&);
		friend void                  save_component(ecs::Serializer& state, const Model_unloaded_comp&);

		Model_unloaded_comp() = default;
		Model_unloaded_comp(ecs::Entity_handle   owner,
		                    ecs::Entity_manager& em,
		                    asset::AID           model_aid       = {},
		                    const glm::mat4&     local_transform = glm::mat4(1.f))
		  : Component(owner, em), _model_aid(std::move(model_aid)), _local_transform(local_transform)
		{
		}

		auto local_transform() const noexcept -> auto& { return _local_transform; }
		auto model_aid() const -> auto& { return _model_aid; }

	  private:
		asset::AID _model_aid;
		glm::mat4  _local_transform = glm::mat4(1.f);
	};

	class Model_loading_comp : public ecs::Component<Model_loading_comp> {
	  public:
		static constexpr const char* name() { return "Model_loading"; }
		static constexpr const char* name_save_as() { return "Model"; }
		friend void                  load_component(ecs::Deserializer& state, Model_loading_comp&);
		friend void                  save_component(ecs::Serializer& state, const Model_loading_comp&);

		Model_loading_comp() = default;
		Model_loading_comp(ecs::Entity_handle   owner,
		                   ecs::Entity_manager& em,
		                   Model_ptr            model           = {},
		                   const glm::mat4&     local_transform = glm::mat4(1.f))
		  : Component(owner, em), _model(std::move(model)), _local_transform(local_transform)
		{
		}

		auto local_transform() const noexcept -> auto& { return _local_transform; }
		auto model_aid() const -> auto& { return _model.aid(); }
		auto model() const -> auto& { return _model; }
		auto model() -> auto& { return _model; }

	  private:
		Model_ptr _model;
		glm::mat4 _local_transform = glm::mat4(1.f);
	};
} // namespace mirrage::renderer


text:
<?php
App::uses('AppController', 'Controller');

class ApiBlocksController extends AppController
{
  public $uses = array('Block');
  public $components = array('Api');

  public function beforeFilter()
  {
    parent::beforeFilter();
  }

/**
 * Add the block.
 *
 * @param string $plugin
 * @param int $beforeBlockId
 * @return void
 */
  public function add()
  {
    $this->tokenFilterApi();
    $this->staffFilterApi();

    $r = $this->Block->addByPackage(
      @$this->request->data['page_id'],
      @$this->request->data['package'],
      @$this->request->data['sheet'],
      @$this->request->data['before_block_id'],
      $addedBlockId
    );
    if ($r !== TRUE) $this->Api->ng($r->getMessage());

    $this->Api->ok(array(
      'html' => $this->_htmlBlock($addedBlockId),
    ));
  }

/**
 * Load the block html
 *
 * @return void
 */
  public function html_block()
  {
    $this->tokenFilterApi();
    $this->staffFilterApi();

    $this->Api->ok(array(
      'html' => $this->_htmlBlock($this->request->data['block_id']),
    ));
  }

  public function save_sort()
  {
    $this->tokenFilterApi();
    $this->staffFilterApi();

    foreach ($this->request->data['sorted_ids'] as $sheet => $ids) {
      $sort = 0;
      foreach ($ids as $id) {
        $data = array(
          'id' => $id,
          'sheet' => $sheet,
          'order' => $sort,
        );
        $r = $this->Block->add($data, TRUE);
        $sort++;
      }
    }

    $this->Api->ok();
  }

/**
 * Delete the block.
 *
 * @param int $blockId
 * @return void
 */
  public function delete()
  {
    $this->tokenFilterApi();
    $this->staffFilterApi();

    $r = $this->Block->delete(@$this->request->data['block_id'], TRUE);
    if ($r !== TRUE) $this->Api->ng($r->getMessage());

    $this->Api->ok();
  }

}


text:
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <FrameLayout android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <fragment android:id="@+id/navigation_drawer"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:name="com.stanford.anglishwordbook.fragments.NavigationDrawerFragment"
        tools:layout="@layout/fragment_navigation_drawer"/>

</android.support.v4.widget.DrawerLayout>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Veiled species of Hebeloma in the western United States (Ann Arbor) 150 (1983)

#### Original name
Hebeloma oregonense var. atrobrunneum A.H. Sm., V.S. Evenson & Mitchel

### Remarks
null


text:
package com.quentindommerc.sentencify.activity;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.analytics.tracking.android.EasyTracker;
import com.quentindommerc.sentencify.R;
import com.quentindommerc.sentencify.adapter.FinalPlaylistAdapter;
import com.quentindommerc.sentencify.bean.Word;
import com.quentindommerc.sentencify.utils.LibSpotifyWrapper;

public class Playlist extends FragmentActivity {

	private com.quentindommerc.sentencify.bean.Playlist mPlaylist;
	private EditText mName;
	private ListView mList;
	private FinalPlaylistAdapter mFinalPlaylistAdapter;

	@Override
	protected void onStart() {
		super.onStart();
		EasyTracker.getInstance(this).activityStart(this);
	}

	@Override
	public void onStop() {
		super.onStop();
		EasyTracker.getInstance(this).activityStop(this);
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		mPlaylist = (com.quentindommerc.sentencify.bean.Playlist) getIntent().getExtras().get(
				"playlist");
		setContentView(R.layout.activity_playlist);
		mName = (EditText) findViewById(R.id.playlist_name);
		mName.setText(mPlaylist.getOriginal());
		mList = (ListView) findViewById(R.id.list);
		mFinalPlaylistAdapter = new FinalPlaylistAdapter(this);
		mFinalPlaylistAdapter.addAll(mPlaylist.getWords());
		mList.setAdapter(mFinalPlaylistAdapter);

	}

	public void create(View v) {
		ArrayList<String> mUri = new ArrayList<String>();
		for (Word w : mPlaylist.getWords()) {
			mUri.add(w.getSelectedTrack().getHref());
		}
		LibSpotifyWrapper.createPlaylist(mPlaylist.getOriginal(), mUri);
		Toast.makeText(this, getString(R.string.congrats), Toast.LENGTH_LONG).show();
		setResult(RESULT_OK);
		finish();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.about, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_about:
			about();
			break;

		case android.R.id.home:
			setResult(RESULT_OK);
			finish();
			break;

		default:
			break;
		}
		return true;
	}

	private void about() {
		Intent i = new Intent(this, About.class);
		startActivity(i);
	}
}


text:
package com.adenki.smpp.util;

/**
 * Some string utility methods.
 * @version $Id:$
 * @since 1.0.0
 */
public final class StringUtil {

    private StringUtil() {
    }

    /**
     * Return a Java String with any non-ASCII characters escaped using "\\u"
     * notation.
     * @param s The string to escape.
     * @return A new String with non-ASCII characters escaped.
     */
    public static String escapeJava(String s) {
        StringBuilder b = new StringBuilder(s.length());
        for (char c : s.toCharArray()) {
            if (Character.isLetterOrDigit(c) || Character.isWhitespace(c)) {
                b.append(c);
            } else {
                b.append(String.format("\\u%04x", (int) c));
            }
        }
        return b.toString();
    }

    /**
     * Return a Java String with any non-ASCII characters escaped using "\\u"
     * notation.
     * @param array An array of bytes to convert.
     * @return A new String with non-ASCII characters escaped.
     */
    public static String escapeJava(byte[] array) {
        StringBuilder b = new StringBuilder(array.length);
        for (byte el : array) {
            int i = (int) el & 0xff;
            if (Character.isLetterOrDigit(i)) {
                b.append((char) i);
            } else {
                b.append(String.format("\\u%04x", i));
            }
        }
        return b.toString();
    }
}


text:
id: 576
title: 'Volume group "VolGroup00" not found'
date: 2010-07-25T20:15:18+00:00
author: edyliu
layout: post
guid: http://192.168.1.77:8880/?p=576
permalink: /2010-07-volume-group-volgroup00-not-found/
categories:
  - Howto
  - linux
tags:
  - tips
  - virtualbox
---
Met a problem when try to copy virtualbox vdi file directly from Windows virtualbox to Linux

"Error: Volume group "VolGroup00″ not found

……

Kernel panic – not syncing: Attempted to kill init!"

Solution:

First, boot up in rescue mode, using the CentOS cd, type "linux rescue" on the first boot prompt.

Now chroot to you actual system:

#chroot /mnt/sysimage

Then, backup your initrd:

#cd /boot

#mv initrd-2.6.18-164.el5.img initrd.backup

(use the last version, or the one you are trying to boot, on the "2.6.18-92.el5.img" part)

Now rebuild your initrd:

#mkinitrd /boot/initrd-2.6.18-164.el5.img 2.6.18-164.el5

(Same thing about the versions)

#reboot


text:
=head1 NAME

LedgerSMB::Payroll::Income_Types - Income Types Searches for LedgerSMB

=head1 SYNPOSIS

 LedgerSMB::Payroll::Income_Types->new(%$request)->render(%$request);

=cut

package LedgerSMB::Report::Payroll::Income_Types;
use Moose;
extends 'LedgerSMB::Report';

=head1 DESCRIPTION

This module provides for searching for income types.

=head1 CONSTANT METHODS

=over

=item columns

=cut

sub columns {
    return [
        { col_id => 'country_name',
            name => LedgerSMB::Report::text('Country'),
            type => 'text',
        },
        { col_id => 'income_class',
            name => LedgerSMB::Report::text('Income Class'),
            type => 'text' },
        { col_id => 'label',
            name => LedgerSMB::Report::text('Label'),
            type => 'href',
       href_base => 'payrol.pl?action=edit&id=' },
    ];
}

=item header_lines

=cut

sub header_lines {
    return [];
}

=item name

=cut

sub name { return LedgerSMB::Report::text('Income Types') }

=back

=head1 CRITERIA PROPERTIES

=over

=item country_id int

Exact match on country id

=cut

has country_id => (is => 'ro', isa => 'Int', required => '0');

=item label string

Matches the beginning of the label

=cut

has label => (is => 'ro', isa => 'Str', required => '0');

=item pic_id int

Exact match on payroll income class id

=cut

has pic_id => (is => 'ro', isa => 'Int', required => '0');

=item account_id int

Exact match of the account id

=cut

has account_id => (is => 'ro', isa => 'Int', required => '0');

=item unit string

Exact match on unit

=cut

has unit => (is => 'ro', isa => 'Str', required => '0');

=back

=head1 METHODS

=over

=item run_report

=cut

sub run_report {
    my ($self) = $_;
    my @rows = $self->call_dbmethod(funcname => 'payroll_income_type__search');
    $_->{row_id} = $_->{id} for @rows;
    $self->rows(@rows);
}

=back

=head1 COPYRIGHT

COPYRIGHT (C) 2012 The LedgerSMB Core Team.  This file may be re-used following
the terms of the GNU General Public License version 2 or at your option any
later version.  Please see included LICENSE.TXT for details.

=cut

__PACKAGE__->meta->make_immutable;

1;


text:
@implementation PMBAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [self initializeStoryBoardBasedOnScreenSize];
    sleep(2);
    return YES;
}

-(void)initializeStoryBoardBasedOnScreenSize {
    UIStoryboard *storyboard = nil;
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone)
    {    // The iOS device = iPhone or iPod Touch
        CGSize iOSDeviceScreenSize = [[UIScreen mainScreen] bounds].size;
        if (iOSDeviceScreenSize.height == 480)
        {   // iPhone 3GS, 4, and 4S and iPod Touch 3rd and 4th generation: 3.5 inch screen (diagonally measured)
            NSLog(@"Loading iphone 4 storyboard");
            // Instantiate a new storyboard object using the storyboard file named MainStoryboard_iPhone
            if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
                // Load resources for iOS 6.1 or earlier
                storyboard = [UIStoryboard storyboardWithName:@"Storyboard_iPhone4_IOS6" bundle:nil];
            } else {
                // Load resources for iOS 7 or later
                storyboard = [UIStoryboard storyboardWithName:@"Storyboard_iPhone4_IOS7" bundle:nil];
            }
        }
        if (iOSDeviceScreenSize.height == 568)
        {   // iPhone 5 and iPod Touch 5th generation: 4 inch screen (diagonally measured)
            NSLog(@"Loading iphone 5 storyboard");
            // Instantiate a new storyboard object using the storyboard file named Storyboard_iPhone4

            if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
                // Load resources for iOS 6.1 or earlier
                NSLog(@"Loading Storyboard_iPhone5_IOS6 storyboard");
                storyboard = [UIStoryboard storyboardWithName:@"Storyboard_iPhone5_IOS6" bundle:nil];
            } else {
                // Load resources for iOS 7 or later
                NSLog(@"Loading Storyboard_iPhone5_IOS7 storyboard");
                storyboard = [UIStoryboard storyboardWithName:@"Storyboard_iPhone5_IOS7" bundle:nil];
            }
        }

    } else if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad){
        // The iOS device = iPad
        NSLog(@"Loading ipad storyboard");
        // Instantiate a new storyboard object using the storyboard file named Storyboard_iPhone35
        storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle:nil];
    }
    // Instantiate the initial view controller object from the storyboard
    UIViewController *initialViewController = [storyboard instantiateInitialViewController];

    // Instantiate a UIWindow object and initialize it with the screen size of the iOS device
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Set the initial view controller to be the root view controller of the window object
    self.window.rootViewController  = initialViewController;

    // Set the window object to be the key window and show it
    [self.window makeKeyAndVisible];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
class StompClient
  extend Memoist

  def initialize(attrs)
    @username = attrs.fetch(:username)
    @password = attrs.fetch(:password)
    @host = attrs.fetch(:host)
    @port = attrs.fetch(:port)
    @topic = attrs.fetch(:topic)
    @client_id = Socket.gethostname
    @subscription_id = @client_id + '-' + SecureRandom.uuid
  end

  def get
    q = Queue.new
    connect
    subscribe do |msg|
      if msg.present?
        q.enq(msg.body)
        unsubscribe
      end
    end
    result = q.deq
    disconnect
    result
  end

  protected

  attr_reader :username, :password, :host, :port, :topic, :client_id, :subscription_id

  def client
    client_headers = { "accept-version" => "1.1", "heart-beat" => "5000,10000", "client-id" => client_id, "host" => host }
    client_hash = { :hosts => [ { :login => username, :passcode => password, :host => host, :port => port } ], :connect_headers => client_headers }
    Stomp::Client.new(client_hash)
  end

  memoize :client

  def subscribe(&block)
    client.subscribe(topic, { 'id' => client.uuid(), 'ack' => 'client', 'activemq.subscriptionName' => subscription_id }) do |msg|
      client.acknowledge(msg, msg.headers)
      block.call(msg)
    end
  end

  def unsubscribe
    client.join
  end

  def connect
    raise "Connection failed" unless client.open?
    raise "Connect error: #{client.connection_frame().body}" if client.connection_frame().command == Stomp::CMD_ERROR
    raise "Unexpected protocol level #{client.protocol}" unless client.protocol == Stomp::SPL_11
  end

  def disconnect
    client.close
  end
end


text:
package org.jenkinsci.plugins.dependencycheck;

import hudson.FilePath;
import hudson.model.Result;
import org.jenkinsci.plugins.DependencyCheck.DependencyCheckPublisher;
import org.jenkinsci.plugins.DependencyCheck.DependencyCheckResultAction;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import static org.junit.Assert.*;

public class DependencyCheckWorkflowTest {

    @Rule
    public JenkinsRule jenkinsRule = new JenkinsRule();

    /**
     * Run a workflow job using {@link org.jenkinsci.plugins.DependencyCheck.DependencyCheckPublisher} and check for success.
     */
    @Test
    public void dependencyCheckPublisherWorkflowStep() throws Exception {
        WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "dependencyCheckWorkPublisherWorkflowStep");
        FilePath workspace = jenkinsRule.jenkins.getWorkspaceFor(job);
        FilePath report = workspace.child("target").child("dependency-check-report.xml");
        report.copyFrom(DependencyCheckWorkflowTest.class.getResourceAsStream("/org/jenkinsci/plugins/dependencycheck/parser/dependency-check-report2.xml"));
        job.setDefinition(new CpsFlowDefinition(""
                        + "node {\n"
                        + "  step([$class: 'DependencyCheckPublisher'])\n"
                        + "}\n", true)
        );
        jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
        DependencyCheckResultAction result = job.getLastBuild().getAction(DependencyCheckResultAction.class);
        assertTrue(result.getResult().getAnnotations().size() == 2);
    }

    /**
     * Run a workflow job using {@link DependencyCheckPublisher} with a failing threshold of 0, so the given example file
     * "/org/jenkinsci/plugins/dependencycheck/parser/dependency-check-report2.xml" will make the build to fail.
     */
    @Test
    public void dependencyCheckPublisherWorkflowStepSetLimits() throws Exception {
        WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "dependencyCheckPublisherWorkflowStepSetLimits");
        FilePath workspace = jenkinsRule.jenkins.getWorkspaceFor(job);
        FilePath report = workspace.child("target").child("dependency-check-report.xml");
        report.copyFrom(DependencyCheckWorkflowTest.class.getResourceAsStream("/org/jenkinsci/plugins/dependencycheck/parser/dependency-check-report2.xml"));
        job.setDefinition(new CpsFlowDefinition(""
                        + "node {\n"
                        + "  step([$class: 'DependencyCheckPublisher', pattern: '**/dependency-check-report.xml', failedTotalAll: '0', usePreviousBuildAsReference: false])\n"
                        + "}\n", true)
        );
        jenkinsRule.assertBuildStatus(Result.FAILURE, job.scheduleBuild2(0).get());
        DependencyCheckResultAction result = job.getLastBuild().getAction(DependencyCheckResultAction.class);
        assertTrue(result.getResult().getAnnotations().size() == 2);
    }

    /**
     * Run a workflow job using {@link DependencyCheckPublisher} with a unstable threshold of 0, so the given example file
     * "/org/jenkinsci/plugins/dependencycheck/parser/dependency-check-report2.xml" will make the build to fail.
     */
    @Test
    public void dependencyCheckPublisherWorkflowStepFailure() throws Exception {
        WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "dependencyCheckPublisherWorkflowStepFailure");
        FilePath workspace = jenkinsRule.jenkins.getWorkspaceFor(job);
        FilePath report = workspace.child("target").child("dependency-check-report.xml");
        report.copyFrom(DependencyCheckWorkflowTest.class.getResourceAsStream("/org/jenkinsci/plugins/dependencycheck/parser/dependency-check-report2.xml"));
        job.setDefinition(new CpsFlowDefinition(""
                        + "node {\n"
                        + "  step([$class: 'DependencyCheckPublisher', pattern: '**/dependency-check-report.xml', unstableTotalAll: '0', usePreviousBuildAsReference: false])\n"
                        + "}\n")
        );
        jenkinsRule.assertBuildStatus(Result.UNSTABLE, job.scheduleBuild2(0).get());
        DependencyCheckResultAction result = job.getLastBuild().getAction(DependencyCheckResultAction.class);
        assertTrue(result.getResult().getAnnotations().size() == 2);
    }
}


text:
package org.apache.commons.validator.routines;

import java.text.DecimalFormat;
import java.text.Format;
import java.math.BigDecimal;

import com.google.gwt.core.shared.GwtIncompatible;

/**
 *
Percentage Validation and Conversion routines (java.math.BigDecimal).

 *
 *
This is one implementation of a percent validator that has the following features:

 *

 *
It is lenient about the the presence of the percent symbol

 *
It converts the percent to a java.math.BigDecimal

 *

 *
 *
However any of the number validators can be used for percent validation.
 *    For example, if you wanted a percent validator that converts to a
 *    java.lang.Float then you can simply instantiate an
 *    FloatValidator with the appropriate format type:

 *
 *
... = new FloatValidator(false, FloatValidator.PERCENT_FORMAT);

 *
 *
Pick the appropriate validator, depending on the type (i.e Float, Double or BigDecimal)
 *    you want the percent converted to. Please note, it makes no sense to use
 *    one of the validators that doesn't handle fractions (i.e. byte, short, integer, long
 *    and BigInteger) since percentages are converted to fractions (i.e 50% is
 *    converted to 0.5).

 *
 * @version $Revision: 1739356 $
 * @since Validator 1.3.0
 */
@GwtIncompatible("incompatible class")
public class PercentValidator extends BigDecimalValidator {

    private static final long serialVersionUID = -3508241924961535772L;

    private static final PercentValidator VALIDATOR = new PercentValidator();

    /** DecimalFormat's percent (thousand multiplier) symbol */
    private static final char PERCENT_SYMBOL = '%';

    private static final BigDecimal POINT_ZERO_ONE = new BigDecimal("0.01");

    /**
     * Return a singleton instance of this validator.
     * @return A singleton instance of the PercentValidator.
     */
    public static BigDecimalValidator getInstance() {
        return VALIDATOR;
    }

    /**
     * Construct a strict instance.
     */
    public PercentValidator() {
        this(true);
    }

    /**
     * Construct an instance with the specified strict setting.
     *
     * @param strict true if strict
     *        Format parsing should be used.
     */
    public PercentValidator(boolean strict) {
        super(strict, PERCENT_FORMAT, true);
    }

    /**
     *
Parse the value with the specified Format.

     *
     *
This implementation is lenient whether the currency symbol
     *    is present or not. The default NumberFormat
     *    behaviour is for the parsing to "fail" if the currency
     *    symbol is missing. This method re-parses with a format
     *    without the currency symbol if it fails initially.

     *
     * @param value The value to be parsed.
     * @param formatter The Format to parse the value with.
     * @return The parsed value if valid or null if invalid.
     */
    @Override
    protected Object parse(String value, Format formatter) {

        // Initial parse of the value
        BigDecimal parsedValue = (BigDecimal)super.parse(value, formatter);
        if (parsedValue != null || !(formatter instanceof DecimalFormat)) {
            return parsedValue;
        }

        // Re-parse using a pattern without the percent symbol
        DecimalFormat decimalFormat = (DecimalFormat)formatter;
        String pattern = decimalFormat.toPattern();
        if (pattern.indexOf(PERCENT_SYMBOL) >= 0) {
            StringBuilder buffer = new StringBuilder(pattern.length());
            for (int i = 0; i < pattern.length(); i++) {
                if (pattern.charAt(i) != PERCENT_SYMBOL) {
                    buffer.append(pattern.charAt(i));
                }
            }
            decimalFormat.applyPattern(buffer.toString());
            parsedValue = (BigDecimal)super.parse(value, decimalFormat);

            // If parsed OK, divide by 100 to get percent
            if (parsedValue != null) {
                parsedValue = parsedValue.multiply(POINT_ZERO_ONE);
            }

        }
        return parsedValue;
    }
}


text:
package VMOMI::VirtualE1000Option;
use parent 'VMOMI::VirtualEthernetCardOption';

use strict;
use warnings;

our @class_ancestors = (
    'VirtualEthernetCardOption',
    'VirtualDeviceOption',
    'DynamicData',
);

our @class_members = ( );

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;