text:
from os.path import join, dirname

import numpy as np
from numpy.testing import assert_array_almost_equal, assert_equal
import pytest
from pytest import raises as assert_raises

from scipy.fftpack.realtransforms import (
    dct, idct, dst, idst, dctn, idctn, dstn, idstn)

# Matlab reference data
MDATA = np.load(join(dirname(__file__), 'test.npz'))
X = [MDATA['x%d' % i] for i in range(8)]
Y = [MDATA['y%d' % i] for i in range(8)]

# FFTW reference data: the data are organized as follows:
#    * SIZES is an array containing all available sizes
#    * for every type (1, 2, 3, 4) and every size, the array dct_type_size
#    contains the output of the DCT applied to the input np.linspace(0, size-1,
#    size)
FFTWDATA_DOUBLE = np.load(join(dirname(__file__), 'fftw_double_ref.npz'))
FFTWDATA_SINGLE = np.load(join(dirname(__file__), 'fftw_single_ref.npz'))
FFTWDATA_SIZES = FFTWDATA_DOUBLE['sizes']

def fftw_dct_ref(type, size, dt):
    x = np.linspace(0, size-1, size).astype(dt)
    dt = np.result_type(np.float32, dt)
    if dt == np.double:
        data = FFTWDATA_DOUBLE
    elif dt == np.float32:
        data = FFTWDATA_SINGLE
    else:
        raise ValueError()
    y = (data['dct_%d_%d' % (type, size)]).astype(dt)
    return x, y, dt

def fftw_dst_ref(type, size, dt):
    x = np.linspace(0, size-1, size).astype(dt)
    dt = np.result_type(np.float32, dt)
    if dt == np.double:
        data = FFTWDATA_DOUBLE
    elif dt == np.float32:
        data = FFTWDATA_SINGLE
    else:
        raise ValueError()
    y = (data['dst_%d_%d' % (type, size)]).astype(dt)
    return x, y, dt

def dct_2d_ref(x, **kwargs):
    """Calculate reference values for testing dct2."""
    x = np.array(x, copy=True)
    for row in range(x.shape[0]):
        x[row, :] = dct(x[row, :], **kwargs)
    for col in range(x.shape[1]):
        x[:, col] = dct(x[:, col], **kwargs)
    return x

def idct_2d_ref(x, **kwargs):
    """Calculate reference values for testing idct2."""
    x = np.array(x, copy=True)
    for row in range(x.shape[0]):
        x[row, :] = idct(x[row, :], **kwargs)
    for col in range(x.shape[1]):
        x[:, col] = idct(x[:, col], **kwargs)
    return x

def dst_2d_ref(x, **kwargs):
    """Calculate reference values for testing dst2."""
    x = np.array(x, copy=True)
    for row in range(x.shape[0]):
        x[row, :] = dst(x[row, :], **kwargs)
    for col in range(x.shape[1]):
        x[:, col] = dst(x[:, col], **kwargs)
    return x

def idst_2d_ref(x, **kwargs):
    """Calculate reference values for testing idst2."""
    x = np.array(x, copy=True)
    for row in range(x.shape[0]):
        x[row, :] = idst(x[row, :], **kwargs)
    for col in range(x.shape[1]):
        x[:, col] = idst(x[:, col], **kwargs)
    return x

def naive_dct1(x, norm=None):
    """Calculate textbook definition version of DCT-I."""
    x = np.array(x, copy=True)
    N = len(x)
    M = N-1
    y = np.zeros(N)
    m0, m = 1, 2
    if norm == 'ortho':
        m0 = np.sqrt(1.0/M)
        m = np.sqrt(2.0/M)
    for k in range(N):
        for n in range(1, N-1):
            y[k] += m*x[n]*np.cos(np.pi*n*k/M)
        y[k] += m0 * x[0]
        y[k] += m0 * x[N-1] * (1 if k % 2 == 0 else -1)
    if norm == 'ortho':
        y[0] *= 1/np.sqrt(2)
        y[N-1] *= 1/np.sqrt(2)
    return y

def naive_dst1(x, norm=None):
    """Calculate textbook definition version  of DST-I."""
    x = np.array(x, copy=True)
    N = len(x)
    M = N+1
    y = np.zeros(N)
    for k in range(N):
        for n in range(N):
            y[k] += 2*x[n]*np.sin(np.pi*(n+1.0)*(k+1.0)/M)
    if norm == 'ortho':
        y *= np.sqrt(0.5/M)
    return y

def naive_dct4(x, norm=None):
    """Calculate textbook definition version of DCT-IV."""
    x = np.array(x, copy=True)
    N = len(x)
    y = np.zeros(N)
    for k in range(N):
        for n in range(N):
            y[k] += x[n]*np.cos(np.pi*(n+0.5)*(k+0.5)/(N))
    if norm == 'ortho':
        y *= np.sqrt(2.0/N)
    else:
        y *= 2
    return y

def naive_dst4(x, norm=None):
    """Calculate textbook definition version of DST-IV."""
    x = np.array(x, copy=True)
    N = len(x)
    y = np.zeros(N)
    for k in range(N):
        for n in range(N):
            y[k] += x[n]*np.sin(np.pi*(n+0.5)*(k+0.5)/(N))
    if norm == 'ortho':
        y *= np.sqrt(2.0/N)
    else:
        y *= 2
    return y

class TestComplex(object):
    def test_dct_complex64(self):
        y = dct(1j*np.arange(5, dtype=np.complex64))
        x = 1j*dct(np.arange(5))
        assert_array_almost_equal(x, y)

    def test_dct_complex(self):
        y = dct(np.arange(5)*1j)
        x = 1j*dct(np.arange(5))
        assert_array_almost_equal(x, y)

    def test_idct_complex(self):
        y = idct(np.arange(5)*1j)
        x = 1j*idct(np.arange(5))
        assert_array_almost_equal(x, y)

    def test_dst_complex64(self):
        y = dst(np.arange(5, dtype=np.complex64)*1j)
        x = 1j*dst(np.arange(5))
        assert_array_almost_equal(x, y)

    def test_dst_complex(self):
        y = dst(np.arange(5)*1j)
        x = 1j*dst(np.arange(5))
        assert_array_almost_equal(x, y)

    def test_idst_complex(self):
        y = idst(np.arange(5)*1j)
        x = 1j*idst(np.arange(5))
        assert_array_almost_equal(x, y)

class _TestDCTBase(object):
    def setup_method(self):
        self.rdt = None
        self.dec = 14
        self.type = None

    def test_definition(self):
        for i in FFTWDATA_SIZES:
            x, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
            y = dct(x, type=self.type)
            assert_equal(y.dtype, dt)
            # XXX: we divide by np.max(y) because the tests fail otherwise. We
            # should really use something like assert_array_approx_equal. The
            # difference is due to fftw using a better algorithm w.r.t error
            # propagation compared to the ones from fftpack.
            assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
                    err_msg="Size %d failed" % i)

    def test_axis(self):
        nt = 2
        for i in [7, 8, 9, 16, 32, 64]:
            x = np.random.randn(nt, i)
            y = dct(x, type=self.type)
            for j in range(nt):
                assert_array_almost_equal(y[j], dct(x[j], type=self.type),
                        decimal=self.dec)

            x = x.T
            y = dct(x, axis=0, type=self.type)
            for j in range(nt):
                assert_array_almost_equal(y[:,j], dct(x[:,j], type=self.type),
                        decimal=self.dec)

class _TestDCTIBase(_TestDCTBase):
    def test_definition_ortho(self):
        # Test orthornomal mode.
        for i in range(len(X)):
            x = np.array(X[i], dtype=self.rdt)
            dt = np.result_type(np.float32, self.rdt)
            y = dct(x, norm='ortho', type=1)
            y2 = naive_dct1(x, norm='ortho')
            assert_equal(y.dtype, dt)
            assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)

class _TestDCTIIBase(_TestDCTBase):
    def test_definition_matlab(self):
        # Test correspondence with MATLAB (orthornomal mode).
        for i in range(len(X)):
            dt = np.result_type(np.float32, self.rdt)
            x = np.array(X[i], dtype=dt)

            yr = Y[i]
            y = dct(x, norm="ortho", type=2)
            assert_equal(y.dtype, dt)
            assert_array_almost_equal(y, yr, decimal=self.dec)

class _TestDCTIIIBase(_TestDCTBase):
    def test_definition_ortho(self):
        # Test orthornomal mode.
        for i in range(len(X)):
            x = np.array(X[i], dtype=self.rdt)
            dt = np.result_type(np.float32, self.rdt)
            y = dct(x, norm='ortho', type=2)
            xi = dct(y, norm="ortho", type=3)
            assert_equal(xi.dtype, dt)
            assert_array_almost_equal(xi, x, decimal=self.dec)

class _TestDCTIVBase(_TestDCTBase):
    def test_definition_ortho(self):
        # Test orthornomal mode.
        for i in range(len(X)):
            x = np.array(X[i], dtype=self.rdt)
            dt = np.result_type(np.float32, self.rdt)
            y = dct(x, norm='ortho', type=4)
            y2 = naive_dct4(x, norm='ortho')
            assert_equal(y.dtype, dt)
            assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)

class TestDCTIDouble(_TestDCTIBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 10
        self.type = 1

class TestDCTIFloat(_TestDCTIBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 4
        self.type = 1

class TestDCTIInt(_TestDCTIBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 5
        self.type = 1

class TestDCTIIDouble(_TestDCTIIBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 10
        self.type = 2

class TestDCTIIFloat(_TestDCTIIBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 5
        self.type = 2

class TestDCTIIInt(_TestDCTIIBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 5
        self.type = 2

class TestDCTIIIDouble(_TestDCTIIIBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 14
        self.type = 3

class TestDCTIIIFloat(_TestDCTIIIBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 5
        self.type = 3

class TestDCTIIIInt(_TestDCTIIIBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 5
        self.type = 3

class TestDCTIVDouble(_TestDCTIVBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 12
        self.type = 3

class TestDCTIVFloat(_TestDCTIVBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 5
        self.type = 3

class TestDCTIVInt(_TestDCTIVBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 5
        self.type = 3

class _TestIDCTBase(object):
    def setup_method(self):
        self.rdt = None
        self.dec = 14
        self.type = None

    def test_definition(self):
        for i in FFTWDATA_SIZES:
            xr, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
            x = idct(yr, type=self.type)
            if self.type == 1:
                x /= 2 * (i-1)
            else:
                x /= 2 * i
            assert_equal(x.dtype, dt)
            # XXX: we divide by np.max(y) because the tests fail otherwise. We
            # should really use something like assert_array_approx_equal. The
            # difference is due to fftw using a better algorithm w.r.t error
            # propagation compared to the ones from fftpack.
            assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
                    err_msg="Size %d failed" % i)

class TestIDCTIDouble(_TestIDCTBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 10
        self.type = 1

class TestIDCTIFloat(_TestIDCTBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 4
        self.type = 1

class TestIDCTIInt(_TestIDCTBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 4
        self.type = 1

class TestIDCTIIDouble(_TestIDCTBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 10
        self.type = 2

class TestIDCTIIFloat(_TestIDCTBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 5
        self.type = 2

class TestIDCTIIInt(_TestIDCTBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 5
        self.type = 2

class TestIDCTIIIDouble(_TestIDCTBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 14
        self.type = 3

class TestIDCTIIIFloat(_TestIDCTBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 5
        self.type = 3

class TestIDCTIIIInt(_TestIDCTBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 5
        self.type = 3

class TestIDCTIVDouble(_TestIDCTBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 12
        self.type = 4

class TestIDCTIVFloat(_TestIDCTBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 5
        self.type = 4

class TestIDCTIVInt(_TestIDCTBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 5
        self.type = 4

class _TestDSTBase(object):
    def setup_method(self):
        self.rdt = None  # dtype
        self.dec = None  # number of decimals to match
        self.type = None  # dst type

    def test_definition(self):
        for i in FFTWDATA_SIZES:
            xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
            y = dst(xr, type=self.type)
            assert_equal(y.dtype, dt)
            # XXX: we divide by np.max(y) because the tests fail otherwise. We
            # should really use something like assert_array_approx_equal. The
            # difference is due to fftw using a better algorithm w.r.t error
            # propagation compared to the ones from fftpack.
            assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
                    err_msg="Size %d failed" % i)

class _TestDSTIBase(_TestDSTBase):
    def test_definition_ortho(self):
        # Test orthornomal mode.
        for i in range(len(X)):
            x = np.array(X[i], dtype=self.rdt)
            dt = np.result_type(np.float32, self.rdt)
            y = dst(x, norm='ortho', type=1)
            y2 = naive_dst1(x, norm='ortho')
            assert_equal(y.dtype, dt)
            assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)

class _TestDSTIVBase(_TestDSTBase):
    def test_definition_ortho(self):
        # Test orthornomal mode.
        for i in range(len(X)):
            x = np.array(X[i], dtype=self.rdt)
            dt = np.result_type(np.float32, self.rdt)
            y = dst(x, norm='ortho', type=4)
            y2 = naive_dst4(x, norm='ortho')
            assert_equal(y.dtype, dt)
            assert_array_almost_equal(y, y2, decimal=self.dec)

class TestDSTIDouble(_TestDSTIBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 12
        self.type = 1

class TestDSTIFloat(_TestDSTIBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 4
        self.type = 1

class TestDSTIInt(_TestDSTIBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 5
        self.type = 1

class TestDSTIIDouble(_TestDSTBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 14
        self.type = 2

class TestDSTIIFloat(_TestDSTBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 6
        self.type = 2

class TestDSTIIInt(_TestDSTBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 6
        self.type = 2

class TestDSTIIIDouble(_TestDSTBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 14
        self.type = 3

class TestDSTIIIFloat(_TestDSTBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 7
        self.type = 3

class TestDSTIIIInt(_TestDSTBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 7
        self.type = 3

class TestDSTIVDouble(_TestDSTIVBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 12
        self.type = 4

class TestDSTIVFloat(_TestDSTIVBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 4
        self.type = 4

class TestDSTIVInt(_TestDSTIVBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 5
        self.type = 4

class _TestIDSTBase(object):
    def setup_method(self):
        self.rdt = None
        self.dec = None
        self.type = None

    def test_definition(self):
        for i in FFTWDATA_SIZES:
            xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
            x = idst(yr, type=self.type)
            if self.type == 1:
                x /= 2 * (i+1)
            else:
                x /= 2 * i
            assert_equal(x.dtype, dt)
            # XXX: we divide by np.max(x) because the tests fail otherwise. We
            # should really use something like assert_array_approx_equal. The
            # difference is due to fftw using a better algorithm w.r.t error
            # propagation compared to the ones from fftpack.
            assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
                    err_msg="Size %d failed" % i)

class TestIDSTIDouble(_TestIDSTBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 12
        self.type = 1

class TestIDSTIFloat(_TestIDSTBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 4
        self.type = 1

class TestIDSTIInt(_TestIDSTBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 4
        self.type = 1

class TestIDSTIIDouble(_TestIDSTBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 14
        self.type = 2

class TestIDSTIIFloat(_TestIDSTBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 6
        self.type = 2

class TestIDSTIIInt(_TestIDSTBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 6
        self.type = 2

class TestIDSTIIIDouble(_TestIDSTBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 14
        self.type = 3

class TestIDSTIIIFloat(_TestIDSTBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 6
        self.type = 3

class TestIDSTIIIInt(_TestIDSTBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 6
        self.type = 3

class TestIDSTIVDouble(_TestIDSTBase):
    def setup_method(self):
        self.rdt = np.double
        self.dec = 12
        self.type = 4

class TestIDSTIVFloat(_TestIDSTBase):
    def setup_method(self):
        self.rdt = np.float32
        self.dec = 6
        self.type = 4

class TestIDSTIVnt(_TestIDSTBase):
    def setup_method(self):
        self.rdt = int
        self.dec = 6
        self.type = 4

class TestOverwrite(object):
    """Check input overwrite behavior."""

    real_dtypes = [np.float32, np.float64]

    def _check(self, x, routine, type, fftsize, axis, norm, overwrite_x, **kw):
        x2 = x.copy()
        routine(x2, type, fftsize, axis, norm, overwrite_x=overwrite_x)

        sig = "%s(%s%r, %r, axis=%r, overwrite_x=%r)" % (
            routine.__name__, x.dtype, x.shape, fftsize, axis, overwrite_x)
        if not overwrite_x:
            assert_equal(x2, x, err_msg="spurious overwrite in %s" % sig)

    def _check_1d(self, routine, dtype, shape, axis):
        np.random.seed(1234)
        if np.issubdtype(dtype, np.complexfloating):
            data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
        else:
            data = np.random.randn(*shape)
        data = data.astype(dtype)

        for type in [1, 2, 3, 4]:
            for overwrite_x in [True, False]:
                for norm in [None, 'ortho']:
                    self._check(data, routine, type, None, axis, norm,
                                overwrite_x)

    def test_dct(self):
        for dtype in self.real_dtypes:
            self._check_1d(dct, dtype, (16,), -1)
            self._check_1d(dct, dtype, (16, 2), 0)
            self._check_1d(dct, dtype, (2, 16), 1)

    def test_idct(self):
        for dtype in self.real_dtypes:
            self._check_1d(idct, dtype, (16,), -1)
            self._check_1d(idct, dtype, (16, 2), 0)
            self._check_1d(idct, dtype, (2, 16), 1)

    def test_dst(self):
        for dtype in self.real_dtypes:
            self._check_1d(dst, dtype, (16,), -1)
            self._check_1d(dst, dtype, (16, 2), 0)
            self._check_1d(dst, dtype, (2, 16), 1)

    def test_idst(self):
        for dtype in self.real_dtypes:
            self._check_1d(idst, dtype, (16,), -1)
            self._check_1d(idst, dtype, (16, 2), 0)
            self._check_1d(idst, dtype, (2, 16), 1)

class Test_DCTN_IDCTN(object):
    dec = 14
    dct_type = [1, 2, 3, 4]
    norms = [None, 'ortho']
    rstate = np.random.RandomState(1234)
    shape = (32, 16)
    data = rstate.randn(*shape)

    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
                                                   (dstn, idstn)])
    @pytest.mark.parametrize('axes', [None,
                                      1, (1,), [1],
                                      0, (0,), [0],
                                      (0, 1), [0, 1],
                                      (-2, -1), [-2, -1]])
    @pytest.mark.parametrize('dct_type', dct_type)
    @pytest.mark.parametrize('norm', ['ortho'])
    def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm):
        tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm)
        tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm)
        assert_array_almost_equal(self.data, tmp, decimal=12)

    @pytest.mark.parametrize('fforward,fforward_ref', [(dctn, dct_2d_ref),
                                                       (dstn, dst_2d_ref)])
    @pytest.mark.parametrize('dct_type', dct_type)
    @pytest.mark.parametrize('norm', norms)
    def test_dctn_vs_2d_reference(self, fforward, fforward_ref,
                                  dct_type, norm):
        y1 = fforward(self.data, type=dct_type, axes=None, norm=norm)
        y2 = fforward_ref(self.data, type=dct_type, norm=norm)
        assert_array_almost_equal(y1, y2, decimal=11)

    @pytest.mark.parametrize('finverse,finverse_ref', [(idctn, idct_2d_ref),
                                                       (idstn, idst_2d_ref)])
    @pytest.mark.parametrize('dct_type', dct_type)
    @pytest.mark.parametrize('norm', [None, 'ortho'])
    def test_idctn_vs_2d_reference(self, finverse, finverse_ref,
                                   dct_type, norm):
        fdata = dctn(self.data, type=dct_type, norm=norm)
        y1 = finverse(fdata, type=dct_type, norm=norm)
        y2 = finverse_ref(fdata, type=dct_type, norm=norm)
        assert_array_almost_equal(y1, y2, decimal=11)

    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
                                                   (dstn, idstn)])
    def test_axes_and_shape(self, fforward, finverse):
        with assert_raises(ValueError,
                           match="when given, axes and shape arguments"
                           " have to be of the same length"):
            fforward(self.data, shape=self.data.shape[0], axes=(0, 1))

        with assert_raises(ValueError,
                           match="when given, axes and shape arguments"
                           " have to be of the same length"):
            fforward(self.data, shape=self.data.shape[0], axes=None)

        with assert_raises(ValueError,
                           match="when given, axes and shape arguments"
                           " have to be of the same length"):
            fforward(self.data, shape=self.data.shape, axes=0)

    @pytest.mark.parametrize('fforward', [dctn, dstn])
    def test_shape(self, fforward):
        tmp = fforward(self.data, shape=(128, 128), axes=None)
        assert_equal(tmp.shape, (128, 128))

    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
                                                   (dstn, idstn)])
    @pytest.mark.parametrize('axes', [1, (1,), [1],
                                      0, (0,), [0]])
    def test_shape_is_none_with_axes(self, fforward, finverse, axes):
        tmp = fforward(self.data, shape=None, axes=axes, norm='ortho')
        tmp = finverse(tmp, shape=None, axes=axes, norm='ortho')
        assert_array_almost_equal(self.data, tmp, decimal=self.dec)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using Granular.Collections;
using System.Windows;

namespace Granular.Presentation.Tests.Threading
{
    public class TestTaskScheduler : ITaskScheduler
    {
        private class CancellableAction
        {
            public TimeSpan TimeSpan { get; private set; }

            private Action action;
            private bool isCancelled;

            public CancellableAction(TimeSpan timeSpan, Action action)
            {
                this.TimeSpan = timeSpan;
                this.action = action;
            }

            public void Cancel()
            {
                isCancelled = true;
            }

            public void Invoke()
            {
                if (!isCancelled)
                {
                    action();
                }
            }
        }

        public TimeSpan CurrentTime { get; private set; }

        private List<CancellableAction> actions;
        private bool isImmediateProcessingDisabled;
        private bool isProcessing;

        public TestTaskScheduler()
        {
            this.actions = new List<CancellableAction>();
        }

        public IDisposable ScheduleTask(TimeSpan timeSpan, Action action)
        {
            CancellableAction cancellableAction = new CancellableAction(CurrentTime + timeSpan, action);
            EnqueueAction(cancellableAction);

            if (timeSpan == TimeSpan.Zero && !isProcessing && !isImmediateProcessingDisabled)
            {
                ProcessDueOperations();
            }

            return new Disposable(() => cancellableAction.Cancel());
        }

        public void AdvanceBy(TimeSpan timeSpan)
        {
            if (timeSpan < TimeSpan.Zero)
            {
                throw new Granular.Exception("Time must be positive");
            }

            AdvanceTo(CurrentTime + timeSpan);
        }

        public void AdvanceTo(TimeSpan time)
        {
            if (time < CurrentTime)
            {
                throw new Granular.Exception("Time must larger than CurrentTime");
            }

            while (actions.Count > 0 && actions.First().TimeSpan <= time)
            {
                CurrentTime = actions.First().TimeSpan;
                ProcessDueOperations();
            }

            CurrentTime = time;
        }

        public void ProcessDueOperations()
        {
            isProcessing = true;

            while (actions.Count > 0 && actions.First().TimeSpan <= CurrentTime)
            {
                DequeueAction().Invoke();
            }

            isProcessing = false;
        }

        public IDisposable DisableImmediateProcessing()
        {
            if (isImmediateProcessingDisabled)
            {
                throw new Granular.Exception("Immediate processing is already disabled");
            }

            isImmediateProcessingDisabled = true;
            return new Disposable(() =>
            {
                isImmediateProcessingDisabled = false;
                ProcessDueOperations();
            });
        }

        private void EnqueueAction(CancellableAction cancellableAction)
        {
            int i = 0;
            foreach (CancellableAction action in actions)
            {
                if (cancellableAction.TimeSpan < action.TimeSpan)
                {
                    break;
                }

                i++;
            }

            actions.Insert(i, cancellableAction);
        }

        private CancellableAction DequeueAction()
        {
            CancellableAction cancellableAction = actions[0];
            actions.RemoveAt(0);
            return cancellableAction;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package flowreader.utils;

import flowreader.model.PDFPage;
import flowreader.model.Page;
import flowreader.view.PDFPageView;
import flowreader.view.PageView;
import flowreader.view.TextPageView;

/**
 * Factory that creates page object depending on the file type
 * @author D-Day
 */
public  class PageViewFactory {

    /**
     *
     * @param page
     * @return the corresponding pageView
     */
    public static PageView getPageView(Page page){
        if(page instanceof PDFPage){
            return new PDFPageView((PDFPage)page);
        }
        else{
            return new TextPageView(page);
        }

    }

}


text:
import { shallowMount } from '@vue/test-utils';
import KGrid from '../../src/views/KGrid';

function makeWrapper(options) {
  return shallowMount(KGrid, options);
}

function getGrid(wrapper) {
  return wrapper.find('.pure-g');
}

describe('KGrid component', () => {
  it('should have a "pure-g" grid element', () => {
    const wrapper = makeWrapper({ propsData: {} });
    expect(getGrid(wrapper).exists()).toEqual(true);
  });
  it('grid should have a -12px offset on large screens', () => {
    const wrapper = makeWrapper({ propsData: {} });
    wrapper.vm._updateWindow({ width: 900, height: 900 });
    expect(wrapper.vm.actualGutterSize).toEqual(24);
    expect(getGrid(wrapper).element.style['margin-left']).toEqual('-12px');
    expect(getGrid(wrapper).element.style['margin-right']).toEqual('-12px');
  });
  it('grid should have a -8px offset on small screens', () => {
    const wrapper = makeWrapper({ propsData: {} });
    wrapper.vm._updateWindow({ width: 400, height: 400 });
    expect(wrapper.vm.actualGutterSize).toEqual(16);
    expect(getGrid(wrapper).element.style['margin-left']).toEqual('-8px');
    expect(getGrid(wrapper).element.style['margin-right']).toEqual('-8px');
  });
  it('grid should have a -8px offset on wide, short screens', () => {
    const wrapper = makeWrapper({ propsData: {} });
    wrapper.vm._updateWindow({ width: 900, height: 500 });
    expect(wrapper.vm.actualGutterSize).toEqual(16);
    expect(getGrid(wrapper).element.style['margin-left']).toEqual('-8px');
    expect(getGrid(wrapper).element.style['margin-right']).toEqual('-8px');
  });
  it('grid should have a -5px offset when 10px gutters are specified', () => {
    const wrapper = makeWrapper({ propsData: { gutter: 10 } });
    expect(wrapper.vm.actualGutterSize).toEqual(10);
    expect(getGrid(wrapper).element.style['margin-left']).toEqual('-5px');
    expect(getGrid(wrapper).element.style['margin-right']).toEqual('-5px');
  });
  it('grid should have 4 columns on small screens', () => {
    const wrapper = makeWrapper({ propsData: {} });
    wrapper.vm._updateWindow({ width: 400, height: 400 });
    expect(wrapper.vm.windowIsSmall).toEqual(true);
    expect(wrapper.vm.windowIsMedium).toEqual(false);
    expect(wrapper.vm.windowIsLarge).toEqual(false);
    expect(wrapper.vm.actualNumCols).toEqual(4);
  });
  it('grid should have 8 columns on medium screens', () => {
    const wrapper = makeWrapper({ propsData: {} });
    wrapper.vm._updateWindow({ width: 700, height: 700 });
    expect(wrapper.vm.windowIsSmall).toEqual(false);
    expect(wrapper.vm.windowIsMedium).toEqual(true);
    expect(wrapper.vm.windowIsLarge).toEqual(false);
    expect(wrapper.vm.actualNumCols).toEqual(8);
  });
  it('grid should have 12 columns on large screens', () => {
    const wrapper = makeWrapper({ propsData: {} });
    wrapper.vm._updateWindow({ width: 900, height: 900 });
    expect(wrapper.vm.windowIsSmall).toEqual(false);
    expect(wrapper.vm.windowIsMedium).toEqual(false);
    expect(wrapper.vm.windowIsLarge).toEqual(true);
    expect(wrapper.vm.actualNumCols).toEqual(12);
  });
  it('grid should allow a custom number of columns', () => {
    const wrapper = makeWrapper({ propsData: { cols: 7 } });
    expect(wrapper.vm.actualNumCols).toEqual(7);
  });
});


text:
package gocql

import (
	"context"
	"time"
)

type ExecutableQuery interface {
	execute(ctx context.Context, conn *Conn) *Iter
	attempt(keyspace string, end, start time.Time, iter *Iter, host *HostInfo)
	retryPolicy() DualRetryPolicy
	speculativeExecutionPolicy() SpeculativeExecutionPolicy
	GetRoutingKey() ([]byte, error)
	Keyspace() string
	IsIdempotent() bool

	withContext(context.Context) ExecutableQuery

	RetryableQuery
}

type queryExecutor struct {
	pool   *policyConnPool
	policy HostSelectionPolicy
}

func (q *queryExecutor) attemptQuery(ctx context.Context, qry ExecutableQuery, conn *Conn) *Iter {
	start := time.Now()
	iter := qry.execute(ctx, conn)
	end := time.Now()

	qry.attempt(q.pool.keyspace, end, start, iter, conn.host)

	return iter
}

func (q *queryExecutor) speculate(ctx context.Context, qry ExecutableQuery, sp SpeculativeExecutionPolicy, results chan *Iter) *Iter {
	ticker := time.NewTicker(sp.Delay())
	defer ticker.Stop()

	for i := 0; i < sp.Attempts(); i++ {
		select {
		case <-ticker.C:
			go q.run(ctx, qry, results)
		case <-ctx.Done():
			return &Iter{err: ctx.Err()}
		case iter := <-results:
			return iter
		}
	}

	return nil
}

func (q *queryExecutor) executeQuery(qry ExecutableQuery) (*Iter, error) {
	// check if the query is not marked as idempotent, if
	// it is, we force the policy to NonSpeculative
	sp := qry.speculativeExecutionPolicy()
	if !qry.IsIdempotent() || sp.Attempts() == 0 {
		return q.do(qry.Context(), qry), nil
	}

	ctx, cancel := context.WithCancel(qry.Context())
	defer cancel()

	results := make(chan *Iter, 1)

	// Launch the main execution
	go q.run(ctx, qry, results)

	// The speculative executions are launched _in addition_ to the main
	// execution, on a timer. So Speculation{2} would make 3 executions running
	// in total.
	if iter := q.speculate(ctx, qry, sp, results); iter != nil {
		return iter, nil
	}

	select {
	case iter := <-results:
		return iter, nil
	case <-ctx.Done():
		return &Iter{err: ctx.Err()}, nil
	}
}

func (q *queryExecutor) do(ctx context.Context, qry ExecutableQuery) *Iter {
	hostIter := q.policy.Pick(qry)
	selectedHost := hostIter()
	rt := qry.retryPolicy()

	var lastErr error
	var iter *Iter
	for selectedHost != nil {
		host := selectedHost.Info()
		if host == nil || !host.IsUp() {
			selectedHost = hostIter()
			continue
		}

		pool, ok := q.pool.getPool(host)
		if !ok {
			selectedHost = hostIter()
			continue
		}

		conn := pool.Pick(selectedHost.Token())
		if conn == nil {
			selectedHost = hostIter()
			continue
		}

		iter = q.attemptQuery(ctx, qry, conn)
		iter.host = selectedHost.Info()
		// Update host
		switch iter.err {
		case context.Canceled, context.DeadlineExceeded, ErrNotFound:
			// those errors represents logical errors, they should not count
			// toward removing a node from the pool
			selectedHost.Mark(nil)
			return iter
		default:
			selectedHost.Mark(iter.err)
		}

		// Exit if the query was successful
		// or no retry policy defined or retry attempts were reached
		if iter.err == nil || rt == nil {
			return iter
		}
		lastErr = iter.err

		// If query is unsuccessful, check the error with RetryPolicy to retry
		switch rt.AttemptWithError(qry, iter.err) {
		case Retry:
			// retry on the same host
			continue
		case Rethrow, Ignore:
			return iter
		case RetryNextHost:
			// retry on the next host
			selectedHost = hostIter()
			continue
		default:
			// Undefined? Return nil and error, this will panic in the requester
			return &Iter{err: ErrUnknownRetryType}
		}
	}

	if lastErr != nil {
		return &Iter{err: lastErr}
	}

	return &Iter{err: ErrNoConnections}
}

func (q *queryExecutor) run(ctx context.Context, qry ExecutableQuery, results chan<- *Iter) {
	select {
	case results <- q.do(ctx, qry):
	case <-ctx.Done():
	}
}


text:
var firstName = "Alana"
var lastName = "Farkas"
console.log(firstName + " " + lastName)

// Write a short program that asks for a user to input their favorite food. After they hit return, have the program respond with "Hey! That's my favorite too!" Paste your program into the eloquent.js file.

prompt("Hey you! What's your fav food in the whole world?");
confirm("That's my favorite food too!");

// Complete one of the exercises: Looping a Triangle, FizzBuzz, or Chess Board

for (var number = 1; number <= 100; number = number + 1) {
  if (number % 3 === 0 && number % 5 == 0) {
  console.log("FizzBuzz");
}

  else if (number % 3 === 0) {
    console.log("Fizz");
}
else if (number % 5 == 0) {
  console.log("Buzz");
}
else {
console.log(number);
  }
}

// Functions

// Complete the `minimum` exercise.

function minimum(x, y) {
  console.log(Math.min(x, y))
}

minimum(19, 99)

// Data Structures: Objects and Arrays
// Create an object called "me" that stores your name, age, 3 favorite foods, and a quirk below.

var me = {name: "Alana", age: 27, favoriteFoods: ["sunflower seeds", "lollipops", "twizzlers"], quirk: "I can wiggle my ears"}


text:
require 'test_helper'

class PriceFieldTest < ActionView::TestCase
  include FormGenerators

  test 'should be a number_field input' do
    concat_form_for_price_field(:user, :price)
    assert_select 'form input[type="number"]'
  end

  test 'has minimum set by default' do
    concat_form_for_price_field(:user, :price)
    assert_select 'input[type="number"][min="0"]'
  end

  test 'allows overwriting minimum' do
    concat_form_for_price_field(:user, :price, min: 10)
    assert_select 'input[type="number"][min="10"]'
  end

  test 'allows negative minimum' do
    concat_form_for_price_field(:user, :price, min: -10)
    assert_select 'input[type="number"][min="-10"]'
  end

  test 'formats output value' do
    concat_form_for_price_field(:user, :price, value: 1)
    assert_select 'input#user_price[value="1.00"]'
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.web.project</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/web-project/3">
            <name>HibernateAndSpring</name>
            <minimum-ant-version>1.6.5</minimum-ant-version>
            <web-module-libraries>
                <library dirs="200">
                    <file>${libs.spring-framework400.classpath}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${libs.jstl.classpath}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${libs.hibernate4-support.classpath}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${libs.jpa2-persistence.classpath}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${file.reference.tiles-api-2.2.1.jar}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${file.reference.tiles-core-2.2.1.jar}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${file.reference.tiles-jsp-2.2.1.jar}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${file.reference.tiles-servlet-2.2.1.jar}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${file.reference.tiles-template-2.2.1.jar}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
            </web-module-libraries>
            <web-module-additional-libraries/>
            <source-roots>
                <root id="src.dir"/>
            </source-roots>
            <test-roots>
                <root id="test.src.dir"/>
            </test-roots>
        </data>
        <spring-data xmlns="http://www.netbeans.org/ns/spring-data/1">
            <config-files>
                <config-file>web/WEB-INF/applicationContext.xml</config-file>
                <config-file>web/WEB-INF/dispatcher-servlet.xml</config-file>
            </config-files>
            <config-file-groups>
                <config-file-group name="Grupo Default">
                    <config-file>web/WEB-INF/applicationContext.xml</config-file>
                    <config-file>web/WEB-INF/dispatcher-servlet.xml</config-file>
                </config-file-group>
            </config-file-groups>
        </spring-data>
    </configuration>
</project>


text:
<?php

namespace Strayobject\CalendarBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="sponsor")
 */
class Sponsor
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @var int
     */
    private $id;
    /**
     * @ORM\Column(type="string", length=200)
     * @var string
     */
    private $name;
    /**
     * @ORM\Column(type="string", length=500)
     * @var string
     */
    private $link;
    /**
     * @ORM\Column(type="string", length=500)
     * @var string
     */
    private $image;
    /**
     * @ORM\ManyToMany(targetEntity="Event", mappedBy="sponsors")
     * @var
     */
    private $events;

    public function __construct()
    {
        $this->events = new ArrayCollection();
    }

    /**
     * Gets the value of id.
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Sets the value of id.
     *
     * @param int $id the id
     *
     * @return self
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * Gets the value of name.
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Sets the value of name.
     *
     * @param string $name the name
     *
     * @return self
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Gets the value of link.
     *
     * @return string
     */
    public function getLink()
    {
        return $this->link;
    }

    /**
     * Sets the value of link.
     *
     * @param string $link the link
     *
     * @return self
     */
    public function setLink($link)
    {
        $this->link = $link;

        return $this;
    }

    /**
     * Gets the value of image.
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Sets the value of image.
     *
     * @param string $image the image
     *
     * @return self
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Gets the value of events.
     *
     * @return mixed
     */
    public function getEvents()
    {
        return $this->events;
    }

    /**
     * Sets the value of events.
     *
     * @param mixed $events the events
     *
     * @return self
     */
    public function setEvents($events)
    {
        $this->events = $events;

        return $this;
    }
}


text:
angular.module('material.core')
.factory('$mdMedia', mdMediaFactory);

/**
 * Exposes a function on the '$mdMedia' service which will return true or false,
 * whether the given media query matches. Re-evaluates on resize. Allows presets
 * for 'sm', 'md', 'lg'.
 *
 * @example $mdMedia('sm') == true if device-width <= sm
 * @example $mdMedia('(min-width: 1200px)') == true if device-width >= 1200px
 * @example $mdMedia('max-width: 300px') == true if device-width <= 300px (sanitizes input, adding parens)
 */
function mdMediaFactory($mdConstant, $rootScope, $window) {
  var queries = {};
  var results = {};

  return $mdMedia;

  function $mdMedia(query) {
    var validated = queries[query];
    if (angular.isUndefined(validated)) {
      validated = queries[query] = validate(query);
    }

    var result = results[validated];
    if (angular.isUndefined(result)) {
      result = add(validated);
    }

    return result;
  }

  function validate(query) {
    return $mdConstant.MEDIA[query] ||
           ((query.charAt(0) !== '(') ? ('(' + query + ')') : query);
  }

  function add(query) {
    var result = $window.matchMedia(query);
    result.addListener(onQueryChange);
    return (results[result.media] = !!result.matches);
  }

  function onQueryChange() {
    var query = this;
    $rootScope.$evalAsync(function() {
      results[query.media] = !!query.matches;
    });
  }

}


text:
<object-stream>
  <com.fatwire.realtime.ResourceDataImpl>
    <id class="string">OpenMarket/Xcelerate/AssetType/Template/ManageSchVars</id>
    <resourceType>ELEMENTCATALOG</resourceType>
    <deps class="empty-set"/>
    <data class="com.openmarket.xcelerate.common.ElementCatalogEntry" serialization="custom">
      <com.openmarket.xcelerate.common.ElementCatalogEntry>
        <int>1</int>
        <string>OpenMarket/Xcelerate/AssetType/Template/ManageSchVars</string>
        <string>Restore  Search  Vars</string>
        <string></string>
        <string></string>
        <string>OpenMarket\Xcelerate\AssetType\Template\ManageSchVars.xml</string>
        <string></string>
        <string></string>
      </com.openmarket.xcelerate.common.ElementCatalogEntry>
    </data>
  </com.fatwire.realtime.ResourceDataImpl>
</object-stream>
<!--==================___ METADATA ___================
<dependencies>
  <list/>
</dependencies>
==================______________________==================
#
#Mon Jan 13 18:18:39 UTC 2014
storable0=/ELEMENTS/OpenMarket/Xcelerate/AssetType/Template/ManageSchVars.xml|null|_storable_type\=%2FELEMENTS%2FOpenMarket%2FXcelerate%2FAssetType%2FTemplate%2FManageSchVars.xml
@hashval=1106479887
key=@ELEMENTCATALOG-OpenMarket/Xcelerate/AssetType/Template/ManageSchVars
type=ELEMENTCATALOG

==================___ END METADATA ___==================-->


text:
Model Data Helper
=================

Model data helper easy the models population introspecting in the django model
fields.

.. py:class:: ModelDataHelper(seed=None)

    Initialize the seed of the instance of model data helper, to allwais
    generate the same data.

.. py:method:: ModelDataHelper.fill_model(model, number, \*args, \*\*kwargs)

    Generate a number of instances of the model and save it. You can overwrite
    the default data generator adding extra kwargs arguments.

    To overwrite a field generation behavior you have to add extra arguments.
    with the name of the field, and the value must be, a fixed value or a
    callable object that receive 2 parameters, the model instance, and a
    SampleDataHelper instance. This overwrite is done alwais at the end of
    fill_model, this mean you can access all auto-generated data in other
    instance fields. This extra arguments can be a named argument using the
    field name as argument name, and the callable as value, or a not named name
    with value a tuple of field name and the callable. Examples::

      fill_model(ModelName, 10, ('field_name', lambda instance, sd: sd.int()))
      fill_model(ModelName, 10, field_name=lambda instance, sd: sd.int())

    The order of field generation is, first the not overwrited fields in any
    order, second the overwrited fields in args, in the same order the
    parameters, and third the overwrited fields in kwargs in any orders. If you
    want to asure the ordering, use the args overwrite.

.. py:method:: ModelDataHelper.fill_model_instance(instance, \*args, \*\*kwargs)

    Fill a instance of a django model. You can overwrite the default data
    generator adding extra arguments like in `fill_model` method. Examples::

      fill_model_instance(instance, ('field_name', lambda instance, sd: sd.int()))
      fill_model_instance(instance, field_name=lambda instance, sd: sd.int())


text:
package play.libs.ws;

import java.io.IOException;

/**
 * This is the WS Client interface.
 */
public interface StandaloneWSClient extends java.io.Closeable {

    /**
     * The underlying implementation of the client, if any.  You must cast the returned value to the type you want.
     *
     * @return the backing class.
     */
    Object getUnderlying();

    /**
     * Returns a StandaloneWSRequest object representing the URL.  You can append additional
     * properties on the StandaloneWSRequest by chaining calls, and execute the request to
     * return an asynchronous {@code CompletionStage<StandaloneWSResponse>}.
     *
     * @param url the URL to request
     * @return the request
     */
    StandaloneWSRequest url(String url);

    /**
     * Closes this client, and releases underlying resources.
     * <p>
     * Use this for manually instantiated clients.
     */
    void close() throws IOException;
}


text:
package com.esotericsoftware.yamlbeans.emitter;

/** @author Nathan Sweet */
public class EmitterException extends RuntimeException {
	public EmitterException (String message) {
		super(message);
	}
}


text:
import genevo as g
import numpy as np
import torch
import array
from ..common import GTestCase

class Owner:
    def __init__(self):
        self.dna_size = 20
        self.population_size = 10
        self.idx = 9

    def make_seed_dna(self):
        result = g.tex.constant(self.idx / 10, self.dna_size)
        self.idx -= 1
        return g.dna.create(result)

    def calculate_fitness(self, dna_tensor):
        mean = torch.mean(dna_tensor, 0) * 10
        bodies = mean.tolist()
        return bodies, mean

class TestPopulation(GTestCase):
    def test_population_fill_and_sort(self):
        owner = Owner()
        pop = g.Population(owner)
        self.assertFalse(pop.sorted)

        with self.assertRaises(RuntimeError):
            pop.sort()

        self.assertEqual(len(pop), 0)
        pop.fill()
        self.assertEqual(len(pop), owner.population_size)
        self.assertEqual(owner.idx, -1)
        self.assertFalse(pop.sorted)

        first = pop.get_organization_and_fitness_at(0, fitness_as_tensor=False)
        self.assertIsInstance(first[0], g.Organization)
        self.assertAlmostEqual(first[0].dna[0], 0.9)
        self.assertIsNone(first[0].body)
        self.assertIsNone(first[1])

        last = pop.get_organization_and_fitness_at(-1, fitness_as_tensor=False)
        self.assertIsInstance(last[0], g.Organization)
        self.assertAlmostEqual(last[0].dna[0], 0)
        self.assertIsNone(last[0].body)
        self.assertIsNone(last[1])

        pop.sort()
        self.assertTrue(pop.sorted)

        def test_sorted():
            first = pop.get_organization_and_fitness_at(0, fitness_as_tensor=False)
            self.assertIsInstance(first[0], g.Organization)
            self.assertAlmostEqual(first[0].dna[0], 0)
            self.assertEqual(round(first[0].body), 0)
            self.assertAlmostEqual(round(first[1]), 0)

            last = pop.get_organization_and_fitness_at(-1, fitness_as_tensor=False)
            self.assertIsInstance(last[0], g.Organization)
            self.assertAlmostEqual(last[0].dna[0], 0.9)
            self.assertEqual(round(last[0].body), 9)
            self.assertAlmostEqual(round(last[1]), 9)

        test_sorted()

        with self.assertRaises(RuntimeError):
            pop.fill()

        with self.assertRaises(RuntimeError):
            pop.sort()

    def test_population_make_crossovered_dna(self):
        owner = Owner()
        pop = g.Population(owner)
        pop.fill()

        with self.assertRaises(RuntimeError):
            pop.make_crossovered_dna()

        pop.sort()

        res = pop.make_crossovered_dna()
        self.assertIsInstance(res, tuple)
        self.assertTrue(torch.is_tensor(res[0]))
        self.assertTrue(torch.is_tensor(res[1]))
        dna_tensor = g.tex.join(1, res[0], res[1])
        self.assertTrue(torch.is_tensor(dna_tensor))
        self.assertEqual(dna_tensor.size(), (owner.dna_size, owner.population_size))

        pop2 = g.Population(owner)
        pop2.push(dna_tensor)
        pop2.sort()

        first = pop2.get_organization_and_fitness_at(0, fitness_as_tensor=False)
        self.assertIsInstance(first[0], g.Organization)
        self.assertAlmostEqual(first[0].dna[0], 0)
        self.assertEqual(round(first[0].body), 0)
        self.assertAlmostEqual(round(first[1]), 0)

    def test_population_make_normal_dist_dna(self):
        owner = Owner()
        pop = g.Population(owner)
        pop.fill()

        with self.assertRaises(RuntimeError):
            pop.make_normal_dist_dna()

        pop.sort()

        res = pop.make_normal_dist_dna(keep_elites_rate=2)
        pop2 = g.Population(owner)
        pop2.push(res)
        pop2.sort()

        first = pop2.get_organization_and_fitness_at(0, fitness_as_tensor=False)
        self.assertIsInstance(first[0], g.Organization)
        self.assertAlmostEqual(first[0].dna[0], 0)
        self.assertEqual(round(first[0].body), 0)
        self.assertAlmostEqual(round(first[1]), 0)

        second = pop2.get_organization_and_fitness_at(1, fitness_as_tensor=False)
        self.assertIsInstance(second[0], g.Organization)
        self.assertAlmostEqual(second[0].dna[0], 0.1)
        self.assertEqual(round(second[0].body), 1)
        self.assertAlmostEqual(round(second[1]), 1)


text:
/**
 *
 */
package com.cg.jdbc.emp.services;
import com.cg.jdbc.emp.dao.EmployeeDao;
import com.cg.jdbc.emp.dao.EmployeeDaoImpl;
import com.cg.jdbc.emp.model.Employee;

/*@author smita*/
public class EmployeeServiceImpl implements IEmployeeService {
	private static EmployeeDao employeeDao;
	static{
		employeeDao= new EmployeeDaoImpl();
	}
	@Override
	public void addEmployee(Employee e) {
		employeeDao.addEmployee(e);
	}
	@Override
	public void removeEmployee(Employee e) {
		employeeDao.removeEmployee(e);
	}
	@Override
	public void modifyEmployee(Employee e) {
		employeeDao.modifyEmployee(e);
	}
	@Override
	public void searchEmployee(Employee e) {
		employeeDao.searchEmployee(e);
	}
	@Override
	public void listAllEmployee() {
		employeeDao.listAllEmployee();
	}
}


text:
package patchless

import shapeless.labelled.{FieldType, field}
import shapeless._

sealed trait Patchable[T] {
  type Updates <: HList
  def apply(t: T, updates: Updates): T
}

object Patchable {
  type Aux[T, U <: HList] = Patchable[T] { type Updates = U }

  def apply[T](implicit patchable: Patchable[T]): Aux[T, patchable.Updates] = patchable

  implicit val hnil: Aux[HNil, HNil] = new Patchable[HNil] {
    final type Updates = HNil
    def apply(t: HNil, updates: HNil): HNil = HNil
  }

  implicit def hcons[K <: Symbol, H, T <: HList, TU <: HList](implicit
    patchTail: Aux[T, TU]
  ): Aux[FieldType[K, H] :: T, FieldType[K, Option[H]] :: TU] = new Patchable[FieldType[K, H] :: T] {
    final type Updates = FieldType[K, Option[H]] :: TU
    def apply(t: FieldType[K, H] :: T, updates: FieldType[K, Option[H]] :: TU) =
      field[K](updates.head.getOrElse(t.head)) :: patchTail(t.tail, updates.tail)
  }

  implicit def generic[T, L <: HList, U <: HList](implicit
    gen: LabelledGeneric.Aux[T, L],
    patchL: Aux[L, U]
  ): Aux[T, U] = new Patchable[T] {
    final type Updates = U
    def apply(t: T, updates: U) = gen.from(patchL(gen.to(t), updates))
  }
}


text:
/*
	Init basic functionality to a page.
	This is necessary for global navigation/footer accordions, responsive breakpoints and other functions.

*/

var NIN = NIN || {};
(function($objNS){
	'use strict';

	var common = $objNS.common();
	common.initialize();

	// Universal interactions
	$(".js-basic-popup").on("click", function(e) {
		e.preventDefault();

		var url = $(this).attr("href");
		window.open(url, "Nintendo.com Popup",'width=800,height=600,scrollbars=no');

	});

})(NIN);


text:
<?php
class TestTest extends \Codeception\TestCase\Test
{
    public function testBaseOne()
    {
        return 'hey';
    }

    /**
     * @depends testBaseOne
     */
    public function testDependentOne($hey)
    {
        $this->assertEquals('hey', $hey);
    }
}


text:
$import("js.util.List", "BootstrapClassLoader");

Class.forName({
  name: "class js.util.Stack extends js.util.List",
  "private _table": [],
  "private _max": 10,
  Stack: function(max) {
    this._max = max || 10;
  },
  "clone": function() {
    var c = new js.util.Stack(this._max);
    var it = this.iterator();
    while (it.hasNext()) {
      var next = it.next();
      it.add(next ? next.clone() : next);
    }
    return c;
  },
  setMaxLength: function(max) {
    this._max = max || 10;
  },
  length: function() {
    return this._table.length;
  },
  clear: function() {
    var length = this.length();
    if (length > 0) {
      this._table.splice(0, length);
    }
  },
  pop: function() {
    return this._table.pop();
  },
  push: function(vargs) {
    if (this.length() > this._max) {
      this._table.shift();
    }
    this._table.push(vargs);
  },
  empty: function() {
    return this._table.length <= 0;
  },
  peek: function() {
    if (this.empty()) {
      return null;
    }
    return this._table[this._table.length - 1];
  },
  search: function(ele) {
    return this._table.indexOf(ele);
  },
  "size": function() {
    return this.length();
  },

  "removeAt": function(index) {
    this.rangeCheck();
    return this._table.splice(index, 1);
  },

  "get": function(index) {
    this.rangeCheck();
    return this._table[index];
  },

  "subList": function(fromIndex, toIndex) {
    return this._table.slice(fromIndex, toIndex);
  },

  "set": function(index, element) {
    this.rangeCheck(index);
    var oldValue = this._table[index];
    this._table[index] = element;
    return oldValue;
  }

});


text:
install_awsadfs() {
  # Use colors, but only if connected to a terminal, and that terminal
  # supports them.
  if which tput >/dev/null 2>&1; then
      ncolors=$(tput colors)
  fi
  if [ -t 1 ] && [ -n "$ncolors" ] && [ "$ncolors" -ge 8 ]; then
    RED="$(tput setaf 1)"
    GREEN="$(tput setaf 2)"
    YELLOW="$(tput setaf 3)"
    BLUE="$(tput setaf 4)"
    BOLD="$(tput bold)"
    NORMAL="$(tput sgr0)"
  else
    RED=""
    GREEN=""
    YELLOW=""
    BLUE=""
    BOLD=""
    NORMAL=""
  fi

  [ "$BRANCH" == "" ] && export BRANCH=master

  # install pyenv if not installed
  if ! which pyenv &>/dev/null; then
    wget https://raw.githubusercontent.com/jig/myubuntu/$BRANCH/install-pyenv.sh -O /tmp/pyenv.sh
    chmod +x /tmp/pyenv.sh
    . /tmp/pyenv.sh
  fi

  # install specific python version
  bash -c "$(wget https://raw.githubusercontent.com/jig/myubuntu/$BRANCH/install-python.sh -O -)"

  set -e

  SUDO=''
  if (( $EUID != 0 )); then
      SUDO='sudo'
  fi

  printf "${BLUE}Installing aws-adfs...${NORMAL}\n"

  $SUDO apt-get -y install libkrb5-dev

  pip3 install -U pyopenssl
  pip3 install aws-adfs

  aws-adfs --version
}

install_awsadfs


text:
START_ATF_NAMESPACE
    namespace vc_attributes
    {
        #pragma pack(push, 4)
        template<>
        struct emitidlAttribute
        {
            int value;
            bool defaultimports;
        };
        #pragma pack(pop)
    }; // end namespace vc_attributes
END_ATF_NAMESPACE


text:
import pytest

from mlflow.utils.string_utils import strip_prefix, strip_suffix, is_string_type, mslex_quote

@pytest.mark.parametrize(
    (("original", "prefix", "expected")),
    [("smoketest", "smoke", "test"), ("", "test", ""), ("", "", ""), ("test", "", "test")],
)
def test_strip_prefix(original, prefix, expected):
    assert strip_prefix(original, prefix) == expected

@pytest.mark.parametrize(
    ("original", "suffix", "expected"),
    [("smoketest", "test", "smoke"), ("", "test", ""), ("", "", ""), ("test", "", "test")],
)
def test_strip_suffix(original, suffix, expected):
    assert strip_suffix(original, suffix) == expected

def test_is_string_type():
    assert is_string_type("validstring")
    assert is_string_type("")
    assert is_string_type((b"dog").decode("utf-8"))
    assert not is_string_type(None)
    assert not is_string_type(["teststring"])
    assert not is_string_type([])
    assert not is_string_type({})
    assert not is_string_type({"test": "string"})
    assert not is_string_type(12)
    assert not is_string_type(12.7)

def test_mslex_quote():
    assert mslex_quote("abc") == "abc"
    assert mslex_quote("a b c") == '"a b c"'
    assert mslex_quote("C:\\path\\to\\file") == "C:\\path\\to\\file"


text:
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {

    $copywriteYear = date("Y");

    $homeContent = file_get_contents(resource_path() . '/content/home.json');
    $homeContent = json_decode($homeContent, true);

    return view('main', compact('copywriteYear', "homeContent"));
});

Route::get('/resume-pdf', function(){

    $resumeFileName = "Rushabh_Padalia_Resume.pdf";

    $file = public_path(). "/resume/". $resumeFileName;

    $headers = array(
        'Content-Type: application/pdf',
    );

    return Response::download($file, $resumeFileName, $headers);
});


text:
author: robmyers
comments: true
date: 2009-07-20 00:13:32+00:00
layout: post
slug: npg_round-up
title: NPG Round-Up
wordpress_id: 1773
categories:
- Free Culture
---

People are blogging legal analyses of the NPG situation and they broadly agree with my understanding that the law in England is a mess that can be clarified by Bridgeman vs. Corel. ;-)

Technollama -

[http://www.technollama.co.uk/national-portrait-gallery-copyright-row](http://www.technollama.co.uk/national-portrait-gallery-copyright-row)

Lawclanger -

[http://lawclanger.blogspot.com/2009/07/its-not-often-that-copyright-cases-get.html](http://lawclanger.blogspot.com/2009/07/its-not-often-that-copyright-cases-get.html)

Art Law Blog -

[http://theartlawblog.blogspot.com/2009/07/bridgeman-two.html](http://theartlawblog.blogspot.com/2009/07/bridgeman-two.html)

It's important to note that the database right claim and the unauthorised access claim are apparently as flimsy as the copyright claim, and that Bridgeman vs. Corel _is_ relevant.

And here's an anecdotal but damning opinion on the NPG's behaviour as a licensor from someone who claims to be in the publishing industry -

[http://blog.wikimedia.org/2009/07/16/protecting-the-public-domain-and-sharing-our-cultural-heritage/#comment-1416](http://blog.wikimedia.org/2009/07/16/protecting-the-public-domain-and-sharing-our-cultural-heritage/#comment-1416)

(Thanks to [Glyn Moody](http://opendotdotdot.blogspot.com/) and [David Gerard](http://davidgerard.co.uk/) for many of the links.)


text:
package org.apache.storm.elasticsearch.bolt;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

import org.apache.storm.elasticsearch.common.EsConfig;
import org.apache.storm.elasticsearch.common.EsTestUtil;
import org.apache.storm.testing.IntegrationTest;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import org.elasticsearch.client.ResponseException;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.runners.MockitoJUnitRunner;

@Category(IntegrationTest.class)
@RunWith(MockitoJUnitRunner.class)
public class EsLookupBoltIntegrationTest extends AbstractEsBoltIntegrationTest<EsLookupBolt> {

    @Captor
    private ArgumentCaptor<Tuple> anchor;

    @Captor
    private ArgumentCaptor<Values> emmitedValues;

    private Tuple tuple = EsTestUtil.generateTestTuple(source, index, type, documentId);

    @Override
    protected EsLookupBolt createBolt(EsConfig esConfig) {
        return new EsLookupBolt(esConfig);
    }

    @Before
    public void populateIndexWithTestData() throws Exception {
        node.client().prepareIndex(index, type, documentId).setSource(source).execute().actionGet();
    }

    @Test
    public void anchorsTheTuple() throws Exception {
        bolt.execute(tuple);

        verify(outputCollector).emit(anchor.capture(), emmitedValues.capture());
        assertThat(anchor.getValue(), is(tuple));
    }

    @Test
    public void emitsExpectedValues() throws Exception {
        Values expectedValues = expectedValues();

        bolt.execute(tuple);

        verify(outputCollector).emit(anchor.capture(), emmitedValues.capture());
        assertThat(emmitedValues.getValue(), is(expectedValues));
    }

    @Test
    public void acksTuple() throws Exception {
        bolt.execute(tuple);

        verify(outputCollector).ack(anchor.capture());
        assertThat(anchor.getValue(), is(tuple));
    }

    @Test
    public void indexMissing() throws Exception {
        Tuple tuple = EsTestUtil.generateTestTuple(source, "missing", type, documentId);
        bolt.execute(tuple);

        verify(outputCollector, never()).emit(any(Tuple.class), any(Values.class));
        verify(outputCollector).reportError(any(ResponseException.class));
        verify(outputCollector).fail(tuple);
    }

    private Values expectedValues() {
        return new Values(index, type, documentId, source);
    }

    @Override
    protected Class<EsLookupBolt> getBoltClass() {
        return EsLookupBolt.class;
    }
}


text:
require 'active_support/inflector'

module OpenEHR
  module RM
    class Factory
      def initialize(cobject)
        @cobject = cobject
      end

      class << self
        def create(type, **param)
          if type.include? '_'
            type = type.downcase.camelize
          else
            type = type.capitalize
          end
          class_eval("#{type}Factory").create(params(param))
        end

        def params(param)
          param.each_with_object({}) do |item, parameters|
            key = item.shift
            value = item.shift
            if value.instance_of? Hash
              parameters[key] = Factory.create(value[:_type], **value)
            else
              parameters[key] = value
            end
          end
        end
      end

      def build
        Factory.create(type, params)
      end

      private
      def type
        @cobject.rm_type_name
      end

      def name
        OpenEHR::RM::DataTypes::Text::DvText.new(value: ' ')
      end

      def params
        @cobject.attributes.inject({}) do |hash, attribute|
          if attribute.children
            hash[attribute.rm_attribute_name.to_sym] =
              attribute.children.map { |child| Factory.new(child).build }
          end
          hash
        end.merge(
        { archetype_node_id: @cobject.node_id,
          occurrences: @cobject.occurrences })
      end
    end

    class DvBooleanFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Basic::DvBoolean.new(*param)
      end
    end

    class DvStateFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Basic::DvState.new(*param)
      end
    end

    class DvIdentifierFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Basic::DvIdentifier.new(*param)
      end
    end

    class DvTextFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Text::DvText.new(*param)
      end
    end

    class TermMappingFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Text::TermMapping.new(*param)
      end
    end

    class CodePhraseFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Text::CodePhrase.new(*param)
      end
    end

    class DvCodedTextFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Text::DvCodedText.new(*param)
      end
    end

    class DvParagraphFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Text::DvParagraph.new(*param)
      end
    end

    class DvOrderedFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Quantity::DvOrdered.new(*param)
      end
    end

    class DvIntervalFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Quantity::DvInterval.new(*param)
      end
    end

    class ReferenceRangeFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Quantity::ReferenceRange.new(*param)
      end
    end

    class DvOrdinalFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Quantity::DvOrdinal.new(*param)
      end
    end

    class DvQuantifiedFactory
      def self.create(*param)
        DataTypes::Quantity::DvQuantified.new(*param)
      end
    end

    class DvAmountFactory
      def self.create(*param)
        DataTypes::Quantity::DvAmount.new(*param)
      end
    end

    class DvQuantityFactory
      def self.create(*param)
        OpenEHR::RM::DataTypes::Quantity::DvQuantity.new(*param)
      end
    end

    class DvCountFactory
      def self.create(*param)
        DataTypes::Quantity::DvCount.new(*param)
      end
    end

    class DvProportionFactory
      def self.create(*param)
        DataTypes::Quantity::DvProportion.new(*param)
      end
    end

    class DvAbsoluteQuantityFactory
      def self.create(*param)
        DataTypes::Quantity::DvAbsoluteQuantity.new(*param)
      end
    end

    class DvTemporalFactory
      def self.create(*param)
        DataTypes::Quantity::DateTime::DvTemporal.new(*param)
      end
    end

    class DvDateFactory
      def self.create(param)
        OpenEHR::RM::DataTypes::Quantity::DateTime::DvDate.new(param)
      end
    end

    class DvTimeFactory
      def self.create(param)
        DataTypes::Quantity::DateTime::DvTime.new(param)
      end
    end

    class DvDateTimeFactory
      def self.create(param)
        DataTypes::Quantity::DateTime::DvDateTime.new(param)
      end
    end

    class DvDurationFactory
      def self.create(param)
        DataTypes::Quantity::DateTime::DvDuration.new(param)
      end
    end

    class DvEncapsulatedFactory
      def self.create(param)
        DataTypes::Encapsulated::DvEncapsulated.new(param)
      end
    end

    class DvMultimediaFactory
      def self.create(param)
        DataTypes::Encapsulated::DvMultimedia.new(param)
      end
    end

    class DvParsableFactory
      def self.create(param)
        DataTypes::Encapsulated::DvParsable.new(param)
      end
    end

    class DvUriFactory
      def self.create(param)
        DataTypes::URI::DvUri.new(param)
      end
    end

    class DvEhrUriFactory
      def self.create(param)
        DataTypes::URI::DvEhrUri.new(param)
      end
    end

    class ObservationFactory
      def self.create(param)
        Composition::Content::Entry::Observation.new(param)
      end
    end

    class SectionFactory
      def self.create(param)
        Composition::Content::Navigation::Section.new(param)
      end
    end

    class ClusterFactory
      def self.create(param)
        DataStructures::ItemStructure::Representation::Cluster.new(param)
      end
    end

    class ArchetypedFactory
      def self.create(param)
        OpenEHR::RM::Common::Archetyped::Archetyped.new(**param)
      end
    end

    class ArchetypeIdFactory
      def self.create(param)
        OpenEHR::RM::Support::Identification::ArchetypeID.new(param)
      end
    end

    class TemplateIdFactory
      def self.create(param)
        OpenEHR::RM::Support::Identification::TemplateID.new(param)
      end
    end

    class TerminologyIdFactory
      def self.create(param)
        OpenEHR::RM::Support::Identification::TerminologyID.new(param)
      end
    end

    class GenericIdFactory
      def self.create(param)
        OpenEHR::RM::Support::Identification::GenericID.new(param)
      end
    end

    class PartyRefFactory
      def self.create(param)
        OpenEHR::RM::Support::Identification::PartyRef.new(param)
      end
    end

    class PartyIdentifiedFactory
      def self.create(param)
        OpenEHR::RM::Common::Generic::PartyIdentified.new(param)
      end
    end

    class EventContextFactory
      def self.create(param)
        OpenEHR::RM::Composition::EventContext.new(param)
      end
    end

    class TermMappingFactory
      def self.create(param)
        OpenEHR::RM::DataTypes::Text::TermMapping.new(param)
      end
    end

    class CompositionFactory < Factory
      class << self
        def create_from_json(json)
          hash = JSON.parse(json, max_nesting: false, symbolize_names: true)
          OpenEHR::RM::Composition::Composition.new(params(hash))
        end
      end
    end
  end
end


text:
static const NSInteger kTotalPageCount = 5;

@interface HomeViewController ()

@property (nonatomic , strong) AutoSlideScrollView *mainScorllView;

@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSMutableArray *viewsArray = [@[] mutableCopy];
    NSArray *colorArray = @[[UIColor cyanColor],[UIColor blueColor],[UIColor greenColor],[UIColor yellowColor],[UIColor purpleColor]];
    for (int i = 0; i < kTotalPageCount; ++i) {
        UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];
        tempLabel.backgroundColor = [(UIColor *)[colorArray objectAtIndex:i] colorWithAlphaComponent:0.5];
        [viewsArray addObject:tempLabel];
    }

    self.mainScorllView = [[AutoSlideScrollView alloc] initWithFrame:CGRectMake(0, 100, 320, 300) animationDuration:3];
    self.mainScorllView.backgroundColor = [[UIColor purpleColor] colorWithAlphaComponent:0.1];

    self.mainScorllView.totalPagesCount = ^NSInteger(void){
        return viewsArray.count;
    };
    self.mainScorllView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex){
        return viewsArray[pageIndex];
    };
    self.mainScorllView.TapActionBlock = ^(NSInteger pageIndex){
        NSLog(@"点击了第%ld个",pageIndex);
    };
    [self.view addSubview:self.mainScorllView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
<add>
<doc>
<field name="uid">doi:10.1371/journal.pntd.0000679</field>
<field name="doi">10.1371/journal.pntd.0000679</field>
<field name="data_source">PLoS Open Access XML</field>
<field name="authors">Daniela A. Bermejo, María C. Amezcua-Vesely, Carolina L. Montes, María C. Merino, Ricardo C. Gehrau, Hugo Cejas, Eva V. Acosta-Rodríguez, Adriana Gruppi</field>
<field name="title">BAFF Mediates Splenic B Cell Response and Antibody Production in Experimental Chagas Disease</field>
<field name="journal">PLoS Neglected Tropical Diseases</field>
<field name="year">2010</field>
<field name="volume">4</field>
<field name="number">5</field>
<field name="pages">e679</field>
<field name="license">Creative Commons Attribution (CC BY)</field>
<field name="license_url">http://creativecommons.org/licenses/by/3.0/</field>
<field name="fulltext">
Abstract

Background

B cells and antibodies are involved not only in controlling the spread of
blood circulating Trypanosoma cruzi, but also in the autoreactive
manifestations observed in Chagas disease. Acute infection results in
polyclonal B cell activation associated with hypergammaglobulinemia, delayed
specific humoral immunity and high levels of non-parasite specific antibodies.
Since TNF superfamily B lymphocyte Stimulator (BAFF) mediates polyclonal B
cell response in vitro triggered by T. cruzi antigens, and BAFF-Tg mice show
similar signs to T. cruzi infected mice, we hypothesized that BAFF can mediate
polyclonal B cell response in experimental Chagas disease.

Methodology/Principal Findings

BAFF is produced early and persists throughout the infection. To analyze BAFF
role in experimental Chagas disease, Balb/c infected mice were injected with
BR3:Fc, a soluble receptor of BAFF, to block BAFF activity. By BAFF blockade
we observed that this cytokine mediates the mature B cell response and the
production of non-parasite specific IgM and IgG. BAFF also influences the
development of antinuclear IgG and parasite-specific IgM response, not
affecting T. cruzi-specific IgG and parasitemia. Interestingly, BAFF
inhibition favors the parasitism in heart.

Conclusions/Significance

Our results demonstrate, for the first time, an active role for BAFF in
shaping the mature B cell repertoire in a parasite infection.

Author Summary

Chagas disease, caused by the protozoan Trypanosoma cruzi, is endemic in
Central and South America. It affects 20 million people and about 100 million
people are at risk of infection in endemic areas. Some cases have been
identified in non-endemic countries as a consequence of blood transfusion and
organ transplantation. Chagas disease presents three stages of infection. The
acute phase appears one to two weeks after infection and includes fever,
swelling around the bite site, enlarged lymph glands and spleen, and fatigue.
This stage is characterized by circulating parasites and many immunological
disturbances including a massive B cell response. In general, the acute
episode self-resolves in about 2 months and is followed by a clinically silent
indeterminate phase characterized by absence of circulating parasites. In
about one-third of the cases, the indeterminate phase evolves into a chronic
phase with clinically defined cardiac or digestive disturbances. Current
knowledge suggests that the persistence of parasites coupled with an
unbalanced immune response sustain inflammatory response in the chronic stage.
We believe that an effective treatment for chronic Chagas disease should
combine antiparasitic drugs with immunomodulators aimed at reducing
inflammation and autoreactive response. Our findings enlighten a new role of
BAFF-BAFF-R signaling in parasite infection that partially controls polyclonal
B cell response but not parasitespecific class-switched primary effectors B
cells.

Introduction

Chagas disease is a chronic disease caused by infection with Trypanosoma
cruzi. Initially, the disease goes through an acute episode which is
characterized by circulating parasites and immunological disturbances that, at
the level of B cell compartment, are mature and immature B</field></doc>
</add>


text:
module Stamina
  #
  # Allows any object to be markable with user-data.
  #
  # This module is expected to be included by classes that want to implement the
  # Markable design pattern. Moreover, if the instances of the including class
  # respond to <tt>state_changed</tt>, this method is automatically invoked when
  # marks change. This method is used by <tt>automaton</tt> in order to make it
  # possible to track changes and check modified automata for consistency.
  #
  # == Detailed API
  module Markable

    #
    # Returns user-value associated to _key_, nil if no such key in user-data.
    #
    def [](key)
      @data[key]
    end

    #
    # Associates _value_ to _key_ in user-data. Overrides previous value if
    # present.
    #
    def []=(key,value)
      oldvalue = @data[key]
      @data[key] = value
      state_changed(:loaded_pair, [key,oldvalue,value]) if self.respond_to? :state_changed
    end

    # Removes a mark
    def remove_mark(key)
      oldvalue = @data[key]
      @data.delete(key)
      state_changed(:loaded_pair, [key,oldvalue,nil]) if self.respond_to? :state_changed
    end

    # Returns the values mapped to `keys` as an array
    def marks(*keys)
      raw_data.values_at(*keys)
    end

    # Returns RAW data, that is without duplicating it. Returns result should not be
    # changed.
    def raw_data
      @data ||= {}
    end

    # Extracts the copy of attributes which can subsequently be modified.
    def data
      @data.nil? ? {} : @data.dup
    end

  end # module Markable
end # module Stamina


text:
module NutrientsHelper
end


text:
package org.deviceconnect.android.manager.setting;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import org.apache.http.protocol.HTTP;
import org.deviceconnect.android.manager.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

/**
 * プライバシーポリシーフラグメント.
 */
public class TextDialogFragment extends DialogFragment {

    /**
     * バッファサイズ.
     */
    private static final int BUFFER_SIZE = 1024;

    /**
     * ロガー.
     */
    private Logger mLogger = Logger.getLogger("dconnect.uiapp");

    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_privacypolicy, null);
        TextView text = (TextView) view.findViewById(android.R.id.text1);

        InputStream is = null;
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            is = getActivity().getResources().openRawResource(
                    getArguments().getInt(Intent.EXTRA_TEXT));
            byte[] buf = new byte[BUFFER_SIZE];
            while (true) {
                int len = is.read(buf);
                if (len < 0) {
                    break;
                }
                os.write(buf, 0, len);
            }
            text.setText(new String(os.toByteArray(), HTTP.UTF_8));
        } catch (IOException e) {
            mLogger.warning(e.toString());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    mLogger.fine(e.toString());
                }
            }
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view);
        builder.setTitle(getArguments().getInt(Intent.EXTRA_TITLE));
        builder.setPositiveButton(R.string.activity_settings_close, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, final int which) {
                dialog.dismiss();
            }
        });

        return builder.create();
    }

}


text:
from qrl.core import config
from qrl.core.qrlnode import QRLNode
from qrl.generated import qrldebug_pb2
from qrl.generated.qrldebug_pb2_grpc import DebugAPIServicer
from qrl.services.grpcHelper import GrpcExceptionWrapper

class DebugAPIService(DebugAPIServicer):
    MAX_REQUEST_QUANTITY = 100

    def __init__(self, qrlnode: QRLNode):
        self.qrlnode = qrlnode

    @GrpcExceptionWrapper(qrldebug_pb2.GetFullStateResp)
    def GetFullState(self, request: qrldebug_pb2.GetFullStateReq, context) -> qrldebug_pb2.GetFullStateResp:
        return qrldebug_pb2.GetFullStateResp(
            coinbase_state=self.qrlnode.get_address_state(config.dev.coinbase_address).pbdata,
            addresses_state=self.qrlnode.get_all_address_state()
        )


text:
require 'azure/core/auth/signer'

# This will break if used against API version prior to 2013-08-15 as the format
# changed
# @see https://msdn.microsoft.com/library/azure/dn140255.aspx for more information on construction
module Azure
  module Blob
    module Auth
      class SharedAccessSignature < Azure::Core::Auth::Signer
        DEFAULTS = {
            resource: 'b',
            permissions: 'r',
            version: '2014-02-14'
        }

        KEY_MAPPINGS = {
            permissions:          :sp,
            start:                :st,
            expiry:               :se,
            resource:             :sr,
            identifier:           :si,
            version:              :sv,
            cache_control:        :rscc,
            content_disposition:  :rscd,
            content_encoding:     :rsce,
            content_language:     :rscl,
            content_type:         :rsct
        }

        OPTIONAL_QUERY_PARAMS = [:sp, :si, :rscc, :rscd, :rsce, :rscl, :rsct]

        attr :account_name

        # Public: Initialize the Signer.
        #
        # @param account_name [String] The account name. Defaults to the one in the global configuration.
        # @param access_key [String]   The access_key encoded in Base64. Defaults to the one in the global configuration.
        def initialize(account_name=Azure.storage_account_name, access_key=Azure.storage_access_key)
          @account_name = account_name
          super(access_key)
        end

        # Construct the plaintext to the spec required for signatures
        # @return [String]
        def signable_string(path, options)
          # Order is significant
          # The newlines from empty strings here are required
          [
              options[:permissions],
              options[:start],
              options[:expiry],
              canonicalized_resource(path),
              options[:identifier],

              options[:version],

              options[:cache_control],
              options[:content_disposition],
              options[:content_encoding],
              options[:content_language],
              options[:content_type]
          ].join("\n")
        end

        # Return the cononicalized resource representation of the blob resource
        # @return [String]
        def canonicalized_resource(path)
          "/#{account_name}#{path.start_with?('/') ? '' : '/'}#{path}"
        end

        # A customised URI reflecting options for the resource signed with the Shared Access Signature
        # @param uri      [URI] uri to resource including query options
        # @param options  [Hash]
        #
        # ==== Options
        #
        # * +:resource+     - String. Resource type, either 'b' (blob) or 'c' (container). Default 'b'
        # * +:permissions+  - String. Combination of 'r','w','d','l' (container only) in this order. Default 'r'
        # * +:start+        - String. UTC Date/Time in ISO8601 format. Optional.
        # * +:expiry+       - String. UTC Date/Time in ISO8601 format. Optional. Default now + 30 minutes.
        # * +:identifier+   - String. Identifier for stored access policy. Optional
        # * +:version+      - String. API version. Default 2014-02-14
        #
        # * +:cache_control+       - String. Response header override. Optional.
        # * +:content_disposition+ - String. Response header override. Optional.
        # * +:content_encoding+    - String. Response header override. Optional.
        # * +:content_language+    - String. Response header override. Optional.
        # * +:content_type+        - String. Response header override. Optional.
        def signed_uri(uri, options)
          parsed_query = CGI::parse(uri.query || '').inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}

          options[:expiry] ||= (Time.now + 60*30).utc.iso8601

          if parsed_query.has_key?(:restype)
            options[:resource] = parsed_query[:restype].first == 'container' ? 'c' : 'b'
          end

          options = DEFAULTS.merge(options)
          sas_params = URI.encode_www_form(query_hash(uri.path, options))
          URI.parse(uri.to_s + (uri.query.nil? ? '?' : '&') + sas_params)
        end

        def sign_request(req)
          header_options = {}.tap do |opts|
            opts[:version] = req.headers['x-ms-version'] if req.headers.has_key?('x-ms-version')
          end

          req.uri = signed_uri(req.uri, header_options)
        end

        private

        def signature(path, options)
          sign(signable_string(path, options))
        end

        def query_hash(path, options)
          Hash[options.map { |k, v|
                 [KEY_MAPPINGS[k], v]
               }].reject { |k, v|
            OPTIONAL_QUERY_PARAMS.include?(k) && v.to_s == ''
          }.merge(
              sig: signature(path, options)
          )
        end

      end
    end
  end
end


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const Source = require("./Source");
const RawSource = require("./RawSource");
const streamChunks = require("./helpers/streamChunks");
const { getMap, getSourceAndMap } = require("./helpers/getFromStreamChunks");

const REPLACE_REGEX = /\n(?=.|\s)/g;

class PrefixSource extends Source {
	constructor(prefix, source) {
		super();
		this._source =
			typeof source === "string" || Buffer.isBuffer(source)
				? new RawSource(source, true)
				: source;
		this._prefix = prefix;
	}

	getPrefix() {
		return this._prefix;
	}

	original() {
		return this._source;
	}

	source() {
		const node = this._source.source();
		const prefix = this._prefix;
		return prefix + node.replace(REPLACE_REGEX, "\n" + prefix);
	}

	// TODO efficient buffer() implementation

	map(options) {
		return getMap(this, options);
	}

	sourceAndMap(options) {
		return getSourceAndMap(this, options);
	}

	streamChunks(options, onChunk, onSource, onName) {
		const prefix = this._prefix;
		const prefixOffset = prefix.length;
		const linesOnly = !!(options && options.columns === false);
		const { generatedLine, generatedColumn, source } = streamChunks(
			this._source,
			options,
			(
				chunk,
				generatedLine,
				generatedColumn,
				sourceIndex,
				originalLine,
				originalColumn,
				nameIndex
			) => {
				if (generatedColumn !== 0) {
					// In the middle of the line, we just adject the column
					generatedColumn += prefixOffset;
				} else if (chunk !== undefined) {
					// At the start of the line, when we have source content
					// add the prefix as generated mapping
					// (in lines only mode we just add it to the original mapping
					// for performance reasons)
					if (linesOnly || sourceIndex < 0) {
						chunk = prefix + chunk;
					} else if (prefixOffset > 0) {
						onChunk(prefix, generatedLine, generatedColumn, -1, -1, -1, -1);
						generatedColumn += prefixOffset;
					}
				} else if (!linesOnly) {
					// Without source content, we only need to adject the column info
					// expect in lines only mode where prefix is added to original mapping
					generatedColumn += prefixOffset;
				}
				onChunk(
					chunk,
					generatedLine,
					generatedColumn,
					sourceIndex,
					originalLine,
					originalColumn,
					nameIndex
				);
			},
			onSource,
			onName
		);
		return {
			generatedLine,
			generatedColumn:
				generatedColumn === 0 ? 0 : prefixOffset + generatedColumn,
			source:
				source !== undefined
					? prefix + source.replace(REPLACE_REGEX, "\n" + prefix)
					: undefined
		};
	}

	updateHash(hash) {
		hash.update("PrefixSource");
		this._source.updateHash(hash);
		hash.update(this._prefix);
	}
}

module.exports = PrefixSource;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE score-partwise PUBLIC "-//Recordare//DTD MusicXML 3.0 Partwise//EN" "http://www.musicxml.org/dtds/partwise.dtd">
<score-partwise>
  <work>
    <work-number>MuseScore testfile</work-number>
    <work-title>Multi-Measure Rests 3</work-title>
    </work>
  <identification>
    <creator type="composer">Leon Vinken</creator>
    <encoding>
      <software>MuseScore 0.7.0</software>
      <encoding-date>2007-09-10</encoding-date>
      </encoding>
    <miscellaneous>
      <miscellaneous-field name="description">
        Test multi-measure rest handling. When exporting to MusicXML, the global
        "create multi-measure rest" flag must be set.
        Alternatively, export as .mscx and verify presence of breakMultiMeasureRest
        flags only in measures 2 and 5.
        </miscellaneous-field>
      </miscellaneous>
    </identification>
  <part-list>
    <score-part id="P1">
      <part-name>Staff 1</part-name>
      <score-instrument id="P1-I3">
        <instrument-name>Staff 1</instrument-name>
        </score-instrument>
      <midi-instrument id="P1-I3">
        <midi-channel>1</midi-channel>
        <midi-program>1</midi-program>
        </midi-instrument>
      </score-part>
    </part-list>
  <part id="P1">
    <measure number="1">
      <attributes>
        <divisions>1</divisions>
        <key>
          <fifths>0</fifths>
          <mode>major</mode>
          </key>
        <time symbol="common">
          <beats>4</beats>
          <beat-type>4</beat-type>
          </time>
        <clef>
          <sign>G</sign>
          <line>2</line>
          </clef>
        </attributes>
      <note>
        <pitch>
          <step>G</step>
          <octave>4</octave>
          </pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>whole</type>
        </note>
      </measure>
    <measure number="2">
      <attributes>
        <measure-style>
          <multiple-rest>3</multiple-rest>
          </measure-style>
        </attributes>
      <note>
        <rest/>
        <duration>4</duration>
        <voice>1</voice>
        </note>
      </measure>
    <measure number="3">
      <note>
        <rest/>
        <duration>4</duration>
        <voice>1</voice>
        </note>
      </measure>
    <measure number="4">
      <note>
        <rest/>
        <duration>4</duration>
        <voice>1</voice>
        </note>
      </measure>
    <measure number="5">
      <note>
        <pitch>
          <step>D</step>
          <octave>5</octave>
          </pitch>
        <duration>4</duration>
        <voice>1</voice>
        <type>whole</type>
        </note>
      <barline location="right">
        <bar-style>light-heavy</bar-style>
        </barline>
      </measure>
    </part>
  </score-partwise>


text:
export default {
    "message": "Unexpected token {",
    "column": 14,
    "index": 13,
    "lineNumber": 1
}


text:
FROM jetty:9-jre7
MAINTAINER derek@battams.ca
RUN mkdir -p /home/jetty
COPY war/*.war /var/lib/jetty/webapps/psmtp.war
COPY conf/etc/* /etc/
COPY conf/default/* /etc/default/
COPY scripts/* /usr/local/jetty/bin/
RUN chmod 755 /usr/local/jetty/bin/*
RUN chown -R jetty.jetty /var/lib/jetty/webapps /home/jetty
EXPOSE 8080 2525 8000
CMD /usr/local/jetty/bin/jetty.sh run


text:
package twizansk.hivemind.integration;

import twizansk.hivemind.api.data.TrainingSample;
import twizansk.hivemind.api.model.Gradient;
import twizansk.hivemind.api.model.Model;
import twizansk.hivemind.api.model.ObjectiveFunction;

public class IntegrationObjective implements ObjectiveFunction<Model> {

	@Override
	public Gradient singlePointGradient(TrainingSample sample, Model model) {
		double[] x = sample.x;
		double y = sample.y;
		double[] params = model.params;
		double multiplier = 2  * (params[0] * x[0] + params[1] - y);
		double[] g = new double[] {multiplier * x[0], multiplier};
		return new Gradient(g);
	}

}


text:
@(resetForm:Form[(String, String)], mailToken: String)(implicit request: RequestHeader, lang: Lang, env: securesocial.core.RuntimeEnvironment[_])
@import helper._
@import com.yetu.oauth2provider.utils.Config
@implicitFieldConstructor = @{ FieldConstructor(com.yetu.oauth2provider.views.html.yetuAuthentication.inputFieldConstructor.f) }

@com.yetu.oauth2provider.views.html.yetuAuthentication.main( Messages("securesocial.password.title") ) {
    <link rel="stylesheet" media="screen" href="@controllers.routes.Assets.versioned("stylesheets/normal_passwordchange.css")">

@Messages("securesocial.password.title")

@Messages("securesocial.passwordReset.subtitle")

    @request.flash.get("error").map { msg =>

            @Messages(msg)

    }

    <form action="@env.routes.handleResetPasswordUrl(mailToken)"
          class="form-horizontal"
          autocomplete="off"
          method="POST"
    >
        <fieldset>
            @CSRF.formField

            @Messages("securesocial.signup.invalidPassword", Config.minimumPasswordLength)

            @helper.inputPassword(
            resetForm("password.password1"),
                '_label -> Messages("securesocial.signup.password1"),
                'class -> "normal__input",
                'placeholder -> Messages("securesocial.signup.password1")
            )

            @helper.inputPassword(
            resetForm("password.password2"),
                '_label -> Messages("securesocial.signup.password2"),
                '_error -> resetForm.error("password"),
                'class -> "normal__input",
                'placeholder -> Messages("securesocial.signup.password2")
            )

                <button type="submit" class="button normal__button">@Messages("securesocial.password.reset")</button>

        </fieldset>
    </form>
}