text:
from __future__ import absolute_import, division, print_function

import os

import pytest

from cryptography.exceptions import AlreadyFinalized, InvalidSignature
from cryptography.hazmat.primitives import hashes, interfaces
from cryptography.hazmat.primitives.asymmetric import dsa
from cryptography.utils import bit_length

from .fixtures_dsa import (
    DSA_KEY_1024, DSA_KEY_2048, DSA_KEY_3072
)
from ...utils import (
    der_encode_dsa_signature, load_fips_dsa_key_pair_vectors,
    load_fips_dsa_sig_vectors, load_vectors_from_file,
)

@pytest.mark.dsa
class TestDSA(object):
    def test_generate_dsa_parameters(self, backend):
        parameters = dsa.generate_parameters(1024, backend)
        assert isinstance(parameters, interfaces.DSAParameters)

    def test_generate_invalid_dsa_parameters(self, backend):
        with pytest.raises(ValueError):
            dsa.generate_parameters(1, backend)

    @pytest.mark.parametrize(
        "vector",
        load_vectors_from_file(
            os.path.join(
                "asymmetric", "DSA", "FIPS_186-3", "KeyPair.rsp"),
            load_fips_dsa_key_pair_vectors
        )
    )
    def test_generate_dsa_keys(self, vector, backend):
        parameters = dsa.DSAParameterNumbers(
            p=vector['p'],
            q=vector['q'],
            g=vector['g']
        ).parameters(backend)
        skey = parameters.generate_private_key()
        if isinstance(skey, interfaces.DSAPrivateKeyWithNumbers):
            numbers = skey.private_numbers()
            skey_parameters = numbers.public_numbers.parameter_numbers
            pkey = skey.public_key()
            parameters = pkey.parameters()
            parameter_numbers = parameters.parameter_numbers()
            assert parameter_numbers.p == skey_parameters.p
            assert parameter_numbers.q == skey_parameters.q
            assert parameter_numbers.g == skey_parameters.g
            assert skey_parameters.p == vector['p']
            assert skey_parameters.q == vector['q']
            assert skey_parameters.g == vector['g']
            assert skey.key_size == bit_length(vector['p'])
            assert pkey.key_size == skey.key_size
            public_numbers = pkey.public_numbers()
            assert numbers.public_numbers.y == public_numbers.y
            assert numbers.public_numbers.y == pow(
                skey_parameters.g, numbers.x, skey_parameters.p
            )

    def test_generate_dsa_private_key_and_parameters(self, backend):
        skey = dsa.generate_private_key(1024, backend)
        assert skey
        if isinstance(skey, interfaces.DSAPrivateKeyWithNumbers):
            numbers = skey.private_numbers()
            skey_parameters = numbers.public_numbers.parameter_numbers
            assert numbers.public_numbers.y == pow(
                skey_parameters.g, numbers.x, skey_parameters.p
            )

    def test_invalid_parameters_values(self, backend):
        # Test a p < 1024 bits in length
        with pytest.raises(ValueError):
            dsa.DSAParameterNumbers(
                p=2 ** 1000,
                q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
            ).parameters(backend)

        # Test a p < 2048 bits in length
        with pytest.raises(ValueError):
            dsa.DSAParameterNumbers(
                p=2 ** 2000,
                q=DSA_KEY_2048.public_numbers.parameter_numbers.q,
                g=DSA_KEY_2048.public_numbers.parameter_numbers.g,
            ).parameters(backend)

        # Test a p < 3072 bits in length
        with pytest.raises(ValueError):
            dsa.DSAParameterNumbers(
                p=2 ** 3000,
                q=DSA_KEY_3072.public_numbers.parameter_numbers.q,
                g=DSA_KEY_3072.public_numbers.parameter_numbers.g,
            ).parameters(backend)

        # Test a p > 3072 bits in length
        with pytest.raises(ValueError):
            dsa.DSAParameterNumbers(
                p=2 ** 3100,
                q=DSA_KEY_3072.public_numbers.parameter_numbers.q,
                g=DSA_KEY_3072.public_numbers.parameter_numbers.g,
            ).parameters(backend)

        # Test a q < 160 bits in length
        with pytest.raises(ValueError):
            dsa.DSAParameterNumbers(
                p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                q=2 ** 150,
                g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
            ).parameters(backend)

        # Test a q < 256 bits in length
        with pytest.raises(ValueError):
            dsa.DSAParameterNumbers(
                p=DSA_KEY_2048.public_numbers.parameter_numbers.p,
                q=2 ** 250,
                g=DSA_KEY_2048.public_numbers.parameter_numbers.g
            ).parameters(backend)

        # Test a q > 256 bits in length
        with pytest.raises(ValueError):
            dsa.DSAParameterNumbers(
                p=DSA_KEY_3072.public_numbers.parameter_numbers.p,
                q=2 ** 260,
                g=DSA_KEY_3072.public_numbers.parameter_numbers.g,
            ).parameters(backend)

        # Test a g < 1
        with pytest.raises(ValueError):
            dsa.DSAParameterNumbers(
                p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                g=0
            ).parameters(backend)

        # Test a g = 1
        with pytest.raises(ValueError):
            dsa.DSAParameterNumbers(
                p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                g=1
            ).parameters(backend)

        # Test a g > p
        with pytest.raises(ValueError):
            dsa.DSAParameterNumbers(
                p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                g=2 ** 1200
            ).parameters(backend)

    def test_invalid_dsa_private_key_arguments(self, backend):
        # Test a p < 1024 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=2 ** 1000,
                        q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                        g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
                    ),
                    y=DSA_KEY_1024.public_numbers.y
                ),
                x=DSA_KEY_1024.x
            ).private_key(backend)

        # Test a p < 2048 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=2 ** 2000,
                        q=DSA_KEY_2048.public_numbers.parameter_numbers.q,
                        g=DSA_KEY_2048.public_numbers.parameter_numbers.g,
                    ),
                    y=DSA_KEY_2048.public_numbers.y
                ),
                x=DSA_KEY_2048.x,
            ).private_key(backend)

        # Test a p < 3072 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=2 ** 3000,
                        q=DSA_KEY_3072.public_numbers.parameter_numbers.q,
                        g=DSA_KEY_3072.public_numbers.parameter_numbers.g,
                    ),
                    y=DSA_KEY_3072.public_numbers.y
                ),
                x=DSA_KEY_3072.x,
            ).private_key(backend)

        # Test a p > 3072 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=2 ** 3100,
                        q=DSA_KEY_3072.public_numbers.parameter_numbers.q,
                        g=DSA_KEY_3072.public_numbers.parameter_numbers.g,
                    ),
                    y=DSA_KEY_3072.public_numbers.y
                ),
                x=DSA_KEY_3072.x,
            ).private_key(backend)

        # Test a q < 160 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                        q=2 ** 150,
                        g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
                    ),
                    y=DSA_KEY_1024.public_numbers.y
                ),
                x=DSA_KEY_1024.x,
            ).private_key(backend)

        # Test a q < 256 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_2048.public_numbers.parameter_numbers.p,
                        q=2 ** 250,
                        g=DSA_KEY_2048.public_numbers.parameter_numbers.g,
                    ),
                    y=DSA_KEY_2048.public_numbers.y
                ),
                x=DSA_KEY_2048.x,
            ).private_key(backend)

        # Test a q > 256 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_3072.public_numbers.parameter_numbers.p,
                        q=2 ** 260,
                        g=DSA_KEY_3072.public_numbers.parameter_numbers.g,
                    ),
                    y=DSA_KEY_3072.public_numbers.y
                ),
                x=DSA_KEY_3072.x,
            ).private_key(backend)

        # Test a g < 1
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                        q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                        g=0,
                    ),
                    y=DSA_KEY_1024.public_numbers.y
                ),
                x=DSA_KEY_1024.x,
            ).private_key(backend)

        # Test a g = 1
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                        q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                        g=1,
                    ),
                    y=DSA_KEY_1024.public_numbers.y
                ),
                x=DSA_KEY_1024.x,
            ).private_key(backend)

        # Test a g > p
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                        q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                        g=2 ** 1200,
                    ),
                    y=DSA_KEY_1024.public_numbers.y
                ),
                x=DSA_KEY_1024.x,
            ).private_key(backend)

        # Test x = 0
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                        q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                        g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
                    ),
                    y=DSA_KEY_1024.public_numbers.y
                ),
                x=0,
            ).private_key(backend)

        # Test x < 0
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                        q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                        g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
                    ),
                    y=DSA_KEY_1024.public_numbers.y
                ),
                x=-2,
            ).private_key(backend)

        # Test x = q
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                        q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                        g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
                    ),
                    y=DSA_KEY_1024.public_numbers.y
                ),
                x=2 ** 159,
            ).private_key(backend)

        # Test x > q
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                        q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                        g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
                    ),
                    y=DSA_KEY_1024.public_numbers.y
                ),
                x=2 ** 200,
            ).private_key(backend)

        # Test y != (g ** x) % p
        with pytest.raises(ValueError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                        q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                        g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
                    ),
                    y=2 ** 100
                ),
                x=DSA_KEY_1024.x,
            ).private_key(backend)

        # Test a non-integer y value
        with pytest.raises(TypeError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                        q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                        g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
                    ),
                    y=None
                ),
                x=DSA_KEY_1024.x,
            ).private_key(backend)

        # Test a non-integer x value
        with pytest.raises(TypeError):
            dsa.DSAPrivateNumbers(
                public_numbers=dsa.DSAPublicNumbers(
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                        q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                        g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
                    ),
                    y=DSA_KEY_1024.public_numbers.y
                ),
                x=None,
            ).private_key(backend)

    def test_invalid_dsa_public_key_arguments(self, backend):
        # Test a p < 1024 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPublicNumbers(
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=2 ** 1000,
                    q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                    g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
                ),
                y=DSA_KEY_1024.public_numbers.y
            ).public_key(backend)

        # Test a p < 2048 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPublicNumbers(
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=2 ** 2000,
                    q=DSA_KEY_2048.public_numbers.parameter_numbers.q,
                    g=DSA_KEY_2048.public_numbers.parameter_numbers.g,
                ),
                y=DSA_KEY_2048.public_numbers.y
            ).public_key(backend)

        # Test a p < 3072 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPublicNumbers(
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=2 ** 3000,
                    q=DSA_KEY_3072.public_numbers.parameter_numbers.q,
                    g=DSA_KEY_3072.public_numbers.parameter_numbers.g,
                ),
                y=DSA_KEY_3072.public_numbers.y
            ).public_key(backend)

        # Test a p > 3072 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPublicNumbers(
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=2 ** 3100,
                    q=DSA_KEY_3072.public_numbers.parameter_numbers.q,
                    g=DSA_KEY_3072.public_numbers.parameter_numbers.g,
                ),
                y=DSA_KEY_3072.public_numbers.y
            ).public_key(backend)

        # Test a q < 160 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPublicNumbers(
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                    q=2 ** 150,
                    g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
                ),
                y=DSA_KEY_1024.public_numbers.y
            ).public_key(backend)

        # Test a q < 256 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPublicNumbers(
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=DSA_KEY_2048.public_numbers.parameter_numbers.p,
                    q=2 ** 250,
                    g=DSA_KEY_2048.public_numbers.parameter_numbers.g,
                ),
                y=DSA_KEY_2048.public_numbers.y
            ).public_key(backend)

        # Test a q > 256 bits in length
        with pytest.raises(ValueError):
            dsa.DSAPublicNumbers(
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=DSA_KEY_3072.public_numbers.parameter_numbers.p,
                    q=2 ** 260,
                    g=DSA_KEY_3072.public_numbers.parameter_numbers.g,
                ),
                y=DSA_KEY_3072.public_numbers.y
            ).public_key(backend)

        # Test a g < 1
        with pytest.raises(ValueError):
            dsa.DSAPublicNumbers(
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                    q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                    g=0,
                ),
                y=DSA_KEY_1024.public_numbers.y
            ).public_key(backend)

        # Test a g = 1
        with pytest.raises(ValueError):
            dsa.DSAPublicNumbers(
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                    q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                    g=1,
                ),
                y=DSA_KEY_1024.public_numbers.y
            ).public_key(backend)

        # Test a g > p
        with pytest.raises(ValueError):
            dsa.DSAPublicNumbers(
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                    q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                    g=2 ** 1200,
                ),
                y=DSA_KEY_1024.public_numbers.y
            ).public_key(backend)

        # Test a non-integer y value
        with pytest.raises(TypeError):
            dsa.DSAPublicNumbers(
                parameter_numbers=dsa.DSAParameterNumbers(
                    p=DSA_KEY_1024.public_numbers.parameter_numbers.p,
                    q=DSA_KEY_1024.public_numbers.parameter_numbers.q,
                    g=DSA_KEY_1024.public_numbers.parameter_numbers.g,
                ),
                y=None
            ).public_key(backend)

@pytest.mark.dsa
class TestDSAVerification(object):
    _algorithms_dict = {
        'SHA1': hashes.SHA1,
        'SHA224': hashes.SHA224,
        'SHA256': hashes.SHA256,
        'SHA384': hashes.SHA384,
        'SHA512': hashes.SHA512
    }

    @pytest.mark.parametrize(
        "vector",
        load_vectors_from_file(
            os.path.join(
                "asymmetric", "DSA", "FIPS_186-3", "SigVer.rsp"),
            load_fips_dsa_sig_vectors
        )
    )
    def test_dsa_verification(self, vector, backend):
        digest_algorithm = vector['digest_algorithm'].replace("-", "")
        algorithm = self._algorithms_dict[digest_algorithm]
        if (
            not backend.dsa_parameters_supported(
                vector['p'], vector['q'], vector['g']
            ) or not backend.dsa_hash_supported(algorithm)
        ):
            pytest.skip(
                "{0} does not support the provided parameters".format(backend)
            )

        public_key = dsa.DSAPublicNumbers(
            parameter_numbers=dsa.DSAParameterNumbers(
                vector['p'], vector['q'], vector['g']
            ),
            y=vector['y']
        ).public_key(backend)
        sig = der_encode_dsa_signature(vector['r'], vector['s'])
        verifier = public_key.verifier(sig, algorithm())
        verifier.update(vector['msg'])
        if vector['result'] == "F":
            with pytest.raises(InvalidSignature):
                verifier.verify()
        else:
            verifier.verify()

    def test_dsa_verify_invalid_asn1(self, backend):
        public_key = DSA_KEY_1024.public_numbers.public_key(backend)
        verifier = public_key.verifier(b'fakesig', hashes.SHA1())
        verifier.update(b'fakesig')
        with pytest.raises(InvalidSignature):
            verifier.verify()

    def test_use_after_finalize(self, backend):
        public_key = DSA_KEY_1024.public_numbers.public_key(backend)
        verifier = public_key.verifier(b'fakesig', hashes.SHA1())
        verifier.update(b'irrelevant')
        with pytest.raises(InvalidSignature):
            verifier.verify()
        with pytest.raises(AlreadyFinalized):
            verifier.verify()
        with pytest.raises(AlreadyFinalized):
            verifier.update(b"more data")

@pytest.mark.dsa
class TestDSASignature(object):
    _algorithms_dict = {
        'SHA1': hashes.SHA1,
        'SHA224': hashes.SHA224,
        'SHA256': hashes.SHA256,
        'SHA384': hashes.SHA384,
        'SHA512': hashes.SHA512}

    @pytest.mark.parametrize(
        "vector",
        load_vectors_from_file(
            os.path.join(
                "asymmetric", "DSA", "FIPS_186-3", "SigGen.txt"),
            load_fips_dsa_sig_vectors
        )
    )
    def test_dsa_signing(self, vector, backend):
        digest_algorithm = vector['digest_algorithm'].replace("-", "")
        algorithm = self._algorithms_dict[digest_algorithm]
        if (
            not backend.dsa_parameters_supported(
                vector['p'], vector['q'], vector['g']
            ) or not backend.dsa_hash_supported(algorithm)
        ):
            pytest.skip(
                "{0} does not support the provided parameters".format(backend)
            )

        private_key = dsa.DSAPrivateNumbers(
            public_numbers=dsa.DSAPublicNumbers(
                parameter_numbers=dsa.DSAParameterNumbers(
                    vector['p'], vector['q'], vector['g']
                ),
                y=vector['y']
            ),
            x=vector['x']
        ).private_key(backend)
        signer = private_key.signer(algorithm())
        signer.update(vector['msg'])
        signature = signer.finalize()
        assert signature

        public_key = private_key.public_key()
        verifier = public_key.verifier(signature, algorithm())
        verifier.update(vector['msg'])
        verifier.verify()

    def test_use_after_finalize(self, backend):
        private_key = DSA_KEY_1024.private_key(backend)
        signer = private_key.signer(hashes.SHA1())
        signer.update(b"data")
        signer.finalize()
        with pytest.raises(AlreadyFinalized):
            signer.finalize()
        with pytest.raises(AlreadyFinalized):
            signer.update(b"more data")

class TestDSANumbers(object):
    def test_dsa_parameter_numbers(self):
        parameter_numbers = dsa.DSAParameterNumbers(p=1, q=2, g=3)
        assert parameter_numbers.p == 1
        assert parameter_numbers.q == 2
        assert parameter_numbers.g == 3

    def test_dsa_parameter_numbers_invalid_types(self):
        with pytest.raises(TypeError):
            dsa.DSAParameterNumbers(p=None, q=2, g=3)

        with pytest.raises(TypeError):
            dsa.DSAParameterNumbers(p=1, q=None, g=3)

        with pytest.raises(TypeError):
            dsa.DSAParameterNumbers(p=1, q=2, g=None)

    def test_dsa_public_numbers(self):
        parameter_numbers = dsa.DSAParameterNumbers(p=1, q=2, g=3)
        public_numbers = dsa.DSAPublicNumbers(
            y=4,
            parameter_numbers=parameter_numbers
        )
        assert public_numbers.y == 4
        assert public_numbers.parameter_numbers == parameter_numbers

    def test_dsa_public_numbers_invalid_types(self):
        with pytest.raises(TypeError):
            dsa.DSAPublicNumbers(y=4, parameter_numbers=None)

        with pytest.raises(TypeError):
            parameter_numbers = dsa.DSAParameterNumbers(p=1, q=2, g=3)
            dsa.DSAPublicNumbers(y=None, parameter_numbers=parameter_numbers)

    def test_dsa_private_numbers(self):
        parameter_numbers = dsa.DSAParameterNumbers(p=1, q=2, g=3)
        public_numbers = dsa.DSAPublicNumbers(
            y=4,
            parameter_numbers=parameter_numbers
        )
        private_numbers = dsa.DSAPrivateNumbers(
            x=5,
            public_numbers=public_numbers
        )
        assert private_numbers.x == 5
        assert private_numbers.public_numbers == public_numbers

    def test_dsa_private_numbers_invalid_types(self):
        parameter_numbers = dsa.DSAParameterNumbers(p=1, q=2, g=3)
        public_numbers = dsa.DSAPublicNumbers(
            y=4,
            parameter_numbers=parameter_numbers
        )
        with pytest.raises(TypeError):
            dsa.DSAPrivateNumbers(x=4, public_numbers=None)

        with pytest.raises(TypeError):
            dsa.DSAPrivateNumbers(x=None, public_numbers=public_numbers)


text:
package Mod.Block;

import cpw.mods.fml.common.network.FMLNetworkHandler;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Icon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import Mod.Lib.Refrence;
import Mod.Main.Main;
import Mod.TileEntity.TileEntityWirelessRedstone;

public class ModBlockWirelessRedstone extends BlockContainer{

	Icon IconSide;
	Icon IconOn;
	Icon IconOff;

	protected ModBlockWirelessRedstone(int par1) {
		super(par1, Material.iron);
		this.setHardness(1.5F);
	}

	@Override
	public TileEntity createNewTileEntity(World world) {
		return new TileEntityWirelessRedstone();
	}

    public void registerIcons(IconRegister register)
    {
    	IconSide = register.registerIcon(Refrence.Mod_Id + ":" + "WireLessRedstoneSide");
    	IconOn = register.registerIcon(Refrence.Mod_Id + ":" + "WireLessRedstoneOn");
    	IconOff = register.registerIcon(Refrence.Mod_Id + ":" + "WireLessRedstoneOff");

    }

    public Icon getIcon(int par1, int par2)
    {
        return par1 == 1 || par1 == 0 ? IconSide : par2 == 0 ? IconOff : IconOn;
    }

    public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9)
    {
        if (par1World.isRemote)
        {

            return true;
        }
        else
        {

        	FMLNetworkHandler.openGui(par5EntityPlayer, Main.instance, 0, par1World, par2, par3, par4);
            return true;
        }
    }

    public int isProvidingWeakPower(IBlockAccess access, int x, int y, int z, int side)
    {
    	if(access.getBlockMetadata(x, y, z) == 1){
    		return 16;
    	}

        return 0;
    }

    public boolean canProvidePower()
    {
        return true;
    }

    public int isProvidingStrongPower(IBlockAccess access, int x, int y, int z, int side)
    {
    	if(access.getBlockMetadata(x, y, z) == 1){
    		return 16;
    	}

        return 0;
    }

    @Override
    public void breakBlock(World World, int x, int y, int z, int id, int meta)
    {
		TileEntity tile = World.getBlockTileEntity(x, y, z);

		if(tile != null && tile instanceof IInventory){
			IInventory inv = (IInventory)tile;

			for(int i = 0; i < inv.getSizeInventory(); i++){
				ItemStack stack = inv.getStackInSlotOnClosing(i);

				if(stack != null){
					float spawnX = x + World.rand.nextFloat();
					float spawnY = y + World.rand.nextFloat();
					float spawnZ = z + World.rand.nextFloat();

					EntityItem droppedItem = new EntityItem(World, spawnX, spawnY, spawnZ, stack);

					float mult = 0.05F;

					droppedItem.motionX = (-0.5 + World.rand.nextFloat()) * mult;
					droppedItem.motionY = (4 + World.rand.nextFloat()) * mult;
					droppedItem.motionZ = (-0.5 + World.rand.nextFloat()) * mult;

					World.spawnEntityInWorld(droppedItem);

				}

			}
			super.breakBlock(World, x, y, z, id, meta);

		}

}
}

redpajama_set_name: RedPajamaGithub


text:
package org.jetbrains.idea.maven.server.embedder;

import org.codehaus.plexus.logging.Logger;
import org.jetbrains.idea.maven.server.MavenServerConsole;

import java.rmi.RemoteException;

public class Maven2ServerConsoleWrapper implements Logger {
  private static final String LINE_SEPARATOR = System.getProperty("line.separator");

  private MavenServerConsole myWrappee;
  private int myThreshold;

  void doPrint(int level, String message, Throwable throwable) {
    if (level < myThreshold) return;

    if (!message.endsWith(LINE_SEPARATOR)) {
      message += LINE_SEPARATOR;
    }

    if (myWrappee != null) {
      try {
        myWrappee.printMessage(level, message, throwable);
      }
      catch (RemoteException e) {
        //todo throw new RuntimeRemoteException(e); ???
      }
    }
  }

  public void setWrappee(MavenServerConsole wrappee) {
    myWrappee = wrappee;
  }

  public void debug(String string, Throwable throwable) {
    doPrint(MavenServerConsole.LEVEL_DEBUG, string, throwable);
  }

  public void info(String string, Throwable throwable) {
    doPrint(MavenServerConsole.LEVEL_INFO, string, throwable);
  }

  public void warn(String string, Throwable throwable) {
    doPrint(MavenServerConsole.LEVEL_WARN, string, throwable);
  }

  public void error(String string, Throwable throwable) {
    doPrint(MavenServerConsole.LEVEL_ERROR, string, throwable);
  }

  public void fatalError(String string, Throwable throwable) {
    doPrint(MavenServerConsole.LEVEL_FATAL, string, throwable);
  }

  public void debug(String message) {
    debug(message, null);
  }

  public boolean isDebugEnabled() {
    return getThreshold() <= MavenServerConsole.LEVEL_DEBUG;
  }

  public void info(String message) {
    info(message, null);
  }

  public boolean isInfoEnabled() {
    return getThreshold() <= MavenServerConsole.LEVEL_INFO;
  }

  public void warn(String message) {
    warn(message, null);
  }

  public boolean isWarnEnabled() {
    return getThreshold() <= MavenServerConsole.LEVEL_WARN;
  }

  public void error(String message) {
    error(message, null);
  }

  public boolean isErrorEnabled() {
    return getThreshold() <= MavenServerConsole.LEVEL_ERROR;
  }

  public void fatalError(String message) {
    fatalError(message, null);
  }

  public boolean isFatalErrorEnabled() {
    return getThreshold() <= MavenServerConsole.LEVEL_FATAL;
  }

  public void setThreshold(int threshold) {
    this.myThreshold = threshold;
  }

  public int getThreshold() {
    return myThreshold;
  }

  public Logger getChildLogger(String s) {
    return null;
  }

  public String getName() {
    return toString();
  }
}


text:
/*
 * This is the "behavior" of the rebot.
 * It should just be a very simple flow of function calls.
 *
 * This was once a fancy "Behavior" system using a library,
 * but the operation was complex and it required outside tools to view and modify.
 *
 * This aims to use simple program logic, so it should be clear if you read the code,
 * what the robot will do,
 * and you can just edit the code to change things.
 *
 * The only "rule" is to try to avoid putting any code here other than the logic and function calls.
 *
 */

const polling = require('./behaviors/polling');
const startROS = require('./behaviors/startROS');
const makeMap = require('./behaviors/makeMap');
const autoExplore = require('./behaviors/autoExplore');
const loadMap = require('./behaviors/loadMap');
const unPlugRobot = require('./behaviors/unPlugRobot');
const goToWaypoint = require('./behaviors/goToWaypoint');
const handlePowerWithoutROS = require('./behaviors/handlePowerWithoutROS');
// const gotoRandomLocation = require('behaviors/gotoRandomLocation');

const webModel = require('./webModel');
const webModelFunctions = require('./webModelFunctions');
const wait = require('./wait');
const killROS = require('./killROS');

async function loop() {
    if (webModel.debugging) {
        console.log('Behave loop starting:');
    }
    // This is a bit of a catchall.
    // Certainly some things here could be broken out into their own behavior files.
    await polling();

    // The pattern is that if a behavior is "working on something" it returns false,
    // causing the loop to abort, so that it can keep working uninterrupted.
    // Otherwise it should always return true, to let the loop do the next thing.

    // A behavior should be callable over and over, even if it is already running.

    if (!await startROS()) {
        return;
    }

    if (webModel.ROSisRunning) {
        if (webModel.autoExplore) {
            if (!await autoExplore()) {
                return;
            }
        } else if (webModel.makeMap) {
            if (!await makeMap()) {
                return;
            }
        } else {
            // TODO: Only call if there is a map name, and make another behavior for "Where am I?"
            if (!await loadMap()) {
                return;
            }
        }

        if (webModel.pluggedIn && (webModel.autoExplore || webModel.mapName !== '')) {
            if (!await unPlugRobot()) {
                return;
            }
        }

        if (webModel.mapName !== '' && !webModel.pluggedIn) {
            if (webModel.wayPointNavigator.goToWaypoint) {
                if (!await goToWaypoint()) {
                    return;
                }
            } else {
                // Robot has a map loaded, and is not plugged in.
                // TODO: GO to random location
            }
        }
    } else {
        // ROS is NOT running
        await handlePowerWithoutROS();
    }
    // TODO: More stuff.

    if (webModel.debugging) {
        console.log("Nothing stopped this behave loop.");
    }

}

async function behave() {
    while (!webModel.shutdownRequested) {
        try {
            await loop();
        } catch (e) {
            console.error('Behavior Loop Error:');
            console.error(e);
        }
        await wait(1);
    }
    // This allows the script to kill itself.
    if (!webModel.killRosHasRun) {
        console.log('Shutdown Requested via webModel.');
    }
    webModelFunctions.behaviorStatusUpdate('Shutdown Requested via webModel.');
    killROS(true);
}

module.exports = behave;


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

#nullable disable

using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osu.Game.Online.API;
using osu.Game.Overlays.Notifications;

namespace osu.Game.Updater
{
    /// <summary>
    /// An update manager that shows notifications if a newer release is detected.
    /// This is a case where updates are handled externally by a package manager or other means, so no action is performed on clicking the notification.
    /// </summary>
    public class NoActionUpdateManager : UpdateManager
    {
        private string version;

        [BackgroundDependencyLoader]
        private void load(OsuGameBase game)
        {
            version = game.Version;
        }

        protected override async Task<bool> PerformUpdateCheck()
        {
            try
            {
                var releases = new OsuJsonWebRequest<GitHubRelease>("https://api.github.com/repos/ppy/osu/releases/latest");

                await releases.PerformAsync().ConfigureAwait(false);

                var latest = releases.ResponseObject;

                // avoid any discrepancies due to build suffixes for now.
                // eventually we will want to support release streams and consider these.
                version = version.Split('-').First();
                string latestTagName = latest.TagName.Split('-').First();

                if (latestTagName != version)
                {
                    Notifications.Post(new SimpleNotification
                    {
                        Text = $"A newer release of osu! has been found ({version} → {latestTagName}).\n\n"
                               + "Check with your package manager / provider to bring osu! up-to-date!",
                        Icon = FontAwesome.Solid.Upload,
                    });

                    return true;
                }
            }
            catch
            {
                // we shouldn't crash on a web failure. or any failure for the matter.
                return true;
            }

            return false;
        }
    }
}


text:
#ifndef FFMPEG_INTFLOAT_READWRITE_H
#define FFMPEG_INTFLOAT_READWRITE_H

#include "common.h"

/* IEEE 80 bits extended float */
typedef struct AVExtFloat  {
    uint8_t exponent[2];
    uint8_t mantissa[8];
} AVExtFloat;

double av_int2dbl(int64_t v);
float av_int2flt(int32_t v);
double av_ext2dbl(const AVExtFloat ext);
int64_t av_dbl2int(double d);
int32_t av_flt2int(float d);
AVExtFloat av_dbl2ext(double d);

#endif /* FFMPEG_INTFLOAT_READWRITE_H */


text:
.. _geogit-pg-export:

geogit-pg-export documentation
###############################

SYNOPSIS
********
geogit pg export [options] <feature_type> <table>

DESCRIPTION
***********

This command exports features from a feature type into a PostGIS database.

The feature type can be defined using the <refspec>:<table> notation, so a feature type from a different tree can be exported.

If no origin tree is specified and just a feature type name is used, the working tree will be used, so ``table`` is equivalent to ``WORK_TREE:table``.

If the table already exists, it will not be overwritten, unless the ``-o`` modifier is used.

OPTIONS
*******

-o 		        Overwrite the output table if it already exists.

--host          Machine name or IP address to connect to. Default: localhost

--port          Port number to connect to.  Default: 5432

--schema        The database schema to access.  Default: public

--database      The databse to connect to.  Default: database

--user          User name.  Default: postgres

--password      Password.  Default: <no password>

SEE ALSO
********

:ref:`geogit-pg-list`

BUGS
****

Discussion is still open.


text:
clear

echo -e "Install gcc-4.7 g++-4.7 on Raspberry Pi\n=======================================\n\nPlease wait..."
sudo apt-get install gcc-4.7 g++-4.7
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7
sudo update-alternatives --config gcc

read -p "Done!. Press [Enter] to continue..."


text:
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Utils;

namespace ICSharpCode.AvalonEdit.Highlighting
{
	/// <summary>
	/// Takes a series of highlighting commands and stores them.
	/// Later, it can build inline objects (for use with WPF TextBlock) from the commands.
	/// </summary>
	/// <remarks>
	/// This class is not used in AvalonEdit - but it is useful for someone who wants to put a HighlightedLine
	/// into a TextBlock.
	/// In SharpDevelop, we use it to provide syntax highlighting inside the search results pad.
	/// </remarks>
	[Obsolete("Use RichText / RichTextModel instead")]
	public sealed class HighlightedInlineBuilder
	{
		static HighlightingBrush MakeBrush(Brush b)
		{
			SolidColorBrush scb = b as SolidColorBrush;
			if (scb != null)
				return new SimpleHighlightingBrush(scb);
			else
				return null;
		}

		readonly string text;
		List<int> stateChangeOffsets = new List<int>();
		List<HighlightingColor> stateChanges = new List<HighlightingColor>();

		int GetIndexForOffset(int offset)
		{
			if (offset < 0 || offset > text.Length)
				throw new ArgumentOutOfRangeException("offset");
			int index = stateChangeOffsets.BinarySearch(offset);
			if (index < 0) {
				index = ~index;
				if (offset < text.Length) {
					stateChanges.Insert(index, stateChanges[index - 1].Clone());
					stateChangeOffsets.Insert(index, offset);
				}
			}
			return index;
		}

		/// <summary>
		/// Creates a new HighlightedInlineBuilder instance.
		/// </summary>
		public HighlightedInlineBuilder(string text)
		{
			if (text == null)
				throw new ArgumentNullException("text");
			this.text = text;
			stateChangeOffsets.Add(0);
			stateChanges.Add(new HighlightingColor());
		}

		/// <summary>
		/// Creates a new HighlightedInlineBuilder instance.
		/// </summary>
		public HighlightedInlineBuilder(RichText text)
		{
			if (text == null)
				throw new ArgumentNullException("text");
			this.text = text.Text;
			stateChangeOffsets.AddRange(text.stateChangeOffsets);
			stateChanges.AddRange(text.stateChanges);
		}

		HighlightedInlineBuilder(string text, List<int> offsets, List<HighlightingColor> states)
		{
			this.text = text;
			stateChangeOffsets = offsets;
			stateChanges = states;
		}

		/// <summary>
		/// Gets the text.
		/// </summary>
		public string Text {
			get { return text; }
		}

		/// <summary>
		/// Applies the properties from the HighlightingColor to the specified text segment.
		/// </summary>
		public void SetHighlighting(int offset, int length, HighlightingColor color)
		{
			if (color == null)
				throw new ArgumentNullException("color");
			if (color.Foreground == null && color.Background == null && color.FontStyle == null && color.FontWeight == null && color.Underline == null) {
				// Optimization: don't split the HighlightingState when we're not changing
				// any property. For example, the "Punctuation" color in C# is
				// empty by default.
				return;
			}
			int startIndex = GetIndexForOffset(offset);
			int endIndex = GetIndexForOffset(offset + length);
			for (int i = startIndex; i < endIndex; i++) {
				stateChanges[i].MergeWith(color);
			}
		}

		/// <summary>
		/// Sets the foreground brush on the specified text segment.
		/// </summary>
		public void SetForeground(int offset, int length, Brush brush)
		{
			int startIndex = GetIndexForOffset(offset);
			int endIndex = GetIndexForOffset(offset + length);
			var hbrush = MakeBrush(brush);
			for (int i = startIndex; i < endIndex; i++) {
				stateChanges[i].Foreground = hbrush;
			}
		}

		/// <summary>
		/// Sets the background brush on the specified text segment.
		/// </summary>
		public void SetBackground(int offset, int length, Brush brush)
		{
			int startIndex = GetIndexForOffset(offset);
			int endIndex = GetIndexForOffset(offset + length);
			var hbrush = MakeBrush(brush);
			for (int i = startIndex; i < endIndex; i++) {
				stateChanges[i].Background = hbrush;
			}
		}

		/// <summary>
		/// Sets the font weight on the specified text segment.
		/// </summary>
		public void SetFontWeight(int offset, int length, FontWeight weight)
		{
			int startIndex = GetIndexForOffset(offset);
			int endIndex = GetIndexForOffset(offset + length);
			for (int i = startIndex; i < endIndex; i++) {
				stateChanges[i].FontWeight = weight;
			}
		}

		/// <summary>
		/// Sets the font style on the specified text segment.
		/// </summary>
		public void SetFontStyle(int offset, int length, FontStyle style)
		{
			int startIndex = GetIndexForOffset(offset);
			int endIndex = GetIndexForOffset(offset + length);
			for (int i = startIndex; i < endIndex; i++) {
				stateChanges[i].FontStyle = style;
			}
		}

		/// <summary>
		/// Creates WPF Run instances that can be used for TextBlock.Inlines.
		/// </summary>
		public Run[] CreateRuns()
		{
			return ToRichText().CreateRuns();
		}

		/// <summary>
		/// Creates a RichText instance.
		/// </summary>
		public RichText ToRichText()
		{
			return new RichText(text, stateChangeOffsets.ToArray(), stateChanges.Select(FreezableHelper.GetFrozenClone).ToArray());
		}

		/// <summary>
		/// Clones this HighlightedInlineBuilder.
		/// </summary>
		public HighlightedInlineBuilder Clone()
		{
			return new HighlightedInlineBuilder(this.text,
			                                    stateChangeOffsets.ToList(),
			                                    stateChanges.Select(sc => sc.Clone()).ToList());
		}
	}
}


text:
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING, List, Optional, Sequence, Union

from airflow.models import BaseOperator
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.providers.ftp.hooks.ftp import FTPHook

if TYPE_CHECKING:
    from airflow.utils.context import Context

class FTPToS3Operator(BaseOperator):
    """
    This operator enables the transfer of files from a FTP server to S3. It can be used to
    transfer one or multiple files.

    :param ftp_path: The ftp remote path. For one file it is mandatory to include the file as well.
        For multiple files, it is the route where the files will be found.
    :type ftp_path: str
    :param s3_bucket: The targeted s3 bucket in which to upload the file(s).
    :type s3_bucket: str
    :param s3_key: The targeted s3 key. For one file it must include the file path. For several,
        it must end with "/".
    :type s3_key: str
    :param ftp_filenames: Only used if you want to move multiple files. You can pass a list
        with exact filenames present in the ftp path, or a prefix that all files must meet. It
        can also be the string '*' for moving all the files within the ftp path.
    :type ftp_filenames: Union(str, list)
    :param s3_filenames: Only used if you want to move multiple files and name them different from
        the originals from the ftp. It can be a list of filenames or file prefix (that will replace
        the ftp prefix).
    :type s3_filenames: Union(str, list)
    :param ftp_conn_id: The ftp connection id. The name or identifier for
        establishing a connection to the FTP server.
    :type ftp_conn_id: str
    :param aws_conn_id: The s3 connection id. The name or identifier for
        establishing a connection to S3.
    :type aws_conn_id: str
    :param replace: A flag to decide whether or not to overwrite the key
        if it already exists. If replace is False and the key exists, an
        error will be raised.
    :type replace: bool
    :param encrypt: If True, the file will be encrypted on the server-side
        by S3 and will be stored in an encrypted form while at rest in S3.
    :type encrypt: bool
    :param gzip: If True, the file will be compressed locally
    :type gzip: bool
    :param acl_policy: String specifying the canned ACL policy for the file being
        uploaded to the S3 bucket.
    :type acl_policy: str
    """

    template_fields: Sequence[str] = ('ftp_path', 's3_bucket', 's3_key', 'ftp_filenames', 's3_filenames')

    def __init__(
        self,
        *,
        ftp_path: str,
        s3_bucket: str,
        s3_key: str,
        ftp_filenames: Optional[Union[str, List[str]]] = None,
        s3_filenames: Optional[Union[str, List[str]]] = None,
        ftp_conn_id: str = 'ftp_default',
        aws_conn_id: str = 'aws_default',
        replace: bool = False,
        encrypt: bool = False,
        gzip: bool = False,
        acl_policy: Optional[str] = None,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self.ftp_path = ftp_path
        self.s3_bucket = s3_bucket
        self.s3_key = s3_key
        self.ftp_filenames = ftp_filenames
        self.s3_filenames = s3_filenames
        self.aws_conn_id = aws_conn_id
        self.ftp_conn_id = ftp_conn_id
        self.replace = replace
        self.encrypt = encrypt
        self.gzip = gzip
        self.acl_policy = acl_policy
        self.s3_hook: Optional[S3Hook] = None
        self.ftp_hook: Optional[FTPHook] = None

    def __upload_to_s3_from_ftp(self, remote_filename, s3_file_key):
        with NamedTemporaryFile() as local_tmp_file:
            self.ftp_hook.retrieve_file(
                remote_full_path=remote_filename, local_full_path_or_buffer=local_tmp_file.name
            )

            self.s3_hook.load_file(
                filename=local_tmp_file.name,
                key=s3_file_key,
                bucket_name=self.s3_bucket,
                replace=self.replace,
                encrypt=self.encrypt,
                gzip=self.gzip,
                acl_policy=self.acl_policy,
            )
            self.log.info(f'File upload to {s3_file_key}')

    def execute(self, context: 'Context'):
        self.ftp_hook = FTPHook(ftp_conn_id=self.ftp_conn_id)
        self.s3_hook = S3Hook(self.aws_conn_id)

        if self.ftp_filenames:
            if isinstance(self.ftp_filenames, str):
                self.log.info(f'Getting files in {self.ftp_path}')

                list_dir = self.ftp_hook.list_directory(
                    path=self.ftp_path,
                )

                if self.ftp_filenames == '*':
                    files = list_dir
                else:
                    ftp_filename: str = self.ftp_filenames
                    files = list(filter(lambda f: ftp_filename in f, list_dir))

                for file in files:
                    self.log.info(f'Moving file {file}')

                    if self.s3_filenames and isinstance(self.s3_filenames, str):
                        filename = file.replace(self.ftp_filenames, self.s3_filenames)
                    else:
                        filename = file

                    s3_file_key = f'{self.s3_key}{filename}'
                    self.__upload_to_s3_from_ftp(file, s3_file_key)

            else:
                if self.s3_filenames:
                    for ftp_file, s3_file in zip(self.ftp_filenames, self.s3_filenames):
                        self.__upload_to_s3_from_ftp(self.ftp_path + ftp_file, self.s3_key + s3_file)
                else:
                    for ftp_file in self.ftp_filenames:
                        self.__upload_to_s3_from_ftp(self.ftp_path + ftp_file, self.s3_key + ftp_file)
        else:
            self.__upload_to_s3_from_ftp(self.ftp_path, self.s3_key)


text:
<?php
class posts_getter {

	private $opml_str;
	private $posts_to_get = 25; //  maximum number of posts to get from each feed
	private $posts_arr;

	function __construct($feed_urls) {
		error_reporting(0);
		$this->feed_urls = $feed_urls;
	}
	function get_posts() {
		return $this->posts_arr;
	}

	/*------------------------------------------------------------------------------------------------------
	this uses the cURL library to get the content of a web page.  It's heavier
	than it needs to be, but I might use some of the extra stuff later
	 from http://nadeausoftware.com/articles/2007/06/php_tip_how_get_web_page_using_curl
	arguments:	the url you want to get stuff from
	returns:	the content of that page
	--------------------------------------------------------------------------------------------------------*/

	function curl_get($url) {
		$options = array(
	        CURLOPT_RETURNTRANSFER => true,     // return web page
	        CURLOPT_HEADER         => false,    // don't return headers
	        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
	        CURLOPT_ENCODING       => "utf-8",       // handle all encodings
	        CURLOPT_USERAGENT      => "spider", // who am i
	        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
	        CURLOPT_CONNECTTIMEOUT => 20,      // timeout on connect
	        CURLOPT_TIMEOUT        => 20,      // timeout on response
	        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
	    );

	    $ch      = curl_init( $url );
	    curl_setopt_array( $ch, $options );
	    $content = curl_exec( $ch );
	    $err     = curl_errno( $ch );
	    $errmsg  = curl_error( $ch );
	    $header  = curl_getinfo( $ch );
	    curl_close( $ch );

	    $header['errno']   = $err;
	    $header['errmsg']  = $errmsg;
	    $header['content'] = $content;
	    return $header;
	}

	/*------------------------------------------------------------------------------------------------------
	Makes sure that a url is valid before we store it.
	------------------------------------------------------------------------------------------------------*/
	function good_url($url) {
		if (filter_var($url, FILTER_VALIDATE_URL)) return $url;
		return 'invalid url';
	}

// 	/*------------------------------------------------------------------------------------------------------
// 	looks through the opml file and returns the urls for feeds.
// 	argument:	location of the opml file; doesn't have to be on your server
// 	returns:	the urls for all the feeds
// 	------------------------------------------------------------------------------------------------------*/
// 	function feed_urls() {
// 		$opml = simplexml_load_string($this->opml_str);
//
// 		foreach ($opml->xpath('//outline') as $outline) {
// 			$url = (string)$outline[xmlUrl];
// //			if (!$url) $url = (string)$outline[url];
//
// 			if (!filter_var($url, FILTER_VALIDATE_URL)) continue;
// 			if (strlen($url) > 100) continue;
// 			$feed_urls[] = $url;
// 		}
// 		return $feed_urls;
// 	}

	/*------------------------------------------------------------------------------------------------------
	Gets the articles from rss feeds.
	argument:  	an RSS feed item loaded as a simpleXML object
	returns:	returns the content or, if there isn't any, returns the description
	------------------------------------------------------------------------------------------------------*/

	function rss_get_post_content($item) {
		$content_ns = 'http://purl.org/rss/1.0/modules/content/';

		//for normal rss feeds:
		if ($item->children($content_ns)->encoded) {
			 $content = (string)$item->children($content_ns)->encoded;

	    //for rss feeds where only the description's included:
		} elseif ($item->description){
			 $content = (string)$item->description;
	    } else {
		    $content = '';
	    }
		 return $content;
	}

	/*------------------------------------------------------------------------------------------------------
	Makes the big array of all the posts.  We sanitize everything EXCEPT the actual post content; that takes
	too long to do correctly, so we'll do it later.
	argument:  	none
	returns:	an numerically-indexed array with information about all posts from all the feeds.
	------------------------------------------------------------------------------------------------------*/

	function build_posts_arr() {
		//initialize variables that'll be used in the loop below
		$post_num = 0;
		$latest_posts = array();

		foreach ($this->feed_urls as $k => $v) {

			////////////// get the data ////////////////////////////////
			$raw_feed = $this->curl_get($v);
			$raw_feed['content'] = $raw_feed['content'];
			//the 'LIBXML_NOCDATA' makes sure we get the escaped cdata as well:
			$xml = simplexml_load_string($raw_feed['content'], 'SimpleXMLElement', LIBXML_NOCDATA);

			// if it's an rss feed:
			if ($xml->channel->item[0]) {
				$posts = $xml->channel->item;
				$posts_count = count($posts);
				for ($i = 0; $i <= $this->posts_to_get && $i < $posts_count; $i++) { // limit number of posts to get

					//data about the blog
					$latest_posts[$post_num]['blog_title'] = strip_tags((string)$xml->channel->title);
					$latest_posts[$post_num]['blog_url'] = $this->good_url((string)$xml->channel->link);

					//data about the post
					$latest_posts[$post_num]['post_title'] = strip_tags((string)$posts[$i]->title);
					$latest_posts[$post_num]['post_url'] = $this->good_url((string)$posts[$i]->link);

					$this_post_time = strtotime((string)$posts[$i]->pubDate);
					$latest_posts[$post_num]['post_time'] = $this_post_time;

					$text = $this->rss_get_post_content($xml->channel->item[$i]);
					$latest_posts[$post_num]['content'] = $text;

					$post_num++;
				}

			//if it's an atom feed.
			} elseif ($xml->entry[0]) {
				$posts = $xml->entry;
				$posts_count = count($posts);
				for ($i = 0; $i <= $this->posts_to_get && $i < $posts_count; $i++) { // limit number of posts to get

					//data about the blog:
					$latest_posts[$post_num]['blog_title'] = strip_tags((string)$xml->title);
					$latest_posts[$post_num]['blog_url'] =  $this->good_url((string)$xml->link[0]['href']);

					//data about the post:
					$latest_posts[$post_num]['post_title'] = strip_tags((string)$posts[$i]->title);
					$this_post_time = strtotime((string)$posts[$i]->published);
					$latest_posts[$post_num]['post_time'] = $this_post_time;
					$latest_posts[$post_num]['content'] = (string)$posts[$i]->content->asXML();

					foreach($posts[$i]->link as $link_num => $link_content) {
						if ($link_content['rel'] == "alternate") {
								$latest_posts[$post_num]['post_url'] = $this->good_url((string)$link_content['href']);
						}
					}
					$post_num++;
				} //end of the entries loop
			 } //end of the atom feed conditional
		} //end of the main loop to build $latest_posts array
		$this->posts_arr = $latest_posts;
		return $latest_posts;
	}
}

?>


text:
/**
 * RelativeData uses to save plist files, armature files, animations and textures for armature data manager.
 * @constructor
 */
ccs.RelativeData = function(){
    this.plistFiles=[];
    this.armatures=[];
    this.animations=[];
    this.textures=[];
};

/**
 * ccs.armatureDataManager is a singleton object which format and manage armature configuration and armature animation
 * @class
 * @name ccs.armatureDataManager
 */
ccs.armatureDataManager = /** @lends ccs.armatureDataManager# */{
    _animationDatas: {},
    _armatureDatas: {},
    _textureDatas: {},
    _autoLoadSpriteFile: false,
    _relativeDatas: {},

    s_sharedArmatureDataManager: null,

    /**
     * Removes armature cache data by configFilePath
     * @param {String} configFilePath
     */
    removeArmatureFileInfo:function(configFilePath){
        var data = this.getRelativeData(configFilePath);
        if(data){
            var i, obj;
            for (i = 0; i < data.armatures.length; i++) {
                obj = data.armatures[i];
                this.removeArmatureData(obj);
            }
            for ( i = 0; i < data.animations.length; i++) {
                obj = data.animations[i];
                this.removeAnimationData(obj);
            }
            for ( i = 0; i < data.textures.length; i++) {
                obj = data.textures[i];
                this.removeTextureData(obj);
            }
            for ( i = 0; i < data.plistFiles.length; i++) {
                obj = data.plistFiles[i];
                cc.spriteFrameCache.removeSpriteFramesFromFile(obj);
            }
            delete this._relativeDatas[configFilePath];
            ccs.dataReaderHelper.removeConfigFile(configFilePath);
        }
    },

    /**
     * Adds armature data
     * @param {string} id The id of the armature data
     * @param {ccs.ArmatureData} armatureData
     */
    addArmatureData:function (id, armatureData, configFilePath) {
        var data = this.getRelativeData(configFilePath);
        if (data){
            data.armatures.push(id);
        }
        this._armatureDatas[id] = armatureData;
    },

    /**
     * Gets armatureData by id
     * @param {String} id
     * @return {ccs.ArmatureData}
     */
    getArmatureData:function (id) {
        var armatureData = null;
        if (this._armatureDatas) {
            armatureData = this._armatureDatas[id];
        }
        return armatureData;
    },

    /**
     * Removes armature data from armature data manager.
     * @param {string} id
     */
    removeArmatureData:function(id){
        if (this._armatureDatas[id])
            delete this._armatureDatas[id];
    },

    /**
     * Adds animation data to armature data manager.
     * @param {String} id
     * @param {ccs.AnimationData} animationData
     */
    addAnimationData:function (id, animationData, configFilePath) {
        var data = this.getRelativeData(configFilePath);
        if(data)
            data.animations.push(id);
        this._animationDatas[id] = animationData;
    },

    /**
     * Gets animationData by id
     * @param {String} id
     * @return {ccs.AnimationData}
     */
    getAnimationData:function (id) {
        var animationData = null;
        if (this._animationDatas[id]) {
            animationData = this._animationDatas[id];
        }
        return animationData;
    },

    /**
     * Removes animation data
     * @param {string} id
     */
    removeAnimationData:function(id){
        if (this._animationDatas[id])
            delete this._animationDatas[id];
    },

    /**
     * Adds texture data to Armature data manager.
     * @param {String} id
     * @param {ccs.TextureData} textureData
     */
    addTextureData:function (id, textureData, configFilePath) {
        var data = this.getRelativeData(configFilePath);
        if (data) {
            data.textures.push(id);
        }
        this._textureDatas[id] = textureData;
    },

    /**
     * Gets textureData by id
     * @param {String} id
     * @return {ccs.TextureData}
     */
    getTextureData:function (id) {
        var textureData = null;
        if (this._textureDatas) {
            textureData = this._textureDatas[id];
        }
        return textureData;
    },

    /**
     * Removes texture data by id
     * @param {string} id
     */
    removeTextureData:function(id){
        if (this._textureDatas[id])
            delete this._textureDatas[id];
    },

    /**
     * Adds ArmatureFileInfo, it is managed by CCArmatureDataManager.
     * @param {String} imagePath
     * @param {String} plistPath
     * @param {String} configFilePath
     * @example
     * //example1
     * ccs.armatureDataManager.addArmatureFileInfo("res/test.json");
     * //example2
     * ccs.armatureDataManager.addArmatureFileInfo("res/test.png","res/test.plist","res/test.json");
     */
    addArmatureFileInfo:function (/*imagePath, plistPath, configFilePath*/) {
        var imagePath, plistPath, configFilePath;
        switch(arguments.length){
            case 1:
                configFilePath = arguments[0];

                this.addRelativeData(configFilePath);

                this._autoLoadSpriteFile = true;
                ccs.dataReaderHelper.addDataFromFile(configFilePath);
                break;
            case 3:
                imagePath = arguments[0];
                plistPath = arguments[1];
                configFilePath = arguments[2];

                this.addRelativeData(configFilePath);

                this._autoLoadSpriteFile = false;
                ccs.dataReaderHelper.addDataFromFile(configFilePath);
                this.addSpriteFrameFromFile(plistPath, imagePath);
        }
    },

    /**
     * Adds ArmatureFileInfo, it is managed by CCArmatureDataManager.
     * @param {String} imagePath
     * @param {String} plistPath
     * @param {String} configFilePath
     * @param {Function} selector
     * @param {Object} target
     */
    addArmatureFileInfoAsync:function (/*imagePath, plistPath, configFilePath, selector, target*/) {
        var imagePath, plistPath, configFilePath, target, selector;
        switch(arguments.length){
            case 3:
                configFilePath = arguments[0];
                target = arguments[2];
                selector = arguments[1];
                this.addRelativeData(configFilePath);
                this._autoLoadSpriteFile = true;
                ccs.dataReaderHelper.addDataFromFileAsync("", "", configFilePath, selector,target);
                break;
            case 5:
                imagePath = arguments[0];
                plistPath = arguments[1];
                configFilePath = arguments[2];
                target = arguments[4];
                selector = arguments[3];
                this.addRelativeData(configFilePath);

                this._autoLoadSpriteFile = false;
                ccs.dataReaderHelper.addDataFromFileAsync(imagePath, plistPath, configFilePath, selector, target);
                this.addSpriteFrameFromFile(plistPath, imagePath);
        }
    },

    /**
     * Add sprite frame to CCSpriteFrameCache, it will save display name and it's relative image name
     * @param {String} plistPath
     * @param {String} imagePath
     * @param {String} configFilePath
     */
    addSpriteFrameFromFile:function (plistPath, imagePath, configFilePath) {
        var data = this.getRelativeData(configFilePath);
        if(data)
            data.plistFiles.push(plistPath);
        ccs.spriteFrameCacheHelper.addSpriteFrameFromFile(plistPath, imagePath);
    },

    /**
     * Returns whether or not need auto load sprite file
     * @returns {boolean}
     */
    isAutoLoadSpriteFile:function(){
        return this._autoLoadSpriteFile;
    },

    /**
     * Returns armature Data of Armature data manager.
     * @return {Object}
     */
    getArmatureDatas:function () {
        return this._armatureDatas;
    },

    /**
     * Returns animation data of Armature data manager.
     * @return {Object}
     */
    getAnimationDatas:function () {
        return this._animationDatas;
    },

    /**
     * Returns texture data of Armature data manager.
     * @return {Object}
     */
    getTextureDatas:function () {
        return this._textureDatas;
    },

    /**
     * Adds Relative data of Armature data manager.
     * @param {String} configFilePath
     */
    addRelativeData: function (configFilePath) {
        if (!this._relativeDatas[configFilePath])
            this._relativeDatas[configFilePath] = new ccs.RelativeData();
    },

    /**
     * Gets RelativeData of Armature data manager.
     * @param {String} configFilePath
     * @returns {ccs.RelativeData}
     */
    getRelativeData: function (configFilePath) {
        return this._relativeDatas[configFilePath];
    },

    /**
     * Clear data
     */
    clear: function() {
        this._animationDatas = {};
        this._armatureDatas = {};
        this._textureDatas = {};
        ccs.spriteFrameCacheHelper.clear();
        ccs.dataReaderHelper.clear();
    }
};


text:
package cn.bishiti.base.test.DesignPattern.proxy;

public interface Sourceable {

	public void method();

}


text:
@echo off
call build_depend.bat %~dp0
cd /d %~dp0
mkdir lib
mkdir include
@xcopy /Y project\src\*.h include\ > nul
@xcopy /Y project\Debug\* lib\ > nul
@xcopy /Y project\Release\* lib\ > nul
rmdir /S /Q project\RCodeLib.dir >nul
rmdir /S /Q project\CMakeFiles >nul
rmdir /S /Q project\Debug >nul
rmdir /S /Q project\Release >nul
del /Q project\*.sln > nul
del /Q project\*.vcxproj* > nul
del /Q project\cmake_install.cmake > nul
del /Q project\CMakeCache.txt > nul
pause


text:
namespace cc {

bool FakeDisplayListRecordingSource::IsSuitableForGpuRasterization() const {
  if (force_unsuitable_for_gpu_rasterization_)
    return false;
  return DisplayListRecordingSource::IsSuitableForGpuRasterization();
}

void FakeDisplayListRecordingSource::
    SetUnsuitableForGpuRasterizationForTesting() {
  force_unsuitable_for_gpu_rasterization_ = true;
}

}  // namespace cc


text:
'use strict';

var services
  ;

services = {
  'xminder.com': require('./xminder.com')
, 'fonefinder.net': require('./fonefinder.net')
, 'data24-7.com': require('./data24-7.com')
, 'freecarrierlookup.com': require('./freecarrierlookup.com')
, 'tel-carrier-cache': require('./tel-carrier-cache')
};

module.exports = services;


text:
cask :v1 => 'font-roboto-condensed' do
  version :latest
  sha256 :no_check

  url 'https://github.com/google/fonts/trunk/apache/robotocondensed',
      :using      => :svn,
      :trust_cert => true
  homepage 'http://www.google.com/fonts/specimen/Roboto%20Condensed'
  license :apache

  font 'RobotoCondensed-Bold.ttf'
  font 'RobotoCondensed-BoldItalic.ttf'
  font 'RobotoCondensed-Italic.ttf'
  font 'RobotoCondensed-Light.ttf'
  font 'RobotoCondensed-LightItalic.ttf'
  font 'RobotoCondensed-Regular.ttf'
end


text:
/*jshint strict:false */
'Use strict';

var resultModule = angular.module('result');

resultModule.controller('resultController', [
	'$scope',
	'$http',
	'$stateParams',
	'$location',
	'Authentication',
	'Result',
	'Orders',
	'Notify',
	'ngTableParams',
	'$modal',
	'$log',
	'ConvertArray',
	'GetResults',
  'resultServices',
	function($scope, $http, $stateParams, $location, Authentication, Result, Orders, Notify, ngTableParams, $modal, $log, ConvertArray, GetResults, resultServices) {
 	this.authentication = Authentication;

   var param1= $stateParams.resultId;
    $scope.resultId = $stateParams.resultId.replace(':', '');
    $scope.resultServices = resultServices;
    $scope.resultServices.getResults().then(function(){
    $scope.resultServices.selectedResult = $scope.resultServices.getResultById($scope.resultId);
    if($scope.resultServices.selectedResult.tipomuestra === 'C'){
      $scope.resultServices.reportName = 'Reporte Citológico';
    }else{
      $scope.resultServices.reportName = 'Reporte Histopatológico';
    }

    if($scope.resultServices.selectedResult.tipomuestra === 'B'){
      $scope.resultServices.tecnica = 'Hematoxilina, Eosina';
    }else if ($scope.resultServices.selectedResult.tipomuestra === 'BG'){
      $scope.resultServices.tecnica  = 'Hematoxilina, Eosina ' + '\n' +
                                       'Histoquímica de Waysson para HP';
      if(!$scope.resultServices.selectedResult.nota){
        $scope.resultServices.notaResult = 'La nota para las Biosia Gastrica siempre tendra nota: la técnica histoquímica de Waysson para helicobacter pylori resulto positivo (se identifican moderados microorganismos espiralados igual a 2 en una escala de 0 a 3) y Tecnica';
      }else{
        $scope.resultServices.notaResult = $scope.resultServices.selectedResult.nota;
      }
    }
     $scope.resultServices.resultado = $scope.resultServices.selectedResult.resultado;
    });

	$scope.update = function(){
          $scope.resultServices.update($scope.resultServices.muestra).then(function(){
              $location.path('/orders');
          });
		};

	 }
]);

 resultModule.controller('resultUpdateController',
 	['$scope',
 	 '$http',
 	'$stateParams',
	'Orders',
	'ngTableParams',
 	'Notify',
 	'$mdToast',
 	'$animate',
 	'$modal',
	'$log',
 	function(
 	 $scope,
 	 $http,
 	 $stateParams,
 	 Orders,
 	 ngTableParams,
 	 Notify,
 	 $mdToast,
 	 $animate,
 	 $modal,
 	 $log
 		//, $stateParams
 		) {

   //Auto Cierre

     }
 ]);

  resultModule.controller('resultListController',
 	['$scope',
 	 '$http',
 	'$stateParams',
	'Orders',
	'ngTableParams',
 	'Notify',
 	'$mdToast',
 	'$animate',
 	'$modal',
	'$log',
	'$location',
  'resultServices',
  'OrderServices',
  'lodash',
  '$q',
  '$rootScope',
  '$timeout',
  'socketio',
 	function(
 	 $scope,
 	 $http,
 	 $stateParams,
 	 Orders,
 	 ngTableParams,
 	 Notify,
 	 $mdToast,
 	 $animate,
 	 $modal,
 	 $log,
 	 $location,
   resultServices,
   OrderServices,
   lodash,
   $q,
   $rootScope,
   $timeout,
   socketio
 		) {
   socketio.on('result.created', function(result) {
    $scope.services.filterResult();
   });

   $scope.services = resultServices;
   $scope.orders = OrderServices;

   $scope.printReport = function(){
    $scope.orders.isPrinting = true;
    var defer = $q.defer();
    $scope.services.printReport().then(function(totalResult){
      $scope.services.printReportList = [];
      if(totalResult.results){
           angular.forEach(totalResult.results, function(item){
             $scope.services.printReportList.push(item);
             $scope.services.totales.costo = parseInt($scope.services.totales.costo) + parseInt(item.costo ? item.costo: 0);
             $scope.services.totales.pago = parseInt($scope.services.totales.pago) + parseInt(item.pago ? item.pago: 0);
             $scope.services.totales.debe = parseInt($scope.services.totales.debe) + parseInt(item.debe ? item.debe: 0);
             $scope.services.totales.seguro = parseInt($scope.services.totales.seguro) + parseInt(item.seguroId ? 1: 0);
           });
        }
        $timeout(function(){

        $scope.orders.isPrinting = false;
        }, 2000);

        $timeout(function(){
           var printSection = document.getElementById('printSection');
            function printElement(elem) {
                    printSection.innerHTML = '';
                    //document.getElementById(attrs.printElementId);
                     printSection.appendChild(elem);
                     window.print();
                    //location.reload(true);
                }
                if (!printSection) {
                    printSection = document.createElement('div');
                    printSection.id = 'printSection';
                    document.body.appendChild(printSection);
                }else{
                   printSection = document.createElement('div');
                    printSection.id = 'printSection';
                    document.body.appendChild(printSection);
                    printSection.innerHTML = '';
                }
                              // printSection.innerHTML = ''

                 var elemToPrint = document.getElementById("printThisElement");
       // //          //elemToPrint.innerHTML = document.getElementById('resultValue').value;
       // //           // var formToHide = document.getElementById('createtemplateForm');
       // //           // formToHide.classList.add('hide');

                if (elemToPrint) {
                    printElement(elemToPrint);
                   // formToHide.classList.remove('hide');
                }
        // var printSection = document.createElement('div');

        }, 2000);

    });

     return defer.promise;
   };

    $scope.filterDoctor = function(val){
          var data = {
              lastName: val
          };
          var result = [];
          var deferred =  $q.defer();

          $http.post('/doctor/filter', data)
              .success(function(response) {
                  angular.forEach(response, function(card) {
                      result.push(card);
                  });
                  return deferred.resolve(result);
              })
              .error(function(){
                  /* error handling */
              });
          return deferred.promise;
      };

    $scope.loadMore = function(newPage, oldPage){
       $scope.services.page = newPage;
       $scope.services.loadResult(newPage);
    };

    $scope.resetSearchForm = function(){
      // $scope.services.date.startDate = moment;
      // $scope.services.date.endDate = moment();
      $scope.services.resetForm();
    };

      Notify.getMsg('newOrderPost', function(event, result){
        $scope.services.filterResult();
     });

    $scope.dateChange = function(pagination, filter){
    	 getResultsPage($scope.cPage, filter, setDateVariables());
    };

    $scope.pageChanged = function(newPage, filter, pgCurrent) {
    	 var startDate = new Date($scope.date.startDate);
    	 var endDate = new Date($scope.date.endDate);

        var dateFilter = {
        	startDate: startDate,
        	endDate: endDate
        };
        getResultsPage(newPage, filter, setDateVariables());
    };

    $scope.onSelectPatient = function($item, $model, $label){
      $scope.services.search.paciente = $item._id;
      $scope.services.filterResult($item);
    };

     $scope.onSelectDoctor = function($item, $model, $label){
      $scope.services.search.doctor = $item._id;
      $scope.services.filterResult();
    };

    $scope.validatePatient = function(){
       if($scope.services.Searchpaciente === ''){
             $scope.services.search.paciente = '';
             $scope.services.filterResult();

       }
    };

     $scope.validateDoctor = function(){
      console.log("nana");
       if($scope.services.searchDoctor === ''){
             $scope.services.search.doctor = '';
             $scope.services.filterResult();

       }
    };

    function setDateVariables(){
      var startDate = new Date($scope.date.startDate);
    	 var endDate = new Date($scope.date.endDate);
        var dateFilter = {
        	startDate: startDate,
        	endDate: endDate

        };
    	return dateFilter;
    }

 	function getResultsPage(pageNumber, filterLetter, dateFilter) {
     var startDate = dateFilter.startDate;
      $http.get('/api/result',  {
        params: {
        page: pageNumber,
        count: 25,
        filter: filterLetter,
        startDate: startDate,
        endDate: dateFilter.endDate
      }
    })
    .then(function(result) {
      //console.log(result);
      ///Logica Para Imprimir
      ///Esta es la logica para imprimir los resultados

    //    $scope.users = result.data.results;
    //    $scope.totalUsers = result.data.total;

    //   $http.get('/api/result', {
    //     params: {
    //     page: 1,
    //     count: $scope.totalUsers,
    //     filter: filterLetter,
    //     startDate: startDate,
    //     endDate: dateFilter.endDate
    //   }
    // })
    // .then(function(totalResult) {
    //   $scope.printReport = totalResult.data.results;
    //   $scope.total = {
    //       costo: 0,
    //       pago : 0,
    //       debe: 0,
    //       seguro: 0
    //   };

    //   for(var i = 0; i < totalResult.data.results.length; i++){
    //     //console.log(totalResult.data.results[i].costo);
    //         $scope.total.costo = parseInt($scope.total.costo) + parseInt(totalResult.data.results[i].costo ? totalResult.data.results[i].costo: 0);
    //         $scope.total.pago = parseInt($scope.total.pago) + parseInt(totalResult.data.results[i].pago ? totalResult.data.results[i].pago: 0);
    //         $scope.total.debe = parseInt($scope.total.debe) + parseInt(totalResult.data.results[i].debe ? totalResult.data.results[i].debe: 0);
    //         $scope.total.seguro = parseInt($scope.total.seguro) + parseInt(totalResult.data.results[i].seguroId ? 1: 0);
    //   }
    //  });
    });
    }

     $scope.setResult = function(result){
      $location.path('/result/:' + result._id);
     };

     $scope.setUpdate = function(proc){
       Notify.sendMsg('orderUpdate', {resultInfo: proc});
       $location.path('/orders');
     };

     }
 ]);

resultModule.directive('ngPrint', function(){
 var printSection = document.getElementById('printSection');
       if (!printSection) {
            printSection = document.createElement('div');
            printSection.id = 'printSection';
            document.body.appendChild(printSection);
        }else{
           printSection.innerHTML = '';
        }

        function link(scope, element, attrs) {
            element.on('click', function () {
                var elemToPrint = document.getElementById(attrs.printElementId);
                //elemToPrint.innerHTML = document.getElementById('resultValue').value;
                 var formToHide = document.getElementById('createtemplateForm');
                 formToHide.classList.add('hide');
                if (elemToPrint) {
                    printElement(elemToPrint);
                    formToHide.classList.remove('hide');
                }
            });
        }
        function printElement(elem) {
            printSection.innerHTML = '';
            //document.getElementById(attrs.printElementId);
            printSection.appendChild(elem);
            window.print();
            //location.reload(true);
        }
        return {
            link: link,
            restrict: 'A',
            controller: ['$scope', function($scope){

            }]
        };

});

resultModule.service('resultServices', ['$q','$timeout', '$http', 'Result', 'Authentication', '$rootScope', 'OrderServices', function($q, $timeout, $http, Result, Authentication, $rootScope, OrderServices){

   var self = {
   'resultList' : [],
   'Results': [],
   'printReportList':[],
   'search': {},
   'date': {},
   'params': {},
   'totales': {},
   'paramsPrint': {},
   'notaResult': null,
   'tecnica': null,
   'hasMore': true,
   'ordersServices': null,
   'page': 1,
   'total': 0,
   'count': 25,
   'selectedResult': null,
   'isPrinting': false,
   'resultado': {},
    test: null,
   'reportName': null,
   'papObservation': null,
   'loadResult': function(){
    if(!OrderServices.filtrarCurrent){
       self.date.startDate = moment().format('YYYY-MM-DD');
       self.date.endDate = moment().format('YYYY-MM-DD');
       self.params.search = {};
     }else{
      self.date.startDate = self.date.startDate ? moment(self.date.startDate).format('YYYY-MM-DD'): '';
      self.date.endDate = self.date.endDate ? moment(self.date.endDate).format('YYYY-MM-DD') : ''
    }
    var defer = $q.defer();
      self.params = {
        'page': self.page,
        'search': self.search,
         startDate : self.date.startDate,
         endDate: self.date.endDate,
        'ordering': self.ordering
      };
      Result.get(self.params, function(data){
        self.total = data.total;
        defer.resolve(data);
        self.Results = [];
       if(data.results){
           angular.forEach(data.results, function(item){
                self.Results.push(item);
           });

           // self.printReport();
        }
        if(self.count >= data.total){
            self.hasMore = false;
        }
      }, function(error){
          defer.reject();
      });
      return defer.promise;
   },
   'filterResult': function(){
        self.Results = [];
        self.count = 25;
        self.loadResult();
   },
   'resetForm': function(){
    self.search = {};
    self.filterResult();
   },
   'loadMore': function(page){
        if(self.hasMore){
            self.count += self.count;
            self.loadResult();
        }
     },
   'getResults' : function(){
    var defer = $q.defer();
     $http.post('result/getList').
          success(function(data){
            if(data){
              self.resultList = [];
                angular.forEach(data, function(dataresult){
                  self.resultList.push(dataresult);
                  defer.resolve();
                });
              }

             }).
             error(function(err){
           });
       return defer.promise;

     },
     'getResultById': function(resultId){
          for (var i = 0; i < self.resultList.length; i++) {
              var obj = self.resultList[i];
              if (obj._id === resultId) {
                return obj;
            }
          }
        },
      'printReport': function(){
         var defer = $q.defer();
        self.paramsPrint = {
              'page': 1,
              'search': self.search,
              'count': self.total
           };
        Result.get(self.paramsPrint, function(totalResult){
           self.totales = {
                costo: 0,
                pago : 0,
                debe: 0,
                seguro: 0
            };
           defer.resolve(totalResult);
        });
          return defer.promise;
      },
      'update': function(muestra){
        var defer = $q.defer();
         var updateResult = new Result({
            _id: self.selectedResult._id,
            resultado: self.resultado,
            nota: self.nota,
            tecnica: self.tecnica,
            noAutho : self.selectedResult.noAutho,
            updatedUser: Authentication.user._id,
            reportStatus: 'Listo'
         });

          updateResult.$update(function(){
            defer.resolve();
             }, function(errorResponse) {
              defer.reject();
          });

          return defer.promise;

      }, 'getDate' : function(param){
          return param.getFullYear() + '-' +  ('0'+(param.getMonth() + 1)).slice(-2)+ '-' + ('0'+(param.getDate())).slice(-2);

      }, 'watchFilters': function () {
          $rootScope.$watch(function () {
            return self.search.paciente;
            }, function (newVal) {
              if(newVal){
              if (angular.isDefined(newVal)) {
                self.loadResult();
              }
          }
        });
         $rootScope.$watch(function () {
            return self.search.doctor;
            }, function (newVal) {
              if(newVal){
              if (angular.isDefined(newVal)) {
                self.loadResult();
              }
          }
        });

        $rootScope.$watch(function () {
            return self.search.seguro;
            }, function (newVal) {
              if (angular.isDefined(newVal)) {
                self.loadResult();
          }
        });

        $rootScope.$watch(function () {
            return self.search.sereal;
            }, function (newVal) {
              if (angular.isDefined(newVal)) {
                self.loadResult();
              }
        });
      }
   };

   self.loadResult();
   self.watchFilters();
   // self.setResult();
   return self;
}
]);

resultModule.directive('printCitologia', function(){
    return {
          restrict: 'E',
          templateUrl: 'results/partials/print-citology.report.html'
     };
});

resultModule.directive('printBiopsia', function(){
    return {
          restrict: 'E',
          templateUrl: 'results/partials/print-biop.report.html'
     };
});

resultModule.directive('resultBody', function(){
    return {
          restrict: 'E',
          templateUrl: 'results/partials/result.body.report.html'
     };
});

resultModule.directive('topHeader', function(){
    return {
          restrict: 'E',
          templateUrl: 'results/partials/report-topHeader.html'
     };
});

resultModule.directive('resultBodypop', function(){
    return {
          restrict: 'E',
          templateUrl: 'results/partials/result.body.pap.report.html'
     };
});

resultModule.directive('resultPrintpop', function(){
    return {
          restrict: 'E',
          templateUrl: 'results/partials/result.body.pap.print.report.html'
     };
});

resultModule.directive('resultFooter', function(){
    return {
          restrict: 'E',
          templateUrl: 'results/partials/footer.html'
     };
});

resultModule.directive('resultDetailreport', function(){
    return {
          restrict: 'E',
          templateUrl: 'results/partials/result.body.pap.print.report.html'
     };
});


text:
describe('angular-panel-snap', function () {
	var $scope;

	beforeEach(module('akreitals.panel-snap'));

	beforeEach(inject(function ($rootScope) {
		$scope = $rootScope.$new();
	}));

	/*
	 * PanelGroupController
	 */
	describe('PanelGroupController', function () {
		var ctrl, $element, $attrs;
		beforeEach(inject(function ($controller) {
			$attrs = {};
			$element = {};
			ctrl = $controller('PanelGroupController', { $scope: $scope, $element: $element, $attrs: $attrs });
		}));

		it('should add the specified panel to the panel group', function () {
			var panel1, panel2;
			ctrl.addPanel(group1 = $scope.$new());
			ctrl.addPanel(group2 = $scope.$new());
			expect(ctrl.panels.length).toBe(2);
			expect(ctrl.panels[0]).toBe(group1);
			expect(ctrl.panels[1]).toBe(group2);
		});

		// it('should allow snapping to be enabled and disabled', function () {
		// 	expect(ctrl.enabled).toBe(true);
		// 	$scope.disableSnap();
		// 	expect(ctrl.enabled).toBe(false);
		// 	$scope.enableSnap();
		// 	expect(ctrl.enabled).toBe(true);
		// 	$scope.toggleSnap();
		// 	expect(ctrl.enabled).toBe(false);
		// 	$scope.toggleSnap();
		// 	expect(ctrl.enabled).toBe(true);
		// });
	});

	/*
	 * akPanelGroup directive
	 */
	describe('panel-group', function () {
		var scope, $compile;
		var element, panels;

		beforeEach(inject(function (_$rootScope_, _$compile_, _$timeout_) {
			scope = _$rootScope_;
			$compile = _$compile_;
			$timeout = _$timeout_;

			var tpl = 	'<ak-panel-group style="height: 100px; width: 100px; overflow: auto">' +
							'<ak-panel>First Panel</ak-panel>' +
							'<ak-panel>Second Panel</ak-panel>' +
							'<ak-panel>Third Panel</ak-panel>' +
						'</ak-panel-group>';
			element = angular.element(tpl);
			element = $compile(element)(scope);
			scope.$digest();
			panels = element.children();
		}));

		afterEach(function () {
			element = panels = scope = $compile = undefined;
		});

		it('should create panels with transcluded content', function () {
			expect(panels.length).toBe(3);
			expect(panels.eq(0).text()).toEqual('First Panel');
			expect(panels.eq(1).text()).toEqual('Second Panel');
			expect(panels.eq(2).text()).toEqual('Third Panel');
		});

		it('should mark first panel as active', function () {
			expect(panels.eq(0).hasClass('active')).toBe(true);
			expect(panels.eq(1).hasClass('active')).toBe(false);
			expect(panels.eq(2).hasClass('active')).toBe(false);
		});

		/* TODO: test scrolling, cannot get scrollTop to work with karma, also
		 		 elements all have 0 height when using tests for some reason so
		 		 cannot be tested */
		// it('should scroll to the next element', function () {
		// 	element.scrollTop(100);
		// 	element.trigger('scroll');
		// 	$timeout.flush();
		// 	expect(panels.eq(0).hasClass('active')).toBe(false);
		// 	expect(panels.eq(1).hasClass('active')).toBe(true);
		// });
	});
});


text:
<#
.SYNOPSIS
Adds licenses to already existing users

.DESCRIPTION
Must connect to Office 365 PowerShell before running the script
Expects a CSV named 'UsersToLicense.csv' to be located in the working directory.

.NOTES
Run Get-MsolAccountSku to determine the SKU to add to the users
#>

Param(
    [Parameter(Mandatory=$True,Position=1)]
    [string]$AccountSku,

    [string]$CsvPath="UsersToLicense.csv"
)

$Users = Import-Csv $CsvPath
$UsersWithError = @()

foreach ($User in $Users) {
    $MsolUser = Get-MsolUser -UserPrincipalName $User.identity

    if ($MsolUser) {
        Write-Host $User.identity
        Set-MsolUser -UserPrincipalName $User.identity -UsageLocation US
        Set-MsolUserLicense -UserPrincipalName $User.identity -AddLicenses $AccountSku
    } else {
        $UsersWithError += new-object psobject -Property @{'identity'=$User.identity}
    }
}

if ($UsersWithError.length -gt 0) {
    $UsersWithError | Export-Csv UsersWithErrors.csv -NoTypeInformation
}


text:
using LNF.Data;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Data;

namespace OnlineServices.Api.Data
{
    public class DryBoxRepository : ApiClient, IDryBoxRepository
    {
        internal DryBoxRepository(IRestClient rc) : base(rc) { }

        public IEnumerable<DryBox> GetDryBoxes()
        {
            return Get<List<DryBox>>("webapi/data/drybox");
        }

        public bool UpdateDryBox(DryBox model)
        {
            return Put("webapi/data/drybox", model);
        }

        public DryBoxAssignmentInfo GetCurrentDryBoxAssignment(int dryBoxId)
        {
            return Get<DryBoxAssignmentInfo>("webapi/data/drybox/{dryBoxId}/assignment", UrlSegments(new { dryBoxId }));
        }

        public DryBoxAssignmentInfo Request(DryBoxRequest request)
        {
            return Post<DryBoxAssignmentInfo>("webapi/data/drybox/{dryBoxId}/request", request);
        }

        public DryBoxAssignmentInfo Reject(int dryBoxAssignmentId)
        {
            return Get<DryBoxAssignmentInfo>("webapi/data/drybox/assignment/{dryBoxAssignmentId}/reject", UrlSegments(new { dryBoxAssignmentId }));
        }

        public DryBoxAssignmentInfo Approve(int dryBoxAssignmentId, DryBoxAssignmentUpdate update)
        {
            return Put<DryBoxAssignmentInfo>("webapi/data/drybox/assignment/{dryBoxAssignmentId}/approve", update, UrlSegments(new { dryBoxAssignmentId }));
        }

        public DryBoxAssignmentInfo UpdateDryBoxAssignment(int dryBoxAssignmentId, DryBoxAssignmentUpdate update)
        {
            return Put<DryBoxAssignmentInfo>("webapi/data/drybox/assignment/{dryBoxAssignmentId}", update, UrlSegments(new { dryBoxAssignmentId }));
        }

        public bool? IsAccountActive(int dryBoxId)
        {
            return Get<bool?>("webapi/data/drybox/{dryBoxId}/account/active", UrlSegments(new { dryBoxId }));
        }

        public bool Remove(int dryBoxAssignmentId, int modifiedByClientId)
        {
            return Get<bool>("webapi/data/drybox/assignment/{dryBoxAssignmentId}/remove",
                UrlSegments(new { dryBoxAssignmentId }) & QueryStrings(new { modifiedByClientId }));
        }

        public DryBoxAssignment GetDryBoxAssignment(int dryBoxAssignmentId)
        {
            return Get<DryBoxAssignment>("webapi/data/drybox/assignment/{dryBoxAssignmentId}", UrlSegments(new { dryBoxAssignmentId }));
        }

        public IEnumerable<DryBoxAssignment> GetActiveDryBoxAssignments(DateTime sd, DateTime ed)
        {
            return Get<List<DryBoxAssignment>>("webapi/data/drybox/assignment/active");
        }

        public bool ClientAccountHasDryBox(int clientAccountId)
        {
            return Get<bool>("webapi/data/drybox/clientaccount/{clientAccountId}/exists", UrlSegments(new { clientAccountId }));
        }

        public bool ClientOrgHasDryBox(int clientOrgId)
        {
            return Get<bool>("webapi/data/drybox/clientorg/{clientOrgId}/exists", UrlSegments(new { clientOrgId }));
        }

        public IClientAccount GetDryBoxClientAccount(int clientOrgId)
        {
            return Get<ClientAccountItem>("webapi/data/drybox/clientorg/{clientOrgId}/clientaccount", UrlSegments(new { clientOrgId }));
        }

        public IEnumerable<DryBoxAssignmentInfo> GetCurrentDryBoxAssignments()
        {
            return Get<List<DryBoxAssignmentInfo>>("webapi/data/drybox/assignment/current");
        }

        public DryBoxAssignmentInfo CancelRequest(int dryBoxAssignmentId)
        {
            return Get<DryBoxAssignmentInfo>("webapi/data/drybox/assignment/{dryBoxAssignmentId}/cancel-request", UrlSegments(new { dryBoxAssignmentId }));
        }

        public DryBoxAssignmentInfo RequestRemove(int dryBoxAssignmentId)
        {
            return Get<DryBoxAssignmentInfo>("webapi/data/drybox/assignment/{dryBoxAssignmentId}/request-remove", UrlSegments(new { dryBoxAssignmentId }));
        }

        public IEnumerable<DryBoxHistory> GetDryBoxHistory(string dryBoxName)
        {
            return Get<List<DryBoxHistory>>("webapi/data/drybox/history/{dryBoxName}", UrlSegments(new { dryBoxName }));
        }

        public IEnumerable<DryBoxHistory> GetDryBoxHistory(int clientId)
        {
            return Get<List<DryBoxHistory>>("webapi/data/drybox/history/client/{clientId}", UrlSegments(new { clientId }));
        }

        public DataSet ReadDryBoxData(DateTime sd, DateTime ed, int clientId = 0)
        {
            throw new NotImplementedException();
        }
    }
}