text:
<?php
namespace inklabs\kommerce\EntityRepository;

use inklabs\kommerce\Entity\TaxRate;
use inklabs\kommerce\Exception\InvalidArgumentException;
use inklabs\kommerce\Lib\UuidInterface;

/**
 * @method TaxRate findOneById(UuidInterface $id)
 */
interface TaxRateRepositoryInterface extends RepositoryInterface
{
    /**
     * @return TaxRate[]
     */
    public function findAll();

    public function findByZip5AndState(string $zip5 = null, string $state = null): ?TaxRate;
}


text:
from typing import Dict, List, Callable, Optional, Any, Union, Iterable, Set, cast
from typing import Generic, Sequence, Tuple, TypeVar, Iterator
import contextlib
from contextvars import ContextVar
import srsly
from pathlib import Path
import copy
import functools
import threading

from .backends import ParamServer, Ops, NumpyOps, CupyOps, get_current_ops
from .optimizers import Optimizer  # noqa: F401
from .shims import Shim
from .util import convert_recursive, is_xp_array, DATA_VALIDATION
from .util import partial, validate_fwd_input_output
from .types import FloatsXd

InT = TypeVar("InT")
OutT = TypeVar("OutT")
SelfT = TypeVar("SelfT", bound="Model")

context_operators: ContextVar[dict] = ContextVar("context_operators", default={})

def empty_init(model: "Model", *args, **kwargs) -> "Model":
    return model

class Model(Generic[InT, OutT]):
    """Class for implementing Thinc models and layers."""

    global_id: int = 0
    global_id_lock: threading.Lock = threading.Lock()
    _context_operators = context_operators

    name: str
    ops: Ops
    id: int
    _func: Callable
    init: Callable
    _params: ParamServer
    _dims: Dict[str, Optional[int]]
    _layers: List["Model"]
    _shims: List[Shim]
    _attrs: Dict[str, Any]
    _has_params: Dict[str, Optional[bool]]

    # This "locks" the class, so we get an error if you try to assign to
    # an unexpected variable.
    __slots__ = [
        "name",
        "id",
        "ops",
        "_func",
        "init",
        "_params",
        "_dims",
        "_attrs",
        "_refs",
        "_layers",
        "_shims",
        "_has_params",
    ]

    def __init__(
        self,
        name: str,
        forward: Callable,
        *,
        init: Optional[Callable] = None,
        dims: Dict[str, Optional[int]] = {},
        params: Dict[str, Optional[FloatsXd]] = {},
        layers: Sequence["Model"] = [],
        shims: List[Shim] = [],
        attrs: Dict[str, Any] = {},
        refs: Dict[str, Optional["Model"]] = {},
        ops: Optional[Union[NumpyOps, CupyOps]] = None,
    ):
        """Initialize a new model."""
        self.name = name
        if init is None:
            init = partial(empty_init, self)
        # Assign to callable attrs: https://github.com/python/mypy/issues/2427
        setattr(self, "_func", forward)
        setattr(self, "init", init)
        self.ops = ops if ops is not None else get_current_ops()
        self._params = ParamServer()
        self._dims = dict(dims)
        self._attrs = dict(attrs)
        self._refs = dict(refs)
        self._layers = list(layers)
        self._shims = list(shims)
        # Take care to increment the base class here! It needs to be unique
        # across all models.
        with Model.global_id_lock:
            Model.global_id += 1
            self.id = Model.global_id
        self._has_params = {}
        for name, value in params.items():
            self._has_params[name] = None
            if value is not None:
                self.set_param(name, value)

    @property
    def layers(self) -> List["Model"]:
        """A list of child layers of the model. You can append to it to add
        layers but not reassign it.
        """
        return self._layers

    @property
    def shims(self) -> List[Shim]:
        return self._shims

    @property
    def attrs(self) -> Dict[str, Any]:
        """A dict of the model's attrs. You can write to it to update attrs but
        not reassign it.
        """
        return self._attrs

    @property
    def param_names(self) -> Tuple[str, ...]:
        """Get the names of registered parameter (including unset)."""
        return tuple(self._has_params.keys())

    @property
    def grad_names(self) -> Tuple[str, ...]:
        """Get the names of parameters with registered gradients (including unset)."""
        return tuple([name for name in self.param_names if self.has_grad(name)])

    @property
    def dim_names(self) -> Tuple[str, ...]:
        """Get the names of registered dimensions (including unset)."""
        return tuple(self._dims.keys())

    @property
    def ref_names(self) -> Tuple[str, ...]:
        """Get the names of registered node references (including unset)."""
        return tuple(self._refs.keys())

    @classmethod
    @contextlib.contextmanager
    def define_operators(cls, operators: Dict[str, Callable]):
        """Bind arbitrary binary functions to Python operators, for use in any
        `Model` instance. Can (and should) be used as a contextmanager.

        EXAMPLE:
            with Model.define_operators({">>": chain}):
                model = Relu(512) >> Relu(512) >> Softmax()
        """
        token = cls._context_operators.set(dict(operators))
        yield
        cls._context_operators.reset(token)

    def has_dim(self, name: str) -> Optional[bool]:
        """Check whether the model has a dimension of a given name. If the
        dimension is registered but the value is unset, returns None.
        """
        if name not in self._dims:
            return False
        elif self._dims[name] is not None:
            return True
        else:
            return None

    def get_dim(self, name: str) -> int:
        """Retrieve the value of a dimension of the given name."""
        if name not in self._dims:
            raise KeyError(f"Cannot get dimension '{name}' for model '{self.name}'")
        value = self._dims[name]
        if value is None:
            err = f"Cannot get dimension '{name}' for model '{self.name}': value unset"
            raise ValueError(err)
        else:
            return value

    def set_dim(self, name: str, value: int, *, force: bool = False) -> None:
        """Set a value for a dimension."""
        if name not in self._dims:
            raise KeyError(
                f"Cannot set unknown dimension '{name}' for model '{self.name}'."
            )
        old_value = self._dims[name]
        has_params = any(bool(y) for x, y in self._has_params.items())
        invalid_change = (old_value is not None and old_value != value) and (
            not force or force and has_params
        )
        if invalid_change:
            err = f"Attempt to change dimension '{name}' for model '{self.name}' from {old_value} to {value}"
            raise ValueError(err)
        self._dims[name] = value

    def maybe_get_dim(self, name: str) -> Optional[int]:
        """Retrieve the value of a dimension of the given name, or None."""
        return self.get_dim(name) if self.has_dim(name) else None

    def has_param(self, name: str) -> Optional[bool]:
        """Check whether the model has a weights parameter of the given name.

        Returns None if the parameter is registered but currently unset.
        """
        if name not in self._has_params:
            return False
        elif self._has_params[name] is not None:
            return True
        else:
            return None

    def get_param(self, name: str) -> FloatsXd:
        """Retrieve a weights parameter by name."""
        if name not in self._has_params:
            raise KeyError(f"Unknown param: '{name}' for model '{self.name}'.")
        if not self._params.has_param(self.id, name):
            raise KeyError(
                f"Parameter '{name}' for model '{self.name}' has not been allocated yet."
            )
        return self._params.get_param(self.id, name)

    def maybe_get_param(self, name: str) -> Optional[FloatsXd]:
        """Retrieve a weights parameter by name, or None."""
        return self.get_param(name) if self.has_param(name) else None

    def set_param(self, name: str, value: Optional[FloatsXd]) -> None:
        """Set a weights parameter's value."""
        if value is None:
            self._has_params[name] = None
        else:
            self._params.set_param(self.id, name, value)
            self._has_params[name] = True

    def has_grad(self, name: str) -> bool:
        """Check whether the model has a non-zero gradient for a parameter."""
        return self._params.has_grad(self.id, name)

    def get_grad(self, name: str) -> FloatsXd:
        """Get a gradient from the model."""
        return self._params.get_grad(self.id, name)

    def set_grad(self, name: str, value: FloatsXd) -> None:
        """Set a gradient value for the model."""
        self._params.set_grad(self.id, name, value)

    def maybe_get_grad(self, name: str) -> Optional[FloatsXd]:
        """Retrieve a gradient by name, or None."""
        return self.get_grad(name) if self.has_grad(name) else None

    def inc_grad(self, name: str, value: FloatsXd) -> None:
        """Increment the gradient of a parameter by a value."""
        self._params.inc_grad(self.id, name, value)

    def has_ref(self, name: str) -> Optional[bool]:
        """Check whether the model has a reference of a given name. If the
        reference is registered but the value is unset, returns None.
        """
        if name not in self._refs:
            return False
        elif self._refs[name] is not None:
            return True
        else:
            return None

    def get_ref(self, name: str) -> "Model":
        """Retrieve the value of a reference of the given name."""
        if name not in self._refs:
            raise KeyError(f"Cannot get reference '{name}' for model '{self.name}'.")
        value = self._refs[name]
        if value is None:
            err = f"Cannot get reference '{name}' for model '{self.name}': value unset."
            raise ValueError(err)
        else:
            return value

    def maybe_get_ref(self, name: str) -> Optional["Model"]:
        """Retrieve the value of a reference if it exists, or None."""
        return self.get_ref(name) if self.has_ref(name) else None

    def set_ref(self, name: str, value: Optional["Model"]) -> None:
        """Set a value for a reference."""
        if value is None:
            self._refs[name] = value
        elif value in self.walk():
            self._refs[name] = value
        else:
            raise ValueError("Cannot add reference to node not in tree.")

    def __call__(self, X: InT, is_train: bool) -> Tuple[OutT, Callable]:
        """Call the model's `forward` function, returning the output and a
        callback to compute the gradients via backpropagation."""
        return self._func(self, X, is_train=is_train)

    def initialize(self, X: Optional[InT] = None, Y: Optional[OutT] = None) -> "Model":
        """Finish initialization of the model, optionally providing a batch of
        example input and output data to perform shape inference."""
        if DATA_VALIDATION.get():
            validate_fwd_input_output(self.name, self._func, X, Y)
        if self.init is not None:
            self.init(self, X=X, Y=Y)
        return self

    def begin_update(self, X: InT) -> Tuple[OutT, Callable[[InT], OutT]]:
        """Run the model over a batch of data, returning the output and a
        callback to complete the backward pass. A tuple (Y, finish_update),
        where Y is a batch of output data, and finish_update is a callback that
        takes the gradient with respect to the output and an optimizer function,
        and returns the gradient with respect to the input.
        """
        return self._func(self, X, is_train=True)

    def predict(self, X: InT) -> OutT:
        """Call the model's `forward` function with `is_train=False`, and return
        only the output, instead of the `(output, callback)` tuple.
        """
        return self._func(self, X, is_train=False)[0]

    def finish_update(self, optimizer: Optimizer) -> None:
        """Update parameters with current gradients. The optimizer is called
        with each parameter and gradient of the model.
        """
        for node in self.walk():
            for shim in node.shims:
                shim.finish_update(optimizer)
        for node in self.walk():
            for name in node.param_names:
                if node.has_grad(name):
                    param, grad = optimizer(
                        (node.id, name), node.get_param(name), node.get_grad(name)
                    )
                    node.set_param(name, param)

    @contextlib.contextmanager
    def use_params(self, params: Dict[Tuple[int, str], FloatsXd]):
        """Context manager to temporarily set the model's parameters to
        specified values. The params are a dictionary keyed by model IDs, whose
        values are arrays of weight values.
        """
        backup = {}
        for name in self.param_names:
            key = (self.id, name)
            if key in params:
                backup[name] = self.get_param(name)
                self.set_param(name, params[key])

        with contextlib.ExitStack() as stack:
            for layer in self.layers:
                stack.enter_context(layer.use_params(params))
            for shim in self.shims:
                stack.enter_context(shim.use_params(params))
            yield
        if backup:
            for name, param in backup.items():
                self.set_param(name, param)

    def walk(self, *, order: str = "bfs") -> Iterable["Model"]:
        """Iterate out layers of the model.

        Nodes are returned in breadth-first order by default. Other possible
        orders are "dfs_pre" (depth-first search in preorder) and "dfs_post"
        (depth-first search in postorder)."""
        if order == "bfs":
            return self._walk_bfs()
        elif order == "dfs_pre":
            return self._walk_dfs(post_order=False)
        elif order == "dfs_post":
            return self._walk_dfs(post_order=True)
        else:
            raise ValueError("Invalid order, must be one of: bfs, dfs_pre, dfs_post")

    def _walk_bfs(self) -> Iterable["Model"]:
        """Iterate out layers of the model, breadth-first."""
        queue = [self]
        seen: Set[int] = set()
        for node in queue:
            if id(node) in seen:
                continue
            seen.add(id(node))
            yield node
            queue.extend(node.layers)

    def _walk_dfs(self, post_order: bool = False) -> Iterable["Model"]:
        """Iterate out layers of the model, depth-first."""
        seen: Dict[int, Iterator["Model"]] = dict()
        stack = [self]
        seen[id(self)] = iter(self.layers)
        if not post_order:
            yield self

        while stack:
            try:
                next_child = next(seen[id(stack[-1])])
                if not id(next_child) in seen:
                    if not post_order:
                        yield next_child

                    stack.append(next_child)
                    seen[id(next_child)] = iter(next_child.layers)
            except StopIteration:
                if post_order:
                    yield stack[-1]
                stack.pop()

    def remove_node(self, node: "Model") -> None:
        """Remove a node from all layers lists, and then update references.
        References that no longer point to a node within the tree will be set
        to `None`. For instance, let's say a node has its grandchild as a reference.
        If the child is removed, the grandchild reference will be left dangling,
        so will be set to None.
        """
        for child in list(self.walk()):
            while node in child.layers:
                child.layers.remove(node)
        tree = set(self.walk())
        for node in tree:
            for name in node.ref_names:
                ref = node.get_ref(name)
                if ref is not None and ref not in tree:
                    node.set_ref(name, None)

    def replace_callbacks(
        self, forward: Callable, *, init: Optional[Callable] = None
    ) -> None:
        setattr(self, "_func", forward)
        setattr(self, "init", init)

    def replace_node(self, old: "Model", new: "Model") -> bool:
        """Replace a node anywhere it occurs within the model. Returns a boolean
        indicating whether the replacement was made."""
        seen = False

        # We need to replace nodes in topological order of the transposed graph
        # to ensure that a node's dependencies are processed before the node.
        # This is equivalent to a post-order traversal of the original graph.
        for node in list(self.walk(order="dfs_post")):
            if node is old:
                seen = True
            else:
                node._layers = [
                    new if layer is old else layer for layer in node._layers
                ]
                for name in node.ref_names:
                    if node.get_ref(name) is old:
                        node.set_ref(name, new)

        return seen

    def get_gradients(self) -> Dict[Tuple[int, str], Tuple[FloatsXd, FloatsXd]]:
        """Get non-zero gradients of the model's parameters, as a dictionary
        keyed by the parameter ID. The values are (weights, gradients) tuples.
        """
        gradients = {}
        for node in self.walk():
            for name in node.grad_names:
                param = node.get_param(name)
                grad = node.get_grad(name)
                gradients[(node.id, name)] = (param, grad)
        return gradients

    def copy(self: SelfT) -> SelfT:
        """
        Create a copy of the model, its attributes, and its parameters. Any child
        layers will also be deep-copied. The copy will receive a distinct `model.id`
        value.
        """
        return self._copy()

    def _copy(
        self: SelfT, seen: Optional[Dict[int, Union["Model", Shim]]] = None
    ) -> SelfT:
        if seen is None:
            seen = {}
        params = {}
        for name in self.param_names:
            params[name] = self.get_param(name) if self.has_param(name) else None

        copied_layers: List[Model] = []
        for layer in self.layers:
            if id(layer) in seen:
                copied_layers.append(cast(Model, seen[id(layer)]))
            else:
                copied_layer = layer._copy(seen)
                seen[id(layer)] = copied_layer
                copied_layers.append(copied_layer)

        copied_shims = []
        for shim in self.shims:
            if id(shim) in seen:
                copied_shims.append(cast(Shim, seen[id(shim)]))
            else:
                copied_shim = shim.copy()
                seen[id(shim)] = copied_shim
                copied_shims.append(copied_shim)

        copied: Model[InT, OutT] = Model(
            self.name,
            self._func,
            init=self.init,
            params=copy.deepcopy(params),
            dims=copy.deepcopy(self._dims),
            attrs=copy.deepcopy(self._attrs),
            layers=copied_layers,
            shims=copied_shims,
        )
        for name in self.grad_names:
            copied.set_grad(name, self.get_grad(name).copy())
        return cast(SelfT, copied)

    def to_gpu(self, gpu_id: int) -> None:  # pragma: no cover
        """Transfer the model to a given GPU device."""
        import cupy.cuda.device

        with cupy.cuda.device.Device(gpu_id):
            self._to_ops(CupyOps())

    def to_cpu(self) -> None:  # pragma: no cover
        """Transfer the model to CPU."""
        self._to_ops(NumpyOps())

    def _to_ops(self, ops: Ops) -> None:  # pragma: no cover
        """Common method for to_cpu/to_gpu."""
        for node in self.walk():
            node.ops = ops
            for name in node.param_names:
                if node.has_param(name):
                    node.set_param(name, ops.asarray_f(node.get_param(name)))
                if node.has_grad(name):
                    node.set_grad(name, ops.asarray_f(node.get_grad(name)))
            for shim in node.shims:
                shim.to_device(ops.device_type, ops.device_id)

    def to_bytes(self) -> bytes:
        """Serialize the model to a bytes representation. Models are usually
        serialized using msgpack, so you should be able to call msgpack.loads()
        on the data and get back a dictionary with the contents.

        Serialization should round-trip identically, i.e. the same bytes should
        result from loading and serializing a model.
        """
        msg = self.to_dict()
        to_numpy_le = partial(self.ops.to_numpy, byte_order="<")
        msg = convert_recursive(is_xp_array, to_numpy_le, msg)
        return srsly.msgpack_dumps(msg)

    def to_disk(self, path: Union[Path, str]) -> None:
        """Serialize the model to disk. Most models will serialize to a single
        file, which should just be the bytes contents of model.to_bytes().
        """
        path = Path(path) if isinstance(path, str) else path
        with path.open("wb") as file_:
            file_.write(self.to_bytes())

    def to_dict(self) -> Dict:
        """Serialize the model to a dict representation.

        Serialization should round-trip identically, i.e. the same dict should
        result from loading and serializing a model.
        """
        # We separate out like this to make it easier to read the data in chunks.
        # The shims might have large weights, while the nodes data will be
        # small. The attrs are probably not very large, but could be.
        # The lists are aligned, and refer to the order of self.walk().
        msg: Dict[str, List] = {"nodes": [], "attrs": [], "params": [], "shims": []}
        nodes = list(self.walk())
        # Serialize references by their index into the flattened tree.
        # This is the main reason we can't accept out-of-tree references:
        # we'd have no way to serialize/deserialize them.
        node_to_i: Dict[int, Optional[int]]
        node_to_i = {node.id: i for i, node in enumerate(nodes)}
        for i, node in enumerate(nodes):
            refs: Dict[str, Optional[int]] = {}
            invalid_refs: List[str] = []
            for name in node.ref_names:
                if not node.has_ref(name):
                    refs[name] = None
                else:
                    ref = node.get_ref(name)
                    if ref.id in node_to_i:
                        refs[name] = node_to_i[ref.id]
                    else:
                        invalid_refs.append(name)
            if invalid_refs:
                raise ValueError(f"Cannot get references: {invalid_refs}")
            dims = {}
            for dim in node.dim_names:
                dims[dim] = node.get_dim(dim) if node.has_dim(dim) else None
            msg["nodes"].append(
                {"index": i, "name": node.name, "dims": dims, "refs": refs}
            )
        for node in nodes:
            attrs = {}
            for name, value in node.attrs.items():
                try:
                    attrs[name] = serialize_attr(value, value, name, node)
                except TypeError:
                    continue
            msg["attrs"].append(attrs)
        for node in nodes:
            msg["shims"].append([shim.to_bytes() for shim in node.shims])
        for node in nodes:
            params: Dict[str, Optional[FloatsXd]] = {}
            for name in node.param_names:
                if node.has_param(name):
                    params[name] = cast(Optional[FloatsXd], node.get_param(name))
                else:
                    params[name] = None
            msg["params"].append(params)
        return msg

    def from_bytes(self, bytes_data: bytes) -> "Model":
        """Deserialize the model from a bytes representation. Models are usually
        serialized using msgpack, so you should be able to call msgpack.loads()
        on the data and get back a dictionary with the contents.

        Serialization should round-trip identically, i.e. the same bytes should
        result from loading and serializing a model.
        """
        msg = srsly.msgpack_loads(bytes_data)
        msg = convert_recursive(is_xp_array, self.ops.asarray, msg)
        return self.from_dict(msg)

    def from_disk(self, path: Union[Path, str]) -> "Model":
        """Deserialize the model from disk. Most models will serialize to a single
        file, which should just be the bytes contents of model.to_bytes().
        """
        path = Path(path) if isinstance(path, str) else path
        with path.open("rb") as file_:
            bytes_data = file_.read()
        return self.from_bytes(bytes_data)

    def from_dict(self, msg: Dict) -> "Model":
        if "nodes" not in msg.keys():  # pragma: no cover
            err = "Trying to read a Model that was created with an incompatible version of Thinc"
            raise ValueError(err)
        nodes = list(self.walk())
        if len(msg["nodes"]) != len(nodes):
            raise ValueError("Cannot deserialize model: mismatched structure")
        for i, node in enumerate(nodes):
            info = msg["nodes"][i]
            node.name = info["name"]
            for dim, value in info["dims"].items():
                if value is not None:
                    node.set_dim(dim, value)
            for ref, ref_index in info["refs"].items():
                if ref_index is None:
                    node.set_ref(ref, None)
                else:
                    node.set_ref(ref, nodes[ref_index])
            for attr, value in msg["attrs"][i].items():
                default_value = node.attrs.get(attr)
                loaded_value = deserialize_attr(default_value, value, attr, node)
                node.attrs[attr] = loaded_value
            for param_name, value in msg["params"][i].items():
                if value is not None:
                    value = node.ops.asarray(value).copy()
                node.set_param(param_name, value)
            for i, shim_bytes in enumerate(msg["shims"][i]):
                node.shims[i].from_bytes(shim_bytes)
        return self

    def can_from_disk(self, path: Union[Path, str], *, strict: bool = True) -> bool:
        """Check whether serialized data on disk is compatible with the model.
        If 'strict', the function returns False if the model has an attribute
        already loaded that would be changed.
        """
        path = Path(path) if isinstance(path, str) else path
        if path.is_dir() or not path.exists():
            return False
        with path.open("rb") as file_:
            bytes_data = file_.read()
        return self.can_from_bytes(bytes_data, strict=strict)

    def can_from_bytes(self, bytes_data: bytes, *, strict: bool = True) -> bool:
        """Check whether the bytes data is compatible with the model. If 'strict',
        the function returns False if the model has an attribute already loaded
        that would be changed.
        """
        try:
            msg = srsly.msgpack_loads(bytes_data)
        except ValueError:
            return False
        return self.can_from_dict(msg, strict=strict)

    def can_from_dict(self, msg: Dict, *, strict: bool = True) -> bool:
        """Check whether a dictionary is compatible with the model.
        If 'strict', the function returns False if the model has an attribute
        already loaded that would be changed.
        """
        if "nodes" not in msg.keys():
            return False
        nodes = list(self.walk())
        if len(msg["nodes"]) != len(nodes):
            return False

        for i, node in enumerate(nodes):
            info = msg["nodes"][i]
            if strict and info["name"] != node.name:
                return False
            if len(msg["shims"][i]) != len(node.shims):
                # TODO: The shims should have a check for this too, but
                # for now we just check if the lengths match.
                return False
            for dim, value in info["dims"].items():
                has_dim = node.has_dim(dim)
                if has_dim is False:
                    return False
                elif has_dim and node.get_dim(dim) != value:
                    return False
            for param_name, value in msg["params"][i].items():
                has_param = node.has_param(param_name)
                if has_param is False:
                    return False
                elif has_param and value is not None:
                    param = node.get_param(param_name)
                    if param.shape != value.shape:
                        return False
            if strict:
                for attr, value in msg["attrs"][i].items():
                    if attr in node.attrs:
                        try:

                            serialized = serialize_attr(
                                node.attrs[attr], node.attrs[attr], attr, node
                            )
                        except TypeError:
                            continue
                        if serialized != value:
                            return False
        return True

    def __add__(self, other: Any) -> "Model":
        """Apply the function bound to the '+' operator."""
        if "+" not in self._context_operators.get():
            raise TypeError("Undefined operator: +")
        return self._context_operators.get()["+"](self, other)

    def __sub__(self, other: Any) -> "Model":
        """Apply the function bound to the '-' operator."""
        if "-" not in self._context_operators.get():
            raise TypeError("Undefined operator: -")
        return self._context_operators.get()["-"](self, other)

    def __mul__(self, other: Any) -> "Model":
        """Apply the function bound to the '*' operator."""
        if "*" not in self._context_operators.get():
            raise TypeError("Undefined operator: *")
        return self._context_operators.get()["*"](self, other)

    def __matmul__(self, other: Any) -> "Model":
        """Apply the function bound to the '@' operator."""
        if "@" not in self._context_operators.get():
            raise TypeError("Undefined operator: @")
        return self._context_operators.get()["@"](self, other)

    def __div__(self, other: Any) -> "Model":  # pragma: no cover
        """Apply the function bound to the '/' operator."""
        if "/" not in self._context_operators.get():
            raise TypeError("Undefined operator: /")
        return self._context_operators.get()["/"](self, other)

    def __truediv__(self, other: Any) -> "Model":
        """Apply the function bound to the '/' operator."""
        if "/" not in self._context_operators.get():
            raise TypeError("Undefined operator: /")
        return self._context_operators.get()["/"](self, other)

    def __floordiv__(self, other: Any) -> "Model":
        """Apply the function bound to the '//' operator."""
        if "//" not in self._context_operators.get():
            raise TypeError("Undefined operator: //")
        return self._context_operators.get()["//"](self, other)

    def __mod__(self, other: Any) -> "Model":
        """Apply the function bound to the '%' operator."""
        if "%" not in self._context_operators.get():
            raise TypeError("Undefined operator: %")
        return self._context_operators.get()["%"](self, other)

    def __pow__(self, other: Any, **kwargs) -> "Model":
        """Apply the function bound to the '**' operator."""
        if "**" not in self._context_operators.get():
            raise TypeError("Undefined operator: **")
        return self._context_operators.get()["**"](self, other)

    def __lshift__(self, other: Any) -> "Model":
        """Apply the function bound to the '<<' operator."""
        if "<<" not in self._context_operators.get():
            raise TypeError("Undefined operator: <<")
        return self._context_operators.get()["<<"](self, other)

    def __rshift__(self, other: Any) -> "Model":
        """Apply the function bound to the '>>' operator."""
        if ">>" not in self._context_operators.get():
            raise TypeError("Undefined operator: >>")
        return self._context_operators.get()[">>"](self, other)

    def __and__(self, other: Any) -> "Model":
        """Apply the function bound to the '&' operator."""
        if "&" not in self._context_operators.get():
            raise TypeError("Undefined operator: &")
        return self._context_operators.get()["&"](self, other)

    def __xor__(self, other: Any) -> "Model":
        """Apply the function bound to the '^' operator."""
        if "^" not in self._context_operators.get():
            raise TypeError("Undefined operator: ^")
        return self._context_operators.get()["^"](self, other)

    def __or__(self, other: Any) -> "Model":
        """Apply the function bound to the '|' operator."""
        if "|" not in self._context_operators.get():
            raise TypeError("Undefined operator: |")
        return self._context_operators.get()["|"](self, other)

@functools.singledispatch
def serialize_attr(_: Any, value: Any, name: str, model: Model) -> bytes:
    """Serialize an attribute value (defaults to msgpack). You can register
    custom serializers using the @serialize_attr.register decorator with the
    type to serialize, e.g.: @serialize_attr.register(MyCustomObject).
    """
    return srsly.msgpack_dumps(value)

@functools.singledispatch
def deserialize_attr(_: Any, value: Any, name: str, model: Model) -> Any:
    """Deserialize an attribute value (defaults to msgpack). You can register
    custom deserializers using the @deserialize_attr.register decorator with the
    type to deserialize, e.g.: @deserialize_attr.register(MyCustomObject).
    """
    return srsly.msgpack_loads(value)

_ModelT = TypeVar("_ModelT", bound=Model)

def change_attr_values(model: _ModelT, mapping: Dict[str, Dict[str, Any]]) -> _ModelT:
    """Walk over the model's nodes, changing the value of attributes using the
    provided mapping, which maps node names to attr names to attr values.
    """
    for node in model.walk():
        if node.name in mapping:
            attrs = mapping[node.name]
            for attr, value in attrs.items():
                if attr in node.attrs:
                    node.attrs[attr] = value
    return model

def set_dropout_rate(model: _ModelT, drop: float, attrs=["dropout_rate"]) -> _ModelT:
    """Walk over the model's nodes, setting the dropout rate. You can specify
    one or more attribute names, by default it looks for ["dropout_rate"].
    """
    for node in model.walk():
        for attr in attrs:
            if attr in node.attrs:
                node.attrs[attr] = drop
    return model

def wrap_model_recursive(model: Model, wrapper: Callable[[Model], _ModelT]) -> _ModelT:
    """Recursively wrap a model and its submodules. The model is updated
    in-place."""
    for node in list(model.walk()):
        model.replace_node(node, wrapper(node))

    return wrapper(model)

__all__ = [
    "Model",
    "serialize_attr",
    "deserialize_attr",
    "change_attr_values",
    "set_dropout_rate",
    "wrap_model_recursive",
]

redpajama_set_name: RedPajamaGithub


text:
(function() {

    var jsfiles = new Array(
        "util.js",
        "data/AutoCompleteProxy.js",
        "data/AutoCompleteReader.js",
        "data/WFSFeatureStore.js",
        "data/WFSProtocolProxy.js",
        "menu/LayerMenu.js",
        "widgets/EmbedMapDialog.js",
        "widgets/FeatureEditPopup.js",
        "widgets/FilterBuilder.js",
        "widgets/QueryPanel.js",
        "widgets/StylePropertiesDialog.js",
        "widgets/WMSLayerPanel.js",
        "widgets/WMSStylesDialog.js",
        "widgets/NewSourceWindow.js",
        "widgets/FillSymbolizer.js",
        "widgets/StrokeSymbolizer.js",
        "widgets/PointSymbolizer.js",
        "widgets/LayerUploadPanel.js",
        "widgets/LineSymbolizer.js",
        "widgets/PolygonSymbolizer.js",
        "widgets/RulePanel.js",
        "widgets/ScaleLimitPanel.js",
        "widgets/TextSymbolizer.js",
        "widgets/Viewer.js",
        "widgets/form/AutoCompleteComboBox.js",
        "widgets/form/ComparisonComboBox.js",
        "widgets/form/ColorField.js",
        "widgets/form/FilterField.js",
        "widgets/form/FontComboBox.js",
        "widgets/form/GoogleGeocoderComboBox.js",
        "widgets/form/ViewerField.js",
        "widgets/grid/CapabilitiesGrid.js",
        "widgets/grid/FeatureGrid.js",
        "widgets/GoogleEarthPanel.js",
        "widgets/GoogleStreetViewPanel.js",
        "widgets/tips/SliderTip.js",
        "widgets/PlaybackToolbar.js",
        "plugins/LayerSource.js",
        "plugins/BingSource.js",
        "plugins/WMSSource.js",
        "plugins/WMSCSource.js",
        "plugins/OSMSource.js",
        "plugins/GoogleSource.js",
        "plugins/OLSource.js",
        "plugins/MapBoxSource.js",
        "plugins/MapQuestSource.js",
        "plugins/StyleWriter.js",
        "plugins/GeoServerStyleWriter.js",
        "plugins/Tool.js",
        "plugins/ClickableFeatures.js",
        "plugins/DeleteSelectedFeatures.js",
        "plugins/GoogleGeocoder.js",
        "plugins/GoogleEarth.js",
        "plugins/WMSFilterView.js",
        "plugins/WMSRasterStylesDialog.js",
        "plugins/WMSGetFeatureInfo.js",
        "plugins/FeatureEditor.js",
        "plugins/FeatureGrid.js",
        "plugins/FeatureManager.js",
        "plugins/FeatureToField.js",
        "plugins/QueryForm.js",
        "plugins/LayerTree.js",
        "plugins/AddLayers.js",
        "plugins/RemoveLayer.js",
        "plugins/SelectedFeatureActions.js",
        "plugins/SnappingAgent.js",
        "plugins/Styler.js",
        "plugins/NavigationHistory.js",
        "plugins/Zoom.js",
        "plugins/ZoomToExtent.js",
        "plugins/ZoomToDataExtent.js",
        "plugins/ZoomToLayerExtent.js",
        "plugins/ZoomToSelectedFeatures.js",
        "plugins/Measure.js",
        "plugins/Navigation.js",
        "plugins/LayerProperties.js",
        "plugins/Legend.js",
        "plugins/Print.js",
        "plugins/LoadingIndicator.js",
        "plugins/Playback.js",
        "locale/tr.js"
    );

    var scripts = document.getElementsByTagName("script");
    var parts = scripts[scripts.length-1].src.split("/");
    parts.pop();
    var path = parts.join("/");

    var len = jsfiles.length;
    var pieces = new Array(len);

    for (var i=0; i<len; i++) {
        pieces[i] = "<script src='" + path + "/" + jsfiles[i] + "'></script>";
    }
    document.write(pieces.join(""));

    if (GeoExt.Lang) {
        GeoExt.Lang.set(OpenLayers.Util.getParameters()["lang"] || GeoExt.Lang.locale);
    }

})();


text:
package com.softserveinc.tender.dto;

public class UnitSaveDto {

    Double quantity;
    String category;
    String item;
    String measurment;
    Character itemType;

    public Double getQuantity() {
        return quantity;
    }

    public void setQuantity(Double quantity) {
        this.quantity = quantity;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public String getMeasurment() {
        return measurment;
    }

    public void setMeasurment(String measurment) {
        this.measurment = measurment;
    }

    public Character getItemType() {
        return itemType;
    }

    public void setItemType(Character itemType) {
        this.itemType = itemType;
    }
}


text:
            id)}}">{{ $project->name }}

            Created on: {{Carbon\Carbon::createFromFormat('Y-m-d H:i:s',$project->created_at)->format('F d, Y')}}

        @if($project->deadline)

            Deadline: {{Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $project->deadline)->diffForHumans()}}
        @endif

        @include('projects.list.active-sprint-container')

                id}}/edit">Edit


text:
package bitbucket

import (
	"encoding/json"
	"net/url"
)

type PullRequests struct {
	c *Client
}

func (p *PullRequests) Create(po *PullRequestsOptions) (interface{}, error) {
	data, err := p.buildPullRequestBody(po)
	if err != nil {
		return nil, err
	}
	urlStr := p.c.requestUrl("/repositories/%s/%s/pullrequests/", po.Owner, po.RepoSlug)
	return p.c.execute("POST", urlStr, data)
}

func (p *PullRequests) Update(po *PullRequestsOptions) (interface{}, error) {
	data, err := p.buildPullRequestBody(po)
	if err != nil {
		return nil, err
	}
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID
	return p.c.execute("PUT", urlStr, data)
}

func (p *PullRequests) Gets(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/"

	if po.States != nil && len(po.States) != 0 {
		parsed, err := url.Parse(urlStr)
		if err != nil {
			return nil, err
		}
		query := parsed.Query()
		for _, state := range po.States {
			query.Set("state", state)
		}
		parsed.RawQuery = query.Encode()
		urlStr = parsed.String()
	}

	if po.Query != "" {
		parsed, err := url.Parse(urlStr)
		if err != nil {
			return nil, err
		}
		query := parsed.Query()
		query.Set("q", po.Query)
		parsed.RawQuery = query.Encode()
		urlStr = parsed.String()
	}

	if po.Sort != "" {
		parsed, err := url.Parse(urlStr)
		if err != nil {
			return nil, err
		}
		query := parsed.Query()
		query.Set("sort", po.Sort)
		parsed.RawQuery = query.Encode()
		urlStr = parsed.String()
	}

	return p.c.executePaginated("GET", urlStr, "")
}

func (p *PullRequests) Get(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID
	return p.c.execute("GET", urlStr, "")
}

func (p *PullRequests) Activities(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/activity"
	return p.c.executePaginated("GET", urlStr, "")
}

func (p *PullRequests) Activity(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/activity"
	return p.c.execute("GET", urlStr, "")
}

func (p *PullRequests) Commits(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/commits"
	return p.c.executePaginated("GET", urlStr, "")
}

func (p *PullRequests) Patch(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/patch"
	return p.c.executeRaw("GET", urlStr, "")
}

func (p *PullRequests) Diff(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/diff"
	return p.c.executeRaw("GET", urlStr, "")
}

func (p *PullRequests) Merge(po *PullRequestsOptions) (interface{}, error) {
	data, err := p.buildPullRequestBody(po)
	if err != nil {
		return nil, err
	}
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/merge"
	return p.c.execute("POST", urlStr, data)
}

func (p *PullRequests) Decline(po *PullRequestsOptions) (interface{}, error) {
	data, err := p.buildPullRequestBody(po)
	if err != nil {
		return nil, err
	}
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/decline"
	return p.c.execute("POST", urlStr, data)
}

func (p *PullRequests) Approve(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/approve"
	return p.c.execute("POST", urlStr, "")
}

func (p *PullRequests) UnApprove(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/approve"
	return p.c.execute("DELETE", urlStr, "")
}

func (p *PullRequests) RequestChanges(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/request-changes"
	return p.c.execute("POST", urlStr, "")
}

func (p *PullRequests) UnRequestChanges(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/request-changes"
	return p.c.execute("DELETE", urlStr, "")
}

func (p *PullRequests) AddComment(co *PullRequestCommentOptions) (interface{}, error) {
	data, err := p.buildPullRequestCommentBody(co)
	if err != nil {
		return nil, err
	}

	urlStr := p.c.requestUrl("/repositories/%s/%s/pullrequests/%s/comments", co.Owner, co.RepoSlug, co.PullRequestID)
	return p.c.execute("POST", urlStr, data)
}

func (p *PullRequests) UpdateComment(co *PullRequestCommentOptions) (interface{}, error) {
	data, err := p.buildPullRequestCommentBody(co)
	if err != nil {
		return nil, err
	}

	urlStr := p.c.requestUrl("/repositories/%s/%s/pullrequests/%s/comments/%s", co.Owner, co.RepoSlug, co.PullRequestID, co.CommentId)
	return p.c.execute("PUT", urlStr, data)
}

func (p *PullRequests) GetComments(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/comments/"
	return p.c.executePaginated("GET", urlStr, "")
}

func (p *PullRequests) GetComment(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/comments/" + po.CommentID
	return p.c.execute("GET", urlStr, "")
}

func (p *PullRequests) Statuses(po *PullRequestsOptions) (interface{}, error) {
	urlStr := p.c.GetApiBaseURL() + "/repositories/" + po.Owner + "/" + po.RepoSlug + "/pullrequests/" + po.ID + "/statuses"
	if po.Query != "" {
		parsed, err := url.Parse(urlStr)
		if err != nil {
			return nil, err
		}
		query := parsed.Query()
		query.Set("q", po.Query)
		parsed.RawQuery = query.Encode()
		urlStr = parsed.String()
	}

	if po.Sort != "" {
		parsed, err := url.Parse(urlStr)
		if err != nil {
			return nil, err
		}
		query := parsed.Query()
		query.Set("sort", po.Sort)
		parsed.RawQuery = query.Encode()
		urlStr = parsed.String()
	}
	return p.c.executePaginated("GET", urlStr, "")
}

func (p *PullRequests) buildPullRequestBody(po *PullRequestsOptions) (string, error) {
	body := map[string]interface{}{}
	body["source"] = map[string]interface{}{}
	body["destination"] = map[string]interface{}{}
	body["reviewers"] = []map[string]string{}
	body["title"] = ""
	body["description"] = ""
	body["message"] = ""
	body["close_source_branch"] = false

	if n := len(po.Reviewers); n > 0 {
		body["reviewers"] = make([]map[string]string, n)
		for i, uuid := range po.Reviewers {
			body["reviewers"].([]map[string]string)[i] = map[string]string{"uuid": uuid}
		}
	}

	if po.SourceBranch != "" {
		body["source"].(map[string]interface{})["branch"] = map[string]string{"name": po.SourceBranch}
	}

	if po.SourceRepository != "" {
		body["source"].(map[string]interface{})["repository"] = map[string]interface{}{"full_name": po.SourceRepository}
	}

	if po.DestinationBranch != "" {
		body["destination"].(map[string]interface{})["branch"] = map[string]interface{}{"name": po.DestinationBranch}
	}

	if po.DestinationCommit != "" {
		body["destination"].(map[string]interface{})["commit"] = map[string]interface{}{"hash": po.DestinationCommit}
	}

	if po.Title != "" {
		body["title"] = po.Title
	}

	if po.Description != "" {
		body["description"] = po.Description
	}

	if po.Message != "" {
		body["message"] = po.Message
	}

	if po.CloseSourceBranch == true || po.CloseSourceBranch == false {
		body["close_source_branch"] = po.CloseSourceBranch
	}

	data, err := json.Marshal(body)
	if err != nil {
		return "", err
	}

	return string(data), nil
}

func (p *PullRequests) buildPullRequestCommentBody(co *PullRequestCommentOptions) (string, error) {
	body := map[string]interface{}{}
	body["content"] = map[string]interface{}{
		"raw": co.Content,
	}

	data, err := json.Marshal(body)
	if err != nil {
		return "", err
	}

	return string(data), nil
}


text:
if defined? Raven
  Raven.configure do |config|
    config.dsn = Settings.sentry.url
   end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>Deprecated API (jruby-gradle-war-plugin 1.5.0-alpha API)</title>
    <meta name="date" content="2017-08-15">
    <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
    <link href="groovy.ico" type="image/x-icon" rel="shortcut icon">
    <link href="groovy.ico" type="image/x-icon" rel="icon">

JavaScript is disabled on your browser.

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Deprecated API

Contents

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Groovy Documentation


text:
package io.fabric8.kubernetes.api.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.sundr.builder.annotations.Buildable;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "apiVersion",
    "kind",
    "metadata",
    "fsType",
    "image",
    "keyring",
    "monitors",
    "pool",
    "readOnly",
    "secretRef",
    "user"
})
@ToString
@EqualsAndHashCode
@Setter
@Accessors(prefix = {
    "_",
    ""
})
@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = true, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder")
public class RBDPersistentVolumeSource implements KubernetesResource
{

    @JsonProperty("fsType")
    private String fsType;
    @JsonProperty("image")
    private String image;
    @JsonProperty("keyring")
    private String keyring;
    @JsonProperty("monitors")
    private List<String> monitors = new ArrayList<String>();
    @JsonProperty("pool")
    private String pool;
    @JsonProperty("readOnly")
    private Boolean readOnly;
    @JsonProperty("secretRef")
    private SecretReference secretRef;
    @JsonProperty("user")
    private String user;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     * No args constructor for use in serialization
     *
     */
    public RBDPersistentVolumeSource() {
    }

    /**
     *
     * @param image
     * @param pool
     * @param secretRef
     * @param readOnly
     * @param fsType
     * @param keyring
     * @param user
     * @param monitors
     */
    public RBDPersistentVolumeSource(String fsType, String image, String keyring, List<String> monitors, String pool, Boolean readOnly, SecretReference secretRef, String user) {
        super();
        this.fsType = fsType;
        this.image = image;
        this.keyring = keyring;
        this.monitors = monitors;
        this.pool = pool;
        this.readOnly = readOnly;
        this.secretRef = secretRef;
        this.user = user;
    }

    @JsonProperty("fsType")
    public String getFsType() {
        return fsType;
    }

    @JsonProperty("fsType")
    public void setFsType(String fsType) {
        this.fsType = fsType;
    }

    @JsonProperty("image")
    public String getImage() {
        return image;
    }

    @JsonProperty("image")
    public void setImage(String image) {
        this.image = image;
    }

    @JsonProperty("keyring")
    public String getKeyring() {
        return keyring;
    }

    @JsonProperty("keyring")
    public void setKeyring(String keyring) {
        this.keyring = keyring;
    }

    @JsonProperty("monitors")
    public List<String> getMonitors() {
        return monitors;
    }

    @JsonProperty("monitors")
    public void setMonitors(List<String> monitors) {
        this.monitors = monitors;
    }

    @JsonProperty("pool")
    public String getPool() {
        return pool;
    }

    @JsonProperty("pool")
    public void setPool(String pool) {
        this.pool = pool;
    }

    @JsonProperty("readOnly")
    public Boolean getReadOnly() {
        return readOnly;
    }

    @JsonProperty("readOnly")
    public void setReadOnly(Boolean readOnly) {
        this.readOnly = readOnly;
    }

    @JsonProperty("secretRef")
    public SecretReference getSecretRef() {
        return secretRef;
    }

    @JsonProperty("secretRef")
    public void setSecretRef(SecretReference secretRef) {
        this.secretRef = secretRef;
    }

    @JsonProperty("user")
    public String getUser() {
        return user;
    }

    @JsonProperty("user")
    public void setUser(String user) {
        this.user = user;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}


text:
class TSharedMem
{
private:
	bool FCreated;
	BYTE *FFileView;
	HANDLE FHandle;
public:
	TSharedMem(const TCHAR* Name, int Size);
	~TSharedMem();
	bool IsUnique();
	BYTE *Buffer();
};
/// end of SharedMem.h

#endif // SharedMem_h__


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>invalid value attribute: host-space</title>
<input type=url value="http://example .org">


text:
import {Component, OnInit, OnDestroy} from "@angular/core";
import {Subscription} from "rxjs/Rx";
import {ActivatedRoute, Router} from "@angular/router";
import {ProjectDataService} from "../../project-data.service";
import {BundleListItem} from "../../types/bundle-list-item";
import {BundleList} from "../../types/bundle-list";
import {getErrorMessage} from "../../core/get-error-message.function";
import {ManagerAPIService} from "../../manager-api.service";
import {countFinishedItems} from "../../core/count-finished-items.function";
import {countCommentedItems} from "../../core/count-commented-items.function"
import {percentageFinishedItems} from "../../core/percentage-finished-items.function";
import {percentageCommentedItems} from "../../core/percentage-commented-items.function";

type State = 'Info' | 'AllBundles' | 'CommentedBundles';

@Component({
	selector: 'emudbmanager-bundle-list-detail',
	templateUrl: './bundle-list-detail.component.html',
	styleUrls: ['./bundle-list-detail.component.css']
})
export class BundleListDetailComponent implements OnInit,OnDestroy {
	public allBundles: BundleListItem[] = [];
	public bundleList: BundleList;
	public commentedBundles: BundleListItem[] = [];
	private database: string = '';
	private deleteError: string = '';
	private duplicationEditor = {
		commentedOnly: false,
		editorName: '',
		messageError: '',
		messageSuccess: ''
	};
	public generalErrors: string[] = [];
	private infoEditor = {
		isEditing: false,
		messageError: '',
		messageSuccess: '',
		newName: '',
		newArchiveLabel: ''
	};
	private reallyDelete: boolean = false;
	public state: State = 'Info';
	private subBundleList: Subscription;
	private subParams: Subscription;
	public tableFormat = [
		{type: 'string', heading: 'Session', value: x => x.session},
		{type: 'string', heading: 'Bundle', value: x => x.name},
		{type: 'boolean', heading: 'Finished editing', value: x => x.finishedEditing},
		{type: 'string', heading: 'Comment', value: x => x.comment}
	];

	constructor(private managerAPIService: ManagerAPIService,
	            private projectDataService: ProjectDataService,
	            private router: Router,
	            private route: ActivatedRoute) {
	}

	ngOnInit() {
		this.subParams = this.route.params.subscribe(nextParams => {
			let archiveLabel = '';
			if (typeof nextParams['archiveLabel'] === 'string') {
				archiveLabel = nextParams['archiveLabel'];
			}

			this.subBundleList = this.projectDataService.getBundleList(
				nextParams['database'],
				archiveLabel,
				nextParams['name']
			).subscribe(nextBundleList => {
				this.database = nextParams['database'];
				this.setBundleList({
					name: nextParams['name'],
					archiveLabel: archiveLabel,
					items: nextBundleList
				});
			},
			error => {
				this.generalErrors.push(getErrorMessage(error));
			});
		});
	}

	ngOnDestroy() {
		if (this.subBundleList) {
			this.subBundleList.unsubscribe();
		}
		if (this.subParams) {
			this.subParams.unsubscribe();
		}
	}

	private setBundleList (bundleList:BundleList) {
		this.bundleList = bundleList;

		if (bundleList) {
			this.bundleList = bundleList;
			this.infoEditor.newName = bundleList.name;
			this.infoEditor.newArchiveLabel = bundleList.archiveLabel;

			this.allBundles = bundleList.items;
			this.commentedBundles = bundleList.items.filter(element => {
				return element.comment !== '';
			});
		}
	}

	public saveEditedInfo () {
		let newName = this.infoEditor.newName;
		let newArchiveLabel = this.infoEditor.newArchiveLabel;
		this.toggleEditInfo(); // that will reset this.infoEditor.newName
		// and .newArchiveLabel

		this.infoEditor.messageError = '';
		this.infoEditor.messageSuccess = '';

		if (this.bundleList.name === newName && this.bundleList.archiveLabel === newArchiveLabel) {
			this.infoEditor.messageSuccess = 'No changes to be saved.';
			return;
		}

		this.managerAPIService.editBundleList(
			this.database,
			this.bundleList.name,
			this.bundleList.archiveLabel,
			newName, newArchiveLabel
		).subscribe (next => {
			this.infoEditor.messageSuccess = 'Successfully edited.';

			if (this.subBundleList) {
				this.subBundleList.unsubscribe();
			}

			this.projectDataService.refresh();

			this.subBundleList = this.projectDataService.getBundleList(
				this.database,
				newArchiveLabel,
				newName
			).subscribe(nextBundleList => {
				this.setBundleList({
					name: newName,
					archiveLabel: newArchiveLabel,
					items: nextBundleList
				})
			},
			error => {
				this.generalErrors.push(getErrorMessage(error));
			});
		}, error => {
			this.infoEditor.messageError = getErrorMessage(error);
			this.projectDataService.refresh();
		});
	}

	private toggleEditInfo () {
		if (this.infoEditor.isEditing) {
			this.infoEditor.newName = this.bundleList.name;
			this.infoEditor.newArchiveLabel = this.bundleList.archiveLabel;
			this.infoEditor.isEditing = false;
		} else {
			this.infoEditor.isEditing = true;
		}
	}

	private deleteBundleList () {
		this.reallyDelete = false;

		this.managerAPIService.deleteBundleList(this.database, this.bundleList).subscribe(next => {
			this.projectDataService.refresh();

			this.router.navigate(['/project/databases', this.database]);
		}, error => {
			this.deleteError = getErrorMessage(error);
			this.projectDataService.refresh();
		});
	}

	private duplicateBundleList () {
		this.duplicationEditor.messageError = '';
		this.duplicationEditor.messageSuccess = '';

		// Reset editorName but keep commentedOnly.
		// This way the user won't be able to click twice without typing again
		let editorName = this.duplicationEditor.editorName;
		this.duplicationEditor.editorName = '';

		this.projectDataService.duplicateBundleList(
			this.database,
			this.bundleList,
			editorName,
			this.duplicationEditor.commentedOnly
		).subscribe (next => {
			this.duplicationEditor.messageSuccess = 'Successfully duplicated' +
				' bundle list.';
			this.projectDataService.refresh();
		}, error => {
			this.duplicationEditor.messageError = getErrorMessage(error);
			this.projectDataService.refresh();
		});
	}

	public countCommentedItems = countCommentedItems;
	public countFinishedItems = countFinishedItems;
	public percentageCommentedItems = percentageCommentedItems;
	public percentageFinishedItems = percentageFinishedItems;
}


text:
package org.motechproject.server.web.controller;

import org.motechproject.security.ex.UserNotFoundException;
import org.motechproject.security.ex.NonAdminUserException;
import org.motechproject.security.service.PasswordRecoveryService;
import org.motechproject.server.config.SettingsFacade;
import org.motechproject.server.config.domain.LoginMode;
import org.motechproject.server.startup.StartupManager;
import org.motechproject.server.web.dto.ForgotViewData;
import org.motechproject.server.web.helper.Header;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import javax.servlet.http.HttpServletRequest;

/**
 * Forgot Controller for reset password.
 */
@Controller
public class ForgotController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ForgotController.class);

    @Autowired
    private SettingsFacade settingsFacade;

    @Autowired
    private StartupManager startupManager;

    @Autowired
    private PasswordRecoveryService recoveryService;

    @Autowired
    private CookieLocaleResolver cookieLocaleResolver;

    @Autowired
    private BundleContext bundleContext;

    @RequestMapping(value = "/forgot", method = RequestMethod.GET)
    public ModelAndView login(final HttpServletRequest request) {
        if (startupManager.isBootstrapConfigRequired()) {
            return new ModelAndView(Constants.REDIRECT_BOOTSTRAP);
        }

        if (startupManager.isConfigRequired()) {
            return new ModelAndView(Constants.REDIRECT_STARTUP);
        }

        ModelAndView view = new ModelAndView("forgot");
        view.addObject("mainHeader", Header.generateHeader(bundleContext.getBundle()));
        view.addObject("error", request.getParameter("error"));

        return view;
    }

   @RequestMapping(value = "/forgotviewdata", method = RequestMethod.GET)
   @ResponseBody
   public ForgotViewData getForgotViewData(final HttpServletRequest request) {
        ForgotViewData view = new ForgotViewData();

        view.setLoginMode(settingsFacade.getPlatformSettings().getLoginMode());
        view.setEmailGetter(true);
        view.setProcessed(false);
        view.setEmail("");
        view.setPageLang(cookieLocaleResolver.resolveLocale(request));

        return view;
    }

    @RequestMapping(value = "/forgot", method = RequestMethod.POST)
    @ResponseBody
    public String forgotPost(@RequestBody String email) {

        LoginMode loginMode = settingsFacade.getPlatformSettings().getLoginMode();

        if (loginMode.isRepository()) {
            try {
                recoveryService.passwordRecoveryRequest(email);
            } catch (UserNotFoundException e) {
                LOGGER.warn("Request for a nonexistent email", e);
                return "security.forgot.noSuchUser";
            } catch (RuntimeException e) {
                LOGGER.error("Error processing recovery", e);
                return "security.forgot.errorSending";
            }
        } else {
            try {
                recoveryService.oneTimeTokenOpenId(email);
            } catch (UserNotFoundException e) {
                LOGGER.warn("Request for a nonexistent email", e);
                return "security.forgot.noSuchUser";
            } catch (NonAdminUserException e) {
                LOGGER.warn("Request for a nonexistent email", e);
                return "security.forgot.nonAdminUser";
            } catch (RuntimeException e) {
                LOGGER.error("Error processing recovery", e);
                return "security.forgot.errorSending";
            }
        }

        return null;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!-- mybatis-generator:generate -->
    <!--targetRuntime="MyBatis3"-->
    <context id="MysqlTables" targetRuntime="tk.mybatis.mapper.generator.TkMyBatis3Impl">

        <!-- 生成的Java文件的编码 -->
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- 格式化java代码-->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化XML代码 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
        <plugin type="${xml.mapperPlugin}">
            <property name="mappers" value="${xml.mapperMapper}"/>
            <!-- caseSensitive默认false,当数据库表名区分大小写时,可以将该属性设置为true -->
            <property name="caseSensitive" value="true"/>
        </plugin>
        <!-- 去掉生成出来的代码的注解 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="${jdbc.driver}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.username}"
                        password="${jdbc.password}"/>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="true"/>
        </javaTypeResolver>

        <javaModelGenerator targetPackage="${xml.modelPackage}"
                            targetProject="${xml.javaProject}">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <sqlMapGenerator
                targetPackage="${xml.xmlPackage}"
                targetProject="${xml.resourcesProject}">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <javaClientGenerator
                targetPackage="${xml.mapperPackage}"
                targetProject="${xml.javaProject}"
                type="XMLMAPPER">

        </javaClientGenerator>
        <!-- 这里设置表的相关信息 -->
        <table tableName="${xml.tableName}" domainObjectName="${xml.objectName}" mapperName="${xml.mapperName}"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false" modelType="flat">
            <property name="useActualColumnNames" value="false"/>
            <generatedKey column="" sqlStatement="MySql" identity="true"/>
            <!--<generatedKey column="ID"-->
            <!--sqlStatement="SELECT LAST_INSERT_ID()" />-->
        </table>
    </context>

</generatorConfiguration>


text:
/*
  https://developer.mozilla.org/en-US/docs/Web/CSS/display

  Tests are used to discover what export object should be.
*/

import deepEqual from 'deep-equal';
import display from './display';
import { getEnumeratedValues } from './utils';

const displayOutsideValues = ['block', 'inline', 'run-in'];

const displayInsideValues = [
  'flow',
  'flow-root',
  'table',
  'flex',
  'grid',
  'ruby',
  'subgrid',
];

const displayOutsidePlusInsideValues = displayOutsideValues.reduce(
  (arr, outsideValue) =>
    arr.concat(
      displayInsideValues.map(insideValue => `${outsideValue} ${insideValue}`)
    ),
  []
);

const displayListItemValues = displayOutsidePlusInsideValues
  .map(
    displayOutsidePlusInsideValue =>
      `list-item ${displayOutsidePlusInsideValue}`
  )
  .concat(['list-item']);

const displayInternalValues = [
  'table-row-group',
  'table-header-group',
  'table-footer-group',
  'table-row',
  'table-cell',
  'table-column-group',
  'table-column',
  'table-caption',
  'ruby-base',
  'ruby-text',
  'ruby-base-container',
  'ruby-text-container',
];

const displayBoxValues = ['contents', 'none'];

const displayLegacyValues = [
  'inline-block',
  'inline-table',
  'inline-flex',
  'inline-grid',
];

const possibleValues = [
  ...displayOutsideValues,
  ...displayInsideValues,
  ...displayOutsidePlusInsideValues,
  ...displayListItemValues,
  ...displayInternalValues,
  ...displayBoxValues,
  ...displayLegacyValues,
];

const exportObject = {
  ...getEnumeratedValues('display', possibleValues),
};

describe('display', () => {
  test('matches export', () => {
    const deepMatch = deepEqual(display, exportObject);
    expect(deepMatch).toBeTruthy();
  });
});


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Earthquake map</title>
  <link rel="stylesheet" type="text/css" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css">


text:
title: 'Aún te espero...'
author: rcg
layout: post
tags:
  - Songs
---

Una preciosa canción de [Riverside][1] titulada [Conceiving you][2] con la que
me siento muy identificado. Del disco Second Life Syndrome. Muy recomendado si
os gusta el Progresivo Ambiental.

*I've been watching you*
*Not waiting for the right*
*moment to make the first move*

*Do you want to know*
*Why I keep avoiding your eyes*
*And why I'm running away?*
*It's crazy, I know*

*I've been conceiving you for too long*

*Or maybe I'm destined to be alone?*
*Or maybe there's someone who will understand*
*That I'm not able to share my world?*
*I'm still running away*
*It's crazy, I know*

*I've been conceiving you for too long*
*If only I could change all things around*
*Still conceiving you all along...*

*I've been conceiving you for too long*
*If only I could change all things around*
*I've been conceiving you for too long*
*I've grown used to that*

*Still conceiving you all along...*

 [1]: http://www.riverside.art.pl/
 [2]: http://www.youtube.com/watch?v=peDCmsJB1AA


text:
define([
    'webida',
    'q'
], function (webida, Q) {
    'use strict';
    var App = function () {};

    $.extend(App.prototype, {
        getMyAppInfo: function () {
            var defer = Q.defer();

            webida.app.getMyAppInfo(function (e, info) {
                if (e) {
                    //e = JSON.parse(e);
                    defer.reject(e);

                } else {
                    defer.resolve(info);
                }
            });

            return defer.promise;
        },
        getHost: function () {
            return webida.app.getHost();
        },
        launchApp: function (domain, mode, queryString, newWindowOption) {
            webida.app.launchApp(domain, mode, queryString, newWindowOption);
        },
        deleteApp: function (appID) {
            var defer = Q.defer();
            webida.app.deleteApp(appID, function (e) {
                if (e) {
                    //e = JSON.parse(e);
                    defer.reject(e);
                } else {
                    defer.resolve();
                }
            });
            return defer.promise;
        },
        getDeployedAppUrl: function (domain) {
            return webida.app.getDeployedAppUrl(domain);
        }
    });

    if (App.instance === undefined) {
        App.instance = new App();
    }

    return App.instance;
});


text:
<?php

namespace ZendTest\Code\TestAsset;

interface FooInterface extends \ArrayAccess
{
    public const BAR = 5;
    public const FOO = self::BAR;

    public function fooBarBaz();

}


text:
package ipc // import "github.com/apache/arrow/go/arrow/ipc"

import (
	"bytes"
	"context"
	"encoding/binary"
	"io"
	"math"
	"sync"

	"github.com/apache/arrow/go/arrow"
	"github.com/apache/arrow/go/arrow/array"
	"github.com/apache/arrow/go/arrow/bitutil"
	"github.com/apache/arrow/go/arrow/internal/flatbuf"
	"github.com/apache/arrow/go/arrow/memory"
	"golang.org/x/xerrors"
)

type swriter struct {
	w   io.Writer
	pos int64
}

func (w *swriter) Start() error { return nil }
func (w *swriter) Close() error {
	_, err := w.Write(kEOS[:])
	return err
}

func (w *swriter) WritePayload(p Payload) error {
	_, err := writeIPCPayload(w, p)
	if err != nil {
		return err
	}
	return nil
}

func (w *swriter) Write(p []byte) (int, error) {
	n, err := w.w.Write(p)
	w.pos += int64(n)
	return n, err
}

// Writer is an Arrow stream writer.
type Writer struct {
	w io.Writer

	mem memory.Allocator
	pw  PayloadWriter

	started    bool
	schema     *arrow.Schema
	codec      flatbuf.CompressionType
	compressNP int
}

// NewWriterWithPayloadWriter constructs a writer with the provided payload writer
// instead of the default stream payload writer. This makes the writer more
// reusable such as by the Arrow Flight writer.
func NewWriterWithPayloadWriter(pw PayloadWriter, opts ...Option) *Writer {
	cfg := newConfig(opts...)
	return &Writer{
		mem:        cfg.alloc,
		pw:         pw,
		schema:     cfg.schema,
		codec:      cfg.codec,
		compressNP: cfg.compressNP,
	}
}

// NewWriter returns a writer that writes records to the provided output stream.
func NewWriter(w io.Writer, opts ...Option) *Writer {
	cfg := newConfig(opts...)
	return &Writer{
		w:      w,
		mem:    cfg.alloc,
		pw:     &swriter{w: w},
		schema: cfg.schema,
		codec:  cfg.codec,
	}
}

func (w *Writer) Close() error {
	if !w.started {
		err := w.start()
		if err != nil {
			return err
		}
	}

	if w.pw == nil {
		return nil
	}

	err := w.pw.Close()
	if err != nil {
		return xerrors.Errorf("arrow/ipc: could not close payload writer: %w", err)
	}
	w.pw = nil

	return nil
}

func (w *Writer) Write(rec array.Record) error {
	if !w.started {
		err := w.start()
		if err != nil {
			return err
		}
	}

	schema := rec.Schema()
	if schema == nil || !schema.Equal(w.schema) {
		return errInconsistentSchema
	}

	const allow64b = true
	var (
		data = Payload{msg: MessageRecordBatch}
		enc  = newRecordEncoder(w.mem, 0, kMaxNestingDepth, allow64b, w.codec, w.compressNP)
	)
	defer data.Release()

	if err := enc.Encode(&data, rec); err != nil {
		return xerrors.Errorf("arrow/ipc: could not encode record to payload: %w", err)
	}

	return w.pw.WritePayload(data)
}

func (w *Writer) start() error {
	w.started = true

	// write out schema payloads
	ps := payloadsFromSchema(w.schema, w.mem, nil)
	defer ps.Release()

	for _, data := range ps {
		err := w.pw.WritePayload(data)
		if err != nil {
			return err
		}
	}

	return nil
}

type recordEncoder struct {
	mem memory.Allocator

	fields []fieldMetadata
	meta   []bufferMetadata

	depth      int64
	start      int64
	allow64b   bool
	codec      flatbuf.CompressionType
	compressNP int
}

func newRecordEncoder(mem memory.Allocator, startOffset, maxDepth int64, allow64b bool, codec flatbuf.CompressionType, compressNP int) *recordEncoder {
	return &recordEncoder{
		mem:        mem,
		start:      startOffset,
		depth:      maxDepth,
		allow64b:   allow64b,
		codec:      codec,
		compressNP: compressNP,
	}
}

func (w *recordEncoder) compressBodyBuffers(p *Payload) error {
	compress := func(idx int, codec compressor) error {
		if p.body[idx] == nil || p.body[idx].Len() == 0 {
			return nil
		}
		var buf bytes.Buffer
		buf.Grow(codec.MaxCompressedLen(p.body[idx].Len()) + arrow.Int64SizeBytes)
		if err := binary.Write(&buf, binary.LittleEndian, uint64(p.body[idx].Len())); err != nil {
			return err
		}
		codec.Reset(&buf)
		if _, err := codec.Write(p.body[idx].Bytes()); err != nil {
			return err
		}
		if err := codec.Close(); err != nil {
			return err
		}
		p.body[idx] = memory.NewBufferBytes(buf.Bytes())
		return nil
	}

	if w.compressNP <= 1 {
		codec := getCompressor(w.codec)
		for idx := range p.body {
			if err := compress(idx, codec); err != nil {
				return err
			}
		}
		return nil
	}

	var (
		wg          sync.WaitGroup
		ch          = make(chan int)
		errch       = make(chan error)
		ctx, cancel = context.WithCancel(context.Background())
	)
	defer cancel()

	for i := 0; i < w.compressNP; i++ {
		go func() {
			defer wg.Done()
			codec := getCompressor(w.codec)
			for {
				select {
				case idx, ok := <-ch:
					if !ok {
						// we're done, channel is closed!
						return
					}

					if err := compress(idx, codec); err != nil {
						errch <- err
						cancel()
						return
					}
				case <-ctx.Done():
					// cancelled, return early
					return
				}
			}
		}()
	}

	for idx := range p.body {
		ch <- idx
	}

	close(ch)
	wg.Wait()
	close(errch)

	return <-errch
}

func (w *recordEncoder) Encode(p *Payload, rec array.Record) error {

	// perform depth-first traversal of the row-batch
	for i, col := range rec.Columns() {
		err := w.visit(p, col)
		if err != nil {
			return xerrors.Errorf("arrow/ipc: could not encode column %d (%q): %w", i, rec.ColumnName(i), err)
		}
	}

	if w.codec != -1 {
		w.compressBodyBuffers(p)
	}

	// position for the start of a buffer relative to the passed frame of reference.
	// may be 0 or some other position in an address space.
	offset := w.start
	w.meta = make([]bufferMetadata, len(p.body))

	// construct the metadata for the record batch header
	for i, buf := range p.body {
		var (
			size    int64
			padding int64
		)
		// the buffer might be null if we are handling zero row lengths.
		if buf != nil {
			size = int64(buf.Len())
			padding = bitutil.CeilByte64(size) - size
		}
		w.meta[i] = bufferMetadata{
			Offset: offset,
			// even though we add padding, we need the Len to be correct
			// so that decompressing works properly.
			Len: size,
		}
		offset += size + padding
	}

	p.size = offset - w.start
	if !bitutil.IsMultipleOf8(p.size) {
		panic("not aligned")
	}

	return w.encodeMetadata(p, rec.NumRows())
}

func (w *recordEncoder) visit(p *Payload, arr array.Interface) error {
	if w.depth <= 0 {
		return errMaxRecursion
	}

	if !w.allow64b && arr.Len() > math.MaxInt32 {
		return errBigArray
	}

	if arr.DataType().ID() == arrow.EXTENSION {
		arr := arr.(array.ExtensionArray)
		err := w.visit(p, arr.Storage())
		if err != nil {
			return xerrors.Errorf("failed visiting storage of for array %T: %w", arr, err)
		}
		return nil
	}

	// add all common elements
	w.fields = append(w.fields, fieldMetadata{
		Len:    int64(arr.Len()),
		Nulls:  int64(arr.NullN()),
		Offset: 0,
	})

	switch arr.NullN() {
	case 0:
		p.body = append(p.body, nil)
	default:
		switch arr.DataType().ID() {
		case arrow.NULL:
			// Null type has no validity bitmap
		default:
			data := arr.Data()
			bitmap := newTruncatedBitmap(w.mem, int64(data.Offset()), int64(data.Len()), data.Buffers()[0])
			p.body = append(p.body, bitmap)
		}
	}

	switch dtype := arr.DataType().(type) {
	case *arrow.NullType:
		// ok. NullArrays are completely empty.

	case *arrow.BooleanType:
		var (
			data = arr.Data()
			bitm *memory.Buffer
		)

		if data.Len() != 0 {
			bitm = newTruncatedBitmap(w.mem, int64(data.Offset()), int64(data.Len()), data.Buffers()[1])
		}
		p.body = append(p.body, bitm)

	case arrow.FixedWidthDataType:
		data := arr.Data()
		values := data.Buffers()[1]
		arrLen := int64(arr.Len())
		typeWidth := int64(dtype.BitWidth() / 8)
		minLength := paddedLength(arrLen*typeWidth, kArrowAlignment)

		switch {
		case needTruncate(int64(data.Offset()), values, minLength):
			// non-zero offset: slice the buffer
			offset := int64(data.Offset()) * typeWidth
			// send padding if available
			len := minI64(bitutil.CeilByte64(arrLen*typeWidth), int64(data.Len())-offset)
			data = array.NewSliceData(data, offset, offset+len)
			defer data.Release()
			values = data.Buffers()[1]
		}
		if values != nil {
			values.Retain()
		}
		p.body = append(p.body, values)

	case *arrow.BinaryType:
		arr := arr.(*array.Binary)
		voffsets, err := w.getZeroBasedValueOffsets(arr)
		if err != nil {
			return xerrors.Errorf("could not retrieve zero-based value offsets from %T: %w", arr, err)
		}
		data := arr.Data()
		values := data.Buffers()[2]

		var totalDataBytes int64
		if voffsets != nil {
			totalDataBytes = int64(len(arr.ValueBytes()))
		}

		switch {
		case needTruncate(int64(data.Offset()), values, totalDataBytes):
			// slice data buffer to include the range we need now.
			var (
				beg = int64(arr.ValueOffset(0))
				len = minI64(paddedLength(totalDataBytes, kArrowAlignment), int64(data.Len())-beg)
			)
			data = array.NewSliceData(data, beg, beg+len)
			defer data.Release()
			values = data.Buffers()[2]
		default:
			if values != nil {
				values.Retain()
			}
		}
		p.body = append(p.body, voffsets)
		p.body = append(p.body, values)

	case *arrow.StringType:
		arr := arr.(*array.String)
		voffsets, err := w.getZeroBasedValueOffsets(arr)
		if err != nil {
			return xerrors.Errorf("could not retrieve zero-based value offsets from %T: %w", arr, err)
		}
		data := arr.Data()
		values := data.Buffers()[2]

		var totalDataBytes int64
		if voffsets != nil {
			totalDataBytes = int64(arr.ValueOffset(arr.Len()) - arr.ValueOffset(0))
		}

		switch {
		case needTruncate(int64(data.Offset()), values, totalDataBytes):
			// slice data buffer to include the range we need now.
			var (
				beg = int64(arr.ValueOffset(0))
				len = minI64(paddedLength(totalDataBytes, kArrowAlignment), int64(data.Len())-beg)
			)
			data = array.NewSliceData(data, beg, beg+len)
			defer data.Release()
			values = data.Buffers()[2]
		default:
			if values != nil {
				values.Retain()
			}
		}
		p.body = append(p.body, voffsets)
		p.body = append(p.body, values)

	case *arrow.StructType:
		w.depth--
		arr := arr.(*array.Struct)
		for i := 0; i < arr.NumField(); i++ {
			err := w.visit(p, arr.Field(i))
			if err != nil {
				return xerrors.Errorf("could not visit field %d of struct-array: %w", i, err)
			}
		}
		w.depth++

	case *arrow.MapType:
		arr := arr.(*array.Map)
		voffsets, err := w.getZeroBasedValueOffsets(arr)
		if err != nil {
			return xerrors.Errorf("could not retrieve zero-based value offsets for array %T: %w", arr, err)
		}
		p.body = append(p.body, voffsets)

		w.depth--
		var (
			values        = arr.ListValues()
			mustRelease   = false
			values_offset int64
			values_length int64
		)
		defer func() {
			if mustRelease {
				values.Release()
			}
		}()

		if voffsets != nil {
			values_offset = int64(arr.Offsets()[0])
			values_length = int64(arr.Offsets()[arr.Len()]) - values_offset
		}

		if len(arr.Offsets()) != 0 || values_length < int64(values.Len()) {
			// must also slice the values
			values = array.NewSlice(values, values_offset, values_length)
			mustRelease = true
		}
		err = w.visit(p, values)

		if err != nil {
			return xerrors.Errorf("could not visit list element for array %T: %w", arr, err)
		}
		w.depth++
	case *arrow.ListType:
		arr := arr.(*array.List)
		voffsets, err := w.getZeroBasedValueOffsets(arr)
		if err != nil {
			return xerrors.Errorf("could not retrieve zero-based value offsets for array %T: %w", arr, err)
		}
		p.body = append(p.body, voffsets)

		w.depth--
		var (
			values        = arr.ListValues()
			mustRelease   = false
			values_offset int64
			values_length int64
		)
		defer func() {
			if mustRelease {
				values.Release()
			}
		}()

		if voffsets != nil {
			values_offset = int64(arr.Offsets()[0])
			values_length = int64(arr.Offsets()[arr.Len()]) - values_offset
		}

		if len(arr.Offsets()) != 0 || values_length < int64(values.Len()) {
			// must also slice the values
			values = array.NewSlice(values, values_offset, values_length)
			mustRelease = true
		}
		err = w.visit(p, values)

		if err != nil {
			return xerrors.Errorf("could not visit list element for array %T: %w", arr, err)
		}
		w.depth++

	case *arrow.FixedSizeListType:
		arr := arr.(*array.FixedSizeList)

		w.depth--

		size := int64(arr.DataType().(*arrow.FixedSizeListType).Len())
		beg := int64(arr.Offset()) * size
		end := int64(arr.Offset()+arr.Len()) * size

		values := array.NewSlice(arr.ListValues(), beg, end)
		defer values.Release()

		err := w.visit(p, values)

		if err != nil {
			return xerrors.Errorf("could not visit list element for array %T: %w", arr, err)
		}
		w.depth++

	default:
		panic(xerrors.Errorf("arrow/ipc: unknown array %T (dtype=%T)", arr, dtype))
	}

	return nil
}

func (w *recordEncoder) getZeroBasedValueOffsets(arr array.Interface) (*memory.Buffer, error) {
	data := arr.Data()
	voffsets := data.Buffers()[1]
	if data.Offset() != 0 {
		// FIXME(sbinet): writer.cc:231
		panic(xerrors.Errorf("not implemented offset=%d", data.Offset()))
	}
	if voffsets == nil || voffsets.Len() == 0 {
		return nil, nil
	}

	voffsets.Retain()
	return voffsets, nil
}

func (w *recordEncoder) encodeMetadata(p *Payload, nrows int64) error {
	p.meta = writeRecordMessage(w.mem, nrows, p.size, w.fields, w.meta, w.codec)
	return nil
}

func newTruncatedBitmap(mem memory.Allocator, offset, length int64, input *memory.Buffer) *memory.Buffer {
	if input != nil {
		input.Retain()
		return input
	}

	minLength := paddedLength(bitutil.BytesForBits(length), kArrowAlignment)
	switch {
	case offset != 0 || minLength < int64(input.Len()):
		// with a sliced array / non-zero offset, we must copy the bitmap
		panic("not implemented") // FIXME(sbinet): writer.cc:75
	default:
		input.Retain()
		return input
	}
}

func needTruncate(offset int64, buf *memory.Buffer, minLength int64) bool {
	if buf == nil {
		return false
	}
	return offset != 0 || minLength < int64(buf.Len())
}

func minI64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}


text:
Modifier keys are a convenient way to save action bar space and make certain
decisions.

## Parameters

May take a number of parameters seperated by slashes `/`.

* ctrl - the CTRL key is pressed down
* shift - the SHIFT key is pressed down
* alt - the ALT key is pressed down

## Examples:

```lua
/cast [mod:ctrl] Healing Wave; Healing Wave (Rank 1)
```

This will cast your highest rank of Healing Wave whenever you have the CTRL key pressed, otherwise Healing Wave rank 1.

---

```lua
/cast [mod:ctrl/shift] Healing Wave
```

You will cast Healing Wave when you have CTRL and SHIFT pressed.


text:
{% if article.series %}
{% if article.status != "draft" and article.status != "hidden" %}

This post is part ({{ article.series.index }}/{{ article.series.all|count }}) of the "{{ article.series.name }}" series:

  {% for part_article in article.series.all %}

    {{ part_article.title }}

  {% endfor %}

{% endif %}
{% endif %}


text:
//-- For OpenNI2
//
#include <stdio.h>
#include <OpenNI.h>

#include "OniSampleUtilities.h"

//-- For OpenCV
//
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <termios.h>
#include <time.h>

#include "cv.h"
#include "highgui.h"

#define DEPTH_IMG_WIDTH		160		//(320)
#define DEPTH_IMG_HEIGHT	120		//(240)
#define DEPTH_IMG_FPS		15

#define COLOR_IMG_WIDTH		320		//(320)
#define COLOR_IMG_HEIGHT	240		//(240)
#define COLOR_IMG_FPS		15

#define SAMPLE_READ_WAIT_TIMEOUT 2000 //2000ms

using namespace openni;

clock_t	start_point, end_point;
struct 	termios orig_termios;

//-- OpenNI 변수
//
VideoStream depth, color;
Device device;

int OpenNI_Init(void);

int main()
{
	IplImage *IplImage_depth;
	IplImage *IplImage_color;

	cv::Mat MatImage_depth;
	cv::Mat MatImage_color;

	double 	process_time;
	int 	process_rate;

	clock_t start_point;
	clock_t end_point;

	Status rc;

	int Cnt = 0;
	int CapturedFlag;

	if( OpenNI_Init() > 0 )
	{
		printf("OpenNI Init Failed\n");
		return 1;
	}
	else
	{
		printf("OpenNI Init OK\n");
	}

	IplImage_depth = cvCreateImage(cvSize(DEPTH_IMG_WIDTH,DEPTH_IMG_HEIGHT), IPL_DEPTH_8U, 1);
	IplImage_color = cvCreateImage(cvSize(COLOR_IMG_WIDTH,COLOR_IMG_HEIGHT), IPL_DEPTH_8U, 3);

	VideoFrameRef *frame_ptr;
	VideoFrameRef frame_depth;
	VideoFrameRef frame_color;
	VideoStream*  streams[] = {&depth, &color};

	//-- OpenCV 초기화
	//
	//image = cvCreateImage(cvSize(DEPTH_IMG_WIDTH,DEPTH_IMG_HEIGHT), 8, 3);

	CapturedFlag = 0;

	while (!wasKeyboardHit())
	{
		int readyStream = -1;

		start_point = clock();

		//VideoStream* pStream = &depth;
		//VideoStream* pStream = &color;

		rc = OpenNI::waitForAnyStream(streams, 2, &readyStream, SAMPLE_READ_WAIT_TIMEOUT);
		//rc = OpenNI::waitForAnyStream(&pStream, 1, &readyStream, SAMPLE_READ_WAIT_TIMEOUT);
		if (rc != STATUS_OK)
		{
			printf("Wait failed! (timeout is %d ms)\n%s\n", SAMPLE_READ_WAIT_TIMEOUT, OpenNI::getExtendedError());
			continue;
		}

		//rc = depth.readFrame(&frame);
		//rc = color.readFrame(&frame);

		switch (readyStream)
		{
		case 0:
			// Depth
			rc = depth.readFrame(&frame_depth);
			CapturedFlag |= (1<<0);

			if (rc != STATUS_OK)
			{
				printf("Read depth failed!\n%s\n", OpenNI::getExtendedError());
				continue;
			}

			frame_ptr = &frame_depth;
			break;
		case 1:
			// Color
			rc = color.readFrame(&frame_color);
			CapturedFlag |= (1<<1);
			if (rc != STATUS_OK)
			{
				printf("Read color failed!\n%s\n", OpenNI::getExtendedError());
				continue;
			}

			frame_ptr = &frame_color;
			break;
		default:
			printf("Unxpected stream\n");
			continue;
			break;
		}

		switch (frame_ptr->getVideoMode().getPixelFormat())
		{
		case PIXEL_FORMAT_DEPTH_1_MM:
		case PIXEL_FORMAT_DEPTH_100_UM:
			//rc = depth.readFrame(&frame);
			printf("Depth Captured %d\n", Cnt++);
			//continue;
			break;

		case PIXEL_FORMAT_RGB888:
			/*
			pColor = (RGB888Pixel*)frame.getData();
			printf("[%08llu] 0x%02x%02x%02x\n", (long long)frame.getTimestamp(),
				pColor[middleIndex].r&0xff,
				pColor[middleIndex].g&0xff,
				pColor[middleIndex].b&0xff);
			*/
			//rc = color.readFrame(&frame);
			printf("Color Captured %d\n", Cnt++ );
			//continue;

			break;
		default:
			printf("Unknown format\n");
			continue;
			break;
		}

		if( readyStream == 0 )
		{
			MatImage_depth = cv::Mat(depth.getVideoMode().getResolutionY(),
	                           depth.getVideoMode().getResolutionX(),
	                           CV_16U,
	                           (char *) frame_depth.getData());
	        //MatImage.convertTo(MatImage, CV_8U, 256.0 / 0xFFFF);
	        MatImage_depth.convertTo(MatImage_depth, CV_8U, 255.0/2000.0);
			//cv::equalizeHist(MatImage, MatImage);
	    	//bitwise_not(MatImage, MatImage);

			//image = &IplImage(MatImage);
			//image = &(MatImage.operator IplImage());

			//cvSaveImage("/srv/depth.jpg",image);
			//imwrite("/mnt/ramdisk/depth/depth.jpg",MatImage);

			IplImage_depth->imageData = (char *) MatImage_depth.data;
		}
		else
		{
			const openni::RGB888Pixel* imageBuffer = (const openni::RGB888Pixel*)frame_color.getData();

   			MatImage_color.create(frame_color.getHeight(), frame_color.getWidth(), CV_8UC3);
			memcpy( MatImage_color.data, imageBuffer, 3*frame_color.getHeight()*frame_color.getWidth()*sizeof(uint8_t) );

			cv::cvtColor(MatImage_color,MatImage_color,CV_BGR2RGB); //this will put colors right

			IplImage_color->imageData = (char *) MatImage_color.data;
		}

		if( CapturedFlag == 0x03 )
		{

			Object_Tracking(IplImage_color, labelImg, segmentated, morphKernel);

			cvSaveImage("/mnt/ramdisk/depth/depth.jpg",IplImage_depth);
			cvSaveImage("/mnt/ramdisk/color/color.jpg",IplImage_color);

			//imwrite("/mnt/ramdisk/depth/depth.jpg",MatImage_depth);
			//imwrite("/mnt/ramdisk/color/color.jpg",MatImage_color);

			CapturedFlag = 0;
		}
		/*
		cv::Mat depth(240,320,CV_16UC1,(void*)frame.getData(), 2*320);
		cv::Mat depthNorm;
		cv::normalize(depth, depthNorm, 0, 255, CV_MINMAX, CV_8UC1);

		cv::Mat bgrMat,rgbMat(240,320,CV_8UC3,(void*)frame.getData(),3*320);

		cv::cvtColor(rgbMat,bgrMat, CV_RGB2BGR);// opencv expects the image in BGR format
		*/

		//DepthPixel* pDepth = (DepthPixel*)frame.getData();
		//int middleIndex = (frame.getHeight()+1)*frame.getWidth()/2;

		end_point = clock();
		process_time = ((double)(end_point - start_point)/(CLOCKS_PER_SEC/1000));
		//printf("Exe time : %04f msec  %03.1f frames\r\n", process_time, 1000./process_time );

		if( readyStream == 0 )
		{
			printf("H : %d, W : %d  %03.1f frames \n", frame_depth.getHeight(), frame_depth.getWidth(), 1000./process_time );
		}
		else
		{
			printf("H : %d, W : %d  %03.1f frames \n", frame_color.getHeight(), frame_color.getWidth(), 1000./process_time );
		}
		//printf("[%08llu] %8d\n", (long long)frame.getTimestamp(), pDepth[middleIndex]);
	}

	depth.stop();
	depth.destroy();
	color.stop();
	color.destroy();

	device.close();
	OpenNI::shutdown();

	// OpenCV 종료
	//
	cvReleaseImage(&IplImage_depth);
	cvReleaseImage(&IplImage_color);

	cvReleaseImage(&labelImg);
	cvReleaseImage(&segmentated);
	cvReleaseStructuringElement(&morphKernel);

	return 0;
}

int OpenNI_Init(void)
{
	Status rc;

	//-- OpenNI 초기화
	//
	rc = OpenNI::initialize();
	if (rc != STATUS_OK)
	{
		printf("Initialize failed\n%s\n", OpenNI::getExtendedError());
		return 1;
	}

	rc = device.open(ANY_DEVICE);
	if (rc != STATUS_OK)
	{
		printf("Couldn't open device\n%s\n", OpenNI::getExtendedError());
		return 2;
	}

	if (device.getSensorInfo(SENSOR_DEPTH) != NULL)
	{
		rc = depth.create(device, SENSOR_DEPTH);
		if (rc != STATUS_OK)
		{
			printf("Couldn't create depth stream\n%s\n", OpenNI::getExtendedError());
			return 3;
		}
	}

	if (device.getSensorInfo(SENSOR_COLOR) != NULL)
	{
		rc = color.create(device, SENSOR_COLOR);
		if (rc != STATUS_OK)
		{
			printf("Couldn't create color stream\n%s\n", OpenNI::getExtendedError());
		}
	}

	device.setDepthColorSyncEnabled(true);

	//-- Start
	//
	VideoMode mode_depth = depth.getVideoMode();

    mode_depth.setResolution(DEPTH_IMG_WIDTH, DEPTH_IMG_HEIGHT);
	//mode_depth.setFps(DEPTH_IMG_FPS);
    depth.setVideoMode(mode_depth);
    depth.setMirroringEnabled(false);

	rc = depth.start();
	if (rc != STATUS_OK)
	{
		printf("Couldn't start the depth stream\n%s\n", OpenNI::getExtendedError());
		return 4;
	}

	VideoMode mode_color = color.getVideoMode();

    mode_color.setResolution(COLOR_IMG_WIDTH, COLOR_IMG_HEIGHT);
	//mode_color.setFps(COLOR_IMG_FPS);
    color.setVideoMode(mode_color);
    color.setMirroringEnabled(false);

    printf("Ver 0.1\n");

	rc = color.start();
	if (rc != STATUS_OK)
	{
		printf("Couldn't start the color stream\n%s\n", OpenNI::getExtendedError());
		return 4;
	}

	return 0;
}


text:
require_relative '../../spec_helper'
require_relative 'shared/begin'

describe "Range#first" do
  it_behaves_like :range_begin, :first

  it "returns the specified number of elements from the beginning" do
    (0..2).first(2).should == [0, 1]
  end

  it "returns an empty array for an empty Range" do
    (0...0).first(2).should == []
  end

  it "returns an empty array when passed zero" do
    (0..2).first(0).should == []
  end

  it "returns all elements in the range when count exceeds the number of elements" do
    (0..2).first(4).should == [0, 1, 2]
  end

  it "raises an ArgumentError when count is negative" do
    -> { (0..2).first(-1) }.should raise_error(ArgumentError)
  end

  it "calls #to_int to convert the argument" do
    obj = mock_int(2)
    (3..7).first(obj).should == [3, 4]
  end

  it "raises a TypeError if #to_int does not return an Integer" do
    obj = mock("to_int")
    obj.should_receive(:to_int).and_return("1")
    -> { (2..3).first(obj) }.should raise_error(TypeError)
  end

  it "truncates the value when passed a Float" do
    (2..9).first(2.8).should == [2, 3]
  end

  it "raises a TypeError when passed nil" do
    -> { (2..3).first(nil) }.should raise_error(TypeError)
  end

  it "raises a TypeError when passed a String" do
    -> { (2..3).first("1") }.should raise_error(TypeError)
  end

  ruby_version_is "2.7" do
    it "raises a RangeError when called on an beginless range" do
      -> { eval("(..1)").first }.should raise_error(RangeError)
    end
  end
end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.jsmpp;

import java.io.DataInputStream;
import java.io.IOException;

import org.jsmpp.bean.Command;
import org.jsmpp.util.OctetUtil;

/**
 * Default implementation of {@link PDUReader}.
 *
 * @author uudashr
 * @version 1.0
 * @since 1.0
 *
 */
public class DefaultPDUReader implements PDUReader {

    /* (non-Javadoc)
     * @see org.jsmpp.PDUReader#readPDUHeader(java.io.DataInputStream)
     */
    public Command readPDUHeader(DataInputStream in)
            throws InvalidCommandLengthException, IOException {
        Command header = new Command();
        header.setCommandLength(in.readInt());

        if (header.getCommandLength() < 16) {
            // command length too short, read the left dump anyway
            byte[] dump = new byte[header.getCommandLength()];
            if (header.getCommandLength() >= 4) {
                in.read(dump, 4, header.getCommandLength() - 4);
            }
            throw new InvalidCommandLengthException("Command length "
                    + header.getCommandLength() + " is too short");
        }
        header.setCommandId(in.readInt());
        header.setCommandStatus(in.readInt());
        header.setSequenceNumber(in.readInt());
        return header;
    }

    /* (non-Javadoc)
     * @see org.jsmpp.PDUReader#readPDU(java.io.InputStream, org.jsmpp.bean.Command)
     */
    public byte[] readPDU(DataInputStream in, Command pduHeader) throws IOException {
        return readPDU(in, pduHeader.getCommandLength(), pduHeader
                .getCommandId(), pduHeader.getCommandStatus(), pduHeader
                .getSequenceNumber());
    }

    /* (non-Javadoc)
     * @see org.jsmpp.PDUReader#readPDU(java.io.InputStream, int, int, int, int)
     */
    public byte[] readPDU(DataInputStream in, int commandLength, int commandId,
            int commandStatus, int sequenceNumber) throws IOException {

        byte[] b = new byte[commandLength];
        System.arraycopy(OctetUtil.intToBytes(commandLength), 0, b, 0, 4);
        System.arraycopy(OctetUtil.intToBytes(commandId), 0, b, 4, 4);
        System.arraycopy(OctetUtil.intToBytes(commandStatus), 0, b, 8, 4);
        System.arraycopy(OctetUtil.intToBytes(sequenceNumber), 0, b, 12, 4);

        if (commandLength > 16) {
            synchronized (in) {
                in.readFully(b, 16, commandLength - 16);
            }
        }
        return b;
    }
}