text:
"""Device, context and memory management on CuPy.

.. note::
   The package ``chainer.cuda`` has been renamed to
   :mod:`chainer.backends.cuda` as of v4.0.0, but the previous module path
   ``chainer.cuda`` is also available.

Chainer uses `CuPy <https://cupy.chainer.org/>`_ (with very thin wrapper)
to exploit the speed of GPU computation. Following modules and classes defined
in CuPy are imported to :mod:`chainer.backends.cuda` module for convenience
(refer to this table when reading chainer's source codes).

===================================== =================================
 imported name                         original name
===================================== =================================
 ``chainer.backends.cuda.cupy``        :mod:`cupy`
 ``chainer.backends.cuda.cupyx``       :mod:`cupyx`
 ``chainer.backends.cuda.ndarray``     :class:`cupy.ndarray`
 ``chainer.backends.cuda.cupy.cuda``   :mod:`cupy.cuda`
 ``chainer.backends.cuda.Device``      :class:`cupy.cuda.Device`
 ``chainer.backends.cuda.Event``       :class:`cupy.cuda.Event`
 ``chainer.backends.cuda.Stream``      :class:`cupy.cuda.Stream`
===================================== =================================

Chainer replaces the default allocator of CuPy by its memory pool
implementation. It enables us to reuse the device memory over multiple
forward/backward computations, and temporary arrays for consecutive elementwise
operations.
"""

import functools
import os
import warnings

import numpy
import six

import chainer
from chainer.backends import intel64
from chainer.configuration import config

available = False
cudnn_enabled = False

try:
    import cupy
    from cupy import cuda  # NOQA
    from cupy.cuda import cublas  # NOQA
    import cupyx  # NOQA

    from cupy import ndarray  # NOQA

    from cupy.cuda import Device  # NOQA
    from cupy.cuda import Event  # NOQA
    from cupy.cuda import Stream  # NOQA

    from . import cuda_fusion as fusion  # NOQA

    available = True
except Exception as e:
    _resolution_error = e
    fusion = numpy

    class ndarray(object):
        pass  # for type testing

    # for `xp is cuda.cupy` to always work
    cupy = object()

if available:
    _cudnn_disabled_by_user = int(os.environ.get('CHAINER_CUDNN', '1')) == 0
    try:
        import cupy.cudnn
        cudnn = cupy.cudnn
        cudnn_enabled = not _cudnn_disabled_by_user
    except Exception as e:
        _resolution_error = e

def check_cuda_available():
    """Checks if CUDA is available.

    When CUDA is correctly set up, nothing happens.
    Otherwise it raises ``RuntimeError``.
    """
    if not available:
        msg = ('CUDA environment is not correctly set up\n'
               '(see https://github.com/chainer/chainer#installation).')
        msg += str(_resolution_error)
        raise RuntimeError(msg)
    if (not cudnn_enabled and
            not _cudnn_disabled_by_user and
            not getattr(check_cuda_available, '_already_warned', False)):
        warnings.warn(
            'cuDNN is not enabled.\n'
            'Please reinstall CuPy after you install cudnn\n'
            '(see https://docs-cupy.chainer.org/en/stable/install.html'
            '#install-cupy-with-cudnn-and-nccl).')
        check_cuda_available._already_warned = True

class DummyDeviceType(object):

    """Dummy device class that does nothing with cupy.cuda.Device interface.

    This class is used to represent CPU device.

    """

    id = -1

    def __int__(self):
        return -1

    def __enter__(self):
        return self

    def __exit__(self, *args):
        pass

    def use(self):
        pass

    def synchronize(self):
        pass

    def __eq__(self, other):
        return isinstance(other, DummyDeviceType)

    def __ne__(self, other):
        return not (self == other)

DummyDevice = DummyDeviceType()

# ------------------------------------------------------------------------------
# Global states
# ------------------------------------------------------------------------------
if available:
    # This is for backward compatibility
    memory_pool = cupy.get_default_memory_pool()
    pinned_memory_pool = cupy.get_default_pinned_memory_pool()

_integer_types = six.integer_types + (numpy.integer,)

# ------------------------------------------------------------------------------
# Global states
# ------------------------------------------------------------------------------
def get_device_from_id(device_id):
    """Gets the device from an ID integer.

    Args:
        device_id (int or None): The ID of the device which this function
            returns.
    """
    if device_id is not None:
        check_cuda_available()
        return Device(device_id)
    else:
        return DummyDevice

def get_device_from_array(*arrays):
    """Gets the device from a list of CuPy array or a single CuPy array.

    The device on which the given CuPy array reside is returned.

    .. note::

        This method only recognizes :class:`cupy.ndarray`\\ s in arguments.
        Especially note that, unlike :func:`get_array_module`, this method
        does not recognize :class:`~chainer.Variable` objects.
        If you need to get device from the :class:`~chainer.Variable` instance
        ``v``, you need to use ``get_device_from_array(v.array)``.

    Args:
        arrays (:class:`cupy.ndarray` or list of :class:`cupy.ndarray`):
            A CuPy array which this function returns the device corresponding
            to. If a list of :class:`cupy.ndarray`\\ s are given, it returns
            the first device object of an array in the list.
    """
    for array in arrays:
        if isinstance(array, ndarray) and array.device is not None:
            return array.device
    return DummyDevice

def get_device(*args):
    """Gets the device from a device object, an ID integer or an array object.

    .. note::

        This API is deprecated. Please use
        :func:`~chainer.backends.cuda.get_device_from_id`
        or :func:`~chainer.backends.cuda.get_device_from_array` instead.

    This is a convenient utility to select a correct device if the type of
    ``arg`` is unknown (i.e., one can use this function on arrays that may be
    on CPU or GPU). The returned device object supports the context management
    protocol of Python for the *with* statement.

    Args:
        args: Values to specify a GPU device. The first device object, integer
            or :class:`cupy.ndarray` object is used to select a device.
            If it is a device object, it is returned. If it is an integer,
            the corresponding device is returned. If it is a CuPy array,
            the device on which this array reside is returned. If any
            arguments are neither integers nor CuPy arrays, a dummy device
            object representing CPU is returned.

    Returns:
        Device object specified by given ``args``.

    .. seealso::
       See :class:`cupy.cuda.Device` for the device selection not by arrays.

    """
    warnings.warn('get_device is deprecated. Please use get_device_from_id or'
                  ' get_device_from_array instead.', DeprecationWarning)
    return _get_device(*args)

def _get_device(*args):
    for arg in args:
        if type(arg) is not bool and isinstance(arg, _integer_types):
            check_cuda_available()
            return Device(arg)
        if isinstance(arg, ndarray):
            if arg.device is None:
                continue
            return arg.device
        if available and isinstance(arg, Device):
            return arg

    return DummyDevice

# ------------------------------------------------------------------------------
# cupy.ndarray allocation and copy
# ------------------------------------------------------------------------------

def to_gpu(array, device=None, stream=None):
    """Copies the given CPU array to the specified device.

    Args:
        array (*array*, None, list or tuple):
            Array or arrays to be sent to GPU.
        device: Device specifier.
        stream (~cupy.cuda.Stream): *(deprecated since v3.0.0)*
            CUDA stream. If not ``None``, the copy runs asynchronously.

    Returns:
        cupy.ndarray, list or tuple: Array or arrays on GPU.

        If some of the arrays are already on GPU, then this function just
        returns those arrays without performing any copy.

        If input arrays include `None`, it is returned as `None` as is.

    """
    if stream is not None:
        warnings.warn(
            'The stream option is deprecated in chainer.backends.cuda.to_gpu. '
            'Please remove it.', DeprecationWarning)

    check_cuda_available()
    with _get_device(device) as device_:
        if isinstance(array, (list, tuple)):
            d = {}
            ret = []
            for arr in array:
                if arr is None:
                    ret.append(None)
                else:
                    arr2 = d.get(id(arr))
                    if arr2 is None:
                        arr2 = _array_to_gpu(arr, device_, stream)
                        d[id(arr)] = arr2
                    ret.append(arr2)
            return type(array)(ret)
        else:
            return _array_to_gpu(array, device_, stream)

def _array_to_gpu(array, device, stream):
    assert device is DummyDevice or isinstance(device, Device)
    if array is None:
        return None

    if isinstance(array, (numpy.number, numpy.bool_)):
        array = numpy.asarray(array)
    elif isinstance(array, intel64.mdarray):
        array = numpy.asarray(array)

    if not isinstance(array, (cupy.ndarray, numpy.ndarray)):
        raise TypeError(
            'The array sent to gpu must be an array or a NumPy scalar.'
            '\nActual type: {0}.'.format(type(array)))

    array_dev = get_device_from_array(array)
    if array_dev.id == cupy.cuda.device.get_device_id():
        return array

    if stream is not None and stream.ptr != 0:
        ret = cupy.empty_like(array)
        if array_dev.id == -1:
            # cpu to gpu
            mem = cupy.cuda.alloc_pinned_memory(array.nbytes)
            src = numpy.frombuffer(
                mem, array.dtype, array.size).reshape(array.shape)
            src[...] = array
            ret.set(src, stream)
            cupy.cuda.pinned_memory._add_to_watch_list(
                stream.record(), mem)
        else:
            # gpu to gpu
            with array_dev:
                src = array.copy()
                event = Stream.null.record()
            stream.wait_event(event)
            ret.data.copy_from_device_async(
                src.data, src.nbytes, stream)

            # to hold a reference until the end of the asynchronous
            # memcpy
            stream.add_callback(lambda *x: None, (src, ret))
        return ret

    if array_dev.id == -1:
        return cupy.asarray(array)

    # Need to make a copy when an array is copied to another device
    return cupy.array(array, copy=True)

def to_cpu(array, stream=None):
    """Copies the given GPU array to host CPU.

    Args:
        array (*array*, None, list or tuple):
            Array or arrays to be sent to CPU.
        stream (cupy.cuda.Stream): CUDA stream.

    Returns:
        numpy.ndarray, list or tuple: Array on CPU.

        If some of the arrays are already on CPU, then this function just
        returns those arrays without performing any copy.

        If input arrays include `None`, it is returned as `None` as is.

    """
    if isinstance(array, (list, tuple)):
        d = {}
        ret = []
        for arr in array:
            if arr is None:
                ret.append(None)
            else:
                arr2 = d.get(id(arr))
                if arr2 is None:
                    arr2 = _array_to_cpu(arr, stream)
                    d[id(arr)] = arr2
                ret.append(arr2)
        return type(array)(ret)
    else:
        return _array_to_cpu(array, stream)

def _array_to_cpu(array, stream):
    if array is None:
        return None
    if isinstance(array, ndarray):
        check_cuda_available()
        with get_device_from_array(array):
            return array.get(stream)
    elif isinstance(array, (numpy.number, numpy.bool_)):
        return numpy.asarray(array)
    elif isinstance(array, chainer.get_cpu_array_types()):
        return array
    else:
        raise TypeError(
            'The array sent to cpu must be numpy.ndarray or cupy.ndarray, '
            'or a NumPy scalar.'
            '\nActual type: {0}.'.format(type(array)))

def copy(array, out=None, out_device=None, stream=None):
    """Copies a :class:`cupy.ndarray` object using the default stream.

    This function can copy the device array to the destination array on another
    device.

    Args:
        array (cupy.ndarray): Array to be copied.
        out (cupy.ndarray): Destination array.
            If it is not ``None``, then ``out_device`` argument is ignored.
        out_device: Destination device specifier. Actual device object is
            obtained by passing this value to :func:`get_device`.
        stream (cupy.cuda.Stream): CUDA stream.

    Returns:
        cupy.ndarray: Copied array.

        If ``out`` is not specified, then the array is allocated on the device
        specified by ``out_device`` argument.

    """
    check_cuda_available()
    assert stream is None  # TODO(beam2d): FIX IT

    if out is None:
        if out_device is None:
            out_device = array
        with _get_device(out_device):
            out = cupy.empty_like(array)

    with get_device_from_array(array):
        cupy.copyto(out, array)

    return out

# ------------------------------------------------------------------------------
# Function result memoization
# ------------------------------------------------------------------------------
def memoize(for_each_device=False):
    """Makes a function memoizing the result for each argument and device.

    This is a similar version of :func:`cupy.memoize`. The difference is that
    this function can be used in the global scope even if CUDA is not
    available. In such case, this function does nothing.

    .. note::
       This decorator acts as a dummy if CUDA is not available. It cannot be
       used for general purpose memoization even if ``for_each_device`` is set
       to False.

    """
    if available:
        return cupy.memoize(for_each_device)

    def dummy_decorator(f):
        @functools.wraps(f)
        def ret(*args, **kwargs):
            return f(*args, **kwargs)
        return ret
    return dummy_decorator

def clear_memo():
    """Clears the memoized results for all functions decorated by memoize.

    This function works like :func:`cupy.clear_memo` as a counterpart for
    :func:`chainer.backends.cuda.memoize`. It can be used even if CUDA is
    not available. In such a case, this function does nothing.

    """
    if available:
        cupy.clear_memo()

# ------------------------------------------------------------------------------
# Kernel definition utility
# ------------------------------------------------------------------------------
@memoize(for_each_device=True)
def elementwise(in_params, out_params, operation, name, **kwargs):
    """Creates an elementwise kernel function.

    This function uses :func:`~chainer.backends.cuda.memoize` to cache the
    kernel object, i.e. the resulting kernel object is cached for each argument
    combination and CUDA device.

    The arguments are the same as those for
    :class:`cupy.ElementwiseKernel`, except that the ``name`` argument is
    mandatory.

    """
    check_cuda_available()
    return cupy.ElementwiseKernel(
        in_params, out_params, operation, name, **kwargs)

@memoize(for_each_device=True)
def reduce(in_params, out_params, map_expr, reduce_expr, post_map_expr,
           identity, name,  **kwargs):
    """Creates a global reduction kernel function.

    This function uses :func:`~chainer.backends.cuda.memoize` to cache the
    resulting kernel object, i.e. the resulting kernel object is cached for
    each argument combination and CUDA device.

    The arguments are the same as those for
    :class:`cupy.ReductionKernel`, except that the ``name`` argument is
    mandatory.

    """
    check_cuda_available()
    return cupy.ReductionKernel(
        in_params, out_params, map_expr, reduce_expr, post_map_expr,
        identity, name, **kwargs)

# ------------------------------------------------------------------------------
# numpy/cupy compatible coding
# ------------------------------------------------------------------------------
def get_array_module(*args):
    """Gets an appropriate one from :mod:`numpy` or :mod:`cupy`.

    This is almost equivalent to :func:`cupy.get_array_module`. The differences
    are that this function can be used even if CUDA is not available and that
    it will return their data arrays' array module for
    :class:`~chainer.Variable` arguments.

    Args:
        args: Values to determine whether NumPy or CuPy should be used.

    Returns:
        module: :mod:`cupy` or :mod:`numpy` is returned based on the types of
        the arguments.

    """
    if available:
        args = [arg.data if isinstance(arg, chainer.variable.Variable) else arg
                for arg in args]
        return cupy.get_array_module(*args)
    else:
        return numpy

def get_max_workspace_size():
    """Gets the workspace size for cuDNN.

    Check "cuDNN Library User Guide" for detail.

    Returns:
        int: The workspace size for cuDNN.

    """
    # To avoid error on no cuDNN environment
    if cudnn_enabled:
        return cudnn.get_max_workspace_size()
    return 0

def set_max_workspace_size(size):
    """Sets the workspace size for cuDNN.

    Check "cuDNN Library User Guide" for detail.

    Args:
        size: The workspace size for cuDNN.

    """
    # To avoid error on no cuDNN environment
    if cudnn_enabled:
        cudnn.set_max_workspace_size(size)

def fuse(*args, **kwargs):
    """Function fusing decorator.

    It calls :func:`cupy.fuse` when CuPy is available to make fused function
    and does nothing otherwise.

    .. seealso::
       :func:`cupy.fuse`

    """
    if available:
        return cupy.fuse(*args, **kwargs)
    else:
        return lambda f: f

# ------------------------------------------------------------------------------
# cuDNN
# ------------------------------------------------------------------------------
_SHOULD_USE_CUDNN = {
    '==always': {'always': True, 'auto': False, 'never': False},
    '>=auto':   {'always': True, 'auto': True,  'never': False},
}

_cudnn_version = cuda.cudnn.getVersion() if cudnn_enabled else -1

def should_use_cudnn(level, lowest_version=0):
    """Determines if we should use cuDNN.

    This function checks ``chainer.config.use_cudnn``,
    ``chainer.backends.cuda.cudnn_enabled``, and the cuDNN version. Note that
    ``cudnn_enabled`` flag is fixed at loading of :mod:`chainer` module.

    Args:
        level (str): cuDNN use level. It must be either ``'==always'`` or
            ``'>=auto'``. ``'==always'`` indicates that the ``use_cudnn``
            config must be ``'always'`` to use cuDNN.
        lowest_version (int): Required lowest cuDNN version. It must be
            non-negative.

    Returns:
        bool: ``True`` if the caller should use cuDNN.

    """
    if _cudnn_version < lowest_version:
        return False

    if level not in _SHOULD_USE_CUDNN:
        raise ValueError('invalid cuDNN use level: %s '
                         '(must be either of "==always" or ">=auto")' %
                         repr(level))
    flags = _SHOULD_USE_CUDNN[level]

    use_cudnn = config.use_cudnn
    if use_cudnn not in flags:
        raise ValueError('invalid use_cudnn configuration: %s '
                         '(must be either of "always", "auto", or "never")' %
                         repr(use_cudnn))
    return flags[use_cudnn]

_tensor_core_flag = {'always': True, 'auto': None, 'never': False}

def should_use_cudnn_tensor_core(dtype):
    """Determines if Tensor Core should be used.

    Args:
        dtype (numpy.dtype): data type of input tensor.

    Returns:
        bool: ``True`` if Tensor Core should be used.
    """

    use_cudnn_tensor_core = config.use_cudnn_tensor_core
    if use_cudnn_tensor_core not in _tensor_core_flag:
        raise ValueError('invalid use_cudnn_tensor_core configuration: %s '
                         '(must be either of "always", "auto", or "never")' %
                         repr(use_cudnn_tensor_core))
    use_tensor_core = _tensor_core_flag[use_cudnn_tensor_core]
    if use_tensor_core is None:
        use_tensor_core = cudnn.is_tensor_core_available(dtype)
    return use_tensor_core


text:
import unittest

import numpy as np
import scipy.stats

import paddle
import config
import parameterize

from paddle.distribution.gumbel import Gumbel

paddle.enable_static()

@parameterize.place(config.DEVICES)
@parameterize.parameterize_cls(
    (parameterize.TEST_CASE_NAME, 'loc', 'scale'),
    [
        ('one-dim', parameterize.xrand((4,)), parameterize.xrand((4,))),
        ('multi-dim', parameterize.xrand((5, 3)), parameterize.xrand((5, 3))),
    ],
)
class TestGumbel(unittest.TestCase):
    def setUp(self):
        startup_program = paddle.static.Program()
        main_program = paddle.static.Program()
        executor = paddle.static.Executor(self.place)
        with paddle.static.program_guard(main_program, startup_program):
            loc = paddle.static.data('loc', self.loc.shape, self.loc.dtype)
            scale = paddle.static.data(
                'scale', self.scale.shape, self.scale.dtype
            )
            self._dist = Gumbel(loc=loc, scale=scale)
            self.sample_shape = [50000]
            mean = self._dist.mean
            var = self._dist.variance
            stddev = self._dist.stddev
            entropy = self._dist.entropy()
            samples = self._dist.sample(self.sample_shape)
        fetch_list = [mean, var, stddev, entropy, samples]
        self.feeds = {'loc': self.loc, 'scale': self.scale}

        executor.run(startup_program)
        [
            self.mean,
            self.var,
            self.stddev,
            self.entropy,
            self.samples,
        ] = executor.run(main_program, feed=self.feeds, fetch_list=fetch_list)

    def test_mean(self):
        self.assertEqual(str(self.mean.dtype).split('.')[-1], self.scale.dtype)
        np.testing.assert_allclose(
            self.mean,
            self._np_mean(),
            rtol=config.RTOL.get(str(self.scale.dtype)),
            atol=config.ATOL.get(str(self.scale.dtype)),
        )

    def test_variance(self):
        self.assertEqual(str(self.var.dtype).split('.')[-1], self.scale.dtype)
        np.testing.assert_allclose(
            self.var,
            self._np_variance(),
            rtol=config.RTOL.get(str(self.scale.dtype)),
            atol=config.ATOL.get(str(self.scale.dtype)),
        )

    def test_stddev(self):
        self.assertEqual(
            str(self.stddev.dtype).split('.')[-1], self.scale.dtype
        )
        np.testing.assert_allclose(
            self.stddev,
            self._np_stddev(),
            rtol=config.RTOL.get(str(self.scale.dtype)),
            atol=config.ATOL.get(str(self.scale.dtype)),
        )

    def test_entropy(self):
        self.assertEqual(
            str(self.entropy.dtype).split('.')[-1], self.scale.dtype
        )

    def test_sample(self):
        self.assertEqual(self.samples.dtype, self.scale.dtype)

        np.testing.assert_allclose(
            self.samples.mean(axis=0),
            scipy.stats.gumbel_r.mean(self.loc, scale=self.scale),
            rtol=0.1,
            atol=config.ATOL.get(str(self.scale.dtype)),
        )
        np.testing.assert_allclose(
            self.samples.var(axis=0),
            scipy.stats.gumbel_r.var(self.loc, scale=self.scale),
            rtol=0.1,
            atol=config.ATOL.get(str(self.scale.dtype)),
        )

    def _np_mean(self):
        return self.loc + self.scale * np.euler_gamma

    def _np_stddev(self):
        return np.sqrt(self._np_variance())

    def _np_variance(self):
        return np.divide(
            np.multiply(np.power(self.scale, 2), np.power(np.pi, 2)), 6
        )

    def _np_entropy(self):
        return np.log(self.scale) + 1 + np.euler_gamma

@parameterize.place(config.DEVICES)
@parameterize.parameterize_cls(
    (parameterize.TEST_CASE_NAME, 'loc', 'scale', 'value'),
    [
        (
            'value-float',
            np.array([0.1, 0.4]),
            np.array([1.0, 4.0]),
            np.array([3.0, 7.0]),
        ),
        ('value-int', np.array([0.1, 0.4]), np.array([1, 4]), np.array([3, 7])),
        (
            'value-multi-dim',
            np.array([0.1, 0.4]),
            np.array([1, 4]),
            np.array([[5.0, 4], [6, 2]]),
        ),
    ],
)
class TestGumbelPDF(unittest.TestCase):
    def setUp(self):
        startup_program = paddle.static.Program()
        main_program = paddle.static.Program()
        executor = paddle.static.Executor(self.place)

        with paddle.static.program_guard(main_program, startup_program):
            loc = paddle.static.data('loc', self.loc.shape, self.loc.dtype)
            scale = paddle.static.data(
                'scale', self.scale.shape, self.scale.dtype
            )
            value = paddle.static.data(
                'value', self.value.shape, self.value.dtype
            )
            self._dist = Gumbel(loc=loc, scale=scale)
            prob = self._dist.prob(value)
            log_prob = self._dist.log_prob(value)
            cdf = self._dist.cdf(value)
        fetch_list = [prob, log_prob, cdf]
        self.feeds = {'loc': self.loc, 'scale': self.scale, 'value': self.value}

        executor.run(startup_program)
        [self.prob, self.log_prob, self.cdf] = executor.run(
            main_program, feed=self.feeds, fetch_list=fetch_list
        )

    def test_prob(self):
        np.testing.assert_allclose(
            self.prob,
            scipy.stats.gumbel_r.pdf(self.value, self.loc, self.scale),
            rtol=config.RTOL.get(str(self.loc.dtype)),
            atol=config.ATOL.get(str(self.loc.dtype)),
        )

    def test_log_prob(self):
        np.testing.assert_allclose(
            self.log_prob,
            scipy.stats.gumbel_r.logpdf(self.value, self.loc, self.scale),
            rtol=config.RTOL.get(str(self.loc.dtype)),
            atol=config.ATOL.get(str(self.loc.dtype)),
        )

    def test_cdf(self):
        np.testing.assert_allclose(
            self.cdf,
            scipy.stats.gumbel_r.cdf(self.value, self.loc, self.scale),
            rtol=0.3,
            atol=config.ATOL.get(str(self.loc.dtype)),
        )

if __name__ == '__main__':
    unittest.main()

redpajama_set_name: RedPajamaGithub


text:
"""
eight_queens.py

Find all solutions to n-queens problem. can use up and down joystick direction
to choose the size of chessboard from 1x1 up to 8x8, speak the number of
solutions found.
"""

__all__ = []

import time

from sense_hat import SenseHat, ACTION_RELEASED

from _helper import QUADRANTS, set_quadrants, speak

sense = SenseHat()
sense.clear()

def tests(queens, size, row, col):
    """Test to see if a queen can be place at the given row/col."""
    for c in range(0, col):
        if queens[c] == row:
            return False

    i = 1
    while row - i >= 0 and col - i >= 0:
        if row - i == queens[col - i]:
            return False
        i += 1

    i = 1
    while row + i < size and col - i >= 0:
        if row + i == queens[col - i]:
            return False
        i += 1

    return True

def find_queens(size):
    """Find all solutions from given size board."""
    row = 0
    col = 0
    solutions = 0
    queens = [0 for i in range(size)]

    while col >= 0:
        if (col == size or row == size):
            col -= 1
            if col < 0:
                message = str(solutions) + ' solutions found.'
                speak('eight_queens', message)
                break
            row = queens[col]
            queens[col] = 0
            row += 1
            continue

        if tests(queens, size, row, col):
            queens[col] = row
            row = 0
            col += 1
            if col == size:
                solutions += 1
                for x, y in enumerate(queens):
                    sense.rotation = 90
                    sense.set_pixel(x, y, (0, 200, 0))
                time.sleep(0.05)
            sense.clear()
        else:
            row += 1

def eight_queens():
    """Solve the 8 queens problem."""
    size = 0
    set_quadrants(QUADRANTS[:1], str(size), (0, 200, 0))

    while True:
        event = sense.stick.wait_for_event(emptybuffer=True)
        if event.action != ACTION_RELEASED:
            if event.direction == 'middle':
                sense.clear()
                sense.rotation = 0
                find_queens(size)
                return
            else:
                direction = event.direction

                if direction == 'left':
                    size -= 1
                    if size < 0:
                        size = 0
                elif direction == 'right':
                    size += 1
                    if size > 8:
                        size = 8

                sense.clear()
                set_quadrants(QUADRANTS[:2], str(size), (0, 200, 0))

if __name__ == '__main__':
    eight_queens()


text:
package com.rezgame.ui;

import com.rezgame.backend.Color;
import com.rezgame.backend.Placement;
import com.rezgame.backend.Move;
import com.rezgame.backend.board.BoardInterface;
import com.rezgame.backend.logic.GameStateInterface;
import com.rezgame.backend.logic.RezSessionController;
import com.rezgame.backend.player.HumanPlayer;
import com.rezgame.backend.player.Player;
import com.rezgame.backend.player.RandomPlayer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Logger;

public class ConsoleUI extends UI implements HumanPlayerInputUI{

    @Override
    public Placement getNewPlacement(GameStateInterface state) {
        System.out.println(state.getCurrentPlayer() + ", please enter a location to put an item: ");
        int x = readInt();
        int y = readInt();
        return new Placement(x, y, state.getCurrentPlayer().getColor());
    }

    @Override
    public Move getMove(GameStateInterface state) {
        System.out.println(state.getCurrentPlayer() + ", please enter the next move: ");
        int x1 = readInt();
        int y1 = readInt();
        int x2 = readInt();
        int y2 = readInt();
        return new Move(x1, y1,x2, y2, state.getCurrentPlayer().getColor());
    }

    @Override
    public void showBadMoveAlert(GameStateInterface state, Move mv) {
        String msg = "Player " + state.getCurrentPlayer() + " cannot perform move: " + mv;
        LOGGER.fine(msg);
        System.out.println(msg);
    }

    @Override
    public Placement getRemoveItem(GameStateInterface state) {
        System.out.println(state.getCurrentPlayer() + ", please enter the item to remove: ");
        int x = readInt();
        int y = readInt();
        return new Placement(x, y, state.getCurrentPlayer().getColor());
    }

    @Override
    public void showWin(GameStateInterface state) {
        System.out.println("Complimenti " + state.getCurrentPlayer() + "! Lo vinci!");
        System.out.println("Do you want to play again? (yes|no): ");
        if(readLine().equalsIgnoreCase("yes")) {
            init();
        } else {
            System.out.println("Era fantastica giocare con te! Buona notte.");
        }
    }

    @Override
    public void showState(GameStateInterface state) {
        System.out.println(state.prettyPrint());
    }

    public String readLine() {
        try {
            return input.readLine();
        } catch (IOException ioex) {
            LOGGER.severe("An io exception was thrown " + ioex);
            return readLine();
        }
    }

    public int readInt() {
        try {
            return Integer.parseInt(readLine());
        } catch (NumberFormatException nfex) {
            LOGGER.fine("Bad number format " + nfex);
            return readInt();
        }
    }

    public void init() {
//        Player p1 = new HumanPlayer("Amanj", this, Color.White);
//        Player p2 = new HumanPlayer("Nosheen", this, Color.Black);

        Player p1 = new RandomPlayer("Amanj", Color.White);
        Player p2 = new RandomPlayer("Nosheen", Color.Black);

        RezSessionController session = new RezSessionController(this, p1, p2);
        session.start();
    }

    public static void main(String... args) {
        new ConsoleUI().init();
    }

    private Logger LOGGER = Logger.getLogger("ConsoleUILogger");
    private BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

    @Override
    public Color getStartingColor() {
        throw new UnsupportedOperationException("Not supported yet getStartingColor()"); //To change body of generated methods, choose Tools | Templates.
    }
}


text:
<!DOCTYPE html>

<title>node_wrappers_node.crypto.Sign.Buffer.js</title>
<link rel="stylesheet" href="../../css/prettify_wynn.css" media="all"></link>
<link rel="stylesheet" href="../../css/all.css" media="all"></link>

goog.provide("node.crypto.Sign.Buffer");

/**
 * @constructor
 */
node.crypto.Sign.Buffer = function() {};

/**
 * @type {number|null}
 */
node.crypto.Sign.Buffer.prototype.poolSize = null;

/**
 * @param {string} b
 */
node.crypto.Sign.Buffer.prototype.isBuffer = function(b) {
  return node.crypto.Sign.Buffer.core_.isBuffer(b);
};

/**
 *
 */
node.crypto.Sign.Buffer.prototype.byteLength = function() {
  return node.crypto.Sign.Buffer.core_.byteLength();
};

/**
 * @private
 * @type {*}
 */
node.crypto.Sign.Buffer.core_ = require("crypto").Sign.Buffer;


text:
.. templatefilter:: timesince

.. function:: timesince

    Formats a date as the time since that date (e.g., "4 days, 6 hours").

    Takes an optional argument that is a variable containing the date to use as
    the comparison point (without the argument, the comparison point is *now*).
    For example, if ``blog_date`` is a date instance representing midnight on 1
    June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
    then the following would return "8 hours"::

        {{ blog_date|timesince(comment_date) }}

    Comparing offset-naive and offset-aware datetimes will return an empty string.

    Minutes is the smallest unit used, and "0 minutes" will be returned for any
    date that is in the future relative to the comparison point.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace com.houseelectrics.serializer
{

    public class DefaultFinder
    {
        //, TypeAliaser aliaser
        public LeafDefaultSet getDefaultsForAllLinkedObjects(Object root, NodeExpander nodeExpander)
        {
            LeafDefaultSet result = new LeafDefaultSet();

            ObjectExplorerImpl explorer = new ObjectExplorerImpl();
                MoveAway down = ( from,  propertyName,  to,  isIndexed, index) =>
                {
                    return (isIndexed || (to != null && !result.Type2Defaults.ContainsKey(to.GetType())));
                };
             MoveBack  up = (from, propertyName, to, isIndexed) =>
                {

                };

             OnLeaf leaf = (from, propertyName, to, index) =>
                {
                    Defaults4Class defaults = null;
                    if (from==null) {return;}
                    Type fromType = from.GetType();
                    if (!result.Type2Defaults.ContainsKey(fromType))
                    {
                        defaults = new Defaults4Class();
                        defaults.FullClassName = fromType.FullName;
                        result.Type2Defaults[fromType] = defaults;
                    }
                    else
                    {
                        defaults = result.Type2Defaults[fromType];
                    }
                    defaults.PropertyName2DefaultValue[propertyName] = to;
                };

             explorer.NodeExpander = nodeExpander;
                explorer.explore(root, down, up, leaf);
                return result;
        }
    }
}


text:
package com.amazonaws.services.applicationdiscovery.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateApplicationRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * Configuration ID of the application to be updated.
     *

     */
    private String configurationId;
    /**
     *

     * New name of the application to be updated.
     *

     */
    private String name;
    /**
     *

     * New description of the application to be updated.
     *

     */
    private String description;

    /**
     *

     * Configuration ID of the application to be updated.
     *

     *
     * @param configurationId
     *        Configuration ID of the application to be updated.
     */

    public void setConfigurationId(String configurationId) {
        this.configurationId = configurationId;
    }

    /**
     *

     * Configuration ID of the application to be updated.
     *

     *
     * @return Configuration ID of the application to be updated.
     */

    public String getConfigurationId() {
        return this.configurationId;
    }

    /**
     *

     * Configuration ID of the application to be updated.
     *

     *
     * @param configurationId
     *        Configuration ID of the application to be updated.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateApplicationRequest withConfigurationId(String configurationId) {
        setConfigurationId(configurationId);
        return this;
    }

    /**
     *

     * New name of the application to be updated.
     *

     *
     * @param name
     *        New name of the application to be updated.
     */

    public void setName(String name) {
        this.name = name;
    }

    /**
     *

     * New name of the application to be updated.
     *

     *
     * @return New name of the application to be updated.
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * New name of the application to be updated.
     *

     *
     * @param name
     *        New name of the application to be updated.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateApplicationRequest withName(String name) {
        setName(name);
        return this;
    }

    /**
     *

     * New description of the application to be updated.
     *

     *
     * @param description
     *        New description of the application to be updated.
     */

    public void setDescription(String description) {
        this.description = description;
    }

    /**
     *

     * New description of the application to be updated.
     *

     *
     * @return New description of the application to be updated.
     */

    public String getDescription() {
        return this.description;
    }

    /**
     *

     * New description of the application to be updated.
     *

     *
     * @param description
     *        New description of the application to be updated.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateApplicationRequest withDescription(String description) {
        setDescription(description);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getConfigurationId() != null)
            sb.append("ConfigurationId: ").append(getConfigurationId()).append(",");
        if (getName() != null)
            sb.append("Name: ").append(getName()).append(",");
        if (getDescription() != null)
            sb.append("Description: ").append(getDescription());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof UpdateApplicationRequest == false)
            return false;
        UpdateApplicationRequest other = (UpdateApplicationRequest) obj;
        if (other.getConfigurationId() == null ^ this.getConfigurationId() == null)
            return false;
        if (other.getConfigurationId() != null && other.getConfigurationId().equals(this.getConfigurationId()) == false)
            return false;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        if (other.getDescription() == null ^ this.getDescription() == null)
            return false;
        if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getConfigurationId() == null) ? 0 : getConfigurationId().hashCode());
        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
        return hashCode;
    }

    @Override
    public UpdateApplicationRequest clone() {
        return (UpdateApplicationRequest) super.clone();
    }

}


text:
<?php

/**
 * This file is part of the Nextras\Orm library.
 * @license    MIT
 * @link       https://github.com/nextras/orm
 */

namespace Nextras\Orm\Collection\Helpers;

use Nextras\Orm\InvalidArgumentException;
use Traversable;

class FetchPairsHelper
{
	public static function process(Traversable $collection, $key = null, $value = null)
	{
		$return = [];
		$rows = iterator_to_array($collection);

		if ($key === null && $value === null) {
			throw new InvalidArgumentException('FetchPairsHelper requires defined key or value.');
		}

		if ($key === null) {
			foreach ($rows as $row) {
				$return[] = $row->{$value};
			}

		} elseif ($value === null) {
			foreach ($rows as $row) {
				$return[is_object($row->{$key}) ? (string) $row->{$key} : $row->{$key}] = $row;
			}

		} else {
			foreach ($rows as $row) {
				$return[is_object($row->{$key}) ? (string) $row->{$key} : $row->{$key}] = $row->{$value};
			}
		}

		return $return;
	}
}


text:
namespace FurnitureManufacturer.Models
{
    using System;

    using FurnitureManufacturer.Interfaces;

    public abstract class Furniture : IFurniture
    {
        private const string ModelArgumentNullExceptionErrorMessage = "Model name cannot be empty or null.";
        private const string ModelArgumentOutOfRangeExceptionErrorMessage = "Model name cannot be with less than 3 symbols.";
        private const string PriceArgumentExceptionErrorMessage = "Price cannot be less or equal to $0.00.";
        private const string HeightArgumentExceptionErrorMessage = "Height cannot be less or equal to 0.00 m.";
        private const string ToStringFormat = "Type: {0}, Model: {1}, Material: {2}, Price: {3}, Height: {4}";
        private const int ModelNameNumberOfCharacters = 3;
        private const decimal PriceMinimumValue = 0.00m;
        private const decimal HeightMinimumValue = 0.00m;

        private string model;
        private MaterialType material;
        private decimal price;
        private decimal height;

        public Furniture(string setModel, MaterialType setMaterial, decimal setPrice, decimal setHeight)
        {
            this.Model = setModel;
            this.material = setMaterial;
            this.Price = setPrice;
            this.Height = setHeight;
        }

        public string Model
        {
            get
            {
                return this.model;
            }

            private set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentNullException(ModelArgumentNullExceptionErrorMessage);
                }

                if (value.Length < ModelNameNumberOfCharacters)
                {
                    throw new ArgumentOutOfRangeException(ModelArgumentOutOfRangeExceptionErrorMessage);
                }

                this.model = value;
            }
        }

        public string Material
        {
            get
            {
                return this.material.ToString();
            }
        }

        public decimal Price
        {
            get
            {
                return this.price;
            }

            set
            {
                if (value <= PriceMinimumValue)
                {
                    throw new ArgumentOutOfRangeException(PriceArgumentExceptionErrorMessage);
                }
                else
                {
                    this.price = value;
                }
            }
        }

        public decimal Height
        {
            get
            {
                return this.height;
            }

            set
            {
                if (value <= HeightMinimumValue)
                {
                    throw new ArgumentOutOfRangeException(HeightArgumentExceptionErrorMessage);
                }
                else
                {
                    this.height = value;
                }
            }
        }

        public override string ToString()
        {
            return string.Format(ToStringFormat, this.GetType().Name, this.Model, this.Material, this.Price, this.Height);
        }
    }
}


text:
from collections import deque
import subprocess
from mplayer.async import AsyncPlayer
import asyncore

from ..lib.youtube.downloader import download
from ..lib.youtube.video import Video
from ..config import SAVE_LOCATION

class App:
  def __init__(self):
    self.playlist = deque()
    self._callbacks = []
    self._state = {
      'playing': False,
      'volume': 1.0,
      'playlist': deque(),
    }

  def add_callback(self, callback):
    self._callbacks.append(callback)

  async def add_video(self, code):
    await download(code)
    self._state['playlist'].append(Video(code))
    self._callbacks[0]()
    if not self._state['playing']:
      self._play(code)

  def set_volume(self, level):
    self._state['volume'] = level

  def get_state(self):
    playlist = [video.serialize() for video in self._state['playlist']]
    return {
      'playing': self._state['playing'],
      'volume': self._state['volume'],
      'playlist': playlist,
    }

  def toggle_playback(self):
    self._state['playing'] = not self._state['playing']
    self._callbacks[0]()

  def _play(self, code):
    self._state['playing'] = True
    self._callbacks[0]()
    print('Playing...')
    location = '{}/{}.m4a'.format(SAVE_LOCATION, code)
    # sp = subprocess.Popen(['ffplay', '-nodisp', '-autoexit', location])
    # self._state['playing'] = False
    # self._state['playlist'].popleft()
    self._callbacks[0]()
    print('Done.')
    # if (len(self._state['playlist']) > 0):
    #   self._play(self._state['playlist'][0].code)


text:
layout: post
title: React router on Amazon S3
tags: [React, AWS, JavaScript]
---

Not so long ago I've finished my [React](https://facebook.github.io/react/) + [ReactRouter](https://github.com/reactjs/react-router)
project and I was looking for a neat way to deploy its production version.

Since it's a 100% static website, the first thing that came to my mind was [Amazon S3](https://aws.amazon.com/s3/) and
their website hosting. The process is very simple:

1. create a bucket
2. make it publicly readable
3. upload your html/css/js/other files
4. enable static website hosting on the bucket
5. change some DNS settings
6. ... you're done - there is no point 6 ;)

To make it even simpler I used awesome [s3_website](https://github.com/laurilehmijoki/s3_website) tool. It required creating simple configuration
file and I was able to push my work to **S3**.

### Issues with routing

Unfortunately **S3** website hosting wasn't playing nice with **ReactRouter**.
I typed `http://my-awesome-site.com/products/cool-product` in the browser's address bar and I got
**404 Not Found** error code. I realized that's completely justified on the **S3** side since this file
wasn't present in the bucket.

On staging I was handling such cases with [Nginx](https://www.nginx.com/) configuration:

{% highlight bash %}
location / {
  ...
  try_files $uri.html $uri $uri/ /index.html;
  ...
}
{% endhighlight %}

This basically means: try to match the uri and if you fail just serve `index.html` from the root directory.

Thanks to above directive routing was done by **ReactRouter** and site was working perfectly on staging.

### Intermediate solution

One possible workaround was to switch **ReactRouter** to use `createHashHistory` and setup [redirect rules](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules.html) on **S3** bucket
like this

{% highlight xml %}
<RoutingRules>
  <RoutingRule>
    <Condition>
      <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
      <HostName>my-awesome-site.com</HostName>
      <ReplaceKeyPrefixWith>#/</ReplaceKeyPrefixWith>
    </Redirect>
  </RoutingRule>
</RoutingRules>
{% endhighlight %}

That way when I typed `http://my-awesome-site.com/products/cool-product` I was redirected to
`http://my-awesome-site.com/#/products/cool-product`. My site worked again but with ugly urls
that were neither user nor google friendly.

### Cloudfront

I was looking through Amazon Management Console, hoping I could find some solution, and I noticed
`Error Pages` section in my [Cloudfront](https://aws.amazon.com/cloudfront/) distribution.
It turned out that I was able to override default behaviour of **404** http error and that was what I needed.
I set `Response Page Path` to `/index.html` and `HTTP Response Code` to `200`

![cloudfront](/public/images/cloudfront_error_pages.png)

Since this is essentially the same configuration that I had in **Nginx**
I was able to access my site through normal url again :)


text:
FROM openjdk:8

ADD build/libs/app.jar /opt/web/app.jar

WORKDIR /opt/web

EXPOSE 8080

ENTRYPOINT ["java", "-Djava.security.egd=file:///dev/urandom", "-jar", "/opt/web/app.jar"]


text:
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import unittest

from dashboard import testing_common
from dashboard import utils
from dashboard.models import bug_label_patterns

class BugLabelPatternsTest(testing_common.TestCase):

  def testAddBugLabelPattern(self):
    bug_label_patterns.AddBugLabelPattern('foo', '*/*/foo')
    bug_label_patterns.AddBugLabelPattern('bar', '*/*/bar')
    bug_label_patterns.AddBugLabelPattern('bar', '*/*/bar-extra')
    self.assertEqual(
        1, len(bug_label_patterns.BugLabelPatterns.query().fetch()))
    self.assertEqual(
        {'foo': ['*/*/foo'], 'bar': ['*/*/bar', '*/*/bar-extra']},
        bug_label_patterns.GetBugLabelPatterns())

  def testRemoveBugLabel(self):
    bug_label_patterns.AddBugLabelPattern('foo', '*/*/foo')
    bug_label_patterns.AddBugLabelPattern('bar', '*/*/bar')
    bug_label_patterns.AddBugLabelPattern('bar', '*/*/bar-extra')
    bug_label_patterns.RemoveBugLabel('bar')
    self.assertEqual(
        {'foo': ['*/*/foo']},
        bug_label_patterns.GetBugLabelPatterns())

  def testRemoveBugLabel_DoesntExist_NoError(self):
    bug_label_patterns.RemoveBugLabel('bar')
    self.assertEqual({}, bug_label_patterns.GetBugLabelPatterns())

  def testGetBugLabelsForTest(self):
    bug_label_patterns.AddBugLabelPattern('foo', '*/*/foo')
    bug_label_patterns.AddBugLabelPattern('f-prefix', '*/*/f*')
    testing_common.AddTests(['M'], ['b'], {'foo': {}, 'bar': {}})
    foo_test = utils.TestKey('M/b/foo').get()
    bar_test = utils.TestKey('M/b/bar').get()
    self.assertEqual(
        ['f-prefix', 'foo'], bug_label_patterns.GetBugLabelsForTest(foo_test))
    self.assertEqual(
        [], bug_label_patterns.GetBugLabelsForTest(bar_test))

if __name__ == '__main__':
  unittest.main()


text:
import i18n from 'i18next';
import { ActionSheetIOS, Platform } from 'react-native';
import DialogAndroid from 'react-native-dialogs';

export default async function displayExportReportDialog(
  showUploadButton: boolean,
  buttonHandler: (idx: number) => any
) {
  const title = i18n.t('report.export.title');
  const message = i18n.t('report.export.description');
  const options = [i18n.t('report.export.option.asSharingBundle'), i18n.t('report.export.option.asCSV')];

  if (showUploadButton) {
    options.push(i18n.t('report.upload'));
  }

  if (Platform.OS === 'ios') {
    ActionSheetIOS.showActionSheetWithOptions(
      {
        options: [...options, i18n.t('commonText.cancel')],
        cancelButtonIndex: options.length,
        title,
        message
      },
      buttonHandler
    );
  } else if (Platform.OS === 'android') {
    const { selectedItem } = await DialogAndroid.showPicker(title, message, {
      items: options.map((item, idx) => ({ label: item, id: idx })),
      positiveText: i18n.t('commonText.cancel')
    });
    if (selectedItem) {
      buttonHandler(selectedItem.id);
    }
  }
}


text:
using System;
using System.Linq;

using Orleans;

namespace Orleankka.Core
{
    /// <summary>
    /// FOR INTERNAL USE ONLY!
    /// </summary>
    public interface IClientEndpoint : IGrainObserver
    {
        void Receive(object message);
    }
}


text:
package org.apache.velocity.runtime.parser.node;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MathException;
import org.apache.velocity.runtime.parser.Parser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Handles number division of nodes

 *
 * Please look at the Parser.jjt file which is
 * what controls the generation of this class.
 *
 * @author Will Glass-Husain
 * @author Peter Romianowski
 * @author Jason van Zyl
 * @author Geir Magnusson Jr.
 * @version $Id: ASTDivNode.java 691048 2008-09-01 20:26:11Z nbubna $
 */
public class ASTDivNode extends ASTMathNode
{
    Logger logger = LoggerFactory.getLogger( ASTDivNode.class );

    /**
     * @param id
     */
    public ASTDivNode(int id)
    {
        super(id);
    }

    /**
     * @param p
     * @param id
     */
    public ASTDivNode(Parser p, int id)
    {
        super(p, id);
    }

    public Number perform(Number left, Number right, InternalContextAdapter context)
    {
        /*
         * check for divide by 0
         */
        if (MathUtils.isZero(right))
        {
            String msg = "Right side of division operation is zero. Must be non-zero. "
                          + getLocation(context);
            if (strictMode)
            {
                logger.error(msg);
                throw new MathException(msg);
            }
            else
            {
                logger.debug(msg);
                return null;
            }
        }
        return MathUtils.divide(left, right);
    }
}


text:
#include "../../GapiOpenGL/Inc/FrameBuffer.h"
#include "../../GapiOpenGL/Inc/Device.h"
#include "../../GapiOpenGL/Inc/WrapFunc.h"

namespace Gapi
{
	/// Конструктор класса.
	FrameBuffer::FrameBuffer(void)
	{
	}

	/// Деструктор класса.
	FrameBuffer::~FrameBuffer(void)
	{
		Destroy();
	}

	void FrameBuffer::Create(ITextureBase* texture)
	{
		GL_ARB_FramebufferObject::GenFramebuffers(1, &_frameBufferID, SOURCE_LOCATION);
		GL_ARB_FramebufferObject::BindFramebuffer(GL_FRAMEBUFFER, _frameBufferID, SOURCE_LOCATION);

		GL_ARB_FramebufferObject::GenRenderbuffers(1, &_renderBufferID, SOURCE_LOCATION);
		GL_ARB_FramebufferObject::BindRenderbuffer(GL_RENDERBUFFER, _renderBufferID, SOURCE_LOCATION);

		//if (Texture::STENCIL)

		GL_ARB_FramebufferObject::RenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_STENCIL, texture->GetWidth(), texture->GetHeight(), SOURCE_LOCATION);

		//else

		//GL_ARB_FramebufferObject::RenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, texture->GetWidth(), texture->GetHeight(), SOURCE_LOCATION);

		GL_ARB_FramebufferObject::BindRenderbuffer(GL_RENDERBUFFER, 0, SOURCE_LOCATION);

		//if (Texture::DEPTH)

		GL_ARB_FramebufferObject::FramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texture->GetID(), 0, SOURCE_LOCATION);

		glDrawBuffer(GL_NONE);
		glReadBuffer(GL_NONE);

		//else if (Texture::STENCIL)

		//GL_ARB_FramebufferObject::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->GetID(), 0, SOURCE_LOCATION);
		//GL_ARB_FramebufferObject::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _renderBufferID, SOURCE_LOCATION);
		//GL_ARB_FramebufferObject::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _renderBufferID, SOURCE_LOCATION);

		//else

		//GL_ARB_FramebufferObject::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->GetID(), 0, SOURCE_LOCATION);
		//GL_ARB_FramebufferObject::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _renderBufferID, SOURCE_LOCATION);

		if (GL_ARB_FramebufferObject::CheckFramebufferStatus(GL_FRAMEBUFFER, SOURCE_LOCATION) != GL_FRAMEBUFFER_COMPLETE)
		{

		}

		GL_ARB_FramebufferObject::BindFramebuffer(GL_FRAMEBUFFER, 0, SOURCE_LOCATION);
	}

	void FrameBuffer::Destroy(void)
	{
		if (GL_ARB_FramebufferObject::IsRenderbuffer(_renderBufferID))
			GL_ARB_FramebufferObject::DeleteRenderbuffers(1, &_renderBufferID);

		if (GL_ARB_FramebufferObject::IsFramebuffer(_frameBufferID))
			GL_ARB_FramebufferObject::DeleteFramebuffers(1, &_frameBufferID);
	}

	void FrameBuffer::Bind(void)
	{
		GL_ARB_FramebufferObject::BindFramebuffer(GL_FRAMEBUFFER, _frameBufferID, SOURCE_LOCATION);
	}

	void FrameBuffer::Unbind(void)
	{
		GL_ARB_FramebufferObject::BindFramebuffer(GL_FRAMEBUFFER, 0, SOURCE_LOCATION);
	}

	IFrameBufferBase* RegisterFrameBuffer(void)
	{
		return new FrameBuffer();
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Br. mycol. Soc. 72: 379 (1979)

#### Original name
Octavianiaceae Locq. ex Pegler & T.W.K. Young

### Remarks
null


text:
package org.jboss.weld.tests.interceptors.circularInvocation;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

/**
 * @author Marius Bogoevici
 */
@ApplicationScoped
public class SucceedingBean {
    @Inject
    @Succeeding
    SomeBean someBean;

    public void handle() {
        someBean.methodB();
    }
}


text:
@interface zhuanTiViewController ()<UITableViewDataSource,UITableViewDelegate>
{

    NSMutableArray *_dataArray;

    UITableView *_tableView;

}
@end

@implementation zhuanTiViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    _dataArray = [[NSMutableArray alloc]init];

    [self createDataSoure];

    [self createTableView];

}

-(void)createDataSoure{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager GET:URL_ZT parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];

        NSArray *array = [rootDic objectForKey:@"data"];

        for (NSDictionary *dic in array) {

            zhuantiModel *model = [[zhuantiModel alloc]init];

            [model setValuesForKeysWithDictionary:dic];

            [_dataArray addObject:model];
        }

        [_tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];

}

-(void)createTableView{

    _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];

    _tableView.delegate = self;

    _tableView.dataSource = self;

    [self.view addSubview:_tableView];

    UIView *subView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 130)];

    subView.backgroundColor =[UIColor whiteColor];

    _tableView.tableFooterView = subView;

}

#pragma mark - tableView

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _dataArray.count;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 200;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    zhuanTiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];

    if (!cell) {

        cell = [[zhuanTiTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ID"];
    }

    zhuantiModel *model = _dataArray[indexPath.row];

    [cell configCellWithModel:model];

    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    zhuantiModel *model = _dataArray[indexPath.row];

    zhuanTiXiangViewController *vc = [[zhuanTiXiangViewController alloc]init];

    vc.topic = model.topic_url;

    vc.title = model.topic_name;

    [self.navigationController pushViewController:vc animated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

@end


text:
package ginpprof

import (
	"net/http/pprof"
	"github.com/gin-gonic/gin"
)

// Wrap adds several routes from package `net/http/pprof` to *gin.Engine object
func Wrap(router *gin.Engine) {
	router.GET("/debug/pprof/", IndexHandler())
	router.GET("/debug/pprof/heap", HeapHandler())
	router.GET("/debug/pprof/goroutine", GoroutineHandler())
	router.GET("/debug/pprof/block", BlockHandler())
	router.GET("/debug/pprof/threadcreate", ThreadCreateHandler())
	router.GET("/debug/pprof/cmdline", CmdlineHandler())
	router.GET("/debug/pprof/profile", ProfileHandler())
	router.GET("/debug/pprof/symbol", SymbolHandler())
	router.POST("/debug/pprof/symbol", SymbolHandler())
	router.GET("/debug/pprof/trace", TraceHandler())
}

// Wrappers make sure we are backward compatible
var Wrapper = Wrap

// IndexHandler will pass the call from /debug/pprof to pprof
func IndexHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		pprof.Index(ctx.Writer, ctx.Request)
	}
}

// HeapHandler will pass the call from /debug/pprof/heap to pprof
func HeapHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		pprof.Handler("heap").ServeHTTP(ctx.Writer, ctx.Request)
	}
}

// GoroutineHandler will pass the call from /debug/pprof/goroutine to pprof
func GoroutineHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		pprof.Handler("goroutine").ServeHTTP(ctx.Writer, ctx.Request)
	}
}

// BlockHandler will pass the call from /debug/pprof/block to pprof
func BlockHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		pprof.Handler("block").ServeHTTP(ctx.Writer, ctx.Request)
	}
}

// ThreadCreateHandler will pass the call from /debug/pprof/threadcreate to pprof
func ThreadCreateHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		pprof.Handler("threadcreate").ServeHTTP(ctx.Writer, ctx.Request)
	}
}

// CmdlineHandler will pass the call from /debug/pprof/cmdline to pprof
func CmdlineHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		pprof.Cmdline(ctx.Writer, ctx.Request)
	}
}

// ProfileHandler will pass the call from /debug/pprof/profile to pprof
func ProfileHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		pprof.Profile(ctx.Writer, ctx.Request)
	}
}

// SymbolHandler will pass the call from /debug/pprof/symbol to pprof
func SymbolHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		pprof.Symbol(ctx.Writer, ctx.Request)
	}
}

// TraceHandler will pass the call from /debug/pprof/trace to pprof
func TraceHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		pprof.Trace(ctx.Writer, ctx.Request)
	}
}


text:
package app.outlay.view.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import app.outlay.domain.model.User;
import app.outlay.mvp.presenter.LoginViewPresenter;
import app.outlay.mvp.view.LoginView;
import app.outlay.view.LoginForm;
import app.outlay.view.Navigator;
import app.outlay.view.fragment.base.BaseMvpFragment;

import javax.inject.Inject;

import butterknife.Bind;

/**
 * Created by bmelnychuk on 12/14/16.
 */

public class SyncGuestFragment extends BaseMvpFragment<LoginView, LoginViewPresenter> implements LoginView {
    @Inject
    LoginViewPresenter presenter;

    @Bind(app.outlay.R.id.loginForm)
    LoginForm loginForm;

    @Bind(app.outlay.R.id.progressLayout)
    View progressLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getApp().getAppComponent().inject(this);
    }

    @Override
    public LoginViewPresenter createPresenter() {
        return presenter;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(app.outlay.R.layout.fragment_sync_guest, null, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        loginForm.setMode(LoginForm.MODE_SIGN_UP);
        loginForm.setToggleModeButtonVisible(false);
        loginForm.setOnSignUpClickListener((email, password, src) -> {
            analytics().trackLinkAccount();
            presenter.linkAccount(email, password);
        });
    }

    @Override
    public void setProgress(boolean running) {
        progressLayout.setVisibility(running ? View.VISIBLE : View.GONE);
    }

    @Override
    public void info(String message) {
        Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccess(User user) {
        getApp().releaseUserComponent();
        getApp().createUserComponent(user);
        Navigator.goToMainScreen(getActivity());
        getActivity().finish();
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Kaj je HUD?</title>
<link rel="stylesheet" type="text/css" href="../vodnik_1404.css">
<link rel="shortcut icon" href="https://www.ubuntu.si/favicon.ico">

Ubuntu Slovenija | Uradna spletna stran slovenske skupnosti Linux distribucije Ubuntu

Novice

Forum

Kaj je Ubuntu?

Pogosta vprašanja

Skupnost

Povezave

 »  Namizni vodnik Ubuntu » Namizje › Namizje »

Kaj je HUD?

HUD ali Heads Up Display je na iskanju temelječe nadomestilo tradicionalnim menijem in je bil predstavljen v Ubuntuju 12.04 LTS.

Nekateri programi kot Gimp ali Inkscape vsebujejo na stotine predmetov menijev. Če uporabljate takšne programe, se boste morda spomnili možnosti menija, ne pa tudi kako jo najti v menijih.

Uporaba iskalnega polja je veliko hitrejša kot krmarjenje po razširjeni hierarhiji menija. HUD je prav tako veliko bolj dostopen kot normalni meniji ker nekateri ljudje ne zmorejo natančno nadzorovati miškin kazalec.

Uporaba HUD

Za preizkus HUD-a:

Pritisnite Alt za odpiranje HUD-a.

Začnite tipkati.

Ko vidite rezultat, ki ga želite zagnati, uporabite tipki gor in dol za izbiro rezultata in pritisnite Enter ali kliknite na želeni rezultat iskanja.

Če spremenite mnenje in želite zapreti HUD ponovno pritisnite na tipko Alt ali Esc. HUD lahko zaprete tudi tako da kliknete zunaj območja HUD-a.

HUD si beleži vašo zgodovino iskanja in prilagodi rezultate iskanja tako, da bodo postali še bolj uporabni.

Več podrobnosti

Namizje

Material v tem dokumentu je na voljo pod prosto licenco. To je prevod dokumentacije Ubuntu, ki jo je sestavila Ubuntu dokumentacijska ekpa za Ubuntu. V slovenščino jo je prevedla skupina Ubuntu prevajalcev. Za poročanje napak v prevodih v tej dokumentaciji ali Ubuntuju pošljite sporočilo na dopisni seznam.


text:
puts "please enter your first name:"
first = gets.chomp
puts "please enter your last name:"
last = gets.chomp
puts "so you are " + first +" "+last


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="BasoProgressView">
        <attr name="baso_finishButtonText" format="string"/>
        <attr name="baso_finishButtonBackground" format="color|reference"/>
        <attr name="baso_finishText" format="string"/>
        <attr name="baso_finishTextSize" format="dimension"/>
        <attr name="baso_finishSrc" format="color|reference"/>
        <attr name="baso_finishSrcWidth" format="dimension"/>
        <attr name="baso_finishSrcHeight" format="dimension"/>
        <attr name="baso_progressText" format="string"/>
    </declare-styleable>
</resources>


text:
"""
A Hyper-V Nova Compute driver.
"""

import functools
import platform
import sys

from os_win import exceptions as os_win_exc
from os_win import utilsfactory
from oslo_log import log as logging
import six

from nova import exception
from nova.virt import driver
from nova.virt.hyperv import eventhandler
from nova.virt.hyperv import hostops
from nova.virt.hyperv import imagecache
from nova.virt.hyperv import livemigrationops
from nova.virt.hyperv import migrationops
from nova.virt.hyperv import rdpconsoleops
from nova.virt.hyperv import serialconsoleops
from nova.virt.hyperv import snapshotops
from nova.virt.hyperv import vmops
from nova.virt.hyperv import volumeops

LOG = logging.getLogger(__name__)

def convert_exceptions(function, exception_map):
    expected_exceptions = tuple(exception_map.keys())

    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except expected_exceptions as ex:
            raised_exception = exception_map.get(type(ex))
            if not raised_exception:
                # exception might be a subclass of an expected exception.
                for expected in expected_exceptions:
                    if isinstance(ex, expected):
                        raised_exception = exception_map[expected]
                        break

            exc_info = sys.exc_info()
            # NOTE(claudiub): Python 3 raises the exception object given as
            # the second argument in six.reraise.
            # The original message will be maintained by passing the original
            # exception.
            exc = raised_exception(six.text_type(exc_info[1]))
            six.reraise(raised_exception, exc, exc_info[2])
    return wrapper

def decorate_all_methods(decorator, *args, **kwargs):
    def decorate(cls):
        for attr in cls.__dict__:
            class_member = getattr(cls, attr)
            if callable(class_member):
                setattr(cls, attr, decorator(class_member, *args, **kwargs))
        return cls

    return decorate

exception_conversion_map = {
    # expected_exception: converted_exception
    os_win_exc.OSWinException: exception.NovaException,
    os_win_exc.HyperVVMNotFoundException: exception.InstanceNotFound,
}

# NOTE(claudiub): the purpose of the decorator below is to prevent any
# os_win exceptions (subclasses of OSWinException) to leak outside of the
# HyperVDriver.

@decorate_all_methods(convert_exceptions, exception_conversion_map)
class HyperVDriver(driver.ComputeDriver):
    capabilities = {
        "has_imagecache": True,
        "supports_evacuate": False,
        "supports_migrate_to_same_host": False,
        "supports_attach_interface": True,
        "supports_device_tagging": True,
        "supports_multiattach": False,
        "supports_trusted_certs": False,
        "supports_pcpus": False,

        # Supported image types
        "supports_image_type_vhd": True,
        "supports_image_type_vhdx": True,
    }

    def __init__(self, virtapi):
        # check if the current version of Windows is supported before any
        # further driver initialisation.
        self._check_minimum_windows_version()

        super(HyperVDriver, self).__init__(virtapi)

        self._hostops = hostops.HostOps()
        self._volumeops = volumeops.VolumeOps()
        self._vmops = vmops.VMOps(virtapi)
        self._snapshotops = snapshotops.SnapshotOps()
        self._livemigrationops = livemigrationops.LiveMigrationOps()
        self._migrationops = migrationops.MigrationOps()
        self._rdpconsoleops = rdpconsoleops.RDPConsoleOps()
        self._serialconsoleops = serialconsoleops.SerialConsoleOps()
        self._imagecache = imagecache.ImageCache()

    def _check_minimum_windows_version(self):
        hostutils = utilsfactory.get_hostutils()
        if not hostutils.check_min_windows_version(6, 2):
            # the version is of Windows is older than Windows Server 2012 R2.
            # Log an error, letting users know that this version is not
            # supported any longer.
            LOG.error('You are running nova-compute on an unsupported '
                      'version of Windows (older than Windows / Hyper-V '
                      'Server 2012). The support for this version of '
                      'Windows has been removed in Mitaka.')
            raise exception.HypervisorTooOld(version='6.2')
        elif not hostutils.check_min_windows_version(6, 3):
            # TODO(claudiub): replace the warning with an exception in Rocky.
            LOG.warning('You are running nova-compute on Windows / Hyper-V '
                        'Server 2012. The support for this version of Windows '
                        'has been deprecated In Queens, and will be removed '
                        'in Rocky.')

    @property
    def need_legacy_block_device_info(self):
        return False

    def init_host(self, host):
        self._serialconsoleops.start_console_handlers()
        event_handler = eventhandler.InstanceEventHandler(
            state_change_callback=self.emit_event)
        event_handler.start_listener()

    def list_instance_uuids(self):
        return self._vmops.list_instance_uuids()

    def list_instances(self):
        return self._vmops.list_instances()

    def spawn(self, context, instance, image_meta, injected_files,
              admin_password, allocations, network_info=None,
              block_device_info=None, power_on=True):
        self._vmops.spawn(context, instance, image_meta, injected_files,
                          admin_password, network_info, block_device_info)

    def reboot(self, context, instance, network_info, reboot_type,
               block_device_info=None, bad_volumes_callback=None):
        self._vmops.reboot(instance, network_info, reboot_type)

    def destroy(self, context, instance, network_info, block_device_info=None,
                destroy_disks=True):
        self._vmops.destroy(instance, network_info, block_device_info,
                            destroy_disks)

    def cleanup(self, context, instance, network_info, block_device_info=None,
                destroy_disks=True, migrate_data=None, destroy_vifs=True):
        """Cleanup after instance being destroyed by Hypervisor."""
        self.unplug_vifs(instance, network_info)

    def get_info(self, instance, use_cache=True):
        return self._vmops.get_info(instance)

    def attach_volume(self, context, connection_info, instance, mountpoint,
                      disk_bus=None, device_type=None, encryption=None):
        return self._volumeops.attach_volume(connection_info,
                                             instance.name)

    def detach_volume(self, context, connection_info, instance, mountpoint,
                      encryption=None):
        return self._volumeops.detach_volume(connection_info,
                                             instance.name)

    def get_volume_connector(self, instance):
        return self._volumeops.get_volume_connector()

    def get_available_resource(self, nodename):
        return self._hostops.get_available_resource()

    def get_available_nodes(self, refresh=False):
        return [platform.node()]

    def host_power_action(self, action):
        return self._hostops.host_power_action(action)

    def snapshot(self, context, instance, image_id, update_task_state):
        self._snapshotops.snapshot(context, instance, image_id,
                                   update_task_state)

    def pause(self, instance):
        self._vmops.pause(instance)

    def unpause(self, instance):
        self._vmops.unpause(instance)

    def suspend(self, context, instance):
        self._vmops.suspend(instance)

    def resume(self, context, instance, network_info, block_device_info=None):
        self._vmops.resume(instance)

    def power_off(self, instance, timeout=0, retry_interval=0):
        self._vmops.power_off(instance, timeout, retry_interval)

    def power_on(self, context, instance, network_info,
                 block_device_info=None):
        self._vmops.power_on(instance, block_device_info, network_info)

    def resume_state_on_host_boot(self, context, instance, network_info,
                                  block_device_info=None):
        """Resume guest state when a host is booted."""
        self._vmops.resume_state_on_host_boot(context, instance, network_info,
                                              block_device_info)

    def live_migration(self, context, instance, dest, post_method,
                       recover_method, block_migration=False,
                       migrate_data=None):
        self._livemigrationops.live_migration(context, instance, dest,
                                              post_method, recover_method,
                                              block_migration, migrate_data)

    def rollback_live_migration_at_destination(self, context, instance,
                                               network_info,
                                               block_device_info,
                                               destroy_disks=True,
                                               migrate_data=None):
        self.destroy(context, instance, network_info, block_device_info,
                     destroy_disks=destroy_disks)

    def pre_live_migration(self, context, instance, block_device_info,
                           network_info, disk_info, migrate_data):
        self._livemigrationops.pre_live_migration(context, instance,
                                                  block_device_info,
                                                  network_info)
        return migrate_data

    def post_live_migration(self, context, instance, block_device_info,
                            migrate_data=None):
        self._livemigrationops.post_live_migration(context, instance,
                                                   block_device_info,
                                                   migrate_data)

    def post_live_migration_at_destination(self, context, instance,
                                           network_info,
                                           block_migration=False,
                                           block_device_info=None):
        self._livemigrationops.post_live_migration_at_destination(
            context,
            instance,
            network_info,
            block_migration)

    def check_can_live_migrate_destination(self, context, instance,
                                           src_compute_info, dst_compute_info,
                                           block_migration=False,
                                           disk_over_commit=False):
        return self._livemigrationops.check_can_live_migrate_destination(
            context, instance, src_compute_info, dst_compute_info,
            block_migration, disk_over_commit)

    def cleanup_live_migration_destination_check(self, context,
                                                 dest_check_data):
        self._livemigrationops.cleanup_live_migration_destination_check(
            context, dest_check_data)

    def check_can_live_migrate_source(self, context, instance,
                                      dest_check_data, block_device_info=None):
        return self._livemigrationops.check_can_live_migrate_source(
            context, instance, dest_check_data)

    def get_instance_disk_info(self, instance, block_device_info=None):
        pass

    def plug_vifs(self, instance, network_info):
        """Plug VIFs into networks."""
        self._vmops.plug_vifs(instance, network_info)

    def unplug_vifs(self, instance, network_info):
        """Unplug VIFs from networks."""
        self._vmops.unplug_vifs(instance, network_info)

    def migrate_disk_and_power_off(self, context, instance, dest,
                                   flavor, network_info,
                                   block_device_info=None,
                                   timeout=0, retry_interval=0):
        return self._migrationops.migrate_disk_and_power_off(context,
                                                             instance, dest,
                                                             flavor,
                                                             network_info,
                                                             block_device_info,
                                                             timeout,
                                                             retry_interval)

    def confirm_migration(self, context, migration, instance, network_info):
        self._migrationops.confirm_migration(context, migration,
                                             instance, network_info)

    def finish_revert_migration(self, context, instance, network_info,
                                migration, block_device_info=None,
                                power_on=True):
        self._migrationops.finish_revert_migration(context, instance,
                                                   network_info,
                                                   block_device_info, power_on)

    def finish_migration(self, context, migration, instance, disk_info,
                         network_info, image_meta, resize_instance,
                         block_device_info=None, power_on=True):
        self._migrationops.finish_migration(context, migration, instance,
                                            disk_info, network_info,
                                            image_meta, resize_instance,
                                            block_device_info, power_on)

    def get_host_ip_addr(self):
        return self._hostops.get_host_ip_addr()

    def get_host_uptime(self):
        return self._hostops.get_host_uptime()

    def get_rdp_console(self, context, instance):
        return self._rdpconsoleops.get_rdp_console(instance)

    def get_serial_console(self, context, instance):
        return self._serialconsoleops.get_serial_console(instance.name)

    def get_console_output(self, context, instance):
        return self._serialconsoleops.get_console_output(instance.name)

    def manage_image_cache(self, context, all_instances):
        self._imagecache.update(context, all_instances)

    def attach_interface(self, context, instance, image_meta, vif):
        return self._vmops.attach_interface(instance, vif)

    def detach_interface(self, context, instance, vif):
        return self._vmops.detach_interface(instance, vif)

    def rescue(self, context, instance, network_info, image_meta,
               rescue_password):
        self._vmops.rescue_instance(context, instance, network_info,
                                    image_meta, rescue_password)

    def unrescue(self, instance, network_info):
        self._vmops.unrescue_instance(instance)

    def update_provider_tree(self, provider_tree, nodename, allocations=None):
        inventory = provider_tree.data(nodename).inventory
        alloc_ratios = self._get_allocation_ratios(inventory)

        self._hostops.update_provider_tree(
            provider_tree, nodename, alloc_ratios, allocations)


text:
import { Role } from '../../shared/roles/roles';
export class User {
    id: number;
    login: string;
    password:string;
    roles: Role[];
}


text:
package com.strato.hidrive.api.bll.news;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;

import com.strato.hidrive.api.connection.gateway.HiDriveDomainGateway;
import com.strato.hidrive.api.connection.httpgateway.request.GetRequest;
import com.strato.hidrive.api.connection.httpgateway.request.Request;
import com.strato.hidrive.api.connection.httpgateway.response.Response;
import com.strato.hidrive.api.utils.StringUtils;

public class ChangelogLanguagesGateway extends HiDriveDomainGateway<List<String>> {

	@Override
	protected List<String> prepareResult(Response<String> response) {
		List<String> languages = new ArrayList<String>();

		if (response.getResponseData() == null) {
			return languages;
		}
		try {
			String responseString = StringUtils.unescapeHiDriveCoding(response.getResponseData());
			JSONArray array = new JSONArray(responseString);
			for (int i = 0; i < array.length(); i++) {
				languages.add((String)array.get(i));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return languages;
	}

	@Override
	protected Request prepareRequest() {
		return new GetRequest("changelog/languages");
	}
}


text:
%%% RenderToolbox3 Copyright (c) 2012-2013 The RenderToolbox3 Team.
%%% About Us://github.com/DavidBrainard/RenderToolbox3/wiki/About-Us
%%% RenderToolbox3 is released under the MIT License.  See LICENSE.txt.
%
% Apply PBRT mappings objects to the adjustments DOM.
%   @param idMap
%   @param objects
%
% @details
% Modify the document represented by the given @a idMap, with the given
% mappings @a objects.  @a objects must be a struct array of mappings
% objects as returned from MappingsToObjects() or GenericObjectsToPBRT().
%
% @details
% Used internally by RTB_ApplyMappings_PBRT().
%
% @details
% Usage:
%   ApplyPBRTObjects(idMap, objects)
%
% @ingroup RendererPlugins
function ApplyPBRTObjects(idMap, objects)

for ii = 1:numel(objects)
    % pull out one object to apply
    obj = objects(ii);

    if strcmp(obj.hints, 'AreaLightSource')
        % for area lights
        %	write properties to a new light source with a new id
        %   bind the original shape object to the new id

        % area light uses two separate ids
        shapeID = obj.id;
        lightID = [obj.id '-area-light'];

        % write out a new light object
        obj.id = lightID;
        obj.class = 'AreaLightSource';
        addObject(idMap, obj);

        % bind the existing shape object to the light object
        addConfiguration(idMap, shapeID, 'reference', ...
            'area-light', 'AreaLightSource', lightID);

    elseif strcmp(obj.hints, 'bumpmap')
        % make a new scale texture that scales the given bump texture
        textureID = GetObjectProperty(obj, 'textureID');
        scale = GetObjectProperty(obj, 'scale');
        scaledID = ['zzz-' obj.id '-scaled'];
        addDeclaration(idMap, scaledID, 'Texture', 'scale');
        addConfiguration(idMap, ...
            scaledID, 'parameter', 'dataType', 'string', 'float');
        addConfiguration(idMap, ...
            scaledID, 'parameter', 'tex1', 'texture', textureID);
        addConfiguration(idMap, ...
            scaledID, 'parameter', 'tex2', 'float', scale);

        % assign the scaled texture to the given material's bumpmap
        materialID = GetObjectProperty(obj, 'materialID');
        addConfiguration(idMap, ...
            materialID, 'parameter', 'bumpmap', 'texture', scaledID);

    else
        % otherwise, add the object to the DOM as-is
        addObject(idMap, obj);
    end
end

% Make sure the DOM contains a node for the given object.
function checkDOMNode(idMap, id, nodeName)
if ~idMap.isKey(id)
    docNode = idMap('document');
    docRoot = docNode.getDocumentElement();
    objectNode = CreateElementChild(docRoot, nodeName, id, 'first');
    idMap(id) = objectNode;
end

% Add a whole object to the DOM.
function addObject(idMap, object)
addDeclaration(idMap, object.id, object.class, object.subclass);
for ii = 1:numel(object.properties)
    prop = object.properties(ii);
    addConfiguration(idMap, object.id, 'parameter', ...
        prop.name, prop.type, prop.value);
end

% Add an object declaration to the DOM.
function addDeclaration(idMap, id, class, subclass)

if isempty(class)
    return;
end

% make sure the DOM has a node for this object
checkDOMNode(idMap, id, class);

% set the node name
path = {id, PrintPathPart('$')};
SetSceneValue(idMap, path, class, true, '=');

if nargin >= 4
    % set the node type
    path = {id, PrintPathPart('.', 'type')};
    SetSceneValue(idMap, path, subclass, true, '=');
end

% Add an object configuration of a given flavor to the DOM.
function addConfiguration(idMap, id, flavor, name, type, value)
% make sure the DOM has a node for this object
checkDOMNode(idMap, id, 'merge');

% set the property "name" and "type" attributes
path = {id, ...
    PrintPathPart(':', flavor, 'name', name), ...
    PrintPathPart('.', 'type')};
SetSceneValue(idMap, path, type, true, '=');

% set the property value
path = {id, ...
    PrintPathPart(':', flavor, 'name', name)};
SetSceneValue(idMap, path, value, true, '=');


text:
from parsel import Selector
from utils import download, get_last_part_url, catch_errors
from data import VideoContent, ImageContent, Meme, Author, Tag, Page
from json import loads
import html
import re

ROOT = "https://9gag.com"
NEXT_CURSOR = re.compile("after=(.+)&c=(\\d+)")

def scrap(url, nsfw=False):
    data = download(url)
    return parse(data, nsfw=nsfw)

def parse(raw, nsfw=False):
    json = loads(raw)
    posts = json["data"]["posts"]
    memes = [catch_errors(parse_meme, post) for post in posts]
    memes = [meme for meme in memes if meme is not None]

    next_page_url = None
    result = NEXT_CURSOR.match(json["data"]["nextCursor"])
    if result:
        if nsfw is True:
            next_page_url = "/9gagnsfw/page/" + result.group(1)
        else:
            next_page_url = "/9gag/page/" + result.group(1)

    return Page(None, memes, next_page_url)

def parse_meme(m):
    title = html.unescape(m["title"])
    url = m["url"]

    comment_count = int(m["commentsCount"])
    points = int(m["upVoteCount"]) - int(m["downVoteCount"])
    tags = [Tag(tag["key"], ROOT + tag["url"]) for tag in m["tags"]]

    content = None

    # Determine type
    t = m["type"]
    if t == "Animated":
        for k, v in m["images"].items():
            if "duration" in v:
                content = VideoContent(v["url"])
    else:
        src = m["images"]["image700"]["url"]
        content = ImageContent(src)

    return Meme(
        title,
        url,
        "/9gag/{}".format(get_last_part_url(url)),
        content,
        None,
        tags,
        points,
        comment_count,
    )


text:
> Message box Layouts

## MessageBoxLayout1 Properties

| propName | propType | defaultValue | isRequired | description |
|----------|----------|--------------|------------|-------------|
| title	 | Node | - | + | Title for Messag Box |
| content | Node | - | + | Content of the Message Box |
| primaryButtonLabel | string | - | + | Primary Button Label |
| secondaryButtonLabel | string | - | - | Secondary Button Label |
| onPrimaryButtonClick | func | - | - | Primary Button Click callback |
| onSecondaryButtonClick | func | - | - | Secondary Button Click handler |
| imageUrl | string | - | - | Header image url |
| onClose | func | - | + | Close callback |

## MessageBoxLayout2 Properties

| propName | propType | defaultValue | isRequired | description |
|----------|----------|--------------|------------|-------------|
| hideFooter | bool | - | - | Hide or show footer |
| confirmText | string | - | - | Confirm button Label |
| cancelText | string | - | - | Cancel button Label |
| theme | string | - | - | theme of the message box, (green, blue , red) |
| onOk | func | - | - | Ok callback |
| onCancel | func | - | - | Cancel callback |
| title | Node | - | - | title of the Message Box |
| children | array | - | - | Message box content |


text:
package com.impetus.kundera.datatypes.datagenerator;

import java.sql.Date;

public class SqlDateDataGenerator implements DataGenerator<Date>
{

    private static final Long LONG = new Long(123456789);

    @Override
    public Date randomValue()
    {

        return new Date(LONG);
    }

    @Override
    public Date maxValue()
    {

        return new Date(Long.MAX_VALUE);
    }

    @Override
    public Date minValue()
    {

        return new Date(0L);
    }

    @Override
    public Date partialValue()
    {

        return null;
    }

}


text:
package com.quadbits.gdxhelper.scenemodel;

/**
 *
 */
public class AssetsScaleMinOperatorModel extends AssetsScaleOperatorModel {
}


text:
class Hash
  def deep_find(key, object=self, found=nil)
    if object.respond_to?(:key?) && object.key?(key)
      return object[key]
    elsif object.is_a? Enumerable
      object.find { |*a| found = deep_find(key, a.last) }
      return found
    end
  end
end


text:
<?php
/**
 *
 */

namespace Mvc5\Service\Config\Hydrator;

use Mvc5\Service\Resolver\Resolvable;

class Hydrator
    implements Resolvable, ServiceHydrator
{
    /**
     *
     */
    use Base;
}