text:
# From https://spglib.github.io/spglib/definition.html#computing-rigid-rotation-introduced-by-idealization
@testset "Computing rigid rotation introduced by idealization" begin
    lattice = [
        [5.0759761474456697, 5.0759761474456697, 0],  # a
        [-2.8280307701821314, 2.8280307701821314, 0],  # b
        [0, 0, 8.57154746],  # c
    ]
    positions = [
        [0.0, 0.84688439, 0.1203133],
        [0.0, 0.65311561, 0.6203133],
        [0.0, 0.34688439, 0.3796867],
        [0.0, 0.15311561, 0.8796867],
        [0.5, 0.34688439, 0.1203133],
        [0.5, 0.15311561, 0.6203133],
        [0.5, 0.84688439, 0.3796867],
        [0.5, 0.65311561, 0.8796867],
    ]
    numbers = fill(35, length(positions))
    cell = Cell(lattice, positions, numbers)
    dataset = get_dataset(cell, 1e-5)
    # Compared with documented results
    @test get_spacegroup_number(cell) == 64
    @test dataset.spacegroup_number == 64
    @test dataset.international_symbol == "Cmce"
    @test get_international(cell, 1e-5) == "Cmce"
    @test dataset.hall_number == 304  # Compared with Python results
    @test dataset.hall_symbol == "-C 2bc 2"  # Compared with Python results
    @test dataset.transformation_matrix == [  # Compared with documented results
        1 0 0
        0 1 0
        0 0 1
    ]
    @test dataset.std_lattice ≈ [  # Compared with documented results
        7.17851431 0 0
        0 3.99943947 0
        0 0 8.57154746
    ]
    # Compared with Python results
    @test isempty(dataset.choice)
    @test isapprox(dataset.origin_shift, [5.55111512e-17, 0, 0]; atol = 1e-16)
    @test dataset.pointgroup_symbol == "mmm"
    @test dataset.std_types == [35, 35, 35, 35, 35, 35, 35, 35] / 35
    @test dataset.std_positions ≈ [
        0.0 0.0 0.0 0.0 0.5 0.5 0.5 0.5
        0.84688439 0.65311561 0.34688439 0.15311561 0.34688439 0.15311561 0.84688439 0.65311561
        0.1203133 0.6203133 0.3796867 0.8796867 0.1203133 0.6203133 0.3796867 0.8796867
    ]
    @test dataset.std_rotation_matrix ≈ [
        0.70710678 -0.70710678 0.0
        0.70710678 0.70710678 0.0
        0.0 0.0 1.0
    ]
    @test dataset.mapping_to_primitive == [0, 1, 2, 3, 0, 1, 2, 3]
    @test dataset.std_mapping_to_primitive == [0, 1, 2, 3, 0, 1, 2, 3]
    @test dataset.wyckoffs == ['f', 'f', 'f', 'f', 'f', 'f', 'f', 'f']
    @test dataset.site_symmetry_symbols ==
          ["m..", "m..", "m..", "m..", "m..", "m..", "m..", "m.."]
    @test dataset.equivalent_atoms == [0, 0, 0, 0, 0, 0, 0, 0]
    if get_version() >= v"1.15"
        @test dataset.crystallographic_orbits == [0, 0, 0, 0, 0, 0, 0, 0]
        @test dataset.primitive_lattice ≈ [
            2.82803077 1.12397269 0.0
            -2.82803077 3.95200346 0.0
            0.0 0.0 8.57154746
        ]
    end
    @test dataset.translations ≈ [
        0.0 -1.11022302e-16 -1.11022302e-16 0.0 0.0 -1.11022302e-16 -1.11022302e-16 0.0 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5
        0.0 2.46519033e-32 0.5 0.5 0.0 2.46519033e-32 0.5 0.5 0.5 0.5 0.0 0.0 0.5 0.5 0.0 0.0
        0.0 0.0 0.5 0.5 0.0 0.0 0.5 0.5 0.0 0.0 0.5 0.5 0.0 0.0 0.5 0.5
    ]
    rotations = dataset.rotations
    python_rotations = [
        [1 0 0; 0 1 0; 0 0 1],
        [-1 0 0; 0 -1 0; 0 0 -1],
        [-1 0 0; 0 -1 0; 0 0 1],
        [1 0 0; 0 1 0; 0 0 -1],
        [1 0 0; 0 -1 0; 0 0 -1],
        [-1 0 0; 0 1 0; 0 0 1],
        [-1 0 0; 0 1 0; 0 0 -1],
        [1 0 0; 0 -1 0; 0 0 1],
        [1 0 0; 0 1 0; 0 0 1],
        [-1 0 0; 0 -1 0; 0 0 -1],
        [-1 0 0; 0 -1 0; 0 0 1],
        [1 0 0; 0 1 0; 0 0 -1],
        [1 0 0; 0 -1 0; 0 0 -1],
        [-1 0 0; 0 1 0; 0 0 1],
        [-1 0 0; 0 1 0; 0 0 -1],
        [1 0 0; 0 -1 0; 0 0 1],
    ]
    @test all(map(1:16) do i
        rotations[:, :, i] == python_rotations[i]
    end)
    @test get_symmetry(cell) == (dataset.rotations, dataset.translations)
end

@testset "Test rutile structure" begin
    lattice = [
        4 0 0
        0 4 0
        0 0 3
    ]
    positions = [
        0.0 0.5 0.3 0.7 0.2 0.8
        0.0 0.5 0.3 0.7 0.8 0.2
        0.0 0.5 0.0 0.0 0.5 0.5
    ]
    types = [14, 14, 8, 8, 8, 8]
    rutile = Cell(lattice, positions, types)
    dataset = get_dataset(rutile, 1e-5)
    @test dataset.spacegroup_number == 136
    @test dataset.site_symmetry_symbols == ["m.mm", "m.mm", "m.2m", "m.2m", "m.2m", "m.2m"]
    @test dataset.hall_number == 419
    @test isempty(dataset.choice)
    @test dataset.equivalent_atoms == [0, 0, 2, 2, 2, 2]
    @test dataset.wyckoffs == ['a', 'a', 'f', 'f', 'f', 'f']
    @test dataset.std_positions == [
        0.0 0.5 0.3 0.7 0.2 0.8
        0.0 0.5 0.3 0.7 0.8 0.2
        0.0 0.5 0.0 0.0 0.5 0.5
    ]
    @test dataset.origin_shift == [0.0, 0.0, 0.0]
    @test dataset.international_symbol == "P4_2/mnm"
    @test get_international(rutile, 1e-5) == "P4_2/mnm"
    @test dataset.std_lattice == [
        4.0 0.0 0.0
        0.0 4.0 0.0
        0.0 0.0 3.0
    ]
    @test dataset.std_types == [1, 1, 2, 2, 2, 2]  # 14, 14, 8, 8, 8, 8
    @test dataset.pointgroup_symbol == "4/mmm"
    @test dataset.hall_symbol == "-P 4n 2n"
    @test dataset.transformation_matrix == [
        1.0 0.0 0.0
        0.0 1.0 0.0
        0.0 0.0 1.0
    ]
    @test dataset.std_mapping_to_primitive == [0, 1, 2, 3, 4, 5]
    if get_version() >= v"1.15"
        @test dataset.crystallographic_orbits == [0, 0, 2, 2, 2, 2]
        @test dataset.primitive_lattice == [
            0.0 4.0 0.0
            0.0 0.0 4.0
            3.0 0.0 0.0
        ]
    end
    @test dataset.std_rotation_matrix == [
        1.0 0.0 0.0
        0.0 1.0 0.0
        0.0 0.0 1.0
    ]
    @test dataset.translations == [
        0.0 0.0 0.5 0.5 0.0 0.0 0.5 0.5 0.5 0.5 0.0 0.0 0.5 0.5 0.0 0.0
        0.0 0.0 0.5 0.5 0.0 0.0 0.5 0.5 0.5 0.5 0.0 0.0 0.5 0.5 0.0 0.0
        0.0 0.0 0.5 0.5 0.0 0.0 0.5 0.5 0.5 0.5 0.0 0.0 0.5 0.5 0.0 0.0
    ]
    rotations = dataset.rotations
    python_rotations = [
        [1 0 0; 0 1 0; 0 0 1],
        [-1 0 0; 0 -1 0; 0 0 -1],
        [0 1 0; -1 0 0; 0 0 1],
        [0 -1 0; 1 0 0; 0 0 -1],
        [-1 0 0; 0 -1 0; 0 0 1],
        [1 0 0; 0 1 0; 0 0 -1],
        [0 -1 0; 1 0 0; 0 0 1],
        [0 1 0; -1 0 0; 0 0 -1],
        [1 0 0; 0 -1 0; 0 0 -1],
        [-1 0 0; 0 1 0; 0 0 1],
        [0 -1 0; -1 0 0; 0 0 -1],
        [0 1 0; 1 0 0; 0 0 1],
        [-1 0 0; 0 1 0; 0 0 -1],
        [1 0 0; 0 -1 0; 0 0 1],
        [0 1 0; 1 0 0; 0 0 -1],
        [0 -1 0; -1 0 0; 0 0 1],
    ]
    @test all(map(1:16) do i
        rotations[:, :, i] == python_rotations[i]
    end)
    @test get_symmetry(rutile) == (dataset.rotations, dataset.translations)
end

@testset "Test distorted rutile structure" begin
    lattice = [
        3.97 0.00 0.00
        0.00 4.03 0.00
        0.00 0.00 3.00
    ]
    positions = [
        0.0 0.5001 0.3 0.7 0.2 0.8
        0.0 0.5 0.3 0.7 0.8 0.2
        0.0 0.5 0.0 0.002 0.5 0.5
    ]
    types = [14, 14, 8, 8, 8, 8]
    distorted_rutile = Cell(lattice, positions, types)
    @testset "Test `get_dataset`" begin
        # These results are compared with Python's spglib results.
        dataset = get_dataset(distorted_rutile, 1e-5)
        @test dataset.mapping_to_primitive == [0, 1, 2, 3, 4, 5]
        @test dataset.international_symbol == "P1"
        @test get_international(distorted_rutile, 1e-5) == "P1"
        @test dataset.spacegroup_number == 1
        @test dataset.site_symmetry_symbols == ["1", "1", "1", "1", "1", "1"]
        @test dataset.hall_number == 1
        @test isempty(dataset.choice)
        @test dataset.equivalent_atoms == [0, 1, 2, 3, 4, 5]
        @test dataset.rotations ==
              permutedims(cat([1 0 0], [0 1 0], [0 0 1]; dims = 3), [2, 3, 1])  # Different dimensions with Python
        @test dataset.wyckoffs == ['a', 'a', 'a', 'a', 'a', 'a']
        @test dataset.primitive_lattice == [
            0.0 3.97 0.0
            0.0 0.0 4.03
            3.0 0.0 0.0
        ]
        @test dataset.std_positions == [
            0.0 0.5 0.0 0.002 0.5 0.5
            0.0 0.5001 0.3 0.7 0.2 0.8
            0.0 0.5 0.3 0.7 0.8 0.2
        ]
        @test dataset.origin_shift == [0.0, 0.0, 0.0]
        @test dataset.std_lattice ≈ [
            3.0 2.4309239e-16 2.4676633e-16
            0.0 3.97 2.4676633e-16
            0.0 0.0 4.03
        ]
        @test dataset.std_types == [1, 1, 2, 2, 2, 2]
        @test dataset.std_rotation_matrix == [
            0.0 1.0 0.0
            0.0 0.0 1.0
            1.0 0.0 0.0
        ]
        @test dataset.translations == [0.0 0.0 0.0]'
        @test dataset.pointgroup_symbol == "1"
        @test dataset.hall_symbol == "P 1"
        @test dataset.transformation_matrix == [
            0.0 1.0 0.0
            0.0 0.0 1.0
            1.0 0.0 0.0
        ]
        @test dataset.std_mapping_to_primitive == [0, 1, 2, 3, 4, 5]
        @test dataset.crystallographic_orbits == [0, 1, 2, 3, 4, 5]
        @test get_symmetry(distorted_rutile) == (dataset.rotations, dataset.translations)
    end
end

# From https://github.com/unkcpz/LibSymspg.jl/blob/53d2f6d/test/test_api.jl#L14-L32
@testset "Test `get_dataset` for a P-3m1 crystal" begin
    lattice = [
        4.0 2.0 0.0
        0.0 3.4641 0.0
        0.0 0.0 12.0
    ]
    positions = [
        0.0 1/3
        0.0 1/3
        0.0 1/3
    ]
    types = [1, 1]
    cell = Cell(lattice, positions, types)
    dataset = get_dataset(cell, 1e-3)
    # Compared results with Python spglib
    @test dataset.spacegroup_number == 164
    @test dataset.hall_number == 456
    @test dataset.international_symbol == "P-3m1"
    @test get_international(cell, 1e-3) == "P-3m1"
    @test isempty(dataset.choice)
    @test dataset.transformation_matrix ≈ [
        1.0 1.0 0.0
        0.0 1.0 0.0
        0.0 0.0 1.0
    ]
    @test dataset.origin_shift ≈ [1 / 3, 2 / 3, 1 / 3]
    @test dataset.n_operations == 12
    rotations = dataset.rotations
    python_rotations = [
        [1 0 0; 0 1 0; 0 0 1],
        [-1 0 0; 0 -1 0; 0 0 -1],
        [-1 1 0; -1 0 0; 0 0 1],
        [1 -1 0; 1 0 0; 0 0 -1],
        [0 -1 0; 1 -1 0; 0 0 1],
        [0 1 0; -1 1 0; 0 0 -1],
        [1 0 0; 1 -1 0; 0 0 -1],
        [-1 0 0; -1 1 0; 0 0 1],
        [0 -1 0; -1 0 0; 0 0 -1],
        [0 1 0; 1 0 0; 0 0 1],
        [-1 1 0; 0 1 0; 0 0 -1],
        [1 -1 0; 0 -1 0; 0 0 1],
    ]
    @test all(map(1:12) do i
        rotations[:, :, i] == python_rotations[i]
    end)
    @test dataset.translations ≈
          [
        0 1 0 1 0 1 1 0 1 0 1 0
        0 1 0 1 0 1 1 0 1 0 1 0
        0 1 0 1 0 1 1 0 1 0 1 0
    ] / 3
    @test size(dataset.rotations) == (3, 3, 12)
    @test size(dataset.translations) == (3, 12)
    @test get_symmetry(cell) == (dataset.rotations, dataset.translations)
    @test dataset.wyckoffs == ['d', 'd']
    @test dataset.site_symmetry_symbols == ["3m.", "3m."]
    @test dataset.equivalent_atoms == [0, 0]
    if get_version() >= v"1.15"
        @test dataset.crystallographic_orbits == [0, 0]
        @test dataset.primitive_lattice == [
            2.0 -2.0 0.0
            -3.4641 -3.4641 0.0
            0.0 0.0 -12.0
        ]
    end
    @test dataset.mapping_to_primitive == [0, 1]
    @test dataset.std_lattice ≈ [
        3.9999986 -1.9999993 0.0
        0.0 3.4641004 0.0
        0.0 0.0 12.0
    ]
    @test dataset.std_types == [1, 1]
    @test dataset.std_positions ≈ [
        1 2
        2 1
        1 2
    ] / 3
    @test dataset.std_rotation_matrix ≈ [
        0.50000017 0.8660253 0.0
        -0.8660253 0.50000017 0.0
        0.0 0.0 1.0
    ]
    @test dataset.std_mapping_to_primitive == [0, 1]
    @test dataset.pointgroup_symbol == "-3m"
end

@testset "Test silicon structure" begin
    lattice = [
        4 0 0
        0 4 0
        0 0 4
    ]
    positions = [
        0.0 0.0 0.5 0.5 0.25 0.25 0.75 0.75
        0.0 0.5 0.0 0.5 0.25 0.75 0.25 0.75
        0.0 0.5 0.5 0.0 0.25 0.75 0.75 0.25
    ]
    types = [14, 14, 14, 14, 14, 14, 14, 14]
    silicon = Cell(lattice, positions, types)
    dataset = get_dataset(silicon, 1e-5)
    # Compared with Python results
    @test dataset.spacegroup_number == 227
    @test dataset.hall_number == 525
    @test dataset.international_symbol == "Fd-3m"
    @test dataset.hall_symbol == "F 4d 2 3 -1d"
    @test get_international(silicon, 1e-5) == "Fd-3m"
    @test dataset.choice == "1"
    @test dataset.transformation_matrix == [
        1 0 0
        0 1 0
        0 0 1
    ]
    @test dataset.origin_shift == [0, 0, 0]
    @test size(dataset.rotations) == (3, 3, 192)
    @test dataset.translations == [
        0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.75 0.5 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0
        0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5
        0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.75 0.0 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5 0.25 0.5
    ]
    @test get_symmetry(silicon) == (dataset.rotations, dataset.translations)
    @test dataset.wyckoffs == ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
    @test dataset.site_symmetry_symbols ==
          ["-43m", "-43m", "-43m", "-43m", "-43m", "-43m", "-43m", "-43m"]
    @test dataset.equivalent_atoms == [0, 0, 0, 0, 0, 0, 0, 0]
    if get_version() >= v"1.15"
        @test dataset.crystallographic_orbits == [0, 0, 0, 0, 0, 0, 0, 0]
        @test dataset.primitive_lattice == [
            2.0 -2.0 2.0
            -2.0 -0.0 2.0
            0.0 -2.0 0.0
        ]
    end
    @test dataset.mapping_to_primitive == [0, 0, 0, 0, 1, 1, 1, 1]
    @test dataset.std_lattice == 4 * [
        1 0 0
        0 1 0
        0 0 1
    ]
    @test dataset.std_types == [14, 14, 14, 14, 14, 14, 14, 14] / 14
    @test dataset.std_positions == [
        0.0 0.25 0.0 0.25 0.5 0.75 0.5 0.75
        0.0 0.75 0.5 0.25 0.0 0.75 0.5 0.25
        0.0 0.75 0.5 0.25 0.5 0.25 0.0 0.75
    ]
    @test dataset.std_rotation_matrix == [
        1 0 0
        0 1 0
        0 0 1
    ]
    @test dataset.std_mapping_to_primitive == [0, 1, 0, 1, 0, 1, 0, 1]
    @test dataset.pointgroup_symbol == "m-3m"
    @testset "Test primitive silicon structure" begin
        lattice = [
            0 2 2
            2 0 2
            2 2 0
        ]
        positions = [
            0.0 0.25
            0.0 0.25
            0.0 0.25
        ]
        types = [14, 14]
        silicon_prim = Cell(lattice, positions, types)
        dataset_prim = get_dataset(silicon_prim, 1e-5)
        for f in (
            :spacegroup_number,
            :hall_number,
            :hall_symbol,
            :international_symbol,
            :choice,
            :std_lattice,
            :std_rotation_matrix,
            :std_mapping_to_primitive,
            :pointgroup_symbol,
        )
            @test getfield(dataset_prim, f) == getfield(dataset, f)
        end
        @test dataset_prim.transformation_matrix == [
            0.0 0.5 0.5
            0.5 0.0 0.5
            0.5 0.5 0.0
        ]
        @test dataset_prim.origin_shift == [0, 0, 1 / 2]
        @test size(dataset_prim.rotations) == (3, 3, 48)
        @test dataset_prim.std_types == [14, 14, 14, 14, 14, 14, 14, 14] / 14
        @test dataset_prim.std_positions == [
            0.0 0.25 0.0 0.25 0.5 0.75 0.5 0.75
            0.0 0.75 0.5 0.25 0.0 0.75 0.5 0.25
            0.5 0.25 0.0 0.75 0.0 0.75 0.5 0.25
        ]
        @test dataset_prim.translations == [
            0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0
            0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0
            0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0 0.25 0.0
        ]
        @test get_symmetry(silicon_prim) ==
              (dataset_prim.rotations, dataset_prim.translations)
        @test dataset_prim.wyckoffs == ['b', 'b']
        @test dataset_prim.site_symmetry_symbols == ["-43m", "-43m"]
        @test dataset_prim.equivalent_atoms == [0, 0]
        if get_version() >= v"1.15"
            @test dataset_prim.crystallographic_orbits == [0, 0]
            @test dataset_prim.primitive_lattice == [
                2.0 -2.0 2.0
                -2.0 0.0 2.0
                0.0 -2.0 0.0
            ]
        end
        @test dataset_prim.mapping_to_primitive == [0, 1]
    end
end


text:
type SoundBufferRecorder
    ptr::Ptr{Void}

    function SoundBufferRecorder(ptr::Ptr{Void})
        s = new(ptr)
        # finalizer(s, destroy)
        # s
    end
end

function SoundBufferRecorder()
    SoundBufferRecorder(ccall((:sfSoundBufferRecorder_create, libcsfml_audio), Ptr{Void}, ()))
end

function destroy(recorder::SoundBufferRecorder)
    println("Destroy")
    ccall((:sfSoundBufferRecorder_destroy, libcsfml_audio), Void, (Ptr{Void},), recorder.ptr)
end

function start(recorder::SoundBufferRecorder, sample_rate::Integer = 44100)
    ccall((:sfSoundBufferRecorder_start, libcsfml_audio), Void, (Ptr{Void}, UInt32), recorder.ptr, sample_rate)
end

function stop(recorder::SoundBufferRecorder)
    ccall((:sfSoundBufferRecorder_stop, libcsfml_audio), Void, (Ptr{Void},), recorder.ptr)
end

function get_sample_rate(recorder::SoundBufferRecorder)
    return Int(ccall((:sfSoundBufferRecorder_getSampleRate, libcsfml_audio), UInt32, (Ptr{Void},), recorder.ptr))
end

function get_buffer(recorder::SoundBufferRecorder)
    return SoundBuffer(ccall((:sfSoundBufferRecorder_getBuffer, libcsfml_audio), Ptr{Void}, (Ptr{Void},), recorder.ptr))
end

ext: jl


text:
# MIT License
#
# Copyright (c) 2020 Joshua E Gentry

# 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.

include("utils.jl")
include("common.jl")

include("tess_inst.jl")
include("tess_inst_config.jl")
include("tess_inst_config_vars.jl")
include("tess_inst_image.jl")
include("tess_inst_output.jl")
include("tess_inst_output_tsv.jl")
include("tess_inst_get_param.jl")
include("tess_inst_set_param.jl")
include("tess_inst_set_debug_param.jl")

include("datafiles/_package.jl")
include("data_file_download.jl")
include("data_file_update.jl")

include("tess_input_name.jl")
include("tess_output.jl")
include("pipeline/_package.jl")
include("tess_pipeline.jl")
include("tess_pipeline_add_alto.jl")
include("tess_pipeline_add_hocr.jl")
include("tess_pipeline_add_lstm_box.jl")
include("tess_pipeline_add_pdf.jl")
include("tess_pipeline_add_text.jl")
include("tess_pipeline_add_tsv.jl")
include("tess_pipeline_add_unlv.jl")
include("tess_pipeline_add_word_box.jl")


text:
"""
MOI_wrapper.jl defines the Juniper.Optimizer struct
with all mandatory MOI functions overloaded
"""

"""
Optimizer struct
"""
mutable struct Optimizer <: MOI.AbstractOptimizer
    inner::Union{JuniperProblem, Nothing}
    model_cache::MOIU.UniversalFallback{MOIU.Model{Float64}}
    options::SolverOptions
end

MOI.is_valid(model::Optimizer, index::MOI.Index) = MOI.is_valid(model.model_cache, index)

MOI.get(::Optimizer, ::MOI.SolverName) = "Juniper"

MOI.supports(::Optimizer, ::MOI.Silent) = true
MOI.supports(::Optimizer, ::MOI.NumberOfThreads) = true
MOI.supports(::Optimizer, ::MOI.TimeLimitSec) = true
MOI.supports(::Optimizer, ::MOI.RawParameter) = true

function MOI.set(model::Optimizer, ::MOI.Silent, value::Bool)
    if value
        model.options.log_levels = []
    end
    model.options.silent = value
    return
end

function MOI.set(model::Optimizer, ::MOI.NumberOfThreads, value::Union{Nothing,Int})
    if value === nothing
        model.options.processors = 1
    else
        model.options.processors = value
    end
    return
end

function MOI.set(model::Optimizer, ::MOI.TimeLimitSec, value::Union{Nothing,Float64})
    if value === nothing
        model.options.time_limit = Inf
    else
        model.options.time_limit = value
    end
    return
end

function MOI.set(model::Optimizer, p::MOI.RawParameter, value)
    p_symbol = Symbol(p.name)
    if in(p_symbol, fieldnames(SolverOptions))
        type_of_param = fieldtype(SolverOptions, p_symbol)
        if hasmethod(convert, (Type{type_of_param}, typeof(value)))
            passed_checks = true
            if p_symbol == :traverse_strategy
                if !(value in [:BFS, :DFS, :DBFS])
                    passed_checks = false
                    @error "Traverse strategy $(value) is not supported. Use one of `[:BFS, :DFS, :DBFS]`."
                end
            end
            if p_symbol == :branch_strategy
                if !(value in [:StrongPseudoCost, :PseudoCost, :Reliability, :MostInfeasible])
                    passed_checks = false
                    @error "Branch strategy $(value) is not supported. Use one of `[:StrongPseudoCost, :PseudoCost, :Reliability, :MostInfeasible]`."
                end
            end
            passed_checks && setfield!(model.options, p_symbol, convert(type_of_param, value))
        else
            @error "The option $(p.name) has a different type ($(type_of_param))"
        end
    else
        @error "The option $(p.name) doesn't exist."
    end
    return
end

# Returns the number of solutions that can be retrieved
MOI.get(model::Optimizer, ::MOI.ResultCount) = length(model.inner.solutions)

MOI.get(model::Optimizer, ::MOI.NumberOfThreads) = model.options.processors

MOI.get(model::Optimizer, ::MOI.TimeLimitSec) = model.options.time_limit

MOI.get(model::Optimizer, ::MOI.Silent) = model.options.silent

function MOI.get(model::Optimizer, p::MOI.RawParameter)
    if in(p.name, fieldnames(SolverOptions))
        return getfield(model.options, p.name)
    end
    @error "The option $(p.name) doesn't exist."
end

function register(s::Symbol, dimension::Integer, f::Function; autodiff::Bool=false)
    return RegisteredFunction(s, dimension, f, nothing, nothing, autodiff)
end

function register(s::Symbol, dimension::Integer, f::Function, gradf::Function; autodiff::Bool=false)
    return RegisteredFunction(s, dimension, f, gradf, nothing, autodiff)
end

function register(s::Symbol, dimension::Integer, f::Function, gradf::Function, grad2f::Function; autodiff::Bool=false)
    return RegisteredFunction(s, dimension, f, gradf, grad2f, autodiff)
end

"""
Optimizer struct constructor
"""
function Optimizer(;options...)

    solver_options = combine_options(options)

    return Optimizer(
    nothing,
    MOIU.UniversalFallback(MOIU.Model{Float64}()),
    solver_options)
end

function Optimizer(options::Vector{Pair{String,Any}})
    symbol_options = Dict{Symbol, Any}()
    for option in options
        symbol_options[Symbol(option.first)] = option.second
    end
    return Optimizer(symbol_options)
end

function Optimizer(options::Dict{Symbol,Any})

    solver_options = combine_options(options)

    return Optimizer(
    nothing,
    MOIU.UniversalFallback(MOIU.Model{Float64}()),
    solver_options)
end

"""
Printing the optimizer
"""
function Base.show(io::IO, model::Optimizer)
    println("A Juniper MathOptInterface model with backend")
    return
end

"""
Copy constructor for the optimizer
"""
MOIU.supports_default_copy_to(model::Optimizer, copy_names::Bool) = true
function MOI.copy_to(model::Optimizer, src::MOI.ModelLike; kws...)
    return MOI.copy_to(model.model_cache, src; kws...)
end

"""
``MOI.is_empty(model::Optimizer)`` overload for Alpine.Optimizer
"""
MOI.is_empty(model::Optimizer) = MOI.is_empty(model.model_cache)

"""
``MOI.empty!(model::Optimizer)`` overload for Alpine.Optimizer
"""
function MOI.empty!(model::Optimizer)
    model.inner = nothing
    MOI.empty!(model.model_cache)
end

"""
ordering of constraints provided to Juniper.jl
"""
linear_le_offset(model::Optimizer) = 0
linear_ge_offset(model::Optimizer) = length(model.linear_le_constraints)
linear_eq_offset(model::Optimizer) = linear_ge_offset(model) + length(model.linear_ge_constraints)
quadratic_le_offset(model::Optimizer) = linear_eq_offset(model) + length(model.linear_eq_constraints)
quadratic_ge_offset(model::Optimizer) = quadratic_le_offset(model) + length(model.quadratic_le_constraints)
quadratic_eq_offset(model::Optimizer) = quadratic_ge_offset(model) + length(model.quadratic_ge_constraints)
nlp_constraint_offset(model::Optimizer) = quadratic_eq_offset(model) + length(model.quadratic_eq_constraints)

function replace_solution!(m::JuniperProblem, tree::BnBTreeObj)
    status_dict = Dict{Symbol,MOI.TerminationStatusCode}()
    status_dict[:Time] = MOI.TIME_LIMIT
    status_dict[:Infeasible] = !tree.global_solver ? MOI.LOCALLY_INFEASIBLE : MOI.INFEASIBLE
    status_dict[:MipGap] = MOI.OBJECTIVE_LIMIT
    status_dict[:BestObjStop] = MOI.OBJECTIVE_LIMIT
    status_dict[:EnoughSolutions] = MOI.SOLUTION_LIMIT

    if isdefined(tree, :incumbent)
        incumbent = tree.incumbent
        m.objval = incumbent.objval
        m.solution = incumbent.solution
    end
    if tree.limit == :None
        if tree.incumbent.only_almost
            if !tree.global_solver
                m.status = MOI.ALMOST_LOCALLY_SOLVED
            else
                m.status = MOI.ALMOST_OPTIMAL
            end
        else
            if !tree.global_solver
                m.status = MOI.LOCALLY_SOLVED
            else
                m.status = MOI.OPTIMAL
            end
        end
    else
        m.status = status_dict[tree.limit]
    end
    m.best_bound = tree.best_bound
end

"""
``MOI.optimize!()`` for Juniper
"""
function MOI.optimize!(model::Optimizer)
    # feasibility_pump only if mip solver exists
    if model.options.feasibility_pump && model.options.mip_solver === nothing
        model.options.feasibility_pump = false
    end
    Random.seed!(JUNIPER_RNG, model.options.seed)

    # fill JuniperProblem
    model.inner = JuniperProblem()
    @views jp = model.inner
    init_juniper_problem!(jp, model)

    ps = jp.options.log_levels
    jp.debugDict = Dict{Any,Any}()

    (:All in ps || :AllOptions in ps) && print_options(jp;all=true)
    (:Options in ps) && print_options(jp;all=false)

    if !jp.options.fixed_gain_mu && jp.obj_sense == :Max
        jp.options.gain_mu = 1-jp.options.gain_mu
    end

    nw = nworkers()
    if nw < jp.options.processors
        jp.options.processors = nw
        @warn "Julia was started with less processors than you defined in your options. Start julia with: `julia -p "*string(jp.options.processors)*"`"
    end
    # set incumbent to nothing might be updated using start values or the feasibility_pump
    incumbent = nothing

    create_root_model!(model, jp)
    (:All in ps || :Info in ps) && print_info(jp)
    # fix primal start to check if we have an incumbent
    fix_primal_start!(jp)

    incumbent = solve_root_incumbent_model(jp)

    unfix_primal_start!(jp)
    relax_start_time = time()
    restarts = solve_root_model!(jp)
    jp.relaxation_time = time()-relax_start_time

    (:All in ps || :Info in ps) && println("Status of relaxation: ", jp.relaxation_status)
    jp.soltime = time()-jp.start_time

    jp.options.debug && debug_fill_basic(jp.debugDict,jp,restarts)

    # if infeasible or unbounded => return
    if !state_is_optimal(jp.relaxation_status; allow_almost=jp.options.allow_almost_solved)
        jp.status = jp.relaxation_status
        if jp.options.debug && jp.options.debug_write
            write(jp.options.debug_file_path, JSON.json(jp.debugDict))
        end
        return
    end

    (:All in ps || :Info in ps || :Timing in ps) && println("Time for relaxation: ", jp.soltime)

    jp.relaxation_objval   = MOI.get(jp.model, MOI.ObjectiveValue())
    jp.relaxation_solution = MOI.get(jp.model, MOI.VariablePrimal(), jp.x)

    jp.options.debug && debug_objective(jp.debugDict,jp)
    # TODO free model for Knitro

    (:All in ps || :Info in ps || :Timing in ps) && println("Relaxation Obj: ", jp.relaxation_objval)

    only_almost_solved = false
    if jp.num_disc_var > 0
        if jp.options.feasibility_pump
            fpump_incumbent = fpump(model,jp)
            if fpump_incumbent !== nothing
                if incumbent === nothing
                    incumbent = fpump_incumbent
                else
                    factor = jp.obj_sense == :Min ? -1 : 1
                    # if found better incumbent
                    if factor*fpump_incumbent.objval > factor*incumbent.objval
                        incumbent = fpump_incumbent
                    end
                end
            end
        end
        bnbtree = init(jp.start_time, jp; incumbent = incumbent)
        solvemip(bnbtree)

        replace_solution!(jp, bnbtree)
        jp.nsolutions = bnbtree.nsolutions
    else
        jp.nsolutions = 1
        jp.best_bound = try
            MOI.get(jp.model, MOI.ObjectiveBound())
        catch
            MOI.get(jp.model, MOI.ObjectiveValue())
        end
        jp.status = jp.relaxation_status
        jp.objval = jp.relaxation_objval
        jp.solution = jp.relaxation_solution
    end
    jp.soltime = time()-jp.start_time

    (:All in ps || :Info in ps) && println("Obj: ",jp.objval)

    if length(jp.solutions) == 0
        push!(jp.solutions, SolutionObj(jp.solution, jp.objval))
    end

    jp.options.debug && debug_set_solution(jp.debugDict,jp)
    if jp.options.debug && jp.options.debug_write
        write(jp.options.debug_file_path, JSON.json(jp.debugDict))
    end

end

getnsolutions(m::JuniperProblem) = m.nsolutions
getsolutions(m::JuniperProblem) = m.solutions
getnbranches(m::JuniperProblem) = m.nbranches

# `UniversalFallback` supports everything so we can return `true`.
MOI.supports(model::Optimizer, attr::MOI.AbstractModelAttribute) = true
MOI.set(model::Optimizer, attr::MOI.AbstractModelAttribute, value) = MOI.set(model.model_cache, attr, value)
MOI.get(model::Optimizer, attr::MOI.AbstractModelAttribute) = MOI.get(model.model_cache, attr)

"""
MOI variables
"""

MOI.add_variable(model::Optimizer) = MOI.add_variable(model.model_cache)
MOI.add_variables(model::Optimizer, n) = MOI.add_variables(model.model_cache, n)

# `UniversalFallback` supports everything so we can return `true`.
MOI.supports(::Optimizer, ::MOI.AbstractVariableAttribute, ::Type{MOI.VariableIndex}) = true
function MOI.set(model::Optimizer, attr::MOI.AbstractVariableAttribute, vi::MOI.VariableIndex, value)
    MOI.set(model.model_cache, attr, vi, value)
    return
end
function MOI.get(model::Optimizer, attr::MOI.AbstractVariableAttribute, vi::MOI.VariableIndex)
    return MOI.get(model.model_cache, attr, vi)
end

"""
MOI constraints
"""

# `UniversalFallback` supports everything so we can return `true`.
MOI.supports_constraint(::Optimizer, ::Type{<:MOI.AbstractFunction}, ::Type{<:MOI.AbstractSet}) = true
function MOI.add_constraint(model::Optimizer, func::MOI.AbstractFunction, set::MOI.AbstractSet)
    return MOI.add_constraint(model.model_cache, func, set)
end

# `UniversalFallback` supports everything so we can return `true`.
MOI.supports(::Optimizer, ::MOI.AbstractConstraintAttribute, ::Type{<:MOI.ConstraintIndex}) = true
function MOI.set(model::Optimizer, attr::MOI.AbstractConstraintAttribute, ci::MOI.ConstraintIndex, value)
    MOI.set(model.model_cache, attr, ci, value)
    return
end
function MOI.get(model::Optimizer, attr::MOI.AbstractConstraintAttribute, ci::MOI.ConstraintIndex)
    return MOI.get(model.model_cache, attr, ci)
end

include("results.jl")


text:
#
# Bucket Sort
#

function bucketSort(A, min_bucket, max_bucket)
    buckets = []
    for i in min_bucket:max_bucket
        push!(buckets, nothing)
    end

    for i in A
        buckets[A[i]] = A[i]
    end

    x = 1
    for i in min_bucket:max_bucket
        if buckets[i] != nothing
            A[x] = buckets[i]
            x = x + 1
        end
    end
end

function main()

  # list to be sorted
  rng = MersenneTwister(1234);
  A = shuffle(rng, Vector(1:100))
  Aorigin = copy(A)

  # sorting
  n = length(A)
  @time bucketSort(A, 1, n)

  print("The original list: ")
  println(Aorigin)

  print("The sorted list: ")
  println(A)

end

if contains(@__FILE__, PROGRAM_FILE)
    main()
end

max_stars_repo_name: szmlb/algorithmsInJulia

max_issues_repo_name: szmlb/algorithmsInJulia

max_forks_repo_name: szmlb/algorithmsInJulia


text:
typealias Float Float64

const gPDEDiffEst = 1e-6
const gPDEBdyReflect = true
const gJDiffEst = 1e-5
const gOptTol = 1e-5
const gOptNMax = 15
const gOptNSubMax = 100
const gOptAbsErrTest = false
const gOptShowTrace = true
const gOptStoreTrace = true

const gSetVerbose = true

macro lintpragma( s )
end

max_stars_repo_name: jgoldfar/isp-julia-mwe

max_issues_repo_name: jgoldfar/isp-julia-mwe

max_forks_repo_name: jgoldfar/isp-julia-mwe


text:
"""
    Moment

Represents an intermediate state within a given circuit.
"""
mutable struct Moment
    gates::Vector{CircuitGate}

    @doc """
        Moment(g::AbstractCircuitGate) where

    Create a `Moment` object consisting of a single `CircuitGate` object.
    """
    function Moment(g::AbstractCircuitGate)
        new([g])
    end

    @doc """
        Moment(g::AbstractVector{<:AbstractCircuitGate}) where

    Create a `Moment` object consisting of multiple `CircuitGate` objects.
    """
    function Moment(cgs::Vector{<:AbstractCircuitGate})
        iwire = Int[]
        for cg in cgs
            length(intersect(iwire, cg.iwire)) == 0 || error("Only gates on different wires are allowed in a Moment")
            append!(iwire, collect(cg.iwire))
        end
        new(cgs)
    end
end

"""
    Base.adjoint(m::Moment)

Construct a `Moment` object that is the adjoint of `m`.
"""
function Base.adjoint(m::Moment)
    return Moment(Base.adjoint.(reverse(m.gates)))
end

"""
    sparse_matrix(m::Moment)

returns matrix representation of a `Moment{M}` object that can applied to a state vector of `N` qubits.
"""
function sparse_matrix(m::Moment, N::Int=0)
    if N == 0
        N = req_wires(m)
    end
    mat = sparse_matrix(m[1], N)
    for i in 2:length(m)
        mat = sparse_matrix(m[i], N) * mat
    end
    mat
end

function sparse_matrix(m::Vector{Moment}, N::Int=0)::SparseMatrixCSC{Complex{Float64},Int}
    if N == 0
        N = maximum(req_wires.(m))
    end
    mat = sparse_matrix(m[1], N)
    for i in 2:length(m)
        mat = sparse_matrix(m[i], N) * mat
    end
    mat
end

# make Moment iterable and indexable
function Base.getindex(m::Moment, i::Integer)
    1 <= i <= length(m.gates) || throw(BoundsError(m, i))
    return m.gates[i]
end

function Base.getindex(m::Moment, ::Colon)
    return m.gates[:]
end

function Base.getindex(m::Moment, ur::UnitRange{Int64})
    return m.gates[ur]
end

function Base.iterate(m::Moment, state=1)
    return state > length(m.gates) ? nothing : (m[state], state + 1)
end

# implement methods required for iteration
function Base.firstindex(::Moment)
    return 1
end

function Base.lastindex(m::Moment)
    return length(m.gates)
end

function Base.length(m::Moment)
    return length(m.gates)
end

function Base.isapprox(m1::Moment, m2::Moment)
    length(m1) == length(m2) || return false
    for (g1, g2) in zip(m1, m2)
        if !(g1 ≈ g2)
            return false
        end
    end
    return true
end

function Base.reverse!(m::Moment)
    m.gates = reverse(m.gates)
    return m
end

function Base.reverse(m::Moment)
    Moment(reverse(m.gates))
end

@memoize function req_wires(m::Moment)
    N = 0
    for cg in m
        N = maximum((N, req_wires(cg)))
    end
    return N
end

function Base.pop!(m::Moment)
    pop!(m.gates)
end

function Base.isempty(m::Moment)
    isempty(m.gates)
end


text:
using TimeSeriesIO
using Base.Test

using DataFrames

@testset "DataFrame to TimeArray" begin
    dat = "Date,Stock,Open,High,Low,Close,Volume
            2016-09-29,KESM,7.92,7.98,7.92,7.97,149400
            2016-09-30,KESM,7.96,7.97,7.84,7.9,29900
            2016-10-04,KESM,7.8,7.94,7.8,7.93,99900
            2016-10-05,KESM,7.93,7.95,7.89,7.93,77500
            2016-10-06,KESM,7.93,7.93,7.89,7.92,130600
            2016-10-07,KESM,7.91,7.94,7.91,7.92,103000"

    io = IOBuffer(dat)

    df = readtable(io)
    df[:Date] = Date(df[:Date])

    a_OHLC = ["Open", "High", "Low", "Close"]

    # Test convert DataFrame to TimeArray
    ta = TimeArray(df, colnames=[:Open, :High, :Low, :Close])
    @test ta.colnames == a_OHLC
    @test Array(df[[:Open, :High, :Low, :Close]]) == ta.values

    ta = TimeArray(df[[:Date, :Open, :High, :Low, :Close]])
    @test ta.colnames == a_OHLC
    @test Array(df[[:Open, :High, :Low, :Close]]) == ta.values

    ## With optional arguments
    names!(df, [:DateTime, :Stock, :Open, :High, :Low, :Close, :Volume])
    ta = TimeArray(df, colnames=[:Open, :High, :Low, :Close], timestamp=:DateTime)
    @test ta.colnames == ["Open", "High", "Low", "Close"]

    filename = joinpath(dirname(@__FILE__), "ford_2012.csv")
    df = readtable(filename)
    df[:Date] = Date(df[:Date])
    ta = TimeArray(df, colnames=[:Open, :High, :Low, :Close])
    @test ta.colnames == a_OHLC
    @test Array(df[[:Open, :High, :Low, :Close]]) == ta.values
end


text:
using Base.Test
using OptimTools

if !isdefined(:probs) || isempty(probs)
	println("getting test problems")
	include("getTestFunctions.jl")
end

his = []; flag = []; x0 = []; xsol = []

firstOrderMethods = (trdogleg,trcauchy)
# try stopping based on atol
for method in firstOrderMethods
	println("testing $(string(method))")
	for k=1:length(probs)
		prob = probs[k]

		println("\t\t$(prob[1])")

		fk   = prob[2]
		dfk  = prob[3]
		d2fk  = prob[4]
		xsol = float(prob[5])
		x0   = float(xsol) + 10*(1+norm(xsol))* randn(size(xsol))
		atol = 1e-4

		xtr,flag,his = method(fk,dfk,d2fk, x0,maxIter=1000000,atol=atol,out=1*(k==3))

		@test norm(dfk(xtr)) .< atol
	end
end


text:
function interpretwasm(f::Func, fs, args)
  params = [convert(jltype(typ), arg) for (typ, arg) in zip(f.params, args)]
  locals = [convert(jltype(typ), 0) for typ in f.locals]
  ms = vcat(params, locals)

  apInstr(f.body, ms, 0, fs)

  returns = popn!(ms, length(f.result))

  # Check to make sure the return types are all correct
  for (rtyp, r) in zip(f.result, returns)
    if jltype(rtyp) != typeof(r)
      error("ERROR: Return type mismatch")
    end
  end

  return returns
end

function toFunction(f::Func, fs)
  return ((args...) -> interpretwasm(f, fs, args))
end

function interpret_module(m::Module)
  d = Dict()
  [(g = toFunction(f, d); d[f.name] = (length(f.params), g); g) for f in m.funcs]
end

function runBody(body, ms, level, fs)
  for i in body
    if typeof(i) in [Branch, Return]
      level_ = apInstr(i, ms, level + 1)
      level_ <= level && return level_
    elseif typeof(i) in [If, Block, Loop]
      level_ = apInstr(i, ms, level + 1, fs)
      level_ <= level && return level_
    elseif i isa Call
      apInstr(i, ms, level + 1, fs)
    else
      apInstr(i, ms)
    end
  end
  return level
end

function popn!(xs, n)
  len = length(xs)
  return splice!(xs, len - n + 1:len)
end

apN(n, f) = ms -> push!(ms, f(popn!(ms, n)...))

# Functions to fix true -> 1 and false -> 0, but that's the case anyway
# function MComp(comparator)
#   return (args...) -> comparator(args...) ? 1 : 0
# end
#
# function cpN(n, f)
#   return apN(n, MComp(f))
# end

unsign(x::Int64) = reinterpret(UInt64, x)
unsign(x::Int32) = reinterpret(UInt32, x)
resign(x::UInt64) = reinterpret(Int64, x)
resign(x::UInt32) = reinterpret(Int32, x)

unsign(x) = x
resign(x) = x

apN_U(n, f) = ms -> push!(ms, resign(f(unsign(popn!(ms, n))...)))

operations =
  Dict(:lt_s   => apN(2, <)
      ,:lt_u   => apN_U(2, <)
      ,:le_s   => apN(2, <=)
      ,:gt_s   => apN(2, >)
      ,:eq     => apN(2, ==)
      ,:ne     => apN(2, !=)
      ,:gt     => apN(2, >)
      ,:eqz    => apN(1, x -> x == 0)
      ,:sub    => apN(2, -)
      ,:add    => apN(2, +)
      ,:div    => apN(2, /)
      ,:mul    => apN(2, *)
      ,:ctz    => apN(1, trailing_zeros)
      ,:shr_s  => apN(2, >>)
      ,:shr_u  => apN(2, >>>)
      ,:shl    => apN(2, <<)
      ,:or     => apN(2, |)
      ,:and    => apN(2, &)
      ,:rem_s  => apN(2, rem)
      ,:rem_u  => apN_U(2, rem)
      ,:div_s  => apN(2, div)
      ,:div_u  => apN_U(2, div)
      )

# Level Agnostic Functions

apInstr(i::Nop,         ms) = nothing
apInstr(i::Local,       ms) = push!(ms,ms[i.id + 1]);
apInstr(i::Const,       ms) = push!(ms,value(i));
apInstr(i::Unreachable, ms) = error("Unreachable")
apInstr(i::Convert,     ms) = push!(ms, convert(jltype(i.to), float(pop!(ms))))
apInstr(i::Op,          ms) = operations[Symbol(split(string(i.name), ".")[2])](ms)

# apInstr(i::SetLocal,    ms) = i.id + 1 == length(ms) ? ms[i.id + 1] = i.tee ? last(ms) : pop!(ms) : ms
apInstr(i::SetLocal,    ms) = ms[i.id + 1] = i.tee ? last(ms) : pop!(ms)

function apInstr(i::Select, ms)
  arg2, cond = popn!(ms, 2)
  if cond == 0
    pop!(ms)
    push!(ms, arg2)
  end
end

# Level Based Functions

apInstr(i::Return, ms, l) = 0
apInstr(i::Branch, ms, l) = i.cond && pop!(ms) != 0 || !i.cond ? l - i.level - 1 : l

# Instructions dependent on in scope functions

apInstr(i::Call,   ms, l, fs) = (f = fs[i.name]; push!(ms, f[2]((popn!(ms, f[1]))...)...))

apInstr(i::If,     ms, l, fs) = pop!(ms) != 0 ? runBody(i.t, ms, l, fs) : runBody(i.f, ms, l, fs)
apInstr(i::Block,  ms, l, fs) = runBody(i.body, ms, l, fs)
function apInstr(loop::Loop, ms, level, fs)
  level_ = level
  while level_ == level
    level_ = runBody(loop.body, ms, level, fs)
  end
  return level_
end


text:
function standardize(y::Real, μ::Real, σ::Real, ξ::Real)::Real
    return 1 / ξ * log( 1 + ξ/σ * ( y - μ ) )

end

function standardize(fm::MaximumLikelihoodEVA)::Vector{<:Real}

    y = fm.model.data.value
    d = getdistribution(fm)

    return standardize.(y, location.(d), scale.(d), shape.(d))

end

function standardize(fm::BayesianEVA)::Vector{<:Real}

    θ̂ = findposteriormode(fm)
    dist = getdistribution(fm.model, θ̂)

    μ = location.(dist)
    σ = scale.(dist)
    ξ = shape.(dist)

    y = fm.model.data.value

    z = standardize.(y, μ, σ, ξ)

    return z
end

function standarddist(::BlockMaxima)::Distribution
    return Gumbel()
end

function standarddist(::ThresholdExceedance)::Distribution
    return Exponential()
end

function probplot_std_data(fm::fittedEVA)::DataFrame

    z = standardize(fm)

    y, p̂ = ecdf(z)

    return DataFrame(Model = cdf.(standarddist(fm.model), y), Empirical = p̂)

end

function qqplot_std_data(fm::fittedEVA)::DataFrame

    z = standardize(fm)

    y, p = ecdf(z)

    return DataFrame(Model = quantile.(standarddist(fm.model), p), Empirical = y)

end

function histplot_std_data(fm::fittedEVA)::Dict

    dist = standarddist(fm.model)

    z = standardize(fm)
    n = length(z)
    nbin = Int64(ceil(sqrt(n)))

    zmin = quantile(dist, 1/1000)
    zmax = quantile(dist, 1 - 1/1000)
    zp = range(zmin, zmax, length=1000)

    return Dict(:h => DataFrame(Data = z), :d => DataFrame(DataRange = zp, Density = pdf.(dist, zp)),
        :nbin => nbin, :xmin => zmin, :xmax => zmax)

end


text:
module TestIntrospection

# using Revise
using MLJBase
import MLJBase
using Test

mutable struct Dummy <: Probabilistic end

MLJBase.load_path(::Type{Dummy}) = "GreatPackage.MLJ.Dummy"
MLJBase.target_scitype_union(::Type{Dummy}) = Continuous
MLJBase.input_scitype_union(::Type{Dummy}) = Union{Continuous, Missing}
MLJBase.input_is_multivariate(::Type{Dummy}) = false
MLJBase.is_pure_julia(::Type{Dummy}) = true
MLJBase.package_name(::Type{Dummy}) = "GreatPackage"
MLJBase.package_uuid(::Type{Dummy}) = "6f286f6a-111f-5878-ab1e-185364afe411"
MLJBase.package_url(::Type{Dummy}) = "https://mickey.mouse.org"

d = Dict(:name => "Dummy",
         :load_path => "GreatPackage.MLJ.Dummy",
         :is_pure_julia => true,
         :package_uuid  => "6f286f6a-111f-5878-ab1e-185364afe411",
         :package_name  => "GreatPackage",
         :target_scitype_union => Continuous,
         :input_scitype_union => Union{Continuous, Missing},
         :input_is_multivariate => false,
         :is_probabilistic => true,
         :package_url   => "https://mickey.mouse.org",
         :is_supervised => true,
         :is_wrapper => false)

info(Dummy)[:name]
@test info(Dummy) == d
@test info(Dummy()) == d

end
true


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

using Test, CompilerSupportLibraries_jll

@testset "CompilerSupportLibraries_jll" begin
    @test isfile(CompilerSupportLibraries_jll.libgcc_s_path)
    @test isfile(CompilerSupportLibraries_jll.libgfortran_path)
    @test isfile(CompilerSupportLibraries_jll.libstdcxx_path)
    @test isfile(CompilerSupportLibraries_jll.libgomp_path)
end

max_stars_repo_name: jonas-schulze/julia

max_issues_repo_name: jonas-schulze/julia

max_forks_repo_name: jonas-schulze/julia


text:
using POMDPToolbox
using POMDPModels
using Base.Test

pomdp = TigerPOMDP()

probability_check(pomdp)

@test ordered_states(pomdp) == [false, true]
@test ordered_observations(pomdp) == [false, true]
@test ordered_actions(pomdp) == [0,1,2]

struct TM <: POMDP{Int, Int, Int} end
POMDPs.states(::TM) = [1,3]
POMDPs.n_states(::TM) = 2

@test_throws ErrorException ordered_states(TM())

struct TM2 <: POMDP{Int, Int, Int} end
POMDPs.states(::TM2) = [1,3]
POMDPs.n_states(::TM2) = 3

println("There should be a warning below:")
ordered_states(TM2())


text:
module ModelsGenerators

using Distributions

export
  randiv, randiv_ts

chisq_02 = Chisq(2)
tstud_02 = TDist(2)
bdist_05 = Bernoulli(.5)

function normm!(y::Array{Float64, 1}, x::Array{Float64, 2})
    n, m = size(x)
    for j=1:n
        for s=1:m
           y[j] += x[j,s]^2
        end
        y[j] = y[j]^.5
    end
    return y
end

function normm(x::Array{Float64, 2})
    y = zeros(Float64, size(x,1))
    normm!(y, x)
end

function genma_one!(y::Vector, u::Vector, nu)
    for j = 2:length(u)
        y[j] = u[j]+nu*u[j-1]
    end
end

function genar_one!(y::Vector, u::Vector, rho)
    for j = 2:length(u)
        y[j] = rho*y[j-1] + u[j]
    end
end

############################################################################
## Instrumental Variables
##
############################################################################

function sim_iv_d01(;
                    n::Int64        = 100,
                    m::Int64         = 5,
                    theta0::Float64  = 0.0,
                    rho::Float64     = 0.9,
                    CP::Int64        = 20)
    ## OLS design with Homo-skedasticity
    ## from: http://economics.mit.edu/files/7422
    randiv(n, m, theta0, rho, CP)
end

function randiv(n::Int64        = 100,
                m::Int64        = 5,
                theta0::Float64 = 0.0,
                rho::Float64    = 0.9,
                CP::Int64       = 20)
    tau     = fill(sqrt(CP/(m*n)), m)
    z       = randn(n, m)
    vi      = randn(n, 1)
    eta     = randn(n, 1)
    epsilon = rho*eta+sqrt(1-rho^2)*vi
    BLAS.gemm!('N', 'N', 1.0, z, tau, 1.0, eta)
    BLAS.gemm!('N', 'N', 1.0, eta, [theta0], 1.0, epsilon)
    return epsilon, eta, z
end

function sim_iv_d02!(Y::Vector, X::Matrix, Z::Matrix;
                     ρ::Float64 = 0.3, ϕ::Float64 = 0.1, μ²::Float64 = 8.)
    ## http://www.cemmap.ac.uk/wps/cwp2207.pdf
    ## Problem how to choose ϕ is not clear
    nx, p = size(X)
    nz, K = size(Z)
    ny    = length(Y)

    @assert nx==nz && nx==ny
    @assert p == 2

    mnk    = min(4, (K-1))
    z₁     = randn(nx)
    X[:,2] = randn(nx)

    @inbounds Z[:, 1:(mnk+1)] = hcat([(z₁.^i) for i = 0:mnk]...)

    if K>5
        @inbounds Z[:, 6:K] = hcat([z₁.*float(randn(nx).>0) for i = 1:(K-5)]...)
    end

    Π   = zeros(2, 1)
    fill!(Π, sqrt(μ²/nx))

    U₂ = randn(nx)
    υ₁ = randn(nx).*z₁
    υ₂ = randn(nx).*.86
    ϵ  = ρ*U₂ + sqrt((1-ρ^2)/(ϕ^2+.86^4))*(ϕ*υ₁ + 0.86*υ₂)

    Y[:] = X*Π + ϵ

end

function sim_iv_d03(; n = 100, m = 5, theta0 = 0.0, rho = 0.9, Pi = 0.1,
                    design = 1, heteroskedastic = false)
    Z = randn(n, m)
    X = randn(n, 1)
    if design == 1
        u = randn(n)
        V = randn(n)
    elseif design == 2
        w = rand(chisq_02, n)
        u = randn(n)/(w/2.0).^.5
        V = rand(tstud_02, n)
    elseif design == 3
        u = randn(n).^2-1
        V = randn(n)
    elseif design == 4
        b = rand(bdist_05, n)
        u = randn(n)
        u = b.*abs(u+2)-(1-b)*abs(u-2)
        V = randn(n)
    else
        throw("Wrong design selected")
    end

    if heteroskedastic
        u = u.*normm(z)
    end

    Y = X*theta0 + u
    X = Z[:,1]*Pi + V

    return Y, X, Z
end

function dgp_hh(n::Int64 = 200, m::Int64 = 2, s::Float64 = 0.2,
                chisqmom::Int64 = 0, chisqdf::Int64 = 2, tmom::Int64 = 0,
                tdf::Int64 = 3, minus::Bool = false)
    ## Adapted from Hall and Horowitz (1996)
    ## They consider s = {0.2, 0.4}

    X = randn(n, 1).*s
    Z = randn(n, 1).*s
    W = Z
    if chisqmom > 0
        z_chisq = (rand(Chisq(chisqdf), (n, chisqmom)) - chisqdf)./sqrt(2*chisqdf)
        W = [W z_chisq]
    end
    if tmom > 0
        z_tstud = rand(TDist(tdf), (n, chisqmom))./sqrt(tdf/(tdf-2))
        W = [W z_tstud]
    end
    return X, Z, W
end

function dgp_hh(;n::Int64 = 200, m::Int64 = 2, s::Float64 = 0.2,
                chisqmom::Int64 = 0, chisqdf::Int64 = 2, tmom::Int64 = 0,
                tdf::Int64 = 3, minus::Bool = false)
    ## Adapted from Hall and Horowitz (1996)
    ## They consider s = {0.2, 0.4}
    ## Notice that mu = - 9s^2/2
    dgp_hh(n, m, s, chisqmom, chisqdf, tmom, tdf, minus)
end

function momfhh_s02(theta::Vector)
    n, m = size(W)
    g = Array(eltype(theta), n, m+1)
    mu = -9*0.2^2/2
    for i = 1:n
        @inbounds g[i, 1] = exp(mu - theta*X[i,1]+(3-theta)*Z[i,1])[1] - 1.0
    end
    for j = 2:m+1
        for i = 1:n
            @inbounds g[i, j] = g[i, 1]*W[i, j-1]
        end
    end
    return g
end

function momfhh_s04(theta)
    n, m = size(W)
    g = Array(Float64, n, m+1)
    mu = -9*0.4^2/2
    for i = 1:n
        @inbounds g[i, 1] = exp(mu - theta[1]*X[i,1]+(3-theta[1])*Z[i,1]) - 1.0
    end

    for j = 2:m+1
        for i = 1:n
            @inbounds g[i, j] = g[i, 1]*W[i, j-1]
        end
    end
    return g
end

function randiv_ts(n::Int64  =128,
                   m::Int64  = 2,
                   σ₁₂::Real = 0.9,
                   ϕ::Real = .5,
                   θ::Real = .5,
                   β::Real = 1.0,
                   burnin::Int64 = 1000)
  ## Same design as in
  ##
  ## http://faculty.georgetown.edu/gk232/research/KGMM.pdf
  ## Guido's parametrization
  ## ρ ∈ {.1, .5, .9}
  ## ϕ ∈ {.1, .3, .5}   # control quality instrument, low value weak
  ## θ ∈ {-.9, -.5, 0. .5, .9}

  nt  = n+m+burnin
  out = (burnin + 1):(n + burnin)
  #    y <- u <- x <- v <- rep(0, nt + 1)
  y1   = Array(Float64, nt+1)
  y2   = Array(Float64, nt+1)

  y1[1] = 0.0
  y2[1] = 0.0

  u₁  = randn(nt, 2)
  ρ   = [1.0 σ₁₂; σ₁₂ 1.0]
  u₁  = u₁*chol(ρ)

  y1[1] = β*y2[1] + u₁[1, 2]

  for j=2:nt
      @inbounds y2[j] = ϕ * y2[j-1] + u₁[j, 1]
      @inbounds y1[j] = β*y2[j] + u₁[j, 2] - θ*u₁[j-1, 2]
  end

  z = Array(Float64, n, 2*m)
  for j = 1:m
      @inbounds z[:, j] = y2[out-j]
  end

  for j = m+1:2*m
      @inbounds z[:, j] = y1[out-j]
  end

  return y1[out], y2[out], z

end

end

max_stars_repo_name: gragusa/ModelsGenerators

max_issues_repo_name: gragusa/ModelsGenerators

max_forks_repo_name: gragusa/ModelsGenerators


text:
using Test
using AdvancedProbabilisticCircuits
using StatsFuns

const log2πhalf = log2π/2

@testset "nodes" begin

    @testset "constructors" begin
        @test Normal(1) isa AdvancedProbabilisticCircuits.AbstractLeaf
        @test Indicator(1) isa AdvancedProbabilisticCircuits.AbstractLeaf
        @test TruncatedNormal(1) isa AdvancedProbabilisticCircuits.AbstractLeaf
        @test Sum(Normal, 1, 2) isa AdvancedProbabilisticCircuits.Node
        @test Sum(Normal(1), Normal(1)) isa AdvancedProbabilisticCircuits.Node
        @test Prod(Normal, [1,2]) isa AdvancedProbabilisticCircuits.Node
        @test Prod(Normal(1), Normal(2)) isa AdvancedProbabilisticCircuits.Node
    end

    @testset "scope functions" begin
        @test scope(Normal(1)) == 1
        @test scope(Sum(Normal(1), Normal(1))) == 1
        @test scope(Prod(Normal(1), Normal(2))) == [1,2]
    end

    @testset "support functions" begin
        @test support(Normal(1)) == (1 => RealInterval(-Inf, Inf))
        @test support(Indicator(1)) == (1 => [1])
        @test support(Sum(Indicator(1, v = 1), Indicator(1, v = 2))) == (1 => [1,2])
    end

    @testset "logpdf functions" begin
        x = 0
        @test logpdf(Normal(1), x) ≈ -log2πhalf
        @test logpdf(Indicator(1), 1) ≈ 0
        @test logpdf(Indicator(1), 0) ≈ -Inf
        @test logpdf(TruncatedNormal(1), x) ≈ -log2πhalf
        @test logpdf(TruncatedNormal(1, min=1), x) ≈ -Inf
        @test logpdf(TruncatedNormal(1, max=-1), x) ≈ -Inf
        s = Sum(Normal(1), Normal(1))
        @test logpdf(s, x) ≈ logsumexp(-log2π/2 .+ params(s))
        @test logpdf(Prod(Normal(1), Normal(2)), [x,x]) ≈ -log2π
    end

end

@testset "properties" begin

end

@testset "util" begin

end

@testset "optimize" begin

end


text:
using LatBo: SandBox
using LatBo.LB: VelocityIOlet, ParabolicVelocityIOlet,
        equilibrium, NashZeroOrderPressure, streaming, speed_of_sound_squared
import LatBo.LB: velocity

type MockVelocityIOlet <: VelocityIOlet
    position::Vector{Float64}
    time::Float64
    MockVelocityIOlet() = new(Float64[], 0)
end
function velocity(streamer::MockVelocityIOlet, position, time)
    streamer.position = deepcopy(position)
    streamer.time = time
    Float64[-10, 10]
end

facts("Inlets and Outlets") do
    sim = SandBox(:D2Q9, (4, 4))

    context("Velocity") do
        context("General algorithm") do
            const cᵢ = sim.lattice.celerities
            const direction = find([all(cᵢ[:, i] .== [-1, 1]) for i in 1:size(cᵢ, 2)])[1]
            const invdir = find([all(cᵢ[:, i] .== [1, -1]) for i in 1:size(cᵢ, 2)])[1]
            const start = index(sim.indexing, (3, 3))
            const finish = index(sim.indexing, (2, 4))
            const halfway = Float64[3, 3] + 0.5*Float64[-1, 1]
            sim.time = 40.0

            sim.populations[:] = 0
            sim.next_populations[:] = 0
            @fact sim.lattice.inversion[direction] --> invdir
            sim.populations[direction, start] = 1
            @fact sim.next_populations .== 0 --> all

            # perform streaming
            iolet = MockVelocityIOlet()
            streaming(iolet, sim, start, direction)

            @fact iolet.position --> roughly(Float64[2.5, 3.5])
            @fact iolet.time --> roughly(sim.time)
            # 20 is the celerity * momentum
            expected = 2sim.lattice.weights[direction] / speed_of_sound_squared * 20
            @fact sim.next_populations[invdir, start] --> roughly(1 - expected)
            @fact sum(abs(sim.next_populations)) --> roughly(abs(1 - expected))
            @fact sim.populations[direction, start] --> roughly(1)
            @fact sum(abs(sim.populations)) --> roughly(1)
        end

        context("parabolic") do
            const n₀, n₁, Γ, r, ν_max = [1., 0], [0., 1], [5., 5], 5., 10.
            const ϵ = 1e-6
            iolet = ParabolicVelocityIOlet{Float64}(n₀, Γ, r, ν_max)

            # should be zero at radius
            @fact velocity(iolet, Γ + r * n₁ + rand() * n₀) --> roughly(zeros(Float64, 2))
            # should be ν_max at origin
            @fact velocity(iolet, Γ) --> roughly(ν_max * n₀)
            # should be 0.75 * ν_max at origin + 1/2 radius
            @fact velocity(iolet, Γ + 0.5r*n₁) --> roughly(0.75ν_max * n₀)

            # velocity should be along normal
            @fact dot(velocity(iolet, Γ + 2r*rand(Float64, 2)), n₁) --> roughly(0)
            # velocity should not depend on position along normal
            α = Γ + 2r*rand(Float64, 2)
            @fact velocity(iolet, α + r * rand() * n₀) --> roughly(velocity(iolet, α))

            # velocity should be maximum at origin and equal to maxspeed
            α = Γ + 2r*rand() * n₀
            δν = velocity(iolet, α + ϵ * n₁) - velocity(iolet, α - ϵ * n₁)
            @fact dot(δν, n₀) --> roughly(0)
        end
    end

    context("Nash zero pressure") do
        const n₀, n₁, ρ = [1., 0], [0., 1], 5.
        const cᵢ = sim.lattice.celerities
        const direction = find([all(cᵢ[:, i] .== [-1, 1]) for i in 1:size(cᵢ, 2)])[1]
        const invdir = find([all(cᵢ[:, i] .== [1, -1]) for i in 1:size(cᵢ, 2)])[1]
        const start = index(sim.indexing, (3, 3))
        const ν₀ = 5n₀ + 6n₁

        iolet = NashZeroOrderPressure{Float64}(n₀, ρ)

        # expected values
        μ = ρ * dot(ν₀, n₀)n₀
        feq = equilibrium(ρ, μ, sim.lattice.celerities, sim.lattice.weights)

        streaming(iolet, ν₀, sim, start, direction)
        @fact sim.next_populations[invdir, start] --> roughly(feq[invdir])
        @fact sum(abs(sim.next_populations[invdir, start])) --> roughly(feq[invdir])

        # original population has no effect
        sim.populations = 1.0 + rand(Float64, size(sim.populations))
        streaming(iolet, ν₀, sim, start, direction)
        @fact sim.next_populations[invdir, start] --> roughly(feq[invdir])
        @fact sum(abs(sim.next_populations[invdir, start])) --> roughly(feq[invdir])
    end
end


text:
using Iscalc
using Plots
#plotlyjs()
#gr()
plotly()

#Svensson = JuliaDB.load("C:/Users/António/Desktop/BaseDados/Svensson_2018-05-26.jdb")
Svensson = obter(:NSS, inicio = "01-01-2000", fim = "28-05-2018")
show(IOContext(STDOUT, limit=true), "text/plain", Svensson)

DataReferencia = Date("2018-05-28")

Portfolio = ["PTOTESOE0013"  "2022-10-17"    0.02200  	 107.63;
             "PTOTEKOE0011"	 "2025-10-15"	 0.02875	 111.03;
             "PTOTETOE0012"	 "2026-07-21"	 0.02875	 109.56;
             "PTOTEUOE0019"	 "2027-04-14"	 0.04125	 118.90;
             "PTOTEROE0014"	 "2030-02-15"	 0.03875	 117.60]

# Juros Corridos das Obrigações
JC = JCorridos(Portfolio,DataReferencia)
println(JC)

# Tenores e Respectivos Fluxos de Caixa
TFC = FluxosCaixa(Portfolio,DataReferencia)
println(TFC)

Tenores = column(TFC,:Tenores)
FC = column(TFC,:FluxosCaixa)

# Estrutura Temporal Taxas de Juro: Curva Spot

FS = fspot(Svensson, Tenores)
printm(FS)

# Gráfico da ETTJ para a data mais recente
plot(Tenores,FS[1,2:end], ylims = (-1,1), ylabel="ETTJ Taxas Spot", xlims = (0, 12.5), xlabel = "Tenores", label="$(FS[1,1])")
gui()

# Estrutura Temporal Taxas de Juro: Função Desconto
FD = fdesconto(Svensson, Tenores)
printm(FD)

#VPortfolio = table(FD[:,1], FD[:,2:(length(Tenores)+1)] * FC, names=[:Data,:Vp])

VPortfolio = hcat(FD[:,1], FD[:,2:end] * FC)
printm(VPortfolio)

c = VPortfolio[:,2] .-lag(VPortfolio[:,2],-1)

media = mean(c[1:end-1])
quantil05 = quantile(convert(Array{Float64},c[1:end-1]), 0.05)

c = hcat(FD[:,1],c)
printm(c)

VaR_05 = media - quantil05
println("VaR_5% = ", VaR_05)

max_stars_repo_name: iscalprog/Iscalc

max_issues_repo_name: iscalprog/Iscalc

max_forks_repo_name: iscalprog/Iscalc


text:
using Test
using URIParser

using ASDF

const pkgpath = joinpath(dirname(pathof(ASDF)), "..")

@testset "basic" begin
    file = ASDF.open(joinpath(pkgpath, "examples", "basic.asdf"))
    @test typeof(file) === ASDF.File

    @test ASDF.comments(file) == ["ASDF_STANDARD 1.0.0"]
    @test ASDF.file_format_version(file) == v"1.0.0"
    @test ASDF.version(file) == v"1.0.0"

    tree = ASDF.tree(file)
    @test typeof(tree) === ASDF.Tree

    asdf_library = ASDF.asdf_library(tree)
    @test typeof(asdf_library) === ASDF.Software
    @test ASDF.name(asdf_library) == "asdf"
    @test ASDF.author(asdf_library) == "Space Telescope Science Institute"
    @test ASDF.homepage(asdf_library) ==
        URI("http://github.com/spacetelescope/asdf")
    @test ASDF.version(asdf_library) == v"1.0.0"

    data = tree["data"]
    @test data isa ASDF.NDArray{Int64, 1}
    # Python 3 requires array-like Python object to support a "buffer
    # protocol" as defined in PEP 3118. Apparently, asdf.py's
    # "NDArrayType" does not, hence we disable this test.
    # @test ASDF.isefficient(data)
    @test isequal(collect(data), Int64[i for i in 0:7])

    ASDF.close(file)
end

@testset "array" begin
    file = ASDF.open(joinpath(pkgpath, "examples", "array.asdf"))
    @test typeof(file) === ASDF.File

    @test ASDF.comments(file) == ["ASDF_STANDARD 1.0.0"]
    @test ASDF.file_format_version(file) == v"1.0.0"
    @test ASDF.version(file) == v"1.0.0"

    tree = ASDF.tree(file)
    @test typeof(tree) === ASDF.Tree

    scalar = tree["scalar"]
    @test typeof(scalar) === Int64
    @test isequal(scalar, 0)

    array1d = tree["array1d"]
    @test array1d isa ASDF.NDArray{Int16, 1}
    # @test ASDF.isefficient(array1d)
    @test size(array1d) == (2,)
    @test isequal(collect(array1d), Int16[0, 1])

    array2d = tree["array2d"]
    @test array2d isa ASDF.NDArray{Int32, 2}
    # @test ASDF.isefficient(array2d)
    @test size(array2d) == (3, 2)
    @test isequal(collect(array2d), Int32[0 1; 10 11; 20 21])

    array3d = tree["array3d"]
    @test array3d isa ASDF.NDArray{Int64, 3}
    # @test ASDF.isefficient(array3d)
    @test size(array3d) == (4, 3, 2)
    @test isequal(collect(array3d)[1,:,:], Int64[0 1; 10 11; 20 21])
    @test isequal(collect(array3d)[2,:,:], Int64[100 101; 110 111; 120 121])
    @test isequal(collect(array3d)[3,:,:], Int64[200 201; 210 211; 220 221])
    @test isequal(collect(array3d)[4,:,:], Int64[300 301; 310 311; 320 321])

    ASDF.close(file)
end

@testset "ascii" begin
    file = ASDF.open(joinpath(pkgpath, "examples", "ascii.asdf"))
    @test typeof(file) === ASDF.File

    @test ASDF.comments(file) == ["ASDF_STANDARD 1.0.0"]
    @test ASDF.file_format_version(file) == v"1.0.0"
    @test ASDF.version(file) == v"1.0.0"

    tree = ASDF.tree(file)
    @test typeof(tree) === ASDF.Tree

    data = tree["data"]
    @test data isa ASDF.NDArray{String, 1}
    @test !ASDF.isefficient(data)
    @test size(data) == (2,)
    @test isequal(collect(data), String["", "ascii"])

    ASDF.close(file)
end

@testset "complex" begin
    file = ASDF.open(joinpath(pkgpath, "examples", "complex.asdf"))
    @test typeof(file) === ASDF.File

    @test ASDF.comments(file) == ["ASDF_STANDARD 1.0.0"]
    @test ASDF.file_format_version(file) == v"1.0.0"
    @test ASDF.version(file) == v"1.0.0"

    tree = ASDF.tree(file)
    @test typeof(tree) === ASDF.Tree

    data = tree["datatype<c16"]
    @test data isa ASDF.NDArray{ComplexF64, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x04030201)
    @test size(data) == (100,)
    @test isequal(collect(data)[1:4], ComplexF64[0, 0, NaN+NaN*im, NaN+Inf*im])

    data = tree["datatype<c8"]
    @test data isa ASDF.NDArray{ComplexF32, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x04030201)
    @test size(data) == (100,)
    @test isequal(collect(data)[1:4], ComplexF32[0, 0, NaN+NaN*im, NaN+Inf*im])

    data = tree["datatype>c16"]
    @test data isa ASDF.NDArray{ComplexF64, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x01020304)
    @test size(data) == (100,)
    @test isequal(collect(data)[1:4], ComplexF64[0, 0, NaN+NaN*im, NaN+Inf*im])

    data = tree["datatype>c8"]
    @test data isa ASDF.NDArray{ComplexF32, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x01020304)
    @test size(data) == (100,)
    @test isequal(collect(data)[1:4], ComplexF32[0, 0, NaN+NaN*im, NaN+Inf*im])

    ASDF.close(file)
end

@testset "compressed" begin
    file = ASDF.open(joinpath(pkgpath, "examples", "compressed.asdf"))
    @test typeof(file) === ASDF.File

    @test ASDF.comments(file) == ["ASDF_STANDARD 1.0.0"]
    @test ASDF.file_format_version(file) == v"1.0.0"
    @test ASDF.version(file) == v"1.0.0"

    tree = ASDF.tree(file)
    @test typeof(tree) === ASDF.Tree

    data = tree["bzp2"]
    @test data isa ASDF.NDArray{Int64, 1}
    # @test ASDF.isefficient(data)
    @test size(data) == (128,)
    @test isequal(collect(data), Int64[i for i in 0:127])

    data = tree["zlib"]
    @test data isa ASDF.NDArray{Int64, 1}
    # @test ASDF.isefficient(data)
    @test size(data) == (128,)
    @test isequal(collect(data), Int64[i for i in 0:127])

    ASDF.close(file)
end

@testset "exploded" begin
    file = ASDF.open(joinpath(pkgpath, "examples", "exploded.asdf"))
    @test typeof(file) === ASDF.File

    @test ASDF.comments(file) == ["ASDF_STANDARD 1.0.0"]
    @test ASDF.file_format_version(file) == v"1.0.0"
    @test ASDF.version(file) == v"1.0.0"

    tree = ASDF.tree(file)
    @test typeof(tree) === ASDF.Tree

    data = tree["data"]
    @test data isa ASDF.NDArray{Int64, 1}
    # @test ASDF.isefficient(data)
    @test size(data) == (8,)
    @test isequal(collect(data), Int64[i for i in 0:7])

    ASDF.close(file)
end

@testset "float" begin
    file = ASDF.open(joinpath(pkgpath, "examples", "float.asdf"))
    @test typeof(file) === ASDF.File

    @test ASDF.comments(file) == ["ASDF_STANDARD 1.0.0"]
    @test ASDF.file_format_version(file) == v"1.0.0"
    @test ASDF.version(file) == v"1.0.0"

    tree = ASDF.tree(file)
    @test typeof(tree) === ASDF.Tree

    data = tree["datatype<f4"]
    @test data isa ASDF.NDArray{Float32, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x04030201)
    @test size(data) == (10,)
    @test isequal(collect(data), Float32[
        0.0, -0.0, NaN, Inf, -Inf, -3.4028234663852886e+38,
        3.4028234663852886e+38, 1.1920928955078125e-07, 5.960464477539063e-08,
        1.1754943508222875e-38])

    data = tree["datatype<f8"]
    @test data isa ASDF.NDArray{Float64, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x04030201)
    @test size(data) == (10,)
    @test isequal(collect(data), Float64[
        0.0, -0.0, NaN, Inf, -Inf, -1.7976931348623157e+308,
        1.7976931348623157e+308, 2.220446049250313e-16, 1.1102230246251565e-16,
        2.2250738585072014e-308])

    data = tree["datatype>f4"]
    @test data isa ASDF.NDArray{Float32, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x01020304)
    @test size(data) == (10,)
    @test isequal(collect(data), Float32[
        0.0, -0.0, NaN, Inf, -Inf, -3.4028234663852886e+38,
        3.4028234663852886e+38, 1.1920928955078125e-07, 5.960464477539063e-08,
        1.1754943508222875e-38])

    data = tree["datatype>f8"]
    @test data isa ASDF.NDArray{Float64, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x01020304)
    @test size(data) == (10,)
    @test isequal(collect(data), Float64[
        0.0, -0.0, NaN, Inf, -Inf, -1.7976931348623157e+308,
        1.7976931348623157e+308, 2.220446049250313e-16, 1.1102230246251565e-16,
        2.2250738585072014e-308])

    ASDF.close(file)
end

@testset "int" begin
    file = ASDF.open(joinpath(pkgpath, "examples", "int.asdf"))
    @test typeof(file) === ASDF.File

    @test ASDF.comments(file) == ["ASDF_STANDARD 1.0.0"]
    @test ASDF.file_format_version(file) == v"1.0.0"
    @test ASDF.version(file) == v"1.0.0"

    tree = ASDF.tree(file)
    @test typeof(tree) === ASDF.Tree

    data = tree["datatype<i1"]
    @test data isa ASDF.NDArray{Int8, 1}
    # @test ASDF.isefficient(data)
    @test size(data) == (3,)
    @test isequal(collect(data), Int8[127, -128, 0])

    data = tree["datatype<i2"]
    @test data isa ASDF.NDArray{Int16, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x04030201)
    @test size(data) == (3,)
    @test isequal(collect(data), Int16[32767, -32768, 0])

    data = tree["datatype<i4"]
    @test data isa ASDF.NDArray{Int32, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x04030201)
    @test size(data) == (3,)
    @test isequal(collect(data), Int32[2147483647, -2147483648, 0])

    data = tree["datatype<u1"]
    @test data isa ASDF.NDArray{UInt8, 1}
    # @test ASDF.isefficient(data)
    @test size(data) == (2,)
    @test isequal(collect(data), UInt8[255, 0])

    data = tree["datatype<u2"]
    @test data isa ASDF.NDArray{UInt16, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x04030201)
    @test size(data) == (2,)
    @test isequal(collect(data), UInt16[65535, 0])

    data = tree["datatype<u4"]
    @test data isa ASDF.NDArray{UInt32, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x04030201)
    @test size(data) == (2,)
    @test isequal(collect(data), UInt32[4294967295, 0])

    data = tree["datatype>i1"]
    @test data isa ASDF.NDArray{Int8, 1}
    # @test ASDF.isefficient(data)
    @test size(data) == (3,)
    @test isequal(collect(data), Int8[127, -128, 0])

    data = tree["datatype>i2"]
    @test data isa ASDF.NDArray{Int16, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x01020304)
    @test size(data) == (3,)
    @test isequal(collect(data), Int16[32767, -32768, 0])

    data = tree["datatype>i4"]
    @test data isa ASDF.NDArray{Int32, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x01020304)
    @test size(data) == (3,)
    @test isequal(collect(data), Int32[2147483647, -2147483648, 0])

    data = tree["datatype>u1"]
    @test data isa ASDF.NDArray{UInt8, 1}
    # @test ASDF.isefficient(data)
    @test size(data) == (2,)
    @test isequal(collect(data), UInt8[255, 0])

    data = tree["datatype>u2"]
    @test data isa ASDF.NDArray{UInt16, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x01020304)
    @test size(data) == (2,)
    @test isequal(collect(data), UInt16[65535, 0])

    data = tree["datatype>u4"]
    @test data isa ASDF.NDArray{UInt32, 1}
    # @test ASDF.isefficient(data) == (ENDIAN_BOM == 0x01020304)
    @test size(data) == (2,)
    @test isequal(collect(data), UInt32[4294967295, 0])

    ASDF.close(file)
end

@testset "shared" begin
    file = ASDF.open(joinpath(pkgpath, "examples", "shared.asdf"))
    @test typeof(file) === ASDF.File

    @test ASDF.comments(file) == ["ASDF_STANDARD 1.0.0"]
    @test ASDF.file_format_version(file) == v"1.0.0"
    @test ASDF.version(file) == v"1.0.0"

    tree = ASDF.tree(file)
    @test typeof(tree) === ASDF.Tree

    data = tree["data"]
    @test data isa ASDF.NDArray{Int64, 1}
    # @test ASDF.isefficient(data)
    @test size(data) == (8,)
    @test isequal(collect(data), Int64[i for i in 0:7])

    data = tree["subset"]
    @test data isa ASDF.NDArray{Int64, 1}
    # @test ASDF.isefficient(data)
    @test size(data) == (4,)
    @test isequal(collect(data), Int64[i for i in 1:2:7])

    ASDF.close(file)
end

@testset "stream" begin
    file = ASDF.open(joinpath(pkgpath, "examples", "stream.asdf"))
    @test typeof(file) === ASDF.File

    @test ASDF.comments(file) == ["ASDF_STANDARD 1.0.0"]
    @test ASDF.file_format_version(file) == v"1.0.0"
    @test ASDF.version(file) == v"1.0.0"

    tree = ASDF.tree(file)
    @test typeof(tree) === ASDF.Tree

    data = tree["my_stream"]
    @test data isa ASDF.NDArray{Float64, 2}
    # @test ASDF.isefficient(data)
    @test size(data) == (8, 8)
    @test isequal(collect(data), Float64[i for i in 0:7, j in 0:7])

    ASDF.close(file)
end

@testset "unicode_bmp" begin
    file = ASDF.open(joinpath(pkgpath, "examples", "unicode_bmp.asdf"))
    @test typeof(file) === ASDF.File

    @test ASDF.comments(file) == ["ASDF_STANDARD 1.0.0"]
    @test ASDF.file_format_version(file) == v"1.0.0"
    @test ASDF.version(file) == v"1.0.0"

    tree = ASDF.tree(file)
    @test typeof(tree) === ASDF.Tree

    data = tree["datatype<U"]
    @test data isa ASDF.NDArray{String, 1}
    @test !ASDF.isefficient(data)
    @test size(data) == (2,)
    @test isequal(collect(data), String["", "Æʩ"])

    data = tree["datatype>U"]
    @test data isa ASDF.NDArray{String, 1}
    @test !ASDF.isefficient(data)
    @test size(data) == (2,)
    @test isequal(collect(data), String["", "Æʩ"])

    ASDF.close(file)
end

@testset "unicode_spp" begin
    file = ASDF.open(joinpath(pkgpath, "examples", "unicode_spp.asdf"))
    @test typeof(file) === ASDF.File

    @test ASDF.comments(file) == ["ASDF_STANDARD 1.0.0"]
    @test ASDF.file_format_version(file) == v"1.0.0"
    @test ASDF.version(file) == v"1.0.0"

    tree = ASDF.tree(file)
    @test typeof(tree) === ASDF.Tree

    data = tree["datatype<U"]
    @test data isa ASDF.NDArray{String, 1}
    @test !ASDF.isefficient(data)
    @test size(data) == (2,)
    @test isequal(collect(data), String["", "\U00010020"])

    data = tree["datatype>U"]
    @test data isa ASDF.NDArray{String, 1}
    @test !ASDF.isefficient(data)
    @test size(data) == (2,)
    @test isequal(collect(data), String["", "\U00010020"])

    ASDF.close(file)
end

@testset "output" begin
    mktempdir() do dir

        # Create a file
        tree = Dict{String, Any}(
            "scalarb" => true,
            "scalari" => 12345678,
            "scalarf" => 1234.5678,
            "scalarc" => 12.34+56.78im,
            "scalars" => String(Char[i for i in 0:300]),
            "array1d" => Int8[i for i in 1:2],
            "array2d" => Int16[i+10j for i in 1:2, j in 1:3],
            "array3d" => Int32[i+10j+100k for i in 1:2, j in 1:3, k in 1:4],
            "strings" => String["hello", "world"])
        file = ASDF.File(tree)
        ASDF.write_to(file, joinpath(dir, "output.asdf"))

        # Read the file back in
        file2 = ASDF.open(joinpath(dir, "output.asdf"))
        tree2 = ASDF.tree(file2)

        # Compare content
        ignored_keys = Set(["asdf_library", "history"])
        @test setdiff(keys(tree2), ignored_keys) == keys(tree)
        for (key, value) in tree
            if !(key in ignored_keys)
                if typeof(value) <: AbstractArray
                    @test isequal(collect(tree2[key]), value)
                else
                    @test isequal(tree2[key], value)
                end
            end
        end
    end
end