def CoarseDropout(p=<NUM_LIT:0>, size_px=None, size_percent=None, per_channel=False, min_size=<NUM_LIT:4>, name=None, deterministic=False,<EOL>random_state=None):

if ia.is_single_number(p):<EOL><INDENT>p2 = iap.Binomial(<NUM_LIT:1> - p)<EOL><DEDENT>elif ia.is_iterable(p):<EOL><INDENT>ia.do_assert(len(p) == <NUM_LIT:2>)<EOL>ia.do_assert(p[<NUM_LIT:0>] < p[<NUM_LIT:1>])<EOL>ia.do_assert(<NUM_LIT:0> <= p[<NUM_LIT:0>] <= <NUM_LIT:1.0>)<EOL>ia.do_assert(<NUM_LIT:0> <= p[<NUM_LIT:1>] <= <NUM_LIT:1.0>)<EOL>p2 = iap.Binomial(iap.Uniform(<NUM_LIT:1> - p[<NUM_LIT:1>], <NUM_LIT:1> - p[<NUM_LIT:0>]))<EOL><DEDENT>elif isinstance(p, iap.StochasticParameter):<EOL><INDENT>p2 = p<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" % (type(p),))<EOL><DEDENT>if size_px is not None:<EOL><INDENT>p3 = iap.FromLowerResolution(other_param=p2, size_px=size_px, min_size=min_size)<EOL><DEDENT>elif size_percent is not None:<EOL><INDENT>p3 = iap.FromLowerResolution(other_param=p2, size_percent=size_percent, min_size=min_size)<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if name is None:<EOL><INDENT>name = "<STR_LIT>" % (ia.caller_name(),)<EOL><DEDENT>return MultiplyElementwise(p3, per_channel=per_channel, name=name, deterministic=deterministic,<EOL>random_state=random_state)<EOL>

Augmenter that sets rectangular areas within images to zero.

In contrast to Dropout, these areas can have larger sizes.
(E.g. you might end up with three large black rectangles in an image.)
Note that the current implementation leads to correlated sizes,
so when there is one large area that is dropped, there is a high likelihood
that all other dropped areas are also large.

This method is implemented by generating the dropout mask at a
lower resolution (than the image has) and then upsampling the mask
before dropping the pixels.

dtype support::

    See ``imgaug.augmenters.arithmetic.MultiplyElementwise``.

Parameters
----------
p : float or tuple of float or imgaug.parameters.StochasticParameter, optional
    The probability of any pixel being dropped (i.e. set to zero).

        * If a float, then that value will be used for all pixels. A value
          of 1.0 would mean, that all pixels will be dropped. A value of
          0.0 would lead to no pixels being dropped.
        * If a tuple ``(a, b)``, then a value p will be sampled from the
          range ``a <= p <= b`` per image and be used as the pixel's dropout
          probability.
        * If a StochasticParameter, then this parameter will be used to
          determine per pixel whether it should be dropped (sampled value
          of 0) or shouldn't (sampled value of 1).

size_px : int or tuple of int or imgaug.parameters.StochasticParameter, optional
    The size of the lower resolution image from which to sample the dropout
    mask in absolute pixel dimensions.

        * If an integer, then that size will be used for both height and
          width. E.g. a value of 3 would lead to a ``3x3`` mask, which is then
          upsampled to ``HxW``, where ``H`` is the image size and W the image width.
        * If a tuple ``(a, b)``, then two values ``M``, ``N`` will be sampled from the
          range ``[a..b]`` and the mask will be generated at size ``MxN``, then
          upsampled to ``HxW``.
        * If a StochasticParameter, then this parameter will be used to
          determine the sizes. It is expected to be discrete.

size_percent : float or tuple of float or imgaug.parameters.StochasticParameter, optional
    The size of the lower resolution image from which to sample the dropout
    mask *in percent* of the input image.

        * If a float, then that value will be used as the percentage of the
          height and width (relative to the original size). E.g. for value
          p, the mask will be sampled from ``(p*H)x(p*W)`` and later upsampled
          to ``HxW``.
        * If a tuple ``(a, b)``, then two values ``m``, ``n`` will be sampled from the
          interval ``(a, b)`` and used as the percentages, i.e the mask size
          will be ``(m*H)x(n*W)``.
        * If a StochasticParameter, then this parameter will be used to
          sample the percentage values. It is expected to be continuous.

per_channel : bool or float, optional
    Whether to use the same value (is dropped / is not dropped)
    for all channels of a pixel (False) or to sample a new value for each
    channel (True).
    If this value is a float ``p``, then for ``p`` percent of all images
    `per_channel` will be treated as True, otherwise as False.

min_size : int, optional
    Minimum size of the low resolution mask, both width and height. If
    `size_percent` or `size_px` leads to a lower value than this, `min_size`
    will be used instead. This should never have a value of less than 2,
    otherwise one may end up with a ``1x1`` low resolution mask, leading easily
    to the whole image being dropped.

name : None or str, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

deterministic : bool, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

random_state : None or int or numpy.random.RandomState, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

Examples
--------
>>> aug = iaa.CoarseDropout(0.02, size_percent=0.5)

drops 2 percent of all pixels on an lower-resolution image that has
50 percent of the original image's size, leading to dropped areas that
have roughly 2x2 pixels size.

>>> aug = iaa.CoarseDropout((0.0, 0.05), size_percent=(0.05, 0.5))

generates a dropout mask at 5 to 50 percent of image's size. In that mask,
0 to 5 percent of all pixels are dropped (random per image).

>>> aug = iaa.CoarseDropout((0.0, 0.05), size_px=(2, 16))

same as previous example, but the lower resolution image has 2 to 16 pixels
size.

>>> aug = iaa.CoarseDropout(0.02, size_percent=0.5, per_channel=True)

drops 2 percent of all pixels at 50 percent resolution (2x2 sizes)
in a channel-wise fashion, i.e. it is unlikely
for any pixel to have all channels set to zero (black pixels).

>>> aug = iaa.CoarseDropout(0.02, size_percent=0.5, per_channel=0.5)

same as previous example, but the `per_channel` feature is only active
for 50 percent of all images.


def ImpulseNoise(p=<NUM_LIT:0>, name=None, deterministic=False, random_state=None):

return SaltAndPepper(p=p, per_channel=True, name=name, deterministic=deterministic, random_state=random_state)<EOL>

Creates an augmenter to apply impulse noise to an image.

This is identical to ``SaltAndPepper``, except that per_channel is always set to True.

dtype support::

    See ``imgaug.augmenters.arithmetic.SaltAndPepper``.


def SaltAndPepper(p=<NUM_LIT:0>, per_channel=False, name=None, deterministic=False, random_state=None):

if name is None:<EOL><INDENT>name = "<STR_LIT>" % (ia.caller_name(),)<EOL><DEDENT>return ReplaceElementwise(<EOL>mask=p,<EOL>replacement=iap.Beta(<NUM_LIT:0.5>, <NUM_LIT:0.5>) * <NUM_LIT:255>,<EOL>per_channel=per_channel,<EOL>name=name,<EOL>deterministic=deterministic,<EOL>random_state=random_state<EOL>)<EOL>

Adds salt and pepper noise to an image, i.e. some white-ish and black-ish pixels.

dtype support::

    See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.

Parameters
----------
p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional
    Probability of changing a pixel to salt/pepper noise.

        * If a float, then that value will be used for all images as the
          probability.
        * If a tuple ``(a, b)``, then a probability will be sampled per image
          from the range ``a <= x <= b``.
        * If a list, then a random value will be sampled from that list
          per image.
        * If a StochasticParameter, then this parameter will be used as
          the *mask*, i.e. it is expected to contain values between
          0.0 and 1.0, where 1.0 means that salt/pepper is to be added
          at that location.

per_channel : bool or float, optional
    Whether to use the same value for all channels (False)
    or to sample a new value for each channel (True).
    If this value is a float ``p``, then for ``p`` percent of all images
    `per_channel` will be treated as True, otherwise as False.

name : None or str, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

deterministic : bool, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

random_state : None or int or numpy.random.RandomState, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

Examples
--------
>>> aug = iaa.SaltAndPepper(0.05)

Replaces 5 percent of all pixels with salt/pepper.


def CoarseSaltAndPepper(p=<NUM_LIT:0>, size_px=None, size_percent=None, per_channel=False, min_size=<NUM_LIT:4>, name=None,<EOL>deterministic=False, random_state=None):

mask = iap.handle_probability_param(p, "<STR_LIT:p>", tuple_to_uniform=True, list_to_choice=True)<EOL>if size_px is not None:<EOL><INDENT>mask_low = iap.FromLowerResolution(other_param=mask, size_px=size_px, min_size=min_size)<EOL><DEDENT>elif size_percent is not None:<EOL><INDENT>mask_low = iap.FromLowerResolution(other_param=mask, size_percent=size_percent, min_size=min_size)<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>replacement = iap.Beta(<NUM_LIT:0.5>, <NUM_LIT:0.5>) * <NUM_LIT:255><EOL>if name is None:<EOL><INDENT>name = "<STR_LIT>" % (ia.caller_name(),)<EOL><DEDENT>return ReplaceElementwise(<EOL>mask=mask_low,<EOL>replacement=replacement,<EOL>per_channel=per_channel,<EOL>name=name,<EOL>deterministic=deterministic,<EOL>random_state=random_state<EOL>)<EOL>

Adds coarse salt and pepper noise to an image, i.e. rectangles that contain noisy white-ish and black-ish pixels.

TODO replace dtype support with uint8 only, because replacement is geared towards that value range

dtype support::

    See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.

Parameters
----------
p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional
    Probability of changing a pixel to salt/pepper noise.

        * If a float, then that value will be used for all images as the
          probability.
        * If a tuple ``(a, b)``, then a probability will be sampled per image
          from the range ``a <= x <= b``.
        * If a list, then a random value will be sampled from that list
          per image.
        * If a StochasticParameter, then this parameter will be used as
          the *mask*, i.e. it is expected to contain values between
          0.0 and 1.0, where 1.0 means that salt/pepper is to be added
          at that location.

size_px : int or tuple of int or imgaug.parameters.StochasticParameter, optional
    The size of the lower resolution image from which to sample the noise
    mask in absolute pixel dimensions.

        * If an integer, then that size will be used for both height and
          width. E.g. a value of 3 would lead to a ``3x3`` mask, which is then
          upsampled to ``HxW``, where ``H`` is the image size and ``W`` the image width.
        * If a tuple ``(a, b)``, then two values ``M``, ``N`` will be sampled from the
          range ``[a..b]`` and the mask will be generated at size ``MxN``, then
          upsampled to ``HxW``.
        * If a StochasticParameter, then this parameter will be used to
          determine the sizes. It is expected to be discrete.

size_percent : float or tuple of float or imgaug.parameters.StochasticParameter, optional
    The size of the lower resolution image from which to sample the noise
    mask *in percent* of the input image.

        * If a float, then that value will be used as the percentage of the
          height and width (relative to the original size). E.g. for value
          p, the mask will be sampled from ``(p*H)x(p*W)`` and later upsampled
          to ``HxW.``
        * If a tuple ``(a, b)``, then two values ``m``, ``n`` will be sampled from the
          interval ``(a, b)`` and used as the percentages, i.e the mask size
          will be ``(m*H)x(n*W)``.
        * If a StochasticParameter, then this parameter will be used to
          sample the percentage values. It is expected to be continuous.

per_channel : bool or float, optional
    Whether to use the same value (is dropped / is not dropped)
    for all channels of a pixel (False) or to sample a new value for each
    channel (True).
    If this value is a float ``p``, then for ``p`` percent of all images
    `per_channel` will be treated as True, otherwise as False.

min_size : int, optional
    Minimum size of the low resolution mask, both width and height. If
    `size_percent` or `size_px` leads to a lower value than this, `min_size`
    will be used instead. This should never have a value of less than 2,
    otherwise one may end up with a 1x1 low resolution mask, leading easily
    to the whole image being replaced.

name : None or str, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

deterministic : bool, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

random_state : None or int or numpy.random.RandomState, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

Examples
--------
>>> aug = iaa.CoarseSaltAndPepper(0.05, size_percent=(0.01, 0.1))

Replaces 5 percent of all pixels with salt/pepper in an image that has
1 to 10 percent of the input image size, then upscales the results
to the input image size, leading to large rectangular areas being replaced.


def Salt(p=<NUM_LIT:0>, per_channel=False, name=None, deterministic=False, random_state=None):

replacement01 = iap.ForceSign(<EOL>iap.Beta(<NUM_LIT:0.5>, <NUM_LIT:0.5>) - <NUM_LIT:0.5>,<EOL>positive=True,<EOL>mode="<STR_LIT>"<EOL>) + <NUM_LIT:0.5><EOL>replacement = replacement01 * <NUM_LIT:255>  <EOL>if name is None:<EOL><INDENT>name = "<STR_LIT>" % (ia.caller_name(),)<EOL><DEDENT>return ReplaceElementwise(mask=p, replacement=replacement, per_channel=per_channel, name=name,<EOL>deterministic=deterministic, random_state=random_state)<EOL>

Adds salt noise to an image, i.e. white-ish pixels.

dtype support::

    See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.

Parameters
----------
p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional
    Probability of changing a pixel to salt noise.

        * If a float, then that value will be used for all images as the
          probability.
        * If a tuple ``(a, b)``, then a probability will be sampled per image
          from the range ``a <= x <= b``.
        * If a list, then a random value will be sampled from that list
          per image.
        * If a StochasticParameter, then this parameter will be used as
          the *mask*, i.e. it is expected to contain values between
          0.0 and 1.0, where 1.0 means that salt is to be added
          at that location.

per_channel : bool or float, optional
    Whether to use the same value for all channels (False)
    or to sample a new value for each channel (True).
    If this value is a float ``p``, then for ``p`` percent of all images
    `per_channel` will be treated as True, otherwise as False.

name : None or str, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

deterministic : bool, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

random_state : None or int or numpy.random.RandomState, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

Examples
--------
>>> aug = iaa.Salt(0.05)

Replaces 5 percent of all pixels with salt.


def CoarseSalt(p=<NUM_LIT:0>, size_px=None, size_percent=None, per_channel=False, min_size=<NUM_LIT:4>, name=None, deterministic=False,<EOL>random_state=None):

mask = iap.handle_probability_param(p, "<STR_LIT:p>", tuple_to_uniform=True, list_to_choice=True)<EOL>if size_px is not None:<EOL><INDENT>mask_low = iap.FromLowerResolution(other_param=mask, size_px=size_px, min_size=min_size)<EOL><DEDENT>elif size_percent is not None:<EOL><INDENT>mask_low = iap.FromLowerResolution(other_param=mask, size_percent=size_percent, min_size=min_size)<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>replacement01 = iap.ForceSign(<EOL>iap.Beta(<NUM_LIT:0.5>, <NUM_LIT:0.5>) - <NUM_LIT:0.5>,<EOL>positive=True,<EOL>mode="<STR_LIT>"<EOL>) + <NUM_LIT:0.5><EOL>replacement = replacement01 * <NUM_LIT:255><EOL>if name is None:<EOL><INDENT>name = "<STR_LIT>" % (ia.caller_name(),)<EOL><DEDENT>return ReplaceElementwise(mask=mask_low, replacement=replacement, per_channel=per_channel, name=name,<EOL>deterministic=deterministic, random_state=random_state)<EOL>

Adds coarse salt noise to an image, i.e. rectangles containing noisy white-ish pixels.

dtype support::

    See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.

Parameters
----------
p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional
    Probability of changing a pixel to salt noise.

        * If a float, then that value will be used for all images as the
          probability.
        * If a tuple ``(a, b)``, then a probability will be sampled per image
          from the range ``a <= x <= b``.
        * If a list, then a random value will be sampled from that list
          per image.
        * If a StochasticParameter, then this parameter will be used as
          the *mask*, i.e. it is expected to contain values between
          0.0 and 1.0, where 1.0 means that salt is to be added
          at that location.

size_px : int or tuple of int or imgaug.parameters.StochasticParameter, optional
    The size of the lower resolution image from which to sample the noise
    mask in absolute pixel dimensions.

        * If an integer, then that size will be used for both height and
          width. E.g. a value of 3 would lead to a ``3x3`` mask, which is then
          upsampled to ``HxW``, where H is the image size and W the image width.
        * If a tuple ``(a, b)``, then two values M, N will be sampled from the
          range ``[a..b]`` and the mask will be generated at size ``MxN``, then
          upsampled to ``HxW``.
        * If a StochasticParameter, then this parameter will be used to
          determine the sizes. It is expected to be discrete.

size_percent : float or tuple of float or imgaug.parameters.StochasticParameter, optional
    The size of the lower resolution image from which to sample the noise
    mask *in percent* of the input image.

        * If a float, then that value will be used as the percentage of the
          height and width (relative to the original size). E.g. for value
          p, the mask will be sampled from ``(p*H)x(p*W)`` and later upsampled
          to ``HxW``.
        * If a tuple ``(a, b)``, then two values ``m``, ``n`` will be sampled from the
          interval ``(a, b)`` and used as the percentages, i.e the mask size
          will be ``(m*H)x(n*W)``.
        * If a StochasticParameter, then this parameter will be used to
          sample the percentage values. It is expected to be continuous.

per_channel : bool or float, optional
    Whether to use the same value (is dropped / is not dropped)
    for all channels of a pixel (False) or to sample a new value for each
    channel (True).
    If this value is a float ``p``, then for ``p`` percent of all images
    `per_channel` will be treated as True, otherwise as False.

min_size : int, optional
    Minimum size of the low resolution mask, both width and height. If
    `size_percent` or `size_px` leads to a lower value than this, `min_size`
    will be used instead. This should never have a value of less than 2,
    otherwise one may end up with a ``1x1`` low resolution mask, leading easily
    to the whole image being replaced.

name : None or str, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

deterministic : bool, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

random_state : None or int or numpy.random.RandomState, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

Examples
--------
>>> aug = iaa.CoarseSalt(0.05, size_percent=(0.01, 0.1))

Replaces 5 percent of all pixels with salt in an image that has
1 to 10 percent of the input image size, then upscales the results
to the input image size, leading to large rectangular areas being replaced.


def Pepper(p=<NUM_LIT:0>, per_channel=False, name=None, deterministic=False, random_state=None):

replacement01 = iap.ForceSign(<EOL>iap.Beta(<NUM_LIT:0.5>, <NUM_LIT:0.5>) - <NUM_LIT:0.5>,<EOL>positive=False,<EOL>mode="<STR_LIT>"<EOL>) + <NUM_LIT:0.5><EOL>replacement = replacement01 * <NUM_LIT:255><EOL>if name is None:<EOL><INDENT>name = "<STR_LIT>" % (ia.caller_name(),)<EOL><DEDENT>return ReplaceElementwise(<EOL>mask=p,<EOL>replacement=replacement,<EOL>per_channel=per_channel,<EOL>name=name,<EOL>deterministic=deterministic,<EOL>random_state=random_state<EOL>)<EOL>

Adds pepper noise to an image, i.e. black-ish pixels.

This is similar to dropout, but slower and the black pixels are not uniformly black.

dtype support::

    See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.

Parameters
----------
p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional
    Probability of changing a pixel to pepper noise.

        * If a float, then that value will be used for all images as the
          probability.
        * If a tuple ``(a, b)``, then a probability will be sampled per image
          from the range ``a <= x <= b``.
        * If a list, then a random value will be sampled from that list
          per image.
        * If a StochasticParameter, then this parameter will be used as
          the *mask*, i.e. it is expected to contain values between
          0.0 and 1.0, where 1.0 means that pepper is to be added
          at that location.

per_channel : bool or float, optional
    Whether to use the same value for all channels (False)
    or to sample a new value for each channel (True).
    If this value is a float ``p``, then for ``p`` percent of all images
    `per_channel` will be treated as True, otherwise as False.

name : None or str, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

deterministic : bool, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

random_state : None or int or numpy.random.RandomState, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

Examples
--------
>>> aug = iaa.Pepper(0.05)

Replaces 5 percent of all pixels with pepper.


def CoarsePepper(p=<NUM_LIT:0>, size_px=None, size_percent=None, per_channel=False, min_size=<NUM_LIT:4>, name=None, deterministic=False,<EOL>random_state=None):

mask = iap.handle_probability_param(p, "<STR_LIT:p>", tuple_to_uniform=True, list_to_choice=True)<EOL>if size_px is not None:<EOL><INDENT>mask_low = iap.FromLowerResolution(other_param=mask, size_px=size_px, min_size=min_size)<EOL><DEDENT>elif size_percent is not None:<EOL><INDENT>mask_low = iap.FromLowerResolution(other_param=mask, size_percent=size_percent, min_size=min_size)<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>replacement01 = iap.ForceSign(<EOL>iap.Beta(<NUM_LIT:0.5>, <NUM_LIT:0.5>) - <NUM_LIT:0.5>,<EOL>positive=False,<EOL>mode="<STR_LIT>"<EOL>) + <NUM_LIT:0.5><EOL>replacement = replacement01 * <NUM_LIT:255><EOL>if name is None:<EOL><INDENT>name = "<STR_LIT>" % (ia.caller_name(),)<EOL><DEDENT>return ReplaceElementwise(<EOL>mask=mask_low,<EOL>replacement=replacement,<EOL>per_channel=per_channel,<EOL>name=name,<EOL>deterministic=deterministic,<EOL>random_state=random_state<EOL>)<EOL>

Adds coarse pepper noise to an image, i.e. rectangles that contain noisy black-ish pixels.

dtype support::

    See ``imgaug.augmenters.arithmetic.ReplaceElementwise``.

Parameters
----------
p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional
    Probability of changing a pixel to pepper noise.

        * If a float, then that value will be used for all images as the
          probability.
        * If a tuple ``(a, b)``, then a probability will be sampled per image
          from the range ``a <= x <= b.``
        * If a list, then a random value will be sampled from that list
          per image.
        * If a StochasticParameter, then this parameter will be used as
          the *mask*, i.e. it is expected to contain values between
          0.0 and 1.0, where 1.0 means that pepper is to be added
          at that location.

size_px : int or tuple of int or imgaug.parameters.StochasticParameter, optional
    The size of the lower resolution image from which to sample the noise
    mask in absolute pixel dimensions.

        * If an integer, then that size will be used for both height and
          width. E.g. a value of 3 would lead to a ``3x3`` mask, which is then
          upsampled to ``HxW``, where ``H`` is the image size and W the image width.
        * If a tuple ``(a, b)``, then two values ``M``, ``N`` will be sampled from the
          range ``[a..b]`` and the mask will be generated at size ``MxN``, then
          upsampled to ``HxW``.
        * If a StochasticParameter, then this parameter will be used to
          determine the sizes. It is expected to be discrete.

size_percent : float or tuple of float or imgaug.parameters.StochasticParameter, optional
    The size of the lower resolution image from which to sample the noise
    mask *in percent* of the input image.

        * If a float, then that value will be used as the percentage of the
          height and width (relative to the original size). E.g. for value
          p, the mask will be sampled from ``(p*H)x(p*W)`` and later upsampled
          to ``HxW``.
        * If a tuple ``(a, b)``, then two values ``m``, ``n`` will be sampled from the
          interval ``(a, b)`` and used as the percentages, i.e the mask size
          will be ``(m*H)x(n*W)``.
        * If a StochasticParameter, then this parameter will be used to
          sample the percentage values. It is expected to be continuous.

per_channel : bool or float, optional
    Whether to use the same value (is dropped / is not dropped)
    for all channels of a pixel (False) or to sample a new value for each
    channel (True).
    If this value is a float ``p``, then for ``p`` percent of all images
    `per_channel` will be treated as True, otherwise as False.

min_size : int, optional
    Minimum size of the low resolution mask, both width and height. If
    `size_percent` or `size_px` leads to a lower value than this, `min_size`
    will be used instead. This should never have a value of less than 2,
    otherwise one may end up with a 1x1 low resolution mask, leading easily
    to the whole image being replaced.

name : None or str, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

deterministic : bool, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

random_state : None or int or numpy.random.RandomState, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

Examples
--------
>>> aug = iaa.CoarsePepper(0.05, size_percent=(0.01, 0.1))

Replaces 5 percent of all pixels with pepper in an image that has
1 to 10 percent of the input image size, then upscales the results
to the input image size, leading to large rectangular areas being replaced.


def ContrastNormalization(alpha=<NUM_LIT:1.0>, per_channel=False, name=None, deterministic=False, random_state=None):

<EOL>from . import contrast as contrast_lib<EOL>return contrast_lib.LinearContrast(alpha=alpha, per_channel=per_channel, name=name, deterministic=deterministic,<EOL>random_state=random_state)<EOL>

Augmenter that changes the contrast of images.

dtype support:

    See ``imgaug.augmenters.contrast.LinearContrast``.

Parameters
----------
alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
    Strength of the contrast normalization. Higher values than 1.0
    lead to higher contrast, lower values decrease the contrast.

        * If a number, then that value will be used for all images.
        * If a tuple ``(a, b)``, then a value will be sampled per image from
          the range ``a <= x <= b`` and be used as the alpha value.
        * If a list, then a random value will be sampled per image from
          that list.
        * If a StochasticParameter, then this parameter will be used to
          sample the alpha value per image.

per_channel : bool or float, optional
    Whether to use the same value for all channels (False)
    or to sample a new value for each channel (True).
    If this value is a float ``p``, then for ``p`` percent of all images
    `per_channel` will be treated as True, otherwise as False.

name : None or str, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

deterministic : bool, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

random_state : None or int or numpy.random.RandomState, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

Examples
--------
>>> iaa.ContrastNormalization((0.5, 1.5))

Decreases oder improves contrast per image by a random factor between
0.5 and 1.5. The factor 0.5 means that any difference from the center value
(i.e. 128) will be halved, leading to less contrast.

>>> iaa.ContrastNormalization((0.5, 1.5), per_channel=0.5)

Same as before, but for 50 percent of all images the normalization is done
independently per channel (i.e. factors can vary per channel for the same
image). In the other 50 percent of all images, the factor is the same for
all channels.


def blend_alpha(image_fg, image_bg, alpha, eps=<NUM_LIT>):

assert image_fg.shape == image_bg.shape<EOL>assert image_fg.dtype.kind == image_bg.dtype.kind<EOL>assert image_fg.dtype.name not in ["<STR_LIT>"]<EOL>assert image_bg.dtype.name not in ["<STR_LIT>"]<EOL>input_was_2d = (len(image_fg.shape) == <NUM_LIT:2>)<EOL>if input_was_2d:<EOL><INDENT>image_fg = np.atleast_3d(image_fg)<EOL>image_bg = np.atleast_3d(image_bg)<EOL><DEDENT>input_was_bool = False<EOL>if image_fg.dtype.kind == "<STR_LIT:b>":<EOL><INDENT>input_was_bool = True<EOL>image_fg = image_fg.astype(np.float32)<EOL>image_bg = image_bg.astype(np.float32)<EOL><DEDENT>alpha = np.array(alpha, dtype=np.float64)<EOL>if alpha.size == <NUM_LIT:1>:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if alpha.ndim == <NUM_LIT:2>:<EOL><INDENT>assert alpha.shape == image_fg.shape[<NUM_LIT:0>:<NUM_LIT:2>]<EOL>alpha = alpha.reshape((alpha.shape[<NUM_LIT:0>], alpha.shape[<NUM_LIT:1>], <NUM_LIT:1>))<EOL><DEDENT>elif alpha.ndim == <NUM_LIT:3>:<EOL><INDENT>assert alpha.shape == image_fg.shape or alpha.shape == image_fg.shape[<NUM_LIT:0>:<NUM_LIT:2>] + (<NUM_LIT:1>,)<EOL><DEDENT>else:<EOL><INDENT>alpha = alpha.reshape((<NUM_LIT:1>, <NUM_LIT:1>, -<NUM_LIT:1>))<EOL><DEDENT>if alpha.shape[<NUM_LIT:2>] != image_fg.shape[<NUM_LIT:2>]:<EOL><INDENT>alpha = np.tile(alpha, (<NUM_LIT:1>, <NUM_LIT:1>, image_fg.shape[<NUM_LIT:2>]))<EOL><DEDENT><DEDENT>if not input_was_bool:<EOL><INDENT>if np.all(alpha >= <NUM_LIT:1.0> - eps):<EOL><INDENT>return np.copy(image_fg)<EOL><DEDENT>elif np.all(alpha <= eps):<EOL><INDENT>return np.copy(image_bg)<EOL><DEDENT><DEDENT>assert <NUM_LIT:0> <= alpha.item(<NUM_LIT:0>) <= <NUM_LIT:1.0><EOL>dt_images = iadt.get_minimal_dtype([image_fg, image_bg])<EOL>isize = dt_images.itemsize * <NUM_LIT:2><EOL>isize = max(isize, <NUM_LIT:4>)  <EOL>dt_blend = np.dtype("<STR_LIT>" % (isize,))<EOL>if alpha.dtype != dt_blend:<EOL><INDENT>alpha = alpha.astype(dt_blend)<EOL><DEDENT>if image_fg.dtype != dt_blend:<EOL><INDENT>image_fg = image_fg.astype(dt_blend)<EOL><DEDENT>if image_bg.dtype != dt_blend:<EOL><INDENT>image_bg = image_bg.astype(dt_blend)<EOL><DEDENT>image_blend = image_bg + alpha * (image_fg - image_bg)<EOL>if input_was_bool:<EOL><INDENT>image_blend = image_blend > <NUM_LIT:0.5><EOL><DEDENT>else:<EOL><INDENT>image_blend = iadt.restore_dtypes_(image_blend, dt_images, clip=False, round=True)<EOL><DEDENT>if input_was_2d:<EOL><INDENT>return image_blend[:, :, <NUM_LIT:0>]<EOL><DEDENT>return image_blend<EOL>

Blend two images using an alpha blending.

In an alpha blending, the two images are naively mixed. Let ``A`` be the foreground image
and ``B`` the background image and ``a`` is the alpha value. Each pixel intensity is then
computed as ``a * A_ij + (1-a) * B_ij``.

dtype support::

    * ``uint8``: yes; fully tested
    * ``uint16``: yes; fully tested
    * ``uint32``: yes; fully tested
    * ``uint64``: yes; fully tested (1)
    * ``int8``: yes; fully tested
    * ``int16``: yes; fully tested
    * ``int32``: yes; fully tested
    * ``int64``: yes; fully tested (1)
    * ``float16``: yes; fully tested
    * ``float32``: yes; fully tested
    * ``float64``: yes; fully tested (1)
    * ``float128``: no (2)
    * ``bool``: yes; fully tested (2)

    - (1) Tests show that these dtypes work, but a conversion to float128 happens, which only
          has 96 bits of size instead of true 128 bits and hence not twice as much resolution.
          It is possible that these dtypes result in inaccuracies, though the tests did not
          indicate that.
    - (2) Not available due to the input dtype having to be increased to an equivalent float
          dtype with two times the input resolution.
    - (3) Mapped internally to ``float16``.

Parameters
----------
image_fg : (H,W,[C]) ndarray
    Foreground image. Shape and dtype kind must match the one of the
    background image.

image_bg : (H,W,[C]) ndarray
    Background image. Shape and dtype kind must match the one of the
    foreground image.

alpha : number or iterable of number or ndarray
    The blending factor, between 0.0 and 1.0. Can be interpreted as the opacity of the
    foreground image. Values around 1.0 result in only the foreground image being visible.
    Values around 0.0 result in only the background image being visible.
    Multiple alphas may be provided. In these cases, there must be exactly one alpha per
    channel in the foreground/background image. Alternatively, for ``(H,W,C)`` images,
    either one ``(H,W)`` array or an ``(H,W,C)`` array of alphas may be provided,
    denoting the elementwise alpha value.

eps : number, optional
    Controls when an alpha is to be interpreted as exactly 1.0 or exactly 0.0, resulting
    in only the foreground/background being visible and skipping the actual computation.

Returns
-------
image_blend : (H,W,C) ndarray
    Blend of foreground and background image.


def SimplexNoiseAlpha(first=None, second=None, per_channel=False, size_px_max=(<NUM_LIT:2>, <NUM_LIT:16>), upscale_method=None,<EOL>iterations=(<NUM_LIT:1>, <NUM_LIT:3>), aggregation_method="<STR_LIT>", sigmoid=True, sigmoid_thresh=None,<EOL>name=None, deterministic=False, random_state=None):

upscale_method_default = iap.Choice(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"], p=[<NUM_LIT>, <NUM_LIT>, <NUM_LIT>])<EOL>sigmoid_thresh_default = iap.Normal(<NUM_LIT:0.0>, <NUM_LIT>)<EOL>noise = iap.SimplexNoise(<EOL>size_px_max=size_px_max,<EOL>upscale_method=upscale_method if upscale_method is not None else upscale_method_default<EOL>)<EOL>if iterations != <NUM_LIT:1>:<EOL><INDENT>noise = iap.IterativeNoiseAggregator(<EOL>noise,<EOL>iterations=iterations,<EOL>aggregation_method=aggregation_method<EOL>)<EOL><DEDENT>if sigmoid is False or (ia.is_single_number(sigmoid) and sigmoid <= <NUM_LIT>):<EOL><INDENT>noise = iap.Sigmoid.create_for_noise(<EOL>noise,<EOL>threshold=sigmoid_thresh if sigmoid_thresh is not None else sigmoid_thresh_default,<EOL>activated=sigmoid<EOL>)<EOL><DEDENT>if name is None:<EOL><INDENT>name = "<STR_LIT>" % (ia.caller_name(),)<EOL><DEDENT>return AlphaElementwise(<EOL>factor=noise, first=first, second=second, per_channel=per_channel,<EOL>name=name, deterministic=deterministic, random_state=random_state<EOL>)<EOL>

Augmenter to alpha-blend two image sources using simplex noise alpha masks.

The alpha masks are sampled using a simplex noise method, roughly creating
connected blobs of 1s surrounded by 0s. If nearest neighbour upsampling
is used, these blobs can be rectangular with sharp edges.

dtype support::

    See ``imgaug.augmenters.blend.AlphaElementwise``.

Parameters
----------
first : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
    Augmenter(s) that make up the first of the two branches.

        * If None, then the input images will be reused as the output
          of the first branch.
        * If Augmenter, then that augmenter will be used as the branch.
        * If iterable of Augmenter, then that iterable will be converted
          into a Sequential and used as the augmenter.

second : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
    Augmenter(s) that make up the second of the two branches.

        * If None, then the input images will be reused as the output
          of the second branch.
        * If Augmenter, then that augmenter will be used as the branch.
        * If iterable of Augmenter, then that iterable will be converted
          into a Sequential and used as the augmenter.

per_channel : bool or float, optional
    Whether to use the same factor for all channels (False)
    or to sample a new value for each channel (True).
    If this value is a float ``p``, then for ``p`` percent of all images
    `per_channel` will be treated as True, otherwise as False.

size_px_max : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
    The simplex noise is always generated in a low resolution environment.
    This parameter defines the maximum size of that environment (in
    pixels). The environment is initialized at the same size as the input
    image and then downscaled, so that no side exceeds `size_px_max`
    (aspect ratio is kept).

        * If int, then that number will be used as the size for all
          iterations.
        * If tuple of two ints ``(a, b)``, then a value will be sampled
          per iteration from the discrete range ``[a..b]``.
        * If a list of ints, then a value will be picked per iteration at
          random from that list.
        * If a StochasticParameter, then a value will be sampled from
          that parameter per iteration.

upscale_method : None or imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional
    After generating the noise maps in low resolution environments, they
    have to be upscaled to the input image size. This parameter controls
    the upscaling method.

        * If None, then either ``nearest`` or ``linear`` or ``cubic`` is picked.
          Most weight is put on linear, followed by cubic.
        * If ia.ALL, then either ``nearest`` or ``linear`` or ``area`` or ``cubic``
          is picked per iteration (all same probability).
        * If string, then that value will be used as the method (must be
          'nearest' or ``linear`` or ``area`` or ``cubic``).
        * If list of string, then a random value will be picked from that
          list per iteration.
        * If StochasticParameter, then a random value will be sampled
          from that parameter per iteration.

iterations : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
    How often to repeat the simplex noise generation process per image.

        * If int, then that number will be used as the iterations for all
          images.
        * If tuple of two ints ``(a, b)``, then a value will be sampled
          per image from the discrete range ``[a..b]``.
        * If a list of ints, then a value will be picked per image at
          random from that list.
        * If a StochasticParameter, then a value will be sampled from
          that parameter per image.

aggregation_method : imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional
    The noise maps (from each iteration) are combined to one noise map
    using an aggregation process. This parameter defines the method used
    for that process. Valid methods are ``min``, ``max`` or ``avg``,
    where ``min`` combines the noise maps by taking the (elementwise) minimum
    over all iteration's results, ``max`` the (elementwise) maximum and
    ``avg`` the (elementwise) average.

        * If imgaug.ALL, then a random value will be picked per image from the
          valid ones.
        * If a string, then that value will always be used as the method.
        * If a list of string, then a random value will be picked from
          that list per image.
        * If a StochasticParameter, then a random value will be sampled
          from that paramter per image.

sigmoid : bool or number, optional
    Whether to apply a sigmoid function to the final noise maps, resulting
    in maps that have more extreme values (close to 0.0 or 1.0).

        * If bool, then a sigmoid will always (True) or never (False) be
          applied.
        * If a number ``p`` with ``0<=p<=1``, then a sigmoid will be applied to
          ``p`` percent of all final noise maps.

sigmoid_thresh : None or number or tuple of number or imgaug.parameters.StochasticParameter, optional
    Threshold of the sigmoid, when applied. Thresholds above zero
    (e.g. 5.0) will move the saddle point towards the right, leading to
    more values close to 0.0.

        * If None, then ``Normal(0, 5.0)`` will be used.
        * If number, then that threshold will be used for all images.
        * If tuple of two numbers ``(a, b)``, then a random value will
          be sampled per image from the range ``[a, b]``.
        * If StochasticParameter, then a random value will be sampled from
          that parameter per image.

name : None or str, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

deterministic : bool, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

random_state : None or int or numpy.random.RandomState, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

Examples
--------
>>> aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0))

Detects per image all edges, marks them in a black and white image and
then alpha-blends the result with the original image using simplex noise
masks.

>>> aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0), upscale_method="linear")

Same as the first example, but uses only (smooth) linear upscaling to
scale the simplex noise masks to the final image sizes, i.e. no nearest
neighbour upsampling is used, which would result in rectangles with hard
edges.

>>> aug = iaa.SimplexNoiseAlpha(iaa.EdgeDetect(1.0), sigmoid_thresh=iap.Normal(10.0, 5.0))

Same as the first example, but uses a threshold for the sigmoid function
that is further to the right. This is more conservative, i.e. the generated
noise masks will be mostly black (values around 0.0), which means that
most of the original images (parameter/branch `second`) will be kept,
rather than using the results of the augmentation (parameter/branch
`first`).


def FrequencyNoiseAlpha(exponent=(-<NUM_LIT:4>, <NUM_LIT:4>), first=None, second=None, per_channel=False,<EOL>size_px_max=(<NUM_LIT:4>, <NUM_LIT:16>), upscale_method=None,<EOL>iterations=(<NUM_LIT:1>, <NUM_LIT:3>), aggregation_method=["<STR_LIT>", "<STR_LIT>"],<EOL>sigmoid=<NUM_LIT:0.5>, sigmoid_thresh=None,<EOL>name=None, deterministic=False, random_state=None):

<EOL>upscale_method_default = iap.Choice(["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"], p=[<NUM_LIT>, <NUM_LIT>, <NUM_LIT>])<EOL>sigmoid_thresh_default = iap.Normal(<NUM_LIT:0.0>, <NUM_LIT>)<EOL>noise = iap.FrequencyNoise(<EOL>exponent=exponent,<EOL>size_px_max=size_px_max,<EOL>upscale_method=upscale_method if upscale_method is not None else upscale_method_default<EOL>)<EOL>if iterations != <NUM_LIT:1>:<EOL><INDENT>noise = iap.IterativeNoiseAggregator(<EOL>noise,<EOL>iterations=iterations,<EOL>aggregation_method=aggregation_method<EOL>)<EOL><DEDENT>if sigmoid is False or (ia.is_single_number(sigmoid) and sigmoid <= <NUM_LIT>):<EOL><INDENT>noise = iap.Sigmoid.create_for_noise(<EOL>noise,<EOL>threshold=sigmoid_thresh if sigmoid_thresh is not None else sigmoid_thresh_default,<EOL>activated=sigmoid<EOL>)<EOL><DEDENT>if name is None:<EOL><INDENT>name = "<STR_LIT>" % (ia.caller_name(),)<EOL><DEDENT>return AlphaElementwise(<EOL>factor=noise, first=first, second=second, per_channel=per_channel,<EOL>name=name, deterministic=deterministic, random_state=random_state<EOL>)<EOL>

Augmenter to alpha-blend two image sources using frequency noise masks.

The alpha masks are sampled using frequency noise of varying scales,
which can sometimes create large connected blobs of 1s surrounded by 0s
and other times results in smaller patterns. If nearest neighbour
upsampling is used, these blobs can be rectangular with sharp edges.

dtype support::

    See ``imgaug.augmenters.blend.AlphaElementwise``.

Parameters
----------
exponent : number or tuple of number of list of number or imgaug.parameters.StochasticParameter, optional
    Exponent to use when scaling in the frequency domain.
    Sane values are in the range -4 (large blobs) to 4 (small patterns).
    To generate cloud-like structures, use roughly -2.

        * If number, then that number will be used as the exponent for all
          iterations.
        * If tuple of two numbers ``(a, b)``, then a value will be sampled
          per iteration from the range ``[a, b]``.
        * If a list of numbers, then a value will be picked per iteration
          at random from that list.
        * If a StochasticParameter, then a value will be sampled from
          that parameter per iteration.

first : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
    Augmenter(s) that make up the first of the two branches.

        * If None, then the input images will be reused as the output
          of the first branch.
        * If Augmenter, then that augmenter will be used as the branch.
        * If iterable of Augmenter, then that iterable will be converted
          into a Sequential and used as the augmenter.

second : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
    Augmenter(s) that make up the second of the two branches.

        * If None, then the input images will be reused as the output
          of the second branch.
        * If Augmenter, then that augmenter will be used as the branch.
        * If iterable of Augmenter, then that iterable will be converted
          into a Sequential and used as the augmenter.

per_channel : bool or float, optional
    Whether to use the same factor for all channels (False)
    or to sample a new value for each channel (True).
    If this value is a float ``p``, then for ``p`` percent of all images
    `per_channel` will be treated as True, otherwise as False.

size_px_max : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
    The noise is generated in a low resolution environment.
    This parameter defines the maximum size of that environment (in
    pixels). The environment is initialized at the same size as the input
    image and then downscaled, so that no side exceeds `size_px_max`
    (aspect ratio is kept).

        * If int, then that number will be used as the size for all
          iterations.
        * If tuple of two ints ``(a, b)``, then a value will be sampled
          per iteration from the discrete range ``[a..b]``.
        * If a list of ints, then a value will be picked per iteration at
          random from that list.
        * If a StochasticParameter, then a value will be sampled from
          that parameter per iteration.

upscale_method : None or imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional
    After generating the noise maps in low resolution environments, they
    have to be upscaled to the input image size. This parameter controls
    the upscaling method.

        * If None, then either ``nearest`` or ``linear`` or ``cubic`` is picked.
          Most weight is put on linear, followed by cubic.
        * If imgaug.ALL, then either ``nearest`` or ``linear`` or ``area`` or ``cubic``
          is picked per iteration (all same probability).
        * If string, then that value will be used as the method (must be
          ``nearest`` or ``linear`` or ``area`` or ``cubic``).
        * If list of string, then a random value will be picked from that
          list per iteration.
        * If StochasticParameter, then a random value will be sampled
          from that parameter per iteration.

iterations : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
    How often to repeat the simplex noise generation process per
    image.

        * If int, then that number will be used as the iterations for all
          images.
        * If tuple of two ints ``(a, b)``, then a value will be sampled
          per image from the discrete range ``[a..b]``.
        * If a list of ints, then a value will be picked per image at
          random from that list.
        * If a StochasticParameter, then a value will be sampled from
          that parameter per image.

aggregation_method : imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional
    The noise maps (from each iteration) are combined to one noise map
    using an aggregation process. This parameter defines the method used
    for that process. Valid methods are ``min``, ``max`` or ``avg``,
    where 'min' combines the noise maps by taking the (elementwise) minimum
    over all iteration's results, ``max`` the (elementwise) maximum and
    ``avg`` the (elementwise) average.

        * If imgaug.ALL, then a random value will be picked per image from the
          valid ones.
        * If a string, then that value will always be used as the method.
        * If a list of string, then a random value will be picked from
          that list per image.
        * If a StochasticParameter, then a random value will be sampled
          from that parameter per image.

sigmoid : bool or number, optional
    Whether to apply a sigmoid function to the final noise maps, resulting
    in maps that have more extreme values (close to 0.0 or 1.0).

        * If bool, then a sigmoid will always (True) or never (False) be
          applied.
        * If a number ``p`` with ``0<=p<=1``, then a sigmoid will be applied to
          ``p`` percent of all final noise maps.

sigmoid_thresh : None or number or tuple of number or imgaug.parameters.StochasticParameter, optional
    Threshold of the sigmoid, when applied. Thresholds above zero
    (e.g. 5.0) will move the saddle point towards the right, leading to
    more values close to 0.0.

        * If None, then ``Normal(0, 5.0)`` will be used.
        * If number, then that threshold will be used for all images.
        * If tuple of two numbers ``(a, b)``, then a random value will
          be sampled per image from the range ``[a, b]``.
        * If StochasticParameter, then a random value will be sampled from
          that parameter per image.

name : None or str, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

deterministic : bool, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

random_state : None or int or numpy.random.RandomState, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

Examples
--------
>>> aug = iaa.FrequencyNoiseAlpha(first=iaa.EdgeDetect(1.0))

Detects per image all edges, marks them in a black and white image and
then alpha-blends the result with the original image using frequency noise
masks.

>>> aug = iaa.FrequencyNoiseAlpha(first=iaa.EdgeDetect(1.0), upscale_method="linear")

Same as the first example, but uses only (smooth) linear upscaling to
scale the frequency noise masks to the final image sizes, i.e. no nearest
neighbour upsampling is used, which would result in rectangles with hard
edges.

>>> aug = iaa.FrequencyNoiseAlpha(first=iaa.EdgeDetect(1.0), upscale_method="linear", exponent=-2, sigmoid=False)

Same as the previous example, but also limits the exponent to -2 and
deactivates the sigmoid, resulting in cloud-like patterns without sharp
edges.

>>> aug = iaa.FrequencyNoiseAlpha(first=iaa.EdgeDetect(1.0), sigmoid_thresh=iap.Normal(10.0, 5.0))

Same as the first example, but uses a threshold for the sigmoid function
that is further to the right. This is more conservative, i.e. the generated
noise masks will be mostly black (values around 0.0), which means that
most of the original images (parameter/branch `second`) will be kept,
rather than using the results of the augmentation (parameter/branch
`first`).


@ia.deprecated(alt_func="<STR_LIT>")<EOL>def InColorspace(to_colorspace, from_colorspace="<STR_LIT>", children=None, name=None, deterministic=False,<EOL>random_state=None):

return WithColorspace(to_colorspace, from_colorspace, children, name, deterministic, random_state)<EOL>


def Grayscale(alpha=<NUM_LIT:0>, from_colorspace="<STR_LIT>", name=None, deterministic=False, random_state=None):

if name is None:<EOL><INDENT>name = "<STR_LIT>" % (ia.caller_name(),)<EOL><DEDENT>return ChangeColorspace(to_colorspace=ChangeColorspace.GRAY, alpha=alpha, from_colorspace=from_colorspace,<EOL>name=name, deterministic=deterministic, random_state=random_state)<EOL>

Augmenter to convert images to their grayscale versions.

NOTE: Number of output channels is still 3, i.e. this augmenter just "removes" color.

TODO check dtype support

dtype support::

    * ``uint8``: yes; fully tested
    * ``uint16``: ?
    * ``uint32``: ?
    * ``uint64``: ?
    * ``int8``: ?
    * ``int16``: ?
    * ``int32``: ?
    * ``int64``: ?
    * ``float16``: ?
    * ``float32``: ?
    * ``float64``: ?
    * ``float128``: ?
    * ``bool``: ?

Parameters
----------
alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
    The alpha value of the grayscale image when overlayed over the
    old image. A value close to 1.0 means, that mostly the new grayscale
    image is visible. A value close to 0.0 means, that mostly the
    old image is visible.

        * If a number, exactly that value will always be used.
        * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will
          be sampled per image.
        * If a list, then a random value will be sampled from that list per image.
        * If a StochasticParameter, a value will be sampled from the
          parameter per image.

from_colorspace : str, optional
    The source colorspace (of the input images).
    Allowed strings are: ``RGB``, ``BGR``, ``GRAY``, ``CIE``, ``YCrCb``, ``HSV``, ``HLS``, ``Lab``, ``Luv``.
    See :func:`imgaug.augmenters.color.ChangeColorspace.__init__`.

name : None or str, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

deterministic : bool, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

random_state : None or int or numpy.random.RandomState, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

Examples
--------
>>> aug = iaa.Grayscale(alpha=1.0)

creates an augmenter that turns images to their grayscale versions.

>>> aug = iaa.Grayscale(alpha=(0.0, 1.0))

creates an augmenter that turns images to their grayscale versions with
an alpha value in the range ``0 <= alpha <= 1``. An alpha value of 0.5 would
mean, that the output image is 50 percent of the input image and 50
percent of the grayscale image (i.e. 50 percent of color removed).


def Positive(other_param, mode="<STR_LIT>", reroll_count_max=<NUM_LIT:2>):

return ForceSign(<EOL>other_param=other_param,<EOL>positive=True,<EOL>mode=mode,<EOL>reroll_count_max=reroll_count_max<EOL>)<EOL>

Converts another parameter's results to positive values.

Parameters
----------
other_param : imgaug.parameters.StochasticParameter
    Other parameter which's sampled values are to be
    modified.

mode : {'invert', 'reroll'}, optional
    How to change the signs. Valid values are ``invert`` and ``reroll``.
    ``invert`` means that wrong signs are simply flipped.
    ``reroll`` means that all samples with wrong signs are sampled again,
    optionally many times, until they randomly end up having the correct
    sign.

reroll_count_max : int, optional
    If `mode` is set to ``reroll``, this determines how often values may
    be rerolled before giving up and simply flipping the sign (as in
    ``mode="invert"``). This shouldn't be set too high, as rerolling is
    expensive.

Examples
--------
>>> param = Positive(Normal(0, 1), mode="reroll")

Generates a normal distribution that has only positive values.


def Negative(other_param, mode="<STR_LIT>", reroll_count_max=<NUM_LIT:2>):

return ForceSign(<EOL>other_param=other_param,<EOL>positive=False,<EOL>mode=mode,<EOL>reroll_count_max=reroll_count_max<EOL>)<EOL>

Converts another parameter's results to negative values.

Parameters
----------
other_param : imgaug.parameters.StochasticParameter
    Other parameter which's sampled values are to be
    modified.

mode : {'invert', 'reroll'}, optional
    How to change the signs. Valid values are ``invert`` and ``reroll``.
    ``invert`` means that wrong signs are simply flipped.
    ``reroll`` means that all samples with wrong signs are sampled again,
    optionally many times, until they randomly end up having the correct
    sign.

reroll_count_max : int, optional
    If `mode` is set to ``reroll``, this determines how often values may
    be rerolled before giving up and simply flipping the sign (as in
    ``mode="invert"``). This shouldn't be set too high, as rerolling is
    expensive.

Examples
--------
>>> param = Negative(Normal(0, 1), mode="reroll")

Generates a normal distribution that has only negative values.


return self.draw_samples(<NUM_LIT:1>, random_state=random_state)[<NUM_LIT:0>]<EOL>

Draws a single sample value from this parameter.

Parameters
----------
random_state : None or numpy.random.RandomState, optional
    A random state to use during the sampling process.
    If None, the libraries global random state will be used.

Returns
-------
any
    A single sample value.


def draw_samples(self, size, random_state=None):

<EOL>random_state = random_state if random_state is not None else ia.current_random_state()<EOL>samples = self._draw_samples(<EOL>size if not ia.is_single_integer(size) else tuple([size]),<EOL>random_state)<EOL>ia.forward_random_state(random_state)<EOL>return samples<EOL>

Draws one or more sample values from the parameter.

Parameters
----------
size : tuple of int or int
    Number of sample values by dimension.

random_state : None or np.random.RandomState, optional
    A random state to use during the sampling process.
    If None, the libraries global random state will be used.

Returns
-------
samples : iterable
    Sampled values. Usually a numpy ndarray of basically any dtype,
    though not strictly limited to numpy arrays. Its shape is expected to
    match `size`.


return copy_module.copy(self)<EOL>

Create a shallow copy of this parameter.

Returns
-------
imgaug.parameters.StochasticParameter
    Shallow copy.


return copy_module.deepcopy(self)<EOL>

Create a deep copy of this parameter.

Returns
-------
imgaug.parameters.StochasticParameter
    Deep copy.


def draw_distribution_graph(self, title=None, size=(<NUM_LIT:1000>, <NUM_LIT:1000>), bins=<NUM_LIT:100>):

<EOL>import matplotlib.pyplot as plt<EOL>points = []<EOL>for _ in sm.xrange(size[<NUM_LIT:0>]):<EOL><INDENT>points.append(self.draw_samples(size[<NUM_LIT:1>:]).flatten())<EOL><DEDENT>points = np.concatenate(points)<EOL>fig = plt.figure()<EOL>fig.add_subplot(<NUM_LIT>)<EOL>ax = fig.gca()<EOL>heights, bins = np.histogram(points, bins=bins)<EOL>heights = heights / sum(heights)<EOL>ax.bar(bins[:-<NUM_LIT:1>], heights, width=(max(bins) - min(bins))/len(bins), color="<STR_LIT>", alpha=<NUM_LIT>)<EOL>if title is None:<EOL><INDENT>title = str(self)<EOL><DEDENT>if title is not False:<EOL><INDENT>title_fragments = [title[i:i+<NUM_LIT:50>] for i in sm.xrange(<NUM_LIT:0>, len(title), <NUM_LIT:50>)]<EOL>ax.set_title("<STR_LIT:\n>".join(title_fragments))<EOL><DEDENT>fig.tight_layout(pad=<NUM_LIT:0>)<EOL>with tempfile.NamedTemporaryFile(suffix="<STR_LIT>") as f:<EOL><INDENT>fig.savefig(f.name)<EOL>data = imageio.imread(f)[..., <NUM_LIT:0>:<NUM_LIT:3>]<EOL><DEDENT>plt.close()<EOL>return data<EOL>

Generate a plot (image) that shows the parameter's distribution of
values.

Parameters
----------
title : None or False or str, optional
    Title of the plot. None is automatically replaced by a title
    derived from ``str(param)``. If set to False, no title will be
    shown.

size : tuple of int
    Number of points to sample. This is always expected to have at
    least two values. The first defines the number of sampling runs,
    the second (and further) dimensions define the size assigned
    to each :func:`imgaug.parameters.StochasticParameter.draw_samples`
    call. E.g. ``(10, 20, 15)`` will lead to ``10`` calls of
    ``draw_samples(size=(20, 15))``. The results will be merged to a single 1d array.

bins : int
    Number of bins in the plot histograms.

Returns
-------
data : (H,W,3) ndarray
    Image of the plot.


@staticmethod<EOL><INDENT>def create_for_noise(other_param, threshold=(-<NUM_LIT:10>, <NUM_LIT:10>), activated=True):<DEDENT>

return Sigmoid(other_param, threshold, activated, mul=<NUM_LIT:20>, add=-<NUM_LIT:10>)<EOL>

Creates a Sigmoid that is adjusted to be used with noise parameters,
i.e. with parameters which's output values are in the range [0.0, 1.0].

Parameters
----------
other_param : imgaug.parameters.StochasticParameter
    See :func:`imgaug.parameters.Sigmoid.__init__`.

threshold : number or tuple of number or iterable of number or imgaug.parameters.StochasticParameter,\
            optional
    See :func:`imgaug.parameters.Sigmoid.__init__`.

activated : bool or number, optional
    See :func:`imgaug.parameters.Sigmoid.__init__`.

Returns
-------
Sigmoid
    A sigmoid adjusted to be used with noise.


def find_path(top_dir, fname, force_type=None):

for dirpath, sub_dirs, file_contents in walk(top_dir):<EOL><INDENT>if fname in file_contents and not force_type == '<STR_LIT>':<EOL><INDENT>return path.join(dirpath, fname)<EOL><DEDENT>elif fname in sub_dirs and not force_type == '<STR_LIT:file>':<EOL><INDENT>return path.join(dirpath, fname)<EOL><DEDENT><DEDENT>return None<EOL>

Find the path a given file somewhere bellow the top_dir.


self.websim = find_websim()<EOL>self.key = self.generate_key()<EOL>self.port = <NUM_LIT><EOL>self.endpoint = "<STR_LIT>".format(self.port)<EOL>return super(RestClientTest, self).__init__(*args, **kwargs)<EOL>

Initalize test by launching kappa server


with open('<STR_LIT>', '<STR_LIT:a>') as logfile:<EOL><INDENT>logfile.write("<STR_LIT:->"*<NUM_LIT> + '<STR_LIT:\n>')<EOL>logfile.write('<STR_LIT>' % (msg, datetime.now()))<EOL>logfile.write("<STR_LIT:->"*<NUM_LIT> + '<STR_LIT:\n>')<EOL><DEDENT>return<EOL>

A convenience method to mark sections of a continuous log file.


print("<STR_LIT>")<EOL>self._mark_log_file('<STR_LIT>')<EOL>Popen([<EOL>self.websim,<EOL>'<STR_LIT>', self.key,<EOL>'<STR_LIT>', str(self.port),<EOL>'<STR_LIT>', '<STR_LIT:info>',  <EOL>'<STR_LIT>', '<STR_LIT>'<EOL>])<EOL>sleep(<NUM_LIT:1>)<EOL>print("<STR_LIT>")<EOL>return<EOL>

Set up unit test by launching client

        Note: This is run automatically by nosetests before EACH test method,
        so there is no object permanence between tests.


runtime = self.getRuntime("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>resp = runtime.shutdown(self.key)<EOL>self._mark_log_file('<STR_LIT>')<EOL>sleep(<NUM_LIT:1>)<EOL>print("<STR_LIT>", resp)<EOL>return<EOL>

Tear down test by shutting down.

        Note: This is run automatically by nosetests afer EACH test method,
        so there is no object permanence between tests.


return '<STR_LIT>'.join(random.<EOL>SystemRandom().<EOL>choice(string.ascii_uppercase + string.digits)<EOL>for _ in range(<NUM_LIT:100>))<EOL>


def _get(self, sub_url=None, data=None):

return self._dispatch('<STR_LIT:GET>', sub_url, data)<EOL>

Thin wrapper around _dispatch function using method GET


def _post(self, sub_url=None, data=None):

return self._dispatch("<STR_LIT:POST>", sub_url, data)<EOL>

Thin wrapper around _dispatch function using method POST


def _delete(self, sub_url=None, data=None):

return self._dispatch("<STR_LIT>", sub_url, data)<EOL>

Thin wrapper around _dispatch function using method DELETE


def _put(self, sub_url=None, data=None):

Thin wrapper around _dispatch function using method PUT


return path.join('<STR_LIT>', self.project_id, *elements)<EOL>

Method to ease navigating the path structure within a project.


parse_url = "<STR_LIT>".format(self.url)<EOL>try:<EOL><INDENT>r = request("<STR_LIT:POST>", parse_url, data=key.encode('<STR_LIT:utf-8>'))<EOL><DEDENT>except exceptions.HTTPError as exception:<EOL><INDENT>raise KappaError(exception.reason)<EOL><DEDENT>if r.status_code == <NUM_LIT:200>:<EOL><INDENT>return r.text<EOL><DEDENT>elif r.status_code == <NUM_LIT>:<EOL><INDENT>print(r.text, r.reason)<EOL>raise KappaError(r.text)<EOL><DEDENT>elif r.status_code == <NUM_LIT>:<EOL><INDENT>raise KappaError(r.text)<EOL><DEDENT>else:<EOL><INDENT>raise KappaError(r.reason)<EOL><DEDENT>

Shut down kappa instance.

        Given a key to a kappa service shutdown a running kappa instance.


return self._get()<EOL>

Get a json dict with info about the kappa server.


return self._post('<STR_LIT>', {"<STR_LIT>": self.project_id})<EOL>


return self._get('<STR_LIT>')<EOL>

Get json with info about all the projects.


return self._delete(self.in_project())<EOL>

Delete this project.

        Note that the project can still be recreated with `project_create`
        method. The effect of these two commands would be to clear the project.


return map(lambda info: cls(**info), metadata_list)<EOL>

Get metadata objects from a list of metadata.


return {"<STR_LIT:id>": self.id,<EOL>"<STR_LIT>": self.compile,<EOL>"<STR_LIT>": self.position,<EOL>"<STR_LIT:version>": self.version}<EOL>

Get a json dict of the attributes of this object.


@classmethod<EOL><INDENT>def from_string(cls, content, position=<NUM_LIT:1>, file_id=None):<DEDENT>

if file_id is None:<EOL><INDENT>file_id = '<STR_LIT>'<EOL><DEDENT>return cls(FileMetadata(file_id, position), content)<EOL>

Convenience method to create a file from a string.

This file object's metadata will have the id 'inlined_input'.

Inputs
------
content -- the content of the file (a string).
position -- (default 1) rank among all files of the model while parsing
    see FileMetadata
file_id -- (default 'inlined_input') the file_id that will be used by
    kappa.


@classmethod<EOL><INDENT>def from_file(cls, fpath, position=<NUM_LIT:1>, file_id=None):<DEDENT>

if file_id is None:<EOL><INDENT>file_id = fpath<EOL><DEDENT>with open(fpath) as f:<EOL><INDENT>code = f.read()<EOL>file_content = str(code)<EOL>file_metadata = FileMetadata(file_id, position)<EOL>return cls(file_metadata, file_content)<EOL><DEDENT>

Convience method to create a kappa file object from a file on disk

Inputs
------
fpath -- path to the file on disk
position -- (default 1) rank among all files of the model while parsing
    see FileMetadata
file_id -- (default = fpath) the file_id that will be used by kappa.


return {"<STR_LIT>": self.file_metadata.toJSON(),<EOL>"<STR_LIT:content>": self.file_content}<EOL>

Get a JSON dict of the data in this file.


return self.file_metadata.id<EOL>

Get the id of the file from the metadata.


return self.file_content<EOL>


<EOL>if sys.version_info >= (<NUM_LIT:3>, <NUM_LIT:5>):<EOL><INDENT>return child_class<EOL><DEDENT>if not issubclass(child_class, this_abc):<EOL><INDENT>raise KappaError('<STR_LIT>')<EOL><DEDENT>for name, child_func in vars(child_class).items():<EOL><INDENT>if callable(child_func) and not child_func.__doc__:<EOL><INDENT>if name in this_abc.__abstractmethods__:<EOL><INDENT>parent_func = getattr(this_abc, name)<EOL>child_func.__doc__ = parent_func.__doc__<EOL><DEDENT><DEDENT><DEDENT>return child_class<EOL>

Make api method docs inheritted.

        Specifically, insepect.getdoc will return values inheritted from this
        abc for standardized api methods.


def add_model_string(self, model_str, position=<NUM_LIT:1>, file_id=None):

if file_id is None:<EOL><INDENT>file_id = self.make_unique_id('<STR_LIT>')<EOL><DEDENT>ret_data = self.file_create(File.from_string(model_str, position,<EOL>file_id))<EOL>return ret_data<EOL>

Add a kappa model given in a string to the project.


def add_model_file(self, model_fpath, position=<NUM_LIT:1>, file_id=None):

if file_id is None:<EOL><INDENT>file_id = self.make_unique_id('<STR_LIT>')<EOL><DEDENT>ret_data = self.file_create(File.from_file(model_fpath, position,<EOL>file_id))<EOL>return ret_data<EOL>

Add a kappa model from a file at given path to the project.


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

if len(args) is <NUM_LIT:1> and isinstance(args[<NUM_LIT:0>], SimulationParameter):<EOL><INDENT>self.__default_param = args[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>self.__default_param = SimulationParameter(*args, **kwargs)<EOL><DEDENT>return<EOL>

Set the simulation default simulation parameters.

        You can pass one of two things in as input:
        - a kappa_common.SimulationParameter instance
        - the arguments and keyword argument to create such an instance.

        The parameters you specify will be used by default in simulations run
        by this client.


if self.__default_param is None:<EOL><INDENT>raise KappaError("<STR_LIT>")<EOL><DEDENT>return self.__default_param<EOL>

Get the default SimulationParameter instance.


sim_info = self.simulation_info()<EOL>try:<EOL><INDENT>progress_info = sim_info['<STR_LIT>']<EOL>ret = progress_info['<STR_LIT>']<EOL><DEDENT>except KeyError:  <EOL><INDENT>ret = False<EOL><DEDENT>return ret<EOL>

Check if the current simulation is running.


start = datetime.now()<EOL>while self.get_is_sim_running():<EOL><INDENT>sleep(<NUM_LIT:0.5>)<EOL>if timeout is not None:<EOL><INDENT>if (datetime.now() - start).seconds >= timeout:<EOL><INDENT>ret = None<EOL>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>ret = self.simulation_info()<EOL><DEDENT>return ret<EOL>

Block until the simulation is done or timeout seconds exceeded.

        If the simulation stops before timeout, siminfo is returned.


Parses the project

overwrites -- list of algebraic variables to overwrite
Each element has the form {var : "variable_name", val : 42 }


Add a file to the project

file_object -- a Kappa_common.File


Returns file file_id stored in the project


Lists the files of the project (returns a FileMetadata array)


Returns the file file_line_id generated by $PRINT interventions


Returns the plot data of the simulation

Note: No actual plot is produced as a result of this function call.

Inputs
------
limit -- optionnal boundaries to only get a subplot
format: { offset : 100, nb_points : 500 }
returns the last points if offset is Null

Returns
-------
simulation_results -- a json containing the data from the simulation.


Returns state and progress of the simulation


Lists files generated by $PRINT during the simulation


Lists DIN generated during the simulation


Lists snapshots generated during the simulation


Fires a intervention in a paused simulation


Start the simulation from the last parsed model.

        Inputs
        ------
        simulation_parameter -- (optional) a kappa_common.SimulationParameter
            instance. The default is set using the `set_default_sim_param`
            method.


Returns the dead rules of the last parsed model


Returns a bunch of invarients on the last parsed model


Returns the contact of the last parsed model

Input
-----
accuracy -- \"high\" means take into account reachability from
   initial state. \"low\" means don't.


Returns the influence_map of the last parsed model

Input
-----
accuracy -- level can be \"low\", \"medium\", \"high\" or \"full\".
    Default is medium.


Shut down kappa instance.

        Given a key to a kappa service shutdown a running kappa instance.


if self.project_ast is None:<EOL><INDENT>raise KappaError("<STR_LIT>")<EOL><DEDENT>result = self._dispatch_sa(["<STR_LIT>", self.project_ast])<EOL>self.analyses_to_init = False<EOL>return result<EOL>

Initialize the static analyser thanks to the result of project_parse


io = StringIO.StringIO()<EOL>io.write('<STR_LIT:">')<EOL>for c in value:<EOL><INDENT>if c in _ESCAPES:<EOL><INDENT>io.write(_ESCAPES[c])<EOL><DEDENT>elif c in _SIMPLE_CHARS:<EOL><INDENT>io.write(c)<EOL><DEDENT>else:<EOL><INDENT>io.write(r'<STR_LIT>'.format(ord(c)))<EOL><DEDENT><DEDENT>io.write('<STR_LIT:">')<EOL>return io.getvalue()<EOL>

Returns value as a valid Go string literal.


return '<STR_LIT>' + name<EOL>

Returns a Go identifier for the given Python variable name.


self.indent(n)<EOL>yield<EOL>self.dedent(n)<EOL>

A context manager that indents by n on entry and dedents on exit.


Outputs the boilerplate necessary for code blocks like functions.

        Args:
          block_: The Block object representing the code block.
          body: String containing Go code making up the body of the code block.


<EOL>func_visitor = block.FunctionBlockVisitor(node)<EOL>for child in node.body:<EOL><INDENT>func_visitor.visit(child)<EOL><DEDENT>func_block = block.FunctionBlock(self.block, node.name, func_visitor.vars,<EOL>func_visitor.is_generator)<EOL>visitor = StatementVisitor(func_block, self.future_node)<EOL>with visitor.writer.indent_block():<EOL><INDENT>visitor._visit_each(node.body)  <EOL><DEDENT>result = self.block.alloc_temp()<EOL>with self.block.alloc_temp('<STR_LIT>') as func_args:<EOL><INDENT>args = node.args<EOL>argc = len(args.args)<EOL>self.writer.write('<STR_LIT>'.format(<EOL>func_args.expr, argc))<EOL>defaults = [None] * (argc - len(args.defaults)) + args.defaults<EOL>for i, (a, d) in enumerate(zip(args.args, defaults)):<EOL><INDENT>with self.visit_expr(d) if d else expr.nil_expr as default:<EOL><INDENT>tmpl = '<STR_LIT>'<EOL>self.writer.write_tmpl(tmpl, args=func_args.expr, i=i,<EOL>name=util.go_str(a.arg), default=default.expr)<EOL><DEDENT><DEDENT>flags = []<EOL>if args.vararg:<EOL><INDENT>flags.append('<STR_LIT>')<EOL><DEDENT>if args.kwarg:<EOL><INDENT>flags.append('<STR_LIT>')<EOL><DEDENT>self.writer.write_tmpl(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>result=result.name, name=util.go_str(node.name),<EOL>filename=util.go_str(self.block.root.filename), args=func_args.expr,<EOL>flags='<STR_LIT>'.join(flags) if flags else <NUM_LIT:0>)<EOL>with self.writer.indent_block():<EOL><INDENT>for var in func_block.vars.values():<EOL><INDENT>if var.type != block.Var.TYPE_GLOBAL:<EOL><INDENT>fmt = '<STR_LIT>'<EOL>self.writer.write(fmt.format(<EOL>util.adjust_local_name(var.name), var.init_expr))<EOL><DEDENT><DEDENT>self.writer.write_temp_decls(func_block)<EOL>self.writer.write('<STR_LIT>')<EOL>self.writer.write('<STR_LIT>')<EOL>if func_block.is_generator:<EOL><INDENT>self.writer.write(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>with self.writer.indent_block():<EOL><INDENT>self.writer.write_block(func_block, visitor.writer.getvalue())<EOL>self.writer.write('<STR_LIT>')<EOL><DEDENT>self.writer.write('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self.writer.write_block(func_block, visitor.writer.getvalue())<EOL>self.writer.write(textwrap.dedent("""<STR_LIT>"""))<EOL><DEDENT><DEDENT>self.writer.write('<STR_LIT>')<EOL><DEDENT>return result<EOL>

Returns an GeneratedExpr for a function with the given body.


<EOL>with self.block.alloc_temp() as mod,self.block.alloc_temp('<STR_LIT>') as mod_slice:<EOL><INDENT>self.writer.write_checked_call2(<EOL>mod_slice, '<STR_LIT>', util.go_str(imp.name))<EOL>for binding in imp.bindings:<EOL><INDENT>if binding.bind_type == imputil.Import.MODULE:<EOL><INDENT>self.writer.write('<STR_LIT>'.format(<EOL>mod.name, mod_slice.expr, binding.value))<EOL>self.block.bind_var(self.writer, binding.alias, mod.expr)<EOL><DEDENT>else:<EOL><INDENT>self.writer.write('<STR_LIT>'.format(<EOL>mod.name, mod_slice.expr, imp.name.count('<STR_LIT:.>')))<EOL>with self.block.alloc_temp() as member:<EOL><INDENT>self.writer.write_checked_call2(<EOL>member, '<STR_LIT>',<EOL>mod.expr, self.block.root.intern(binding.value))<EOL>self.block.bind_var(self.writer, binding.alias, member.expr)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

Generates code that imports a module and binds it to a variable.

        Args:
          imp: Import object representing an import of the form "import x.y.z" or
              "from x.y import z". Expects only a single binding.


def _write_except_dispatcher(self, exc, tb, handlers):

handler_labels = []<EOL>for i, except_node in enumerate(handlers):<EOL><INDENT>handler_labels.append(self.block.genlabel())<EOL>if except_node.type:<EOL><INDENT>with self.visit_expr(except_node.type) as type_,self.block.alloc_temp('<STR_LIT:bool>') as is_inst:<EOL><INDENT>self.writer.write_checked_call2(<EOL>is_inst, '<STR_LIT>', exc, type_.expr)<EOL>self.writer.write_tmpl(textwrap.dedent("""<STR_LIT>"""), is_inst=is_inst.expr, label=handler_labels[-<NUM_LIT:1>])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if i != len(handlers) - <NUM_LIT:1>:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise util.ParseError(except_node, msg)<EOL><DEDENT>self.writer.write('<STR_LIT>'.format(handler_labels[-<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>if handlers[-<NUM_LIT:1>].type:<EOL><INDENT>self.writer.write(<EOL>'<STR_LIT>'.format(exc, tb))<EOL>self.writer.write('<STR_LIT>')<EOL><DEDENT>return handler_labels<EOL>

Outputs a Go code that jumps to the appropriate except handler.

        Args:
          exc: Go variable holding the current exception.
          tb: Go variable holding the current exception's traceback.
          handlers: A list of ast.ExceptHandler nodes.

        Returns:
          A list of Go labels indexes corresponding to the exception handlers.

        Raises:
          ParseError: Except handlers are in an invalid order.


def calculate_transitive_deps(modname, script, gopath):

deps = set()<EOL>def calc(modname, script):<EOL><INDENT>if modname in deps:<EOL><INDENT>return<EOL><DEDENT>deps.add(modname)<EOL>for imp in collect_imports(modname, script, gopath):<EOL><INDENT>if imp.is_native:<EOL><INDENT>deps.add(imp.name)<EOL>continue<EOL><DEDENT>parts = imp.name.split('<STR_LIT:.>')<EOL>calc(imp.name, imp.script)<EOL>if len(parts) == <NUM_LIT:1>:<EOL><INDENT>continue<EOL><DEDENT>package_dir, filename = os.path.split(imp.script)<EOL>if filename == '<STR_LIT>':<EOL><INDENT>package_dir = os.path.dirname(package_dir)<EOL><DEDENT>for i in xrange(len(parts) - <NUM_LIT:1>, <NUM_LIT:0>, -<NUM_LIT:1>):<EOL><INDENT>modname = '<STR_LIT:.>'.join(parts[:i])<EOL>script = os.path.join(package_dir, '<STR_LIT>')<EOL>calc(modname, script)<EOL>package_dir = os.path.dirname(package_dir)<EOL><DEDENT><DEDENT><DEDENT>calc(modname, script)<EOL>deps.remove(modname)<EOL>return deps<EOL>

Determines all modules that script transitively depends upon.


assert isinstance(node, ast.ImportFrom)<EOL>assert node.module == '<STR_LIT>'<EOL>features = FutureFeatures()<EOL>for alias in node.names:<EOL><INDENT>name = alias.name<EOL>if name in _FUTURE_FEATURES:<EOL><INDENT>if name not in _IMPLEMENTED_FUTURE_FEATURES:<EOL><INDENT>msg = '<STR_LIT>'.format(name)<EOL>raise util.ParseError(node, msg)<EOL><DEDENT>setattr(features, name, True)<EOL><DEDENT>elif name == '<STR_LIT>':<EOL><INDENT>raise util.ParseError(node, '<STR_LIT>')<EOL><DEDENT>elif name not in _REDUNDANT_FUTURE_FEATURES:<EOL><INDENT>msg = '<STR_LIT>'.format(name)<EOL>raise util.ParseError(node, msg)<EOL><DEDENT><DEDENT>return features<EOL>

Processes a future import statement, returning set of flags it defines.


assert isinstance(mod, ast.Module)<EOL>found_docstring = False<EOL>for node in mod.body:<EOL><INDENT>if isinstance(node, ast.ImportFrom):<EOL><INDENT>if node.module == '<STR_LIT>':<EOL><INDENT>return node, _make_future_features(node)<EOL><DEDENT>break<EOL><DEDENT>elif isinstance(node, ast.Expr) and not found_docstring:<EOL><INDENT>if not isinstance(node.value, ast.Str):<EOL><INDENT>break<EOL><DEDENT>found_docstring = True<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return None, FutureFeatures()<EOL>

Accumulates a set of flags for the compiler __future__ imports.


@abc.abstractmethod<EOL><INDENT>def bind_var(self, writer, name, value):<DEDENT>

pass<EOL>

Writes Go statements for assigning value to named var in this block.

        This is overridden in the different concrete block types since in Python,
        binding a variable in, e.g. a function is quite different than binding at
        global block.

        Args:
          writer: The Writer object where statements will be written.
          name: The name of the Python variable.
          value: A Go expression to assign to the variable.


@abc.abstractmethod<EOL><INDENT>def resolve_name(self, writer, name):<DEDENT>

pass<EOL>

Returns a GeneratedExpr object for accessing the named var in this block.

        This is overridden in the different concrete block types since name
        resolution in Python behaves differently depending on where in what kind of
        block its happening within, e.g. local vars are different than globals.

        Args:
          writer: Writer object where intermediate calculations will be printed.
          name: The name of the Python variable.


for v in sorted(self.free_temps, key=lambda k: k.name):<EOL><INDENT>if v.type_ == type_:<EOL><INDENT>self.free_temps.remove(v)<EOL>self.used_temps.add(v)<EOL>return v<EOL><DEDENT><DEDENT>self.temp_index += <NUM_LIT:1><EOL>name = '<STR_LIT>'.format(self.temp_index)<EOL>v = expr.GeneratedTempVar(self, name, type_)<EOL>self.used_temps.add(v)<EOL>return v<EOL>

Create a new temporary Go variable having type type_ for this block.


self.used_temps.remove(v)<EOL>self.free_temps.add(v)<EOL>

Release the GeneratedTempVar v so it can be reused.


def Test(self):<EOL><INDENT>code = textwrap.dedent("""<STR_LIT>""")<EOL>status, output = _GrumpRun(code.format(subscript))<EOL>self.assertEqual(<NUM_LIT:0>, status, output)<EOL>self.assertEqual(want, output.strip())<EOL><DEDENT>return Test<EOL>

Define a test function that evaluates a slice expression.


def decorator(test_item):<EOL><INDENT>if not isinstance(test_item, type):<EOL><INDENT>def skip_wrapper(*args, **kwargs):<EOL><INDENT>raise SkipTest(reason)<EOL><DEDENT>skip_wrapper = functools.wraps(test_item)(skip_wrapper)<EOL>test_item = skip_wrapper<EOL><DEDENT>test_item.__unittest_skip__ = True<EOL>test_item.__unittest_skip_why__ = reason<EOL>return test_item<EOL><DEDENT>return decorator<EOL>


if condition:<EOL><INDENT>return skip(reason)<EOL><DEDENT>return _id<EOL>


if not condition:<EOL><INDENT>return skip(reason)<EOL><DEDENT>return _id<EOL>

Skip a test unless the condition is true.


self._testMethodName = methodName<EOL>self._resultForDoCleanups = None<EOL>try:<EOL><INDENT>testMethod = getattr(self, methodName)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>(self.__class__, methodName))<EOL><DEDENT>self._cleanups = []<EOL>self._type_equality_funcs = {}<EOL>self.addTypeEqualityFunc(dict, '<STR_LIT>')<EOL>self.addTypeEqualityFunc(list, '<STR_LIT>')<EOL>self.addTypeEqualityFunc(tuple, '<STR_LIT>')<EOL>self.addTypeEqualityFunc(set, '<STR_LIT>')<EOL>self.addTypeEqualityFunc(frozenset, '<STR_LIT>')<EOL>try:<EOL><INDENT>self.addTypeEqualityFunc(str, '<STR_LIT>')<EOL><DEDENT>except NameError:<EOL><INDENT>pass<EOL><DEDENT>

Create an instance of the class that will use the named test
           method when executed. Raises a ValueError if the instance does
           not have a method with the specified name.


def addTypeEqualityFunc(self, typeobj, function):

self._type_equality_funcs[typeobj] = function<EOL>

Add a type specific assertEqual style function to compare a type.

        This method is for use by TestCase subclasses that need to register
        their own type equality functions to provide nicer error messages.

        Args:
            typeobj: The data type to call this function on when both values
                    are of the same type in assertEqual().
            function: The callable taking two arguments and an optional
                    msg= argument that raises self.failureException with a
                    useful error message when the two arguments are not equal.


def addCleanup(self, function, *args, **kwargs):

self._cleanups.append((function, args, kwargs))<EOL>

Add a function, with arguments, to be called when the test is
        completed. Functions added are called on a LIFO basis and are
        called after tearDown on test failure or success.

        Cleanup items are called even if setUp fails (unlike tearDown).


pass<EOL>

Hook method for setting up the test fixture before exercising it.


pass<EOL>

Hook method for deconstructing the test fixture after testing it.


Hook method for setting up class fixture before running tests in the class.


Hook method for deconstructing the class fixture after running all tests in the class.


<EOL>return '<STR_LIT>'<EOL>

Returns a one-line description of the test, or None if no
        description has been provided.

        The default implementation of this method returns the first line of
        the specified test method's docstring.


result = self._resultForDoCleanups<EOL>ok = True<EOL>while self._cleanups:<EOL><INDENT>function, args, kwargs = self._cleanups.pop(-<NUM_LIT:1>)<EOL>try:<EOL><INDENT>function(*args, **kwargs)<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>ok = False<EOL>result.addError(self, sys.exc_info())<EOL><DEDENT><DEDENT>return ok<EOL>

Execute all cleanup functions. Normally called for you after
        tearDown.


self.setUp()<EOL>getattr(self, self._testMethodName)()<EOL>self.tearDown()<EOL>while self._cleanups:<EOL><INDENT>function, args, kwargs = self._cleanups.pop(-<NUM_LIT:1>)<EOL>function(*args, **kwargs)<EOL><DEDENT>

Run the test without collecting errors in a TestResult


raise SkipTest(reason)<EOL>


raise self.failureException(msg)<EOL>

Fail immediately, with the given message.


if expr:<EOL><INDENT>msg = self._formatMessage(msg, "<STR_LIT>" % safe_repr(expr))<EOL>raise self.failureException(msg)<EOL><DEDENT>


if not expr:<EOL><INDENT>msg = self._formatMessage(msg, "<STR_LIT>" % safe_repr(expr))<EOL>raise self.failureException(msg)<EOL><DEDENT>


def _formatMessage(self, msg, standardMsg):

if not self.longMessage:<EOL><INDENT>return msg or standardMsg<EOL><DEDENT>if msg is None:<EOL><INDENT>return standardMsg<EOL><DEDENT>try:<EOL><INDENT>return '<STR_LIT>' % (standardMsg, msg)<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>return  '<STR_LIT>' % (safe_repr(standardMsg), safe_repr(msg))<EOL><DEDENT>

Honour the longMessage attribute when generating failure messages.
        If longMessage is False this means:
        * Use only an explicit message if it is provided
        * Otherwise use the standard message for the assert

        If longMessage is True:
        * Use the standard message
        * If an explicit message is provided, plus ' : ' and the explicit message


def assertRaises(self, excClass, callableObj=None, *args, **kwargs):

context = _AssertRaisesContext(excClass, self)<EOL>if callableObj is None:<EOL><INDENT>return context<EOL><DEDENT>with context:<EOL><INDENT>callableObj(*args, **kwargs)<EOL><DEDENT>

Fail unless an exception of class excClass is raised
           by callableObj when invoked with arguments args and keyword
           arguments kwargs. If a different type of exception is
           raised, it will not be caught, and the test case will be
           deemed to have suffered an error, exactly as for an
           unexpected exception.

           If called with callableObj omitted or None, will return a
           context object used like this::

                with self.assertRaises(SomeException):
                    do_something()

           The context manager keeps a reference to the exception as
           the 'exception' attribute. This allows you to inspect the
           exception after the assertion::

               with self.assertRaises(SomeException) as cm:
                   do_something()
               the_exception = cm.exception
               self.assertEqual(the_exception.error_code, 3)


def _getAssertEqualityFunc(self, first, second):

<EOL>if type(first) is type(second):<EOL><INDENT>asserter = self._type_equality_funcs.get(type(first))<EOL>if asserter is not None:<EOL><INDENT>if isinstance(asserter, str):<EOL><INDENT>asserter = getattr(self, asserter)<EOL><DEDENT>return asserter<EOL><DEDENT><DEDENT>return self._baseAssertEqual<EOL>

Get a detailed comparison function for the types of the two args.

        Returns: A callable accepting (first, second, msg=None) that will
        raise a failure exception if first != second with a useful human
        readable error message for those types.


def _baseAssertEqual(self, first, second, msg=None):

if not first == second:<EOL><INDENT>standardMsg = '<STR_LIT>' % (safe_repr(first), safe_repr(second))<EOL>msg = self._formatMessage(msg, standardMsg)<EOL>raise self.failureException(msg)<EOL><DEDENT>

The default assertEqual implementation, not type specific.


def assertEqual(self, first, second, msg=None):

assertion_func = self._getAssertEqualityFunc(first, second)<EOL>assertion_func(first, second, msg=msg)<EOL>

Fail if the two objects are unequal as determined by the '=='
           operator.


def assertNotEqual(self, first, second, msg=None):

if not first != second:<EOL><INDENT>msg = self._formatMessage(msg, '<STR_LIT>' % (safe_repr(first),<EOL>safe_repr(second)))<EOL>raise self.failureException(msg)<EOL><DEDENT>

Fail if the two objects are equal as determined by the '!='
           operator.


def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None):

if first == second:<EOL><INDENT>return<EOL><DEDENT>if delta is not None and places is not None:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if delta is not None:<EOL><INDENT>if abs(first - second) <= delta:<EOL><INDENT>return<EOL><DEDENT>standardMsg = '<STR_LIT>' % (safe_repr(first),<EOL>safe_repr(second),<EOL>safe_repr(delta))<EOL><DEDENT>else:<EOL><INDENT>if places is None:<EOL><INDENT>places = <NUM_LIT:7><EOL><DEDENT>if round(abs(second-first), places) == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>standardMsg = '<STR_LIT>' % (safe_repr(first),<EOL>safe_repr(second),<EOL>places)<EOL><DEDENT>msg = self._formatMessage(msg, standardMsg)<EOL>raise self.failureException(msg)<EOL>

Fail if the two objects are unequal as determined by their
           difference rounded to the given number of decimal places
           (default 7) and comparing to zero, or by comparing that the
           between the two objects is more than the given delta.

           Note that decimal places (from zero) are usually not the same
           as significant digits (measured from the most signficant digit).

           If the two objects compare equal then they will automatically
           compare almost equal.


def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):

if delta is not None and places is not None:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if delta is not None:<EOL><INDENT>if not (first == second) and abs(first - second) > delta:<EOL><INDENT>return<EOL><DEDENT>standardMsg = '<STR_LIT>' % (safe_repr(first),<EOL>safe_repr(second),<EOL>safe_repr(delta))<EOL><DEDENT>else:<EOL><INDENT>if places is None:<EOL><INDENT>places = <NUM_LIT:7><EOL><DEDENT>if not (first == second) and round(abs(second-first), places) != <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>standardMsg = '<STR_LIT>' % (safe_repr(first),<EOL>safe_repr(second),<EOL>places)<EOL><DEDENT>msg = self._formatMessage(msg, standardMsg)<EOL>raise self.failureException(msg)<EOL>

Fail if the two objects are equal as determined by their
           difference rounded to the given number of decimal places
           (default 7) and comparing to zero, or by comparing that the
           between the two objects is less than the given delta.

           Note that decimal places (from zero) are usually not the same
           as significant digits (measured from the most signficant digit).

           Objects that are equal automatically fail.


def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):

if seq_type is not None:<EOL><INDENT>seq_type_name = seq_type.__name__<EOL>if not isinstance(seq1, seq_type):<EOL><INDENT>raise self.failureException('<STR_LIT>'<EOL>% (seq_type_name, safe_repr(seq1)))<EOL><DEDENT>if not isinstance(seq2, seq_type):<EOL><INDENT>raise self.failureException('<STR_LIT>'<EOL>% (seq_type_name, safe_repr(seq2)))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>seq_type_name = "<STR_LIT>"<EOL><DEDENT>differing = None<EOL>try:<EOL><INDENT>len1 = len(seq1)<EOL><DEDENT>except (TypeError, NotImplementedError):<EOL><INDENT>differing = '<STR_LIT>' % (<EOL>seq_type_name)<EOL><DEDENT>if differing is None:<EOL><INDENT>try:<EOL><INDENT>len2 = len(seq2)<EOL><DEDENT>except (TypeError, NotImplementedError):<EOL><INDENT>differing = '<STR_LIT>' % (<EOL>seq_type_name)<EOL><DEDENT><DEDENT>if differing is None:<EOL><INDENT>if seq1 == seq2:<EOL><INDENT>return<EOL><DEDENT>seq1_repr = safe_repr(seq1)<EOL>seq2_repr = safe_repr(seq2)<EOL>if len(seq1_repr) > <NUM_LIT:30>:<EOL><INDENT>seq1_repr = seq1_repr[:<NUM_LIT:30>] + '<STR_LIT>'<EOL><DEDENT>if len(seq2_repr) > <NUM_LIT:30>:<EOL><INDENT>seq2_repr = seq2_repr[:<NUM_LIT:30>] + '<STR_LIT>'<EOL><DEDENT>elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)<EOL>differing = '<STR_LIT>' % elements<EOL>for i in range(min(len1, len2)):<EOL><INDENT>try:<EOL><INDENT>item1 = seq1[i]<EOL><DEDENT>except (TypeError, IndexError, NotImplementedError):<EOL><INDENT>differing += ('<STR_LIT>' %<EOL>(i, seq_type_name))<EOL>break<EOL><DEDENT>try:<EOL><INDENT>item2 = seq2[i]<EOL><DEDENT>except (TypeError, IndexError, NotImplementedError):<EOL><INDENT>differing += ('<STR_LIT>' %<EOL>(i, seq_type_name))<EOL>break<EOL><DEDENT>if item1 != item2:<EOL><INDENT>differing += ('<STR_LIT>' %<EOL>(i, safe_repr(item1), safe_repr(item2)))<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if (len1 == len2 and seq_type is None and<EOL>type(seq1) != type(seq2)):<EOL><INDENT>return<EOL><DEDENT><DEDENT>if len1 > len2:<EOL><INDENT>differing += ('<STR_LIT>'<EOL>'<STR_LIT>' % (seq_type_name, len1 - len2))<EOL>try:<EOL><INDENT>differing += ('<STR_LIT>' %<EOL>(len2, safe_repr(seq1[len2])))<EOL><DEDENT>except (TypeError, IndexError, NotImplementedError):<EOL><INDENT>differing += ('<STR_LIT>'<EOL>'<STR_LIT>' % (len2, seq_type_name))<EOL><DEDENT><DEDENT>elif len1 < len2:<EOL><INDENT>differing += ('<STR_LIT>'<EOL>'<STR_LIT>' % (seq_type_name, len2 - len1))<EOL>try:<EOL><INDENT>differing += ('<STR_LIT>' %<EOL>(len1, safe_repr(seq2[len1])))<EOL><DEDENT>except (TypeError, IndexError, NotImplementedError):<EOL><INDENT>differing += ('<STR_LIT>'<EOL>'<STR_LIT>' % (len1, seq_type_name))<EOL><DEDENT><DEDENT><DEDENT>standardMsg = differing<EOL>diffMsg = '<STR_LIT:\n>' + '<STR_LIT:\n>'.join(<EOL>difflib.ndiff(pprint.pformat(seq1).splitlines(),<EOL>pprint.pformat(seq2).splitlines()))<EOL>standardMsg = self._truncateMessage(standardMsg, diffMsg)<EOL>msg = self._formatMessage(msg, standardMsg)<EOL>self.fail(msg)<EOL>

An equality assertion for ordered sequences (like lists and tuples).

        For the purposes of this function, a valid ordered sequence type is one
        which can be indexed, has a length, and has an equality operator.

        Args:
            seq1: The first sequence to compare.
            seq2: The second sequence to compare.
            seq_type: The expected datatype of the sequences, or None if no
                    datatype should be enforced.
            msg: Optional message to use on failure instead of a list of
                    differences.


def assertListEqual(self, list1, list2, msg=None):

self.assertSequenceEqual(list1, list2, msg, seq_type=list)<EOL>

A list-specific equality assertion.

        Args:
            list1: The first list to compare.
            list2: The second list to compare.
            msg: Optional message to use on failure instead of a list of
                    differences.


def assertTupleEqual(self, tuple1, tuple2, msg=None):

self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)<EOL>

A tuple-specific equality assertion.

        Args:
            tuple1: The first tuple to compare.
            tuple2: The second tuple to compare.
            msg: Optional message to use on failure instead of a list of
                    differences.


def assertSetEqual(self, set1, set2, msg=None):

try:<EOL><INDENT>difference1 = set1.difference(set2)<EOL><DEDENT>except TypeError as e:<EOL><INDENT>self.fail('<STR_LIT>' % e)<EOL><DEDENT>except AttributeError as e:<EOL><INDENT>self.fail('<STR_LIT>' % e)<EOL><DEDENT>try:<EOL><INDENT>difference2 = set2.difference(set1)<EOL><DEDENT>except TypeError as e:<EOL><INDENT>self.fail('<STR_LIT>' % e)<EOL><DEDENT>except AttributeError as e:<EOL><INDENT>self.fail('<STR_LIT>' % e)<EOL><DEDENT>if not (difference1 or difference2):<EOL><INDENT>return<EOL><DEDENT>lines = []<EOL>if difference1:<EOL><INDENT>lines.append('<STR_LIT>')<EOL>for item in difference1:<EOL><INDENT>lines.append(repr(item))<EOL><DEDENT><DEDENT>if difference2:<EOL><INDENT>lines.append('<STR_LIT>')<EOL>for item in difference2:<EOL><INDENT>lines.append(repr(item))<EOL><DEDENT><DEDENT>standardMsg = '<STR_LIT:\n>'.join(lines)<EOL>self.fail(self._formatMessage(msg, standardMsg))<EOL>

A set-specific equality assertion.

        Args:
            set1: The first set to compare.
            set2: The second set to compare.
            msg: Optional message to use on failure instead of a list of
                    differences.

        assertSetEqual uses ducktyping to support different types of sets, and
        is optimized for sets specifically (parameters must support a
        difference method).


def assertIn(self, member, container, msg=None):

if member not in container:<EOL><INDENT>standardMsg = '<STR_LIT>' % (safe_repr(member),<EOL>safe_repr(container))<EOL>self.fail(self._formatMessage(msg, standardMsg))<EOL><DEDENT>

Just like self.assertTrue(a in b), but with a nicer default message.


def assertNotIn(self, member, container, msg=None):

if member in container:<EOL><INDENT>standardMsg = '<STR_LIT>' % (safe_repr(member),<EOL>safe_repr(container))<EOL>self.fail(self._formatMessage(msg, standardMsg))<EOL><DEDENT>

Just like self.assertTrue(a not in b), but with a nicer default message.


def assertIs(self, expr1, expr2, msg=None):

if expr1 is not expr2:<EOL><INDENT>standardMsg = '<STR_LIT>' % (safe_repr(expr1),<EOL>safe_repr(expr2))<EOL>self.fail(self._formatMessage(msg, standardMsg))<EOL><DEDENT>

Just like self.assertTrue(a is b), but with a nicer default message.


def assertIsNot(self, expr1, expr2, msg=None):

if expr1 is expr2:<EOL><INDENT>standardMsg = '<STR_LIT>' % (safe_repr(expr1),)<EOL>self.fail(self._formatMessage(msg, standardMsg))<EOL><DEDENT>

Just like self.assertTrue(a is not b), but with a nicer default message.