text:
# Biryani -- A conversion and validation toolbox
# By: Emmanuel Raviart <emmanuel@raviart.com>
#
# Copyright (C) 2015 Emmanuel Raviart
# https://github.com/eraviart/Biryani.jl
#
# This file is part of Biryani.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Test converters.

# call
@test Convertible("42") |> call(value -> parse(Int, value)) |> to_value == 42
@test Convertible([3, 2, 1]) |> call(sort) |> to_value == [1, 2, 3]
@test Convertible(42) |> call(value -> value + 1) |> to_value == 43
@test Convertible(nothing) |> call(value -> value + 1) |> to_value === nothing
@test Convertible("42") |> fail("Initial error.") |> call(int) |> to_value_error == ("42", "Initial error.")
@test_throws MethodError Convertible("hello world") |> call(value -> value + 1) |> to_value
@test_throws MethodError Convertible(nothing) |> call(value -> value + 1, handle_nothing = true) |> to_value

# condition
detect_unknown_values = condition(
  test_in(['?', 'x']),
  from_value(false),
  from_value(true),
)
@test Convertible("Hello world!") |> detect_unknown_values |> to_value === true
@test Convertible('x') |> detect_unknown_values |> to_value === false
@test Convertible(nothing) |> detect_unknown_values |> to_value === false
@test Convertible("Hello world!") |> fail("Initial error.") |> detect_unknown_values |> to_value_error == (
  "Hello world!", "Initial error.")

# default
@test Convertible(nothing) |> default(42) |> to_value == 42
@test Convertible("Hello world!") |> default(42) |> to_value == "Hello world!"
@test Convertible("    \n  ") |> input_to_int |> default(42) |> to_value == 42
@test Convertible(nothing) |> input_to_int |> default(42) |> to_value == 42
@test Convertible(nothing) |> fail("Initial error.") |> default(42) |> to_value_error == (nothing, "Initial error.")

# empty_to_nothing
@test Convertible("") |> empty_to_nothing |> to_value === nothing
@test Convertible("Hello world!") |> empty_to_nothing |> to_value == "Hello world!"
@test Convertible(" ") |> empty_to_nothing |> to_value == " "
@test Convertible(" ") |> strip |> empty_to_nothing |> to_value === nothing
@test Convertible([]) |> empty_to_nothing |> to_value === nothing
@test Convertible([42, 43]) |> empty_to_nothing |> to_value == [42, 43]
@test Convertible(Dict()) |> empty_to_nothing |> to_value === nothing
@test Convertible(Dict("answer" => 42)) |> empty_to_nothing |> to_value == Dict("answer" => 42)
@test Convertible(nothing) |> empty_to_nothing |> to_value === nothing
@test Convertible("") |> fail("Initial error.") |> empty_to_nothing |> to_value_error == ("", "Initial error.")

# extract_when_singleton
@test Convertible([42]) |> extract_when_singleton |> to_value == 42
@test Convertible([42, 43]) |> extract_when_singleton |> to_value == [42, 43]
@test Convertible([]) |> extract_when_singleton |> to_value == []
@test Convertible(nothing) |> extract_when_singleton |> to_value === nothing
@test Convertible([42]) |> fail("Initial error.") |> extract_when_singleton |> to_value_error == ([42],
  "Initial error.")

# fail
@test Convertible(42) |> fail |> to_value_error == (42, "An error occured.")
@test Convertible(42) |> fail("Wrong answer.") |> to_value_error == (42, "Wrong answer.")
@test Convertible(nothing) |> fail |> to_value_error == (nothing, "An error occured.")
@test Convertible(42) |> fail("Initial error.") |> fail("Next error.") |> to_value_error == (42, "Initial error.")

# first_match
@test Convertible(42) |> first_match(to_int, test_equal("NaN")) |> to_value == 42
@test Convertible("NaN") |> first_match(to_int, test_equal("NaN")) |> to_value == "NaN"
@test Convertible("Hello world!") |> first_match(to_int, test_equal("NaN")) |> to_value_error == ("Hello world!",
  "Value must be equal to NaN.")
@test Convertible("Hello world!") |> first_match(to_int, test_equal("NaN"),
  error = "Value must be a integer or NaN.") |> to_value_error == ("Hello world!", "Value must be a integer or NaN.")
@test Convertible("Hello world!") |> first_match(to_int, test_equal("NaN"), from_value(0)) |> to_value == 0
@test Convertible("Hello world!") |> first_match() |> to_value == "Hello world!"
@test Convertible("Hello world!") |> first_match(error = "An error occured.") |> to_value == "Hello world!"
@test Convertible(nothing) |> first_match(to_int, test_equal("NaN")) |> to_value === nothing
@test Convertible(42) |> fail("Initial error.") |> first_match(to_int, test_equal("NaN")) |> to_value_error == (42,
  "Initial error.")

# from_value
@test Convertible("Answer to the Ultimate Question of Life, the Universe, and Everything") |> from_value(42) |>
  to_value == 42
@test Convertible(nothing) |> from_value(42) |> to_value == 42
@test Convertible("Hello world!") |> fail |> from_value(42) |> to_value_error == ("Hello world!", "An error occured.")
@test Convertible("Answer to the Ultimate Question of Life, the Universe, and Everything") |> fail("Initial error.") |>
  from_value(42) |> to_value_error == ("Answer to the Ultimate Question of Life, the Universe, and Everything",
    "Initial error.")

# guess_bool
@test Convertible("0") |> guess_bool |> to_value === false
@test Convertible("f") |> guess_bool |> to_value === false
@test Convertible("FALSE") |> guess_bool |> to_value === false
@test Convertible("false") |> guess_bool |> to_value === false
@test Convertible("n") |> guess_bool |> to_value === false
@test Convertible("no") |> guess_bool |> to_value === false
@test Convertible("off") |> guess_bool |> to_value === false
@test Convertible("   0\n  ") |> guess_bool |> to_value === false
@test Convertible("   f\n  ") |> guess_bool |> to_value === false
@test Convertible(false) |> guess_bool |> to_value === false
@test Convertible("1") |> guess_bool |> to_value === true
@test Convertible("on") |> guess_bool |> to_value === true
@test Convertible("t") |> guess_bool |> to_value === true
@test Convertible("TRUE") |> guess_bool |> to_value === true
@test Convertible("true") |> guess_bool |> to_value === true
@test Convertible("y") |> guess_bool |> to_value === true
@test Convertible("yes") |> guess_bool |> to_value === true
@test Convertible("   1\n  ") |> guess_bool |> to_value === true
@test Convertible("   tRUE\n  ") |> guess_bool |> to_value === true
@test Convertible(true) |> guess_bool |> to_value === true
@test Convertible(1) |> guess_bool |> to_value === true
@test Convertible(2) |> guess_bool |> to_value === true
@test Convertible(-1) |> guess_bool |> to_value === true
@test Convertible("") |> guess_bool |> to_value === nothing
@test Convertible("   \n  ") |> guess_bool |> to_value === nothing
@test Convertible(nothing) |> guess_bool |> to_value === nothing
@test Convertible("vrai") |> guess_bool |> to_value_error == ("vrai", "Value must be a boolean.")
@test Convertible("0") |> fail("Initial error.") |> guess_bool |> to_value_error == ("0", "Initial error.")

# input_to_bool
@test Convertible("0") |> input_to_bool |> to_value === false
@test Convertible("   0\n  ") |> input_to_bool |> to_value === false
@test Convertible("1") |> input_to_bool |> to_value === true
@test Convertible("   1\n  ") |> input_to_bool |> to_value === true
@test Convertible("42") |> input_to_bool |> to_value === true
@test Convertible("   \n  ") |> input_to_bool |> to_value === nothing
@test Convertible(nothing) |> input_to_bool |> to_value === nothing
@test Convertible("vrai") |> input_to_bool |> to_value_error == ("vrai", "Value must be a boolean.")
@test Convertible("on") |> input_to_bool |> to_value_error == ("on", "Value must be a boolean.")
@test Convertible("0") |> fail("Initial error.") |> input_to_bool |> to_value_error == ("0", "Initial error.")

# input_to_email
@test Convertible("john@doe.name") |> input_to_email |> to_value == "john@doe.name"
@test Convertible("mailto:john@doe.name") |> input_to_email |> to_value == "john@doe.name"
@test Convertible("root@localhost") |> input_to_email |> to_value == "root@localhost"
@test Convertible("root@127.0.0.1") |> input_to_email |> to_value_error == ("root@127.0.0.1",
  "Invalid domain name.")
@test Convertible("root@127.0.0.1") |> input_to_email(accept_ip_address = true) |> to_value == "root@127.0.0.1"
@test Convertible("root") |> input_to_email |> to_value_error == ("root",
  """An email must contain exactly one "@".""")
@test Convertible("    john@doe.name\n  ") |> input_to_email |> to_value == "john@doe.name"
@test Convertible(nothing) |> input_to_email |> to_value === nothing
@test Convertible("    \n  ") |> input_to_email |> to_value === nothing
@test Convertible("john@doe.name") |> fail("Initial error.") |> input_to_email |> to_value_error == ("john@doe.name",
  "Initial error.")

# input_to_float
@test Convertible("42") |> input_to_float |> to_value == 42.0
@test Convertible("   42.75\n  ") |> input_to_float |> to_value == 42.75
@test Convertible("Hello world!") |> input_to_float |> to_value_error == ("Hello world!",
  "Value must be a float number.")
@test Convertible("(42 / 42 + 1) * 42 - 42") |> input_to_float |> to_value_error == ("(42 / 42 + 1) * 42 - 42",
  "Value must be a float number.")
@test Convertible("(42 / 42 + 1) * 42 - 42") |> input_to_float(accept_expression = true) |> to_value == 42.0
@test Convertible("pi / 2") |> input_to_float(accept_expression = true) |> to_value_error == ("pi / 2",
  "Value must be a valid floating point expression.")
@test Convertible("1 / 3") |> input_to_float(accept_expression = true) |> to_value == 0.3333333333333333
@test Convertible(nothing) |> input_to_float |> to_value === nothing
@test Convertible("42") |> fail("Initial error.") |> input_to_float |> to_value_error == ("42", "Initial error.")

# input_to_int
@test Convertible("42") |> input_to_int |> to_value == 42
@test Convertible("   42\n") |> input_to_int |> to_value == 42
@test Convertible("42.75") |> input_to_int |> to_value_error == ("42.75", "Value must be an integer number.")
@test Convertible("(42 / 42 + 1) * 42 - 42") |> input_to_int |> to_value_error == ("(42 / 42 + 1) * 42 - 42",
  "Value must be an integer number.")
@test Convertible("(42 / 42 + 1) * 42 - 42") |> input_to_int(accept_expression = true) |> to_value == 42
@test Convertible("pi / 2") |> input_to_int(accept_expression = true) |> to_value_error == ("pi / 2",
  "Value must be a valid integer expression.")
@test Convertible("1 / 3") |> input_to_int(accept_expression = true) |> to_value_error == (0.3333333333333333,
  "Value must be an integer number.")
@test Convertible(nothing) |> input_to_int |> to_value === nothing
@test Convertible("42") |> fail("Initial error.") |> input_to_int |> to_value_error == ("42", "Initial error.")

# input_to_ipv4
@test Convertible("127.0.0.1") |> input_to_ipv4 |> to_value == IPv4(127, 0, 0, 1)
@test Convertible("0.0.0.0") |> input_to_ipv4 |> to_value == IPv4(0, 0, 0, 0)
@test Convertible("   192.168.1.1\n  ") |> input_to_ipv4 |> to_value == IPv4(192, 168, 1, 1)
@test Convertible("1.2.3") |> input_to_ipv4 |> to_value_error == ("1.2.3", "Invalid IPv4 address.")
@test Convertible("1.2.3.4.5") |> input_to_ipv4 |> to_value_error == ("1.2.3.4.5", "Invalid IPv4 address.")
@test Convertible("localhost") |> input_to_ipv4 |> to_value_error == ("localhost", "Invalid IPv4 address.")
@test Convertible("hello.world.!.0") |> input_to_ipv4 |> to_value_error == ("hello.world.!.0", "Invalid IPv4 address.")
@test Convertible("256.0.0.1") |> input_to_ipv4 |> to_value_error == ("256.0.0.1", "Invalid IPv4 address.")
@test Convertible(nothing) |> input_to_ipv4 |> to_value === nothing
@test Convertible("    \n  ") |> input_to_ipv4 |> to_value === nothing
@test Convertible("127.0.0.1") |> fail("Initial error.") |> input_to_ipv4 |> to_value_error == ("127.0.0.1",
  "Initial error.")

# input_to_url_name
@test Convertible("   Hello \n world!\n  ") |> input_to_url_name |> to_value == "hello_world!"
@test Convertible("   Hello \n world!\n  ") |> input_to_url_name(separator = ' ') |> to_value == "hello world!"
@test Convertible("ÉÀÎÔÛêâîôùÆŒæœÇç") |> input_to_url_name |> to_value == "éàîôûêâîôùæœæœçç"
@test Convertible("ÉÀÎÔÛêâîôùÆŒæœÇç") |> input_to_url_name(stripmark = true) |> to_value == "eaioueaiouæœæœcc"
@test Convertible(nothing) |> input_to_url_name |> to_value === nothing
@test Convertible("    \n  ") |> input_to_url_name |> to_value === nothing
@test Convertible("   Hello \n world!\n  ") |> fail("Initial error.") |> input_to_url_name |> to_value_error == (
  "   Hello \n world!\n  ", "Initial error.")

# item_or_sequence
@test Convertible("42") |> item_or_sequence(input_to_int) |> to_value == 42
@test Convertible(["42"]) |> item_or_sequence(input_to_int) |> to_value == 42
@test Convertible(["42", "43"]) |> item_or_sequence(input_to_int) |> to_value == [42, 43]
@test Convertible(["42", "43", "Hello world!"]) |> item_or_sequence(input_to_int) |> to_value_error == (
  [42, 43, "Hello world!"], Dict(3 => "Value must be an integer number."))
@test Convertible(nothing) |> item_or_sequence(input_to_int) |> to_value === nothing
@test Convertible([nothing]) |> item_or_sequence(input_to_int, drop_nothing = true) |> to_value == []
@test Convertible([nothing, nothing]) |> item_or_sequence(input_to_int) |> to_value == [nothing, nothing]
@test Convertible([nothing, nothing]) |> item_or_sequence(input_to_int, drop_nothing = true) |> to_value == []
@test Convertible(["42", "    \n  ", "43"]) |> item_or_sequence(input_to_int) |> to_value == [42, nothing, 43]
@test Convertible(["42", "    \n  ", "43"]) |> item_or_sequence(input_to_int, drop_nothing = true) |> to_value == [42,
  43]
@test Convertible("42") |> fail("Initial error.") |> item_or_sequence(input_to_int) |> to_value_error == ("42",
  "Initial error.")

# item_to_singleton
@test Convertible("Hello world!") |> item_to_singleton |> to_value == ["Hello world!"]
@test Convertible(["Hello world!"]) |> item_to_singleton |> to_value == ["Hello world!"]
@test Convertible([42, "Hello world!"]) |> item_to_singleton |> to_value == [42, "Hello world!"]
@test Convertible([]) |> item_to_singleton |> to_value == []
@test Convertible(nothing) |> item_to_singleton |> to_value == nothing
@test Convertible("Hello world!") |> fail("Initial error.") |> item_to_singleton |> to_value_error == ("Hello world!",
  "Initial error.")

# pipe
@test_throws MethodError Convertible(42) |> input_to_bool
@test_throws MethodError Convertible(42) |> pipe(input_to_bool)
@test Convertible(42) |> pipe(test_isa(AbstractString), input_to_bool) |> to_value_error == (42,
  "Value must be an instance of AbstractString.")
@test Convertible(42) |> pipe(to_string, input_to_bool) |> to_value === true
@test Convertible(42) |> pipe() |> to_value == 42
@test Convertible(42) |> fail("Initial error.") |> pipe(to_string, input_to_bool) |> to_value_error == (42,
  "Initial error.")

# require
@test Convertible(42) |> require |> to_value == 42
@test Convertible("") |> require |> to_value == ""
@test Convertible(nothing) |> require |> to_value_error == (nothing, "Missing value.")
@test Convertible("   \n  ") |> strip |> require |> to_value_error == (nothing, "Missing value.")
@test Convertible(42) |> fail("Initial error.") |> require |> to_value_error == (42, "Initial error.")

# strip
@test Convertible("   Hello world!\n   ") |> strip |> to_value == "Hello world!"
@test Convertible("   \n   ") |> strip |> to_value === nothing
@test Convertible(nothing) |> strip |> to_value === nothing
@test Convertible("   Hello world!\n   ") |> fail("Initial error.") |> strip |> to_value_error == (
  "   Hello world!\n   ", "Initial error.")

# struct
dict_strict_converter = struct(
  Dict(
    "name" => pipe(strip, require),
    "age" => input_to_int,
    "email" => input_to_email,
  ),
)
@test Convertible(Dict(
  "name" => "John Doe",
  "age" => "72",
  "email" => "john@doe.name",
)) |> dict_strict_converter |> to_value == Dict(
  "name" => "John Doe",
  "age" => 72,
  "email" => "john@doe.name",
)
@test Convertible(Dict(
  "name" => "John Doe",
  "email" => "john@doe.name",
)) |> dict_strict_converter |> to_value == Dict(
  "name" => "John Doe",
  "age" => nothing,
  "email" => "john@doe.name",
)
@test Convertible(Dict(
  "name" => "John Doe",
  "age" => nothing,
  "email" => "john@doe.name",
)) |> dict_strict_converter |> to_value == Dict(
  "name" => "John Doe",
  "age" => nothing,
  "email" => "john@doe.name",
)
@test Convertible(Dict(
  "name" => "John Doe",
  "age" => "72",
  "email" => "john@doe.name",
  "phone" => "   +33 9 12 34 56 78   ",
)) |> dict_strict_converter |> to_value_error == (
  Dict(
    "name" => "John Doe",
    "age" => 72,
    "email" => "john@doe.name",
    "phone" => "   +33 9 12 34 56 78   ",
  ),
  Dict(
    "phone" => "Unexpected item.",
  ),
)
dict_non_strict_converter = struct(
  Dict(
    "name" => pipe(strip, require),
    "age" => input_to_int,
    "email" => input_to_email,
  ),
  default = strip,
)
@test Convertible(Dict(
  "name" => "John Doe",
  "age" => "72",
  "email" => "john@doe.name",
)) |> dict_non_strict_converter |> to_value == Dict(
  "name" => "John Doe",
  "age" => 72,
  "email" => "john@doe.name",
)
@test Convertible(Dict(
  "name" => "John Doe",
  "email" => "john@doe.name",
)) |> dict_non_strict_converter |> to_value == Dict(
  "name" => "John Doe",
  "age" => nothing,
  "email" => "john@doe.name",
)
@test Convertible(Dict(
  "name" => "John Doe",
  "age" => "72",
  "email" => "john@doe.name",
  "phone" => "   +33 9 12 34 56 78   ",
)) |> dict_non_strict_converter |> to_value == Dict(
  "name" => "John Doe",
  "age" => 72,
  "email" => "john@doe.name",
  "phone" => "+33 9 12 34 56 78",
)
tuple_strict_converter = struct(
  (
    pipe(strip, require),
    input_to_int,
    input_to_email,
  ),
)
@test Convertible([
  "John Doe",
  "72",
  "john@doe.name",
]) |> tuple_strict_converter |> to_value == (
  "John Doe",
  72,
  "john@doe.name",
)
@test Convertible([
  "John Doe",
  nothing,
  "john@doe.name",
]) |> tuple_strict_converter |> to_value == (
  "John Doe",
  nothing,
  "john@doe.name",
)
@test Convertible([
  "John Doe",
  "72",
  "john@doe.name",
  "   +33 9 12 34 56 78   ",
]) |> tuple_strict_converter |> to_value_error == (
  (
    "John Doe",
    72,
    "john@doe.name",
    "   +33 9 12 34 56 78   ",
  ),
  Dict(
    4 => "Unexpected item.",
  ),
)
tuple_non_strict_converter = struct(
  (
    pipe(strip, require),
    input_to_int,
    input_to_email,
  ),
  default = strip,
)
@test Convertible([
  "John Doe",
  "72",
  "john@doe.name",
]) |> tuple_non_strict_converter |> to_value == (
  "John Doe",
  72,
  "john@doe.name",
)
@test Convertible([
  "John Doe",
  nothing,
  "john@doe.name",
]) |> tuple_non_strict_converter |> to_value == (
  "John Doe",
  nothing,
  "john@doe.name",
)
@test Convertible([
  "John Doe",
  "72",
  "john@doe.name",
  "   +33 9 12 34 56 78   ",
]) |> tuple_non_strict_converter |> to_value == (
  "John Doe",
  72,
  "john@doe.name",
  "+33 9 12 34 56 78",
)
@test Convertible(nothing) |> dict_strict_converter |> to_value === nothing
@test Convertible(Dict(
  "name" => "John Doe",
  "age" => "72",
  "email" => "john@doe.name",
)) |> fail("Initial error.") |> dict_strict_converter |> to_value_error == (
  Dict(
    "name" => "John Doe",
    "age" => "72",
    "email" => "john@doe.name",
  ),
  "Initial error.")

# test
@test Convertible("hello") |> test(value -> isa(value, AbstractString)) |> to_value == "hello"
@test Convertible(1) |> test(value -> isa(value, AbstractString)) |> to_value_error == (1, "Test failed.")
@test Convertible(1) |> test(value -> isa(value, AbstractString), error = "Value is not a string.") |> to_value_error == (1,
  "Value is not a string.")
@test Convertible(nothing) |> test(value -> isa(value, AbstractString)) |> to_value === nothing
@test Convertible(nothing) |> test(value -> isa(value, AbstractString), handle_nothing = true) |> to_value_error == (nothing,
  "Test failed.")
@test Convertible("hello") |> fail("Initial error.") |> test(value -> isa(value, AbstractString)) |> to_value_error == ("hello",
  "Initial error.")

# test_between
@test Convertible(5) |> test_between(0, 9) |> to_value == 5
@test Convertible(0) |> test_between(0, 9) |> to_value == 0
@test Convertible(10) |> test_between(0, 9) |> to_value_error == (10, "Value must be between 0 and 9.")
@test Convertible(10) |> test_between(0, 9, error = "Number must be a digit.") |> to_value_error == (10,
  "Number must be a digit.")
@test Convertible(nothing) |> test_between(0, 9) |> to_value === nothing
@test Convertible(5) |> fail("Initial error.") |> test_between(0, 9) |> to_value_error == (5, "Initial error.")

# test_equal
@test Convertible(42) |> test_equal(42) |> to_value == 42
@test Convertible(Dict("a" => 1, "b" => 2)) |> test_equal(Dict("a" => 1, "b" => 2)) |> to_value == Dict("a" => 1, "b" => 2)
@test Convertible(41) |> test_equal(42) |> to_value_error == (41, "Value must be equal to 42.")
@test Convertible(41) |> test_equal(42, error = "Value is not the answer.") |> to_value_error == (41,
  "Value is not the answer.")
@test Convertible(42) |> test_equal(nothing) |> to_value_error == (42, "Value must be equal to nothing.")
@test Convertible(nothing) |> test_equal(42) |> to_value === nothing
@test Convertible(nothing) |> test_equal(nothing) |> to_value === nothing
@test Convertible(nothing) |> test_equal(nothing, handle_nothing = true) |> to_value === nothing
@test Convertible(nothing) |> test_equal(42, handle_nothing = true) |> to_value_error == (nothing,
  "Value must be equal to 42.")
@test Convertible(42) |> fail("Initial error.") |> test_equal(42) |> to_value_error == (42, "Initial error.")

# test_greater_or_equal
@test Convertible(5) |> test_greater_or_equal(0) |> to_value == 5
@test Convertible(5) |> test_greater_or_equal(9) |> to_value_error == (5,
  "Value must be greater than or equal to 9.")
@test Convertible(5) |> test_greater_or_equal(9, error = "Value must be a positive two-digits number.") |>
  to_value_error == (5, "Value must be a positive two-digits number.")
@test Convertible(nothing) |> test_greater_or_equal(0) |> to_value === nothing
@test Convertible(5) |> fail("Initial error.") |> test_greater_or_equal(0) |> to_value_error == (5, "Initial error.")

# test_in
@test Convertible('a') |> test_in("abcd") |> to_value == 'a'
@test Convertible('a') |> test_in(['a', 'b', 'c', 'd']) |> to_value == 'a'
@test Convertible('z') |> test_in(['a', 'b', 'c', 'd']) |> to_value_error == ('z',
  "Value must belong to ['a','b','c','d'].")
@test Convertible('z') |> test_in(Set(['a', 'b', 'c', 'd'])) |> to_value_error == ('z',
  "Value must belong to ['d','b','c','a'].")
@test Convertible('z') |> test_in(['a', 'b', 'c', 'd'], error = """Value must be a letter less than "e".""") |>
  to_value_error == ('z', """Value must be a letter less than "e".""")
@test Convertible('z') |> test_in([]) |> to_value_error == ('z', "Value must belong to Any[].")
@test Convertible(nothing) |> test_in("abcd") |> to_value == nothing
@test Convertible(nothing) |> test_in("abcd", handle_nothing = true) |> to_value_error == (nothing,
  "Value must belong to abcd.")
@test_throws MethodError Convertible('z') |> test_in(nothing)
@test Convertible('a') |> fail("Initial error.") |> test_in("abcd") |> to_value_error == ('a', "Initial error.")

# test_isa
@test Convertible("This is a string.") |> test_isa(AbstractString) |> to_value == "This is a string."
@test Convertible(42) |> test_isa(AbstractString) |> to_value_error == (42, "Value must be an instance of AbstractString.")
@test Convertible(42) |> test_isa(AbstractString, error = "Value is not a string.") |> to_value_error == (42,
  "Value is not a string.")
@test Convertible(nothing) |> test_isa(AbstractString) |> to_value === nothing
@test Convertible(nothing) |> test_isa(AbstractString, handle_nothing = true) |> to_value_error == (nothing,
  "Value must be an instance of AbstractString.")
@test Convertible("This is a string.") |> fail("Initial error.") |> test_isa(AbstractString) |> to_value_error == (
  "This is a string.", "Initial error.")

# test_nothing
@test Convertible(42) |> test_nothing() |> to_value_error == (42, "Unexpected value")
@test Convertible(42) |> test_nothing(error = "No value allowed.") |> to_value_error == (42, "No value allowed.")
@test Convertible("") |> test_nothing() |> to_value_error == ("", "Unexpected value")
@test Convertible(nothing) |> test_nothing() |> to_value_error == (nothing, nothing)
@test Convertible(42) |> test_nothing |> to_value_error == (42, "Unexpected value")
@test Convertible("") |> test_nothing |> to_value_error == ("", "Unexpected value")
@test Convertible(nothing) |> test_nothing |> to_value_error == (nothing, nothing)

# to_bool
@test Convertible("0") |> to_bool |> to_value === false
@test Convertible("1") |> to_bool |> to_value === true
@test Convertible(42) |> to_bool |> to_value === true
@test Convertible("42") |> to_bool |> to_value === true
@test Convertible(nothing) |> to_bool |> to_value === nothing
@test Convertible("vrai") |> to_bool |> to_value_error == ("vrai", "Value must be a boolean.")
@test Convertible("on") |> to_bool |> to_value_error == ("on", "Value must be a boolean.")
@test Convertible("0") |> fail("Initial error.") |> to_bool |> to_value_error == ("0", "Initial error.")

# to_float
@test Convertible(42) |> to_float |> to_value == 42.0
@test Convertible("42") |> to_float |> to_value == 42.0
@test Convertible(42.75) |> to_float |> to_value == 42.75
@test Convertible("42.75") |> to_float |> to_value == 42.75
@test Convertible("   42.75  ") |> to_float |> to_value == 42.75
@test Convertible("   42.75\n  ") |> to_float |> to_value == 42.75
@test Convertible("(42 / 42 + 1) * 42 - 42") |> to_float |> to_value_error == ("(42 / 42 + 1) * 42 - 42",
  "Value must be a float number.")
@test Convertible("(42 / 42 + 1) * 42 - 42") |> to_float(accept_expression = true) |> to_value == 42.0
@test Convertible("pi / 2") |> to_float(accept_expression = true) |> to_value_error == ("pi / 2",
  "Value must be a valid floating point expression.")
@test Convertible("1 / 3") |> to_float(accept_expression = true) |> to_value == 0.3333333333333333
@test Convertible(nothing) |> to_float |> to_value === nothing
@test Convertible(42) |> fail("Initial error.") |> to_float |> to_value_error == (42, "Initial error.")

# to_int
@test Convertible(42) |> to_int |> to_value == 42
@test Convertible("42") |> to_int |> to_value == 42
@test Convertible("42.75") |> to_int |> to_value_error == ("42.75", "Value must be an integer number.")
@test Convertible("42,75") |> to_int |> to_value_error == ("42,75", "Value must be an integer number.")
@test Convertible("(42 / 42 + 1) * 42 - 42") |> to_int |> to_value_error == ("(42 / 42 + 1) * 42 - 42",
  "Value must be an integer number.")
@test Convertible("(42 / 42 + 1) * 42 - 42") |> to_int(accept_expression = true) |> to_value == 42
@test Convertible("pi / 2") |> to_int(accept_expression = true) |> to_value_error == ("pi / 2",
  "Value must be a valid integer expression.")
@test Convertible("1 / 3") |> to_int(accept_expression = true) |> to_value_error == (0.3333333333333333,
  "Value must be an integer number.")
@test Convertible(nothing) |> to_int |> to_value === nothing
@test Convertible(42) |> fail("Initial error.") |> to_int |> to_value_error == (42, "Initial error.")

# to_string
@test Convertible(42) |> to_string |> to_value == "42"
@test Convertible("42") |> to_string |> to_value == "42"
@test Convertible(nothing) |> to_string |> to_value === nothing
@test Convertible(42) |> fail("Initial error.") |> to_string |> to_value_error == (42, "Initial error.")

# uniform_mapping
@test Convertible(Dict("a" => "1", "b" => "2")) |> uniform_mapping(strip, input_to_int) |> to_value == Dict("a" => 1, "b" => 2)
@test Convertible(Dict("   answer\n  " => "42")) |> uniform_mapping(strip, input_to_int) |> to_value == Dict("answer" => 42)
@test Convertible(Dict("a" => "1", "b" => "2", "c" => 3)) |> uniform_mapping(strip, test_isa(AbstractString), input_to_int) |>
  to_value_error == (Dict("a" => 1, "b" => 2, "c" => 3), Dict("c" => "Value must be an instance of AbstractString."))
@test Convertible(Dict("a" => "1", "b" => "2", "c" => 3)) |>
  uniform_mapping(strip, condition(test_isa(AbstractString), input_to_int)) |>
  to_value == Dict("a" => 1, "b" => 2, "c" => 3)
@test Convertible(Dict()) |> uniform_mapping(strip, input_to_int) |> to_value == Dict{Void,Void}()
@test Convertible(Dict(nothing => "42")) |> uniform_mapping(strip, input_to_int) |> to_value == Dict(nothing => 42)
@test Convertible(Dict("   \n  " => "42")) |> uniform_mapping(strip, input_to_int) |> to_value == Dict(nothing => 42)
@test Convertible(Dict(nothing => "42")) |> uniform_mapping(strip, input_to_int, drop_nothing_keys = true) |>
  to_value == Dict{Void,Void}()
    # >>> uniform_mapping(cleanup_line, input_to_int)(None)
    # (None, None)
@test Convertible(nothing) |> uniform_mapping(strip, input_to_int) |> to_value === nothing
@test Convertible(Dict("a" => "1", "b" => "2")) |> fail("Initial error.") |> uniform_mapping(strip, input_to_int) |>
  to_value_error == (Dict("a" => "1", "b" => "2"), "Initial error.")

# uniform_sequence
@test Convertible(["42"]) |> uniform_sequence(input_to_int) |> to_value == [42]
@test Convertible(["42", "43"]) |> uniform_sequence(input_to_int) |> to_value == [42, 43]
@test Convertible(["42", "43", "Hello world!"]) |> uniform_sequence(input_to_int) |> to_value_error == (
  [42, 43, "Hello world!"], Dict(3 => "Value must be an integer number."))
@test Convertible([nothing, nothing]) |> uniform_sequence(input_to_int) |> to_value == [nothing, nothing]
@test Convertible([nothing, nothing]) |> uniform_sequence(input_to_int, drop_nothing = true) |> to_value == []
@test Convertible(["42", "    \n  ", "43"]) |> uniform_sequence(input_to_int) |> to_value == [42, nothing, 43]
@test Convertible(["42", "    \n  ", "43"]) |> uniform_sequence(input_to_int, drop_nothing = true) |> to_value == [42,
  43]
@test Convertible(["42"]) |> fail("Initial error.") |> uniform_sequence(input_to_int) |> to_value_error == (["42"],
  "Initial error.")

# Test tools.

# is_valid
@test Convertible("42") |> input_to_int |> is_valid === true
@test Convertible("Hello world!") |> input_to_int |> is_valid === false

# .value
@test (Convertible("42") |> input_to_int).value == 42
@test (Convertible("Hello world!") |> input_to_int).value == "Hello world!"

# to_value
@test Convertible("42") |> input_to_int |> to_value == 42
@test_throws ErrorException Convertible("Hello world!") |> input_to_int |> to_value

# to_value_error
@test Convertible("42") |> input_to_int |> to_value_error == (42, nothing)
@test Convertible("Hello world!") |> input_to_int |> to_value_error == ("Hello world!", "Value must be an integer number.")


text:
const MatrixModels = ["IID Matrices",
                "Hermitian Matrices",
                "Unitary Matrices",
                "CorrelatedMatrices"]

for model in MatrixModels
    include(joinpath("MatrixModels", "$(model).jl"))
end

ext: jl


text:
#Function for angular calculation in Blockade shift
#25/07/2017

function angcalc(lli,jji,mji,ll1,jj1)
  spin = 0.5 #Electron spin
  angvec1 = zeros(3)
  for qq = -1:1
    mj1 = mji - qq
    j1vec = collect(-jj1:jj1)
    if length(find(j1vec -> j1vec==mj1,j1vec))==1
      ang11 = (-1)^float(jji-mji+spin+jj1+1)
      ang12 = sqrt((2*jji+1)*(2*jj1+1)*(2*lli+1)*(2*ll1+1))
      ang13 = Wigner6j(jji,1,jj1,ll1,spin,lli)
      ang14 = Wigner3j(jji,1,jj1,-mji,qq,mj1)
      ang15 = Wigner3j(lli,1,ll1,0,0,0)
      angvec1[qq+2] = ang11*ang12*ang13*ang14*ang15 #Shift for Julia indexing
    end
  end
  return angvec1
end

max_stars_repo_name: CSChisholm/Rydberg

max_issues_repo_name: CSChisholm/Rydberg

max_forks_repo_name: CSChisholm/Rydberg


text:
# Unit test for Atmacs file reading
@testset "DataFrame stacking" begin
	# First set (with overlapping)
	f1 = DataFrame(datetime=[DateTime(2010,1,1,0),DateTime(2010,1,1,1),
	           DateTime(2010,1,1,2),DateTime(2010,1,1,3)],
			   grav=[10.,11.,12.,13.]);
	f2 = DataFrame(datetime=[DateTime(2010,1,1,2),DateTime(2010,1,1,3),
	           DateTime(2010,1,1,4),DateTime(2010,1,1,5)],
			   grav=[22.,23.,24.,25.]);
	data = stackframes(f1,f2,maxtime=Dates.Hour(1),maxval=NaN,corroffset=true);
	@test size(data) == (6,2)
	@test names(data)==[:datetime,:grav]
	@test data[:datetime][3] == f1[:datetime][3]
	@test data[:datetime][4] == f2[:datetime][2]
	@test data[:datetime][end] == f2[:datetime][end]
	@test data[:grav] == [10.,11.,12.,13.,14.,15];

	# Same as above but without offset correction
	data = stackframes(f1,f2,maxtime=Dates.Hour(1),maxval=NaN,corroffset=false);
	@test size(data) == (6,2)
	@test names(data)==[:datetime,:grav]
	@test data[:datetime][3] == f1[:datetime][3]
	@test data[:datetime][4] == f2[:datetime][2]
	@test data[:datetime][end] == f2[:datetime][end]
	@test data[:grav] == [10.,11.,12.,13.,24.,25];

	# Same as above but without offset > as allowed threshold => not stacked
	data = stackframes(f1,f2,maxtime=Dates.Hour(1),maxval=1.,corroffset=true);
	@test size(data) == (4,2)
	@test names(data)==[:datetime,:grav]
	@test data[:datetime] == f1[:datetime]
	@test data[:grav] == data[:grav];

	# No overlapping but within maximum time stap
	f2 = DataFrame(datetime=[DateTime(2010,1,1,6),DateTime(2010,1,1,7),
		DateTime(2010,1,1,8),DateTime(2010,1,1,9)],
		grav=[22.,23.,24.,25.]);
	data = stackframes(f1,f2,maxtime=Dates.Hour(3),maxval=NaN,corroffset=false);
	@test size(data) == (size(f2,1)+size(f1,1)+1,2)
	@test names(data)==[:datetime,:grav]
	@test data[:datetime][4] == f1[:datetime][end]
	@test data[:datetime][5] == f1[:datetime][end]+(f1[:datetime][end]-f1[:datetime][end-1])
	@test data[:datetime][end] == f2[:datetime][end]
	@test data[:grav][1:4] == [10.,11.,12.,13.]
	@test isnan(data[:grav][5])
	@test data[:grav][6:end] == [22.,23.,24.,25.]

	# Same as above but with maximum time step exceeded
	data = stackframes(f1,f2,maxtime=Dates.Hour(1),maxval=NaN,corroffset=true);
	@test size(data) == (4,2)
	@test names(data)==[:datetime,:grav]
	@test data[:datetime] == f1[:datetime]
	@test data[:grav] == data[:grav];
end

# Load global and local part
@testset "Atmacs Load global and local part" begin
	glo,loc = loadatmacs(glofiles=[joinpath(dirname(@__DIR__),"test","input","atmacs_glo.grav")],
						locfiles=[joinpath(dirname(@__DIR__),"test","input","atmacs_loc.grav")]);
	# Independent loading
	glo_m = readdlm(joinpath(dirname(@__DIR__),"test","input","atmacs_glo.grav"))
	loc_m = readdlm(joinpath(dirname(@__DIR__),"test","input","atmacs_loc.grav"))
	@test glo[:global_newton] == glo_m[:,2]
	@test glo[:total_loading] == glo_m[:,3]
	@test loc[:pressure] == loc_m[:,2]
	@test loc[:local_newton] == loc_m[:,3]
	@test loc[:regional_newton] == loc_m[:,4]
	@test glo[:datetime] == DateTime.(string.(round.(Int,glo_m[:,1])),"yyyymmddHH")
	@test loc[:datetime] == DateTime.(string.(round.(Int,loc_m[:,1])),"yyyymmddHH")

	# Stack multiple global files covering global+local part (`loc` will be empty)
	gfiles=[joinpath(dirname(@__DIR__),"test","input","atmacs_all_1.grav"),
			joinpath(dirname(@__DIR__),"test","input","atmacs_all_2.grav"),
			joinpath(dirname(@__DIR__),"test","input","atmacs_all_3.grav")];
	glo,loc = loadatmacs(glofiles=gfiles);
	total_m = Matrix{Float64}(undef,0,5);
	for i in gfiles
		temp = readdlm(i)
		total_m = vcat(total_m,temp);
	end
	total_time = DateTime.(string.(round.(Int,total_m[:,1])),"yyyymmddHH")
	@test glo[:datetime] == DateTime.(string.(round.(Int,total_m[:,1])),"yyyymmddHH")
	for i in 2:size(glo,2)
		@test glo[i] == total_m[:,i]
	end
end


text:
module BaseAgent

using Movement
using Params
using Channel.Gilbert
using Traffic.Simple
using Distributions
using DataStructures: Queue, Deque, enqueue!, dequeue!, front, back

export AgentState, Environment, Agent, Result, Success, Collision, BufOverflow, LostInChannel,
       Action, Transmit, Sense, Idle, move, fillbuffer, idle, act_then_idle, sense, feedback,
       switch!, transmit!, Status, Initialized, Switched, Sensed, Transmitted, initial_action,
       act, switch, Switch, EndTransmission, initcoordinator, cooperate, detect_traffic

type Environment
    channels :: Vector{GilbertChannel}
    traffics :: Vector{SimpleTraffic}
end

abstract Agent

# Define an enum as in enum macro in examples
immutable Result
    n :: Int
    Result(n::Int) = new(n)
end

const Success = Result(0)
const Collision = Result(1)
const BufOverflow = Result(2)
const LostInChannel = Result(3)

immutable Status
    n :: Int
    Status(n) = new(n)
end

const Initialized = Status(0)
const Switched = Status(1)
const Sensed = Status(2)
const Transmitted = Status(3)

# Energy saving modes
immutable EnergySavingMode
    n :: Int
end

MaxThroughput = EnergySavingMode(1)
EnergySaving = Params.energysaving ? EnergySavingMode(2) : MaxThroughput

export EnergySavingMode, EnergySaving, MaxThroughput

# I align structures for smaller memory footprint (size matters!)
type AgentState
    pos :: Point{Float64} # position
    t_remaining :: Float64
    speed :: Float64
    # Slot statistics
    n_pkt_slot :: Int64
    E_idle :: Float64
    E_tx :: Float64
    E_sw :: Float64
    E_sense :: Float64
    E_slot :: Float64
    walk :: Function
    pd :: Float64 # Probability of detection
    pf :: Float64 # Probability of false alarm
    cap_level :: Int # capability level
    location_error :: ZeroMeanIsoNormal # Location accuracy distribution
    B_empty :: Int16 # empty buffer slots
    B_max :: Int16
    buf_overflow :: Bool
    id :: Int8
    chan :: Int8 # current channel
    energysaving :: EnergySavingMode
    pktqueue :: Queue{Deque{Int}} # Creation time-slot of packets
    indoor :: Bool
    function AgentState(i :: Int8, P :: ParamT, pos :: Point{Float64})
        a = new()
        a.pos = pos
        a.t_remaining = Params.t_slot
        a.speed = i < P.n_stationary_agent ? 30. / 3.6 : 0
        a.n_pkt_slot = 0
        a.E_slot = 0
        a.E_sw = 0
        a.E_tx = 0
        a.E_sense = 0
        a.E_idle = 0
        a.walk = randomwalk(a.speed, int(20 / Params.t_slot))
        a.cap_level = P.caplevels[i]
        # distribute pd-pf pairs using round robin
        a.pd = Params.pd[a.cap_level]
        a.pf = Params.pf[a.cap_level]
        a.location_error = MvNormal(2, Params.eps_accuracy[a.cap_level])
        a.B_max = Params.B
        a.B_empty = Params.B
        a.buf_overflow = false
        a.id = i
        a.chan = rand(1:Params.n_channel)
        a.energysaving = i % 2 == 0 ? (Params.energysaving ? EnergySaving : MaxThroughput) : EnergySaving
        a.pktqueue = Queue(Int)
        a.indoor = false
        a
    end
end

abstract Action

type Transmit <: Action
    power :: Float64
    bitrate :: Float64
    chan :: Int8
    n_pkt :: Int16
    i :: Int8
end

type EndTransmission <: Action
    power :: Float64
    bitrate :: Float64
    chan :: Int8
    n_pkt :: Int16
    i :: Int8
    EndTransmission(t::Transmit) = new(t.power,t.bitrate,t.chan,t.n_pkt,t.i)
end

Transmit(t::EndTransmission) = Transmit(t.power,t.bitrate,t.chan,t.n_pkt-1,t.i)

type Idle <: Action
    i :: Int8
end

type Sense <: Action
    chan :: Int8
    i :: Int8
end

type Switch <: Action
    chan :: Int8
    i :: Int8
end

function move!(s :: AgentState, t :: Int64)
    s.pos += s.walk(t)
end

function fillbuffer(a :: Agent, P :: ParamT, t :: Int64)
    s :: AgentState = a.s
    pkgs = rand(Params.pkt_min:P.pkt_max)
    if pkgs > s.B_empty
        s.buf_overflow = true
        feedback(a, BufOverflow)
        pkgs = s.B_empty
        s.B_empty = 0
    else
        s.buf_overflow = false
        s.B_empty -= pkgs
    end
    for i = 1:pkgs
        enqueue!(s.pktqueue, t)
    end
    nothing
end

function idle(a :: Agent, t :: Float64 = -1.)
    s :: AgentState = a.s
    if t < 0 || t > s.t_remaining
        t = s.t_remaining
    end
    s.E_idle += Params.P_idle * t
    s.E_slot += Params.P_idle * t
    s.t_remaining -= t
    Idle(s.id)
end

function initial_action(a :: Agent, env :: Environment, t :: Int64, P)
    fillbuffer(a, P, t)
    if length(a.s.pktqueue) + a.s.B_empty != a.s.B_max
        error("Buffer inconsistency at $(a.s)")
    end
    move!(a.s, t)
    s :: AgentState = a.s
    s.n_pkt_slot = 0
    s.t_remaining = Params.t_slot
    # Add backoff
    idle(a, Params.t_backoff * rand())
    s.E_slot = 0
    s.E_sw = 0
    s.E_tx = 0
    s.E_sense = 0
    s.E_idle = 0
    a.status = Initialized
    act(a, env, t)
end

function sense(a :: Agent, env :: Environment, detect_traffic :: Function)
    s :: AgentState = a.s
    if s.t_remaining < Params.t_sense
        error("No time remained for sensing")
    end
    s.t_remaining -= Params.t_sense
    E_sense = Params.P_sense * Params.t_sense
    s.E_sense += E_sense
    s.E_slot += E_sense
    a.status = Sensed
    Sense(s.chan, s.id)
end

function detect_traffic(s :: AgentState, t :: SimpleTraffic, t_remaining :: Float64)
    # if channel is occupied for less than half of sensing time
    # we can't sense the traffic, so use pf (actually this logic should be revised)
    sensing = t.occupancy < (Params.t_slot - t_remaining - 0.5 * Params.t_sense)
    rand() < (sensing ? s.pd : s.pf)
end

function feedback(s :: AgentState, res :: Result, idle :: Bool = false, n_pkt :: Int = 0)
    if idle || res == BufOverflow
        return
    elseif res == Success
        s.B_empty += n_pkt
    end
    if s.B_empty > s.B_max
        error("Error in simulation, buffer underflow!")
        s.B_empty = s.B_max
    end
    nothing
end

function feedback(a :: Agent, res :: Result, idle :: Bool = false, n_pkt :: Int = 0)
    feedback(a.s, res, idle, n_pkt)
end

function switch(a :: Agent, c :: Int8)
    Switch(c, a.s.id)
end

function switch!(a :: Agent, c :: Int8)
    s :: AgentState = a.s
    t_sw = Params.t_sw * abs(c - s.chan)
    if s.t_remaining < t_sw
        error(sprintf("No time remained for switching from chan #%d to chan #%d", s.chan, c))
    end

    E_sw = t_sw * Params.P_sw
    s.E_sw += E_sw
    s.E_slot += E_sw
    s.t_remaining -= t_sw
    s.chan = c
    a.status = Switched
    nothing
end

function transmit!(a :: Agent, P_tx, env, n_pkt)
    s :: AgentState = a.s
    n_bits = n_pkt * Params.pkt_size
    bitrate = capacity(env.channels[s.chan], P_tx, s.pos)
    if s.t_remaining < n_bits / bitrate
        println(s.t_remaining)
        error(@sprintf("Not enough time to transmit %d bits with bitrate %f", n_bits, bitrate))
    end
    s.n_pkt_slot = n_pkt
    s.t_remaining -= n_bits / bitrate
    E_tx = P_tx * n_bits / bitrate
    s.E_tx += E_tx
    s.E_slot += E_tx
    a.status = Transmitted
    Transmit(P_tx, bitrate, s.chan, n_pkt, s.id)
end

function act(a :: Agent)
    error("Not implemented")
end

initcoordinator{AgentT <: Agent}(:: Type{AgentT}, P :: ParamT) = nothing

cooperate{AgentT <: Agent}(agents :: Vector{AgentT}, P :: ParamT, coordinator, t) = nothing

end


text:
function main()
	N = 1_000
	for a = 1:N
		for b = 1:N
			for c = 1:N
				if a+b+c == 1000 && a*a + b*b == c*c
					println("$a $b $c")
				end
			end
		end
	end
end

main()

max_stars_repo_name: cmey/euler

max_issues_repo_name: cmey/euler

max_forks_repo_name: cmey/euler


text:
################
# Content Type #
################

type Content <: GitHubType
    typ::Nullable{GitHubString}
    filename::Nullable{GitHubString}
    name::Nullable{GitHubString}
    path::Nullable{GitHubString}
    target::Nullable{GitHubString}
    encoding::Nullable{GitHubString}
    content::Nullable{GitHubString}
    sha::Nullable{GitHubString}
    url::Nullable{HttpCommon.URI}
    git_url::Nullable{HttpCommon.URI}
    html_url::Nullable{HttpCommon.URI}
    download_url::Nullable{HttpCommon.URI}
    size::Nullable{Int}
end

Content(data::Dict) = json2github(Content, data)
Content(path::AbstractString) = Content(Dict("path" => path))

namefield(content::Content) = content.path

###############
# API Methods #
###############

function file(repo, path; options...)
    result = gh_get_json(content_uri(repo, path); options...)
    return Content(result)
end

function directory(repo, path; options...)
    results, page_data = gh_get_paged_json(content_uri(repo, path); options...)
    return map(Content, results), page_data
end

function create_file(repo, path; options...)
    result = gh_put_json(content_uri(repo, path); options...)
    return build_content_response(result)
end

function update_file(repo, path; options...)
    result = gh_put_json(content_uri(repo, path); options...)
    return build_content_response(result)
end

function delete_file(repo, path; options...)
    result = gh_delete_json(content_uri(repo, path); options...)
    return build_content_response(result)
end

function readme(repo; options...)
    result = gh_get_json("/repos/$(name(repo))/readme"; options...)
    return Content(result)
end

function permalink(content::Content, commit)
    url = string(get(content.html_url))
    prefix = get(content.typ) == "file" ? "blob" : "tree"
    rgx = Regex(string("\/", prefix, "\/.*?\/"))
    replacement = string("/", prefix, "/", name(commit), "/")
    return HttpCommon.URI(replace(url, rgx, replacement))
end

###########################
# Content Utility Methods #
###########################

content_uri(repo, path) = "/repos/$(name(repo))/contents/$(name(path))"

function build_content_response(json::Dict)
    results = Dict()
    haskey(json, "commit") && setindex!(results, Commit(json["commit"]), "commit")
    haskey(json, "content") && setindex!(results, Content(json["content"]), "content")
    return results
end


text:
# Sequence Record
# ===============
#
# Sequence record with name and attached metadata.
#
# This file is a part of BioJulia.
# License is MIT: https://github.com/BioJulia/Bio.jl/blob/master/LICENSE.md

"""
`SeqRecord{S,T}` is a type holding a named sequence of type `S`, along with
some arbitrary metadata of type `T`.
"""
type SeqRecord{S<:Sequence,T}
    name::StringField
    seq::S
    metadata::T
end

function SeqRecord(name::AbstractString, seq::Sequence, metadata=nothing)
    return SeqRecord(StringField(name), seq, metadata)
end

@compat function (::Type{SeqRecord{S,T}}){S,T}()
    return SeqRecord{S,T}(StringField(), S(), T())
end

function seqtype{S,T}(::Type{SeqRecord{S,T}})
    return S
end

# Degelgate sequence operations
"Return a `SeqRecord` holding just the nucleotide at position `i`"
function Base.getindex(seqrec::SeqRecord, i::Integer)
    return SeqRecord(seqreq.name, seqrec.seq[i], seqreq.metadata)
end

"Return a `SeqRecord` holding the specified subsequence"
function Base.getindex(seqrec::SeqRecord, r::UnitRange)
    return SeqRecord(seqrec.name, seqrec.seq[r], seqrec.metadata)
end

@compat function Base.:(==){T<:SeqRecord}(a::T, b::T)
    return a.name == b.name && a.seq == b.seq && a.metadata == b.metadata
end

function Base.copy{T <: SeqRecord}(seqrec::T)
    return T(copy(seqrec.name), copy(seqrec.seq), copy(seqrec.metadata))
end

typealias DNASeqRecord{T}       SeqRecord{DNASequence, T}
typealias RNASeqRecord{T}       SeqRecord{RNASequence, T}
typealias AminoAcidSeqRecord{T} SeqRecord{AminoAcidSequence, T}


text: #include("test_sample_blocking_scheduler.jl")


text:
n=parse(Int,ARGS[1])          # take one integer argument
println(rand(1:n,n,n))  # generate and print n x n matrix of random integers between 1 and n
@show b=3               # set b to 3 and show the result
c=4                     # set c to 4

max_stars_repo_path: src/Module A - Short Julia Course/deploy.jl

max_stars_repo_name: ivanslapnicar/GIAN-Applied-NLA-Course

max_issues_repo_name: ivanslapnicar/GIAN-Applied-NLA-Course

max_forks_repo_name: ivanslapnicar/GIAN-Applied-NLA-Course


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder
name = "ImageMagick"
upstream_version = v"6.9.12-34"
version = VersionNumber(upstream_version.major, upstream_version.minor, upstream_version.patch)

# Collection of sources required to build imagemagick
sources = [
    ArchiveSource("https://github.com/ImageMagick/ImageMagick6/archive/$(upstream_version).tar.gz",
                  "990f93f39ae36f917c64f7e5929810150de416b275e8afc2580fdea68be28255"),
    DirectorySource("./bundled"),
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/ImageMagick6*/
if [[ "${target}" == *-linux-gnu ]]; then
    atomic_patch -p1 ../patches/utilities-link-rt.patch
elif [[ "${target}" == *-mingw* ]]; then
    # Link to ws2_32 to fix undefined reference to `__imp_WSAStartup`.
    atomic_patch -p1 ../patches/windows-undefined-reference-__imp_WSAStartup.patch
fi
atomic_patch -p1 ../patches/check-have-clock-realtime.patch
./configure --prefix=${prefix} \
    --build=${MACHTYPE} \
    --host=${target} \
    --without-x \
    --disable-openmp \
    --disable-installed \
    --disable-dependency-tracking \
    --without-frozenpaths \
    --without-perl \
    --disable-docs \
    --disable-static
make -j${nproc}
make install
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = expand_cxxstring_abis(supported_platforms(;experimental=true))

# The products that we will ensure are always built
products = [
    LibraryProduct(["libMagickWand", "libMagickWand-6.Q16"], :libwand),
    ExecutableProduct("convert", :imagemagick_convert),
    ExecutableProduct("identify", :identify),
    ExecutableProduct("montage", :montage),
    ExecutableProduct("mogrify", :mogrify),
]

# Dependencies that must be installed before this package can be built
dependencies = [
    Dependency("Zlib_jll"),
    Dependency("libpng_jll"),
    Dependency("JpegTurbo_jll"),
    Dependency("Libtiff_jll"; compat="4.3.0"),
    Dependency("Ghostscript_jll"),
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies; julia_compat="1.6")

max_stars_repo_name: jakebolewski/Yggdrasil

max_issues_repo_name: jakebolewski/Yggdrasil

max_forks_repo_name: jakebolewski/Yggdrasil


text:
module PhomericsTest

using ForwardDiff    # used in my_test_functions.jl
using SparseArrays   # used in CalcD.jl

include("my_test_functions.jl")
export f1
export f2
export f_diff2

include("Operators.jl")
export DX
export DXX
export DY
export DYY

include("MaxwellSolver.jl")
include("ScalarSolver.jl")

include("Tools.jl")
export first_derivative

end # module


text:
export AD, FD, VE, sensitivity, sensitivity_trace, extract_STMs, extract_stability, has_variational_equations

#---------------------------#
# SENSITIVITIES (i.e. STMs) #
#---------------------------#

# TODO: Use Symbols instead of these constants?
const AD = ForwardDiff
const FD = FiniteDiff
const VE = Val(:VariationalEquations)

@traitdef HasVE{X}
@traitimpl HasVE{X} <- has_variational_equations(X)
has_variational_equations(X::Type{<:Abstract_ModelODEFunctions}) = hasfield(X, :ode_stm_f)
has_variational_equations(X::Type{<:Abstract_DynamicalModel}) = has_variational_equations(fieldtype(X, :ode))
has_variational_equations(X::Type{<:State}) = has_variational_equations(fieldtype(X, :model))

@doc """ Sensitivity of the final state with respect to initial state. """
sensitivity(m::Module, args...; kwargs...) = sensitivity(Val(first(fullname(m))), args...; kwargs...)
function sensitivity(::Val{:ForwardDiff}, state, desired_frame=state.frame, alg=DEFAULT_ALG; kwargs...)
    ForwardDiff.jacobian(state.u0) do u0
        new_state = remake(state, u0=u0)
        return convert_to_frame(solve(new_state, alg; kwargs...), desired_frame).sol[end]
    end
end
function sensitivity(::Val{:FiniteDiff}, state, desired_frame=state.frame, alg=DEFAULT_ALG; kwargs...)
    FiniteDiff.finite_difference_jacobian(state.u0) do u0
        new_state = remake(state, u0=u0)
        return convert_to_frame(solve(new_state, alg; kwargs...), desired_frame).sol[end]
    end
end
function sensitivity(v::Val{:VariationalEquations}, state, args...; kwargs...)
    STM_VE = sensitivity_trace(v, state, args...; kwargs...).sol[end]
    dim = length(state.u0)
    return reshape(STM_VE[dim+1:end], (dim, dim))
end

@doc """ Sensitivity of the full propagated trajectory with respect to initial state. """
sensitivity_trace(m::Module, args...; kwargs...) = sensitivity_trace(Val(first(fullname(m))), args...; kwargs...)
function sensitivity_trace(::Val{:ForwardDiff}, state::State, desired_frame=state.frame, alg=DEFAULT_ALG; trace_time=false, kwargs...)
    values = trace_time ? [state.u0..., state.tspan[end] - state.tspan[begin]] : state.u0

    # Seed the values we want to trace with Dual numbers
    tag = typeof(state.model)
    duals = DiffEqSensitivity.seed_duals(values, tag)
    u0 = MVector{length(state.u0)}(duals[1:length(state.u0)])

    # Remake the state with the seeded values
    tspan = trace_time ? (state.tspan[begin], state.tspan[begin] + duals[end]) : state.tspan
    state_AD = remake(state; u0, tspan)

    # Solve and convert to the desired frame
    sol = solve(state_AD, alg; kwargs...)
    return convert_to_frame(sol, desired_frame)
end
@traitfn function sensitivity_trace(::Val{:VariationalEquations}, state::S, desired_frame=state.frame, alg=DEFAULT_ALG; kwargs...) where {S; HasVE{S}}
    dim = length(state.u0)
    I_flat = reshape(Matrix{Float64}(I, dim, dim), dim^2)
    u0_STM = MVector{dim^2 + dim}(vcat(state.u0, I_flat))
    prob_vareqns = State(state.model, state.frame, ODEProblem(state.model.ode.ode_stm_f, u0_STM, state.tspan, state.p))
    traj_vareqns_unconverted = solve(prob_vareqns, alg; kwargs...)

    # Convert to the desired frame
    return convert_to_frame(traj_vareqns_unconverted, desired_frame)
end

@doc """ Sensitivity of the state at time t with respect to initial state. """
function sensitivity(sol::Trajectory, t)
    extract_STMs(sol, t)
end

@doc """ Sensitivity of the state at time t2 with respect to the state at time t1 <= t2. """
function sensitivity(sol::Trajectory, t1, t2)
    @assert t1 <= t2  "Expected t1 <= t2"
    if t2 == t1
        return Matrix(1.0 * I, 6, 6)  # TODO: Make this type and size-generic
    else
        return sensitivity(sol, t2) / sensitivity(sol, t1)
    end
end

# TODO: Better functions for extracting STMs and stability index from Dual numbers
# TODO: Use ForwardDiff.extract_jacobian
function extract_STMs(sol::Trajectory, t)
    extract_STMs(sol(t))
end
function extract_STMs(sol::Trajectory)
    extract_STMs(sol.u)
end
function extract_STMs(state::State)
    extract_STMs([state.u0])[1]
end
function extract_STMs(u)
    [hcat([Array(t.partials) for t in ut]...)' for ut in u]
end
function extract_stability(u)
    hcat(eigvals.(extract_STMs(u))...)
end


text:
#=
Copyright (c) 2015, Intel Corporation
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
=#

module TestKmeans
using ParallelAccelerator
using CompilerTools

#CompilerTools.OptFramework.set_debug_level(3)
#ParallelAccelerator.set_debug_level(3)
#ParallelAccelerator.DomainIR.set_debug_level(3)
#ParallelAccelerator.ParallelIR.set_debug_level(3)
#ParallelAccelerator.CGen.set_debug_level(3)

@acc function kmeans(iterations::Int64, points, numCenter)
    D,N = size(points) # number of features, instances
    centroids = Float64[convert(Float64,i+j) for i in 1:D, j in 1:numCenter]

    for l in 1:iterations
        dist::Array{Array{Float64,1},1} = [ Float64[sqrt(sum((points[:,i]-centroids[:,j]).^2)) for j in 1:numCenter] for i in 1:N]
        labels::Array{Int,1} = [indmin(dist[i]) for i in 1:N]
        centroids::Array{Float64,2} = [ sum(points[j,labels.==i])/sum(labels.==i) for j in 1:D, i in 1:numCenter]
    end
    return centroids
end

end

using Base.Test

points = [1. 2. 3. 4.; 4. 3. 2. 1.; 4. 5. 6. 7.]

println("Testing kmeans...")
@test_approx_eq TestKmeans.kmeans(10, points, 2) [1.5  3.5; 3.5  1.5; 4.5  6.5]
println("Done testing kmeans...")


text:
# optical_absorption.jl

"""
----------------------------------------------------------------------
Polaron absorption coefficient Γ(Ω).
----------------------------------------------------------------------
"""

"""
optical_absorption_ac(Ω::Float64, β::Float64, α::Float64, v::Float64, w::Float64)

    Calculate the absorption coefficient Γ(Ω) for the polaron at finite temperatures (equation (11a) in Devreese's et al.) for a given frequency Ω. β is the thermodynamic beta. v and w are the variational Polaron parameters that minimise the free energy, for the supplied α Frohlich coupling.
"""
function optical_absorption_ac(Ω, β, α, v, w)
    X = χ(Ω, β, α, v, w)
    Reχ = real(X)
    Imχ = imag(X)
    result = Ω * Imχ / (Ω^4 - 2 * Ω^2 * Reχ + Reχ^2 + Imχ^2)
    return result
end

"""
optical_absorption_ac(Ω::Float64, α::Float64, v::Float64, w::Float64)

    Calculate the absorption coefficient Γ(Ω) for the polaron at zero temperatures (equation (11a) in Devreese's et al.) for a given frequency Ω. β is the thermodynamic beta. v and w are the variational Polaron parameters that minimise the free energy, for the supplied α Frohlich coupling.
"""
function optical_absorption_ac(Ω, α, v, w)
    X = χ(Ω, α, v, w)
    Reχ = real(X)
    Imχ = imag(X)
    result = Ω * Imχ / (Ω^4 - 2 * Ω^2 * Reχ + Reχ^2 + Imχ^2)
    return result
end

"""
optical_absorption_dc(β::Float64, α::Float64, v::Float64, w::Float64)

    Calculate the absorption coefficient Γ(Ω) for the polaron at finite temperatures (equation (11a) in Devreese's et al.) at zero frequency. β is the thermodynamic beta. v and w are the variational Polaron parameters that minimise the free energy, for the supplied α Frohlich coupling.
"""
function optical_absorption_dc(β, α, v, w)
    X = χ_dc(β, α, v, w)
    Reχ = real(X)
    Imχ = imag(X)
    result = Ω * Imχ / (Ω^4 - 2 * Ω^2 * Reχ + Reχ^2 + Imχ^2)
    return result
end


text:
# this file depends on jacobi.jl from JuliaOptics/OpticsPolynomials that
# should be found in the same directory

export cheby1, cheby1_series, cheby1_sum, cheby2, cheby2_series, cheby2_sum

"""
    cheby1(n, x)

Compute the Chebyshev polynomial of the first kind of order n at point x.

This family of Chebyshev polynomials are a special case of the Jacobi polynomials
with α, β = -1/2.

See also: [`cheby1_series`](@ref), [`cheby1_sum`](@ref)
"""
function cheby1(n, x)
    return jacobi(n, -0.5, -0.5, x)
end

"""
    cheby1_series(ns, α, β, x)

Compute a series of Chebyshev polynomials of the first kind of orders n.
Returns an array with shape (size(x)..., length(ns)).
That is, the _final_ dimension contains the modes and the first dimension(s)
are spatial.

See also: [`cheby1`](@ref), [`cheby1_sum`](@ref)
"""
function cheby1_series(ns, x)
    return jacobi_series(ns, -0.5, -0.5, x)
end
"""
    cheby1_sum(ns, weights, x)

Compute a sum of Chebyshev polynomial of the first kind of order n weighted by weights.

See also: [`cheby1`](@ref), [`cheby1_series`](@ref)
"""
function cheby1_sum(ns, weights, x)
    return jacobi_sum(ns, weights, -0.5, -0.5, x)
end

"""
    cheby2(n, x)

Compute the Chebyshev polynomial of the second kind of order n at point x.

This family of Chebyshev polynomials are a special case of the Jacobi polynomials
with α, β = 1/2.

See also: [`cheby2_series`](@ref), [`cheby2_sum`](@ref)
"""
function cheby2(n, x)
    return jacobi(n, 0.5, 0.5, x)
end

"""
    cheby2_series(ns, α, β, x)

Compute a series of Chebyshev polynomials of the second kind of orders n.
Returns an array with shape (size(x)..., length(ns)).
That is, the _final_ dimension contains the modes and the first dimension(s)
are spatial.

See also: [`cheby1`](@ref), [`cheby1_sum`](@ref)
"""
function cheby2_series(ns, x)
    return jacobi_series(ns, 0.5, 0.5, x)
end
"""
    cheby1_sum(ns, weights, x)

Compute a sum of Chebyshev polynomial of the second kind of order n weighted by weights.

See also: [`cheby1`](@ref), [`cheby1_series`](@ref)
"""
function cheby2_sum(ns, weights, x)
    return jacobi_sum(ns, weights, 0.5, 0.5, x)
end


text:
A = rand(-4:4,5,3)
B = rand(-4:4,3,4)

C = A*B

C[2,3]

m = 5; n = 3; p = 4;
C = zeros(m,p);
for i = 1:m
    for j = 1:p
        for k = 1:n
            C[i,j] += A[i,k]*B[k,j]
        end
    end
end

C

m = 5; n = 3; p = 4;
C = zeros(m,p);
for i = 1:m
    for j = 1:p
        C[i,j] = sum( A[i,k]*B[k,j] for k = 1:n );
    end
end
C

m = 5; n = 3; p = 4;
C = [ sum( A[i,k]*B[k,j] for k = 1:n ) for i=1:m, j=1:p ]

# C is a matrix of inner products
i=2; j=3;
using LinearAlgebra
dot(A[i,:],B[:,j])
C = [ dot(A[i,:],B[:,j]) for i=1:m, j=1:p ]

# C columnwise is a linear combination of columns
C[:,j]
sum( B[k,j]*A[:,k] for k=1:n  )
hcat( [ sum( B[k,j]*A[:,k] for k=1:n  ) for j=1:p ]... )
q = [ sum( B[k,j]*A[:,k] for k=1:n  ) for j=1:p ];
hcat(q[1],q[2],q[3],q[4])

length(C)

length(q)

# C is a sum of outer products
sum( A[:,k]*B[k,:]' for k=1:n)

B[1,:]'

(B[1,:]')'


text:
using Test
using CInclude

@cinclude "sys/socket.h" quiet

@test SOCK_RAW == 3


text:
mutable struct JointEstimationPolyaGammaModel
    parameters::Vector{<:AbstractParameters}
    latents::Vector{<:AbstractLatent}
    responses_per_item::Vector{Vector{Float64}}
    responses_per_examinee::Vector{Vector{Float64}}
    n_index::Vector{Vector{Int64}}
    i_index::Vector{Vector{Int64}}
    item_sampling::Bool
    examinee_sampling::Bool
    ext_opt_settings::Vector{Float64}

    JointEstimationPolyaGammaModel(parameters, latents, responses_per_item, responses_per_examinee, n_index, i_index,item_sampling, examinee_sampling, ext_opt_settings) =
     new(parameters, latents, responses_per_item, responses_per_examinee, n_index, i_index, item_sampling, examinee_sampling, ext_opt_settings)
end


text:
"""
# KM3NeT Data Definitions v1.3.1-8-gae7dfb2
https://git.km3net.de/common/km3net-dataformat
"""

module Fitparameters
  const JGANDALF_BETA0_RAD = 0
  const JGANDALF_BETA1_RAD = 1
  const JGANDALF_CHI2 = 2
  const JGANDALF_NUMBER_OF_HITS = 3
  const JENERGY_ENERGY = 4
  const JENERGY_CHI2 = 5
  const JGANDALF_LAMBDA = 6
  const JGANDALF_NUMBER_OF_ITERATIONS = 7
  const JSTART_NPE_MIP = 8
  const JSTART_NPE_MIP_TOTAL = 9
  const JSTART_LENGTH_METRES = 10
  const JVETO_NPE = 11
  const JVETO_NUMBER_OF_HITS = 12
  const JENERGY_MUON_RANGE_METRES = 13
  const JENERGY_NOISE_LIKELIHOOD = 14
  const JENERGY_NDF = 15
  const JENERGY_NUMBER_OF_HITS = 16
  const JCOPY_Z_M = 17
  const JSHOWERFIT_ENERGY = 4
end


text:
# Unit test for the Nonlinear Arnoldi method (in src/method_nlar.jl)
# The "Gun" problem form gun_native.jl

using NonlinearEigenproblemsTest
using NonlinearEigenproblems
using Test
using LinearAlgebra
using Random

@bench @testset "Nonlinear Arnoldi" begin
	TOL = 1e-10;

    @info "Testing gun problem"
    Random.seed!(0)

    nep = nep_gallery("nlevp_native_gun")
    n = size(nep,1);

    #The eigenvalues of the gun problem lie within a semi-circle centred approximately around the "shift" with an approximate radius "scale"
    shift = 250^2;
    scale = 330^2-220^2;

    #Run Quasi-Newton for initial guess obtained from the knowledge of the eigenvalue distribution
    λ_ref,v_ref = quasinewton(nep, λ = shift+scale*(-0.131403+0.00759532im), v = ones(n), logger = displaylevel, tol = TOL/50, maxit = 500)
    @info "Eigenvalue computed by quasi newton: $λ_ref"

    #Shift and scale the NEP(mainly to avoid round-off errors because of the large entries in the coefficient matrices)
    nep1_spmf = SPMF_NEP(get_Av(nep),get_fv(nep))
    nep1 = shift_and_scale(nep1_spmf,shift=shift,scale=scale);

    #Run NLAR on the shifted and scaled NEP (neigs set to 1 to save time. Method works for the case of finding multiple eigenvalues as well)
    λ,u = nlar(nep1, tol=TOL, λ=0, maxit=100, neigs=2, R=0.01, logger=displaylevel, v=ones(n),
        eigval_sorter=residual_eigval_sorter, inner_solver_method=IARInnerSolver(),
        qrfact_orth=false, num_restart_ritz_vecs=8, max_subspace=150)

    λ_shifted = λ[1];v=u[:,1];

    #Rescale and shift back to the eigenvalue of the original problem
    λ_orig = shift+scale*λ_shifted;

    #Test residual and distance from reference eigenvalue
    @test norm(compute_Mlincomb(nep, λ_orig, v)) < sqrt(TOL)*50
    @test norm(compute_Mder(nep, λ_orig) * v) < sqrt(TOL)*50
    @test norm(λ_ref - λ_orig) < sqrt(TOL)*500
    ###########################################################################################################3

    #Testing PEP
    @info "Testing a PEP"
    pepnep = nep_gallery("pep0",60)
    Dc,Vc = polyeig(pepnep,DefaultEigSolver)
    c = sortperm(abs.(Dc))
    @info " 6 smallest eigenvalues found by polyeig() according to the absolute values: $(Dc[c[1:6]])"

    λ,u = nlar(pepnep, tol=TOL, maxit=60, neigs=3, R=0.001, logger=displaylevel,
        λ=Dc[4]+1e-2, v=ones(size(pepnep,1)), eigval_sorter=residual_eigval_sorter,
        inner_solver_method=IARInnerSolver(), qrfact_orth=false, errmeasure=ResidualErrmeasure(pepnep))

    verify_lambdas(3, pepnep, λ, u, TOL)

    @info "Testing errors thrown"
    nep = nep_gallery("pep0",4)
    @test_throws NEPCore.NoConvergenceException λ,u= nlar(nep, tol=1e-20, maxit=2, neigs=3)

end


text:
module MatrixPlot
using PyPlot
export matrices_plot, matrix_prep

# convert a matrix to PyPlot format
function matrix_prep(A::Array{Float64,2})
	x::Array{Float64,1} = Float64[]
	y::Array{Float64,1} = Float64[]
	z::Array{Float64,1} = Float64[]
	for i=1:size(A,1)
		xyz = A[i,:]
		push!(x,xyz[1])
		push!(y,xyz[2])
		push!(z,xyz[3])
	end

	return x, y, z
end

# Plot a 3D scatterplot of two matrices
function matrices_plot(P::Array{Float64,2},Q::Array{Float64,2}, reads_line::Bool)
	try
		pygui(true)
		x::Array{Float64,1}, y::Array{Float64,1}, z::Array{Float64,1} = matrix_prep(P)
		x_plot = scatter3D(x, y, z, color="red")
		display(x_plot)
		x,y,z = matrix_prep(Q)
		y_plot = scatter3D(x, y, z, color="green")

		display(x_plot)

		if (reads_line)
			readline()
		end
		return true
	catch
		warn("no GUI backend for matplotlib, skipping...")
		return true
	end
end
end


text:
import Adapt: adapt, adapt_storage
using Zygote: IdSet

functor(x) = (), _ -> x

functor(x::Tuple) = x, y -> y
functor(x::NamedTuple) = x, y -> y

functor(x::AbstractArray) = x, y -> y
functor(x::AbstractArray{<:Number}) = (), _ -> x

function makefunctor(m::Module, T, fs = fieldnames(T))
  @eval m begin
    Flux.functor(x::$T) = ($([:($f=x.$f) for f in fs]...),), y -> $T(y...)
  end
end

function functorm(T, fs = nothing)
  fs == nothing || isexpr(fs, :tuple) || error("@functor T (a, b)")
  fs = fs == nothing ? [] : [:($(map(QuoteNode, fs.args)...),)]
  :(makefunctor(@__MODULE__, $(esc(T)), $(fs...)))
end

macro functor(args...)
  functorm(args...)
end

isleaf(x) = functor(x)[1] === ()

function fmap1(f, x)
  func, re = functor(x)
  re(map(f, func))
end

function fmap(f, x; cache = IdDict())
  haskey(cache, x) && return cache[x]
  cache[x] = isleaf(x) ? f(x) : fmap1(x -> fmap(f, x, cache = cache), x)
end

trainable(m) = functor(m)[1]

params!(p::Params, x::AbstractArray{<:Number}, seen = IdSet()) = push!(p, x)

function params!(p::Params, x, seen = IdSet())
  x in seen && return
  push!(seen, x)
  for child in trainable(x)
    params!(p, child, seen)
  end
end

function params(m...)
  ps = Params()
  params!(ps, m)
  return ps
end

# Deprecated stuff
macro treelike(args...)
  functorm(args...)
end
mapleaves(f, x) = fmap(f, x)

function loadparams!(m, xs)
  for (p, x) in zip(params(m), xs)
    size(p) == size(x) ||
      error("Expected param size $(size(p)), got $(size(x))")
    copyto!(p, x)
  end
end

# CPU/GPU movement conveniences

cpu(m) = fmap(x -> adapt(Array, x), m)

gpu(x) = use_cuda[] ? fmap(CuArrays.cu, x) : x

# Precision

adapt_storage(T::Type{<:Real}, xs::AbstractArray{<:Real}) = convert.(T, xs)

paramtype(T::Type{<:Real}, m) = fmap(x -> adapt(T, x), m)

f32(m) = paramtype(Float32, m)
f64(m) = paramtype(Float64, m)


text:
module MCAnalyzer
export mark_start, mark_end, analyze

import LLVM
import LLVM.Interop: @asmcall

using GPUCompiler
import LLVM_jll

function __init__()
    @assert LLVM.InitializeNativeTarget() == false
end

#=========================================================#
# GPUCompiler
#=========================================================#

module MockRuntime
    signal_exception() = return
    malloc(sz) = ccall("extern malloc", llvmcall, Ptr{Int8}, (Int64,), sz)
    report_oom(sz) = return
    report_exception(ex) = return
    report_exception_name(ex) = return
    report_exception_frame(idx, func, file, line) = return
end

struct CompilerParams <: AbstractCompilerParams end
GPUCompiler.runtime_module(::CompilerJob{<:Any,CompilerParams}) = MockRuntime

function mcjob(@nospecialize(func), @nospecialize(types);
               cpu::String = (LLVM.version() < v"8") ? "" : unsafe_string(LLVM.API.LLVMGetHostCPUName()),
               features::String=(LLVM.version() < v"8") ? "" : unsafe_string(LLVM.API.LLVMGetHostCPUFeatures()),
               kwargs...)
    source = FunctionSpec(func, Base.to_tuple_type(types), #=kernel=# false)
    target = NativeCompilerTarget(cpu=cpu, features=features)
    params = CompilerParams()
    CompilerJob(target, source, params), kwargs
end

include("reflection.jl")

#=========================================================#
# LLVM-MCA
#=========================================================#

if isdefined(LLVM_jll, :llvm_mca)
    import LLVM_jll: llvm_mca
else
    function llvm_mca(f)
        llvm_mca = get(ENV, "LLVM_MCA_PATH", joinpath(LLVM_jll.artifact_dir, "tools", "llvm_mca"))
        @assert !isempty(llvm_mca)
        f(llvm_mca)
    end
end

"""
    analyze(func, types, march = :SKL)

Analyze a given function `func` with the signature `types`.
The specific method needs to be annotated with the `IACA` markers.
Supported `march` are :HSW, :BDW, :SKL, and :SKX.

# Example

```julia
function mysum(A)
    acc = zero(eltype(A))
    for i in eachindex(A)
        mark_start()
        @inbounds acc += A[i]
    end
    mark_end()
    return acc
end

analyze(mysum, (Vector{Float64},))
```
"""
function analyze(@nospecialize(func), @nospecialize(tt), march=:SKL; kwargs...)
    job, kwargs = mcjob(func, tt; cpu=llvm_march(march), kwargs...)
    ir, func = GPUCompiler.compile(:llvm, job; kwargs...)

    GPUCompiler.finish_module!(job, ir)

    mktempdir() do dir
        asmfile = joinpath(dir, "a.S")

        tm = GPUCompiler.llvm_machine(job.target)
        LLVM.emit(tm, ir, LLVM.API.LLVMAssemblyFile, asmfile)

        # Now call analyzer
        llvm_mca() do llvm_mca_path
            Base.run(`$llvm_mca_path -mcpu $(llvm_march(march)) $asmfile`)
        end
    end
    return nothing
end

function llvm_march(march)
    cpus = Dict(
        :HSW => "haswell",
        :BDW => "broadwell",
        :SKL => "skylake",
        :SKX => "skx",
    )
    @assert haskey(cpus, march) "Arch: $march not supported"
    return cpus[march]
end

#=========================================================#
# Markers
#=========================================================#

"""
    mark_start()

Insert `iaca` and `llvm-mca` start markers at this position.
"""
function mark_start()
    @asmcall("""
    movl \$\$111, %ebx
    .byte 0x64, 0x67, 0x90
    # LLVM-MCA-BEGIN
    """, "~{memory},~{ebx}", true)
end

"""
    mark_end()

Insert `iaca` and `llvm-mca` end markers at this position.
"""
function mark_end()
    @asmcall("""
    # LLVM-MCA-END
    movl \$\$222, %ebx
    .byte 0x64, 0x67, 0x90
    """, "~{memory},~{ebx}", true)
end

end # module


text:
using OrdinaryDiffEq, ForwardDiff, Zygote, Test
using DiffEqSensitivity
using Random

function dt!(du, u, p, t)
  x, y = u
  α, β, δ, γ = p
  du[1] = dx = α*x - β*x*y
  du[2] = dy = -δ*y + γ*x*y
end

n_par=3
Random.seed!(2)
u0=rand(2,n_par)
u0[:,1] = [1.0,1.0]
tspan = (0.0, 10.0)
p = [2.2, 1.0, 2.0, 0.4]
prob_ode = ODEProblem(dt!, u0[:,1], tspan)

function test_loss(p1,prob)

	function prob_func(prob, i, repeat)
		@show i
		remake(prob,u0=u0[:,i])
	end

	#define ensemble problem
	ensembleprob = EnsembleProblem(prob,prob_func = prob_func)

	u = Array(solve(ensembleprob, Tsit5(), EnsembleThreads(), trajectories=n_par,
	p=p1,
	sensealg = ForwardDiffSensitivity(),
	saveat = 0.1, dt=0.001))[:,end,:]
	loss=sum(u)
	return loss
end

test_loss(p,prob_ode)

@time gs = Zygote.gradient(p) do p
	test_loss(p,prob_ode)
end
@test gs[1] isa Vector

### https://github.com/SciML/DiffEqFlux.jl/issues/595

function fiip(du,u,p,t)
  du[1] = dx = p[1]*u[1] - p[2]*u[1]*u[2]
  du[2] = dy = -p[3]*u[2] + p[4]*u[1]*u[2]
end

p = [1.5,1.0,3.0,1.0]; u0 = [1.0;1.0]
prob = ODEProblem(fiip,u0,(0.0,10.0),p)
sol = solve(prob,Tsit5())

function sum_of_solution(x)
    _prob = remake(prob,u0=x[1:2],p=x[3:end])
    sum(solve(_prob,Tsit5(),saveat=0.1))
end
Zygote.gradient(sum_of_solution,[u0;p])

# Testing ensemble problem. Works with ForwardDiff. Does not work with Zygote.
N = 3
eu0 = rand(N,2)
ep = rand(N,4)

ensemble_prob = EnsembleProblem(prob, prob_func=(prob, i, repeat)->remake(prob, u0=eu0[i,:], p=ep[i,:],saveat=0.1))
esol = solve(ensemble_prob, Tsit5(), trajectories=N)

cache = Ref{Any}()

function sum_of_e_solution(p)
    ensemble_prob = EnsembleProblem(prob, prob_func=(prob, i, repeat)->remake(prob, u0=eu0[i,:],p=p[i,:],saveat=0.1))
    sol = solve(ensemble_prob,Tsit5(),EnsembleSerial(),trajectories=N,abstol=1e-12,reltol=1e-12)
    z = Array(sol[1])
    cache[] = sol[1].t
    sum(z) # just test for the first solutions, gradients should be zero for others
end

sum_of_e_solution(ep)

x = ForwardDiff.gradient(sum_of_e_solution, ep)
y = Zygote.gradient(sum_of_e_solution, ep)[1] # Zygote second to test cache of forward pass
@test x ≈ y
@test cache[] == 0:0.1:10.0 # test prob.kwargs is forwarded


text:
using ApproxFunOrthogonalPolynomials, ApproxFunBase, BandedMatrices, SpecialFunctions, Test
    import ApproxFunBase: bandwidth

#
# Fix for BigFloat stackoverflow
# https://github.com/JuliaLang/julia/pull/30952
#
Base._range(a::T, step::T, ::Nothing, len::Integer) where {T <: AbstractFloat} =
	    Base._rangestyle(Base.OrderStyle(T), Base.ArithmeticStyle(T), a, step, len)

@testset "Eigenvalue problems" begin
    @testset "Negative Laplacian with Neumann boundary conditions" begin
        #
        # -𝒟² u = λu,  u'(±1) = 0.
        #
        d = Segment(-1..1)
        S = Ultraspherical(0.5, d)
        NS = NormalizedPolynomialSpace(S)
        L = -Derivative(S, 2)
        C = Conversion(domainspace(L), rangespace(L))
        B = Neumann(S)
        QS = QuotientSpace(B)
        Q = Conversion(QS, S)
        D1 = Conversion(S, NS)
        D2 = Conversion(NS, S)
        R = D1*Q
        P = cache(PartialInverseOperator(C, (0, bandwidth(L, 1) + bandwidth(R, 1) + bandwidth(C, 2))))
        A = R'D1*P*L*D2*R
        B = R'R

        # Currently a hack to avoid a LAPACK calling bug with a pencil (A, B)
        # with smaller bandwidth in A.
        n = 50
        SA = Symmetric(Matrix(A[1:n,1:n]), :L)
        SB = Symmetric(Matrix(B[1:n,1:n]), :L)
        λ = eigvals(SA, SB)

        @test λ[1:round(Int, 2n/5)] ≈ (π^2/4).*(0:round(Int, 2n/5)-1).^2
    end

    @testset "Schrödinger with piecewise-linear potential with Dirichlet boundary conditions" begin
        #
        # [-𝒟² + V] u = λu,  u(±1) = 0,
        #
        # where V = 100|x|.
        #
        d = Segment(-1..0)∪Segment(0..1)
        S = PiecewiseSpace(Ultraspherical.(0.5, d.domains))
        NS = PiecewiseSpace(NormalizedUltraspherical.(0.5, d.domains))
        V = 100Fun(abs, S)
        L = -Derivative(S, 2) + V
        C = Conversion(domainspace(L), rangespace(L))
        B = [Dirichlet(S); continuity(S, 0:1)]
        QS = QuotientSpace(B)
        Q = Conversion(QS, S)
        D1 = Conversion(S, NS)
        D2 = Conversion(NS, S)
        R = D1*Q
        P = cache(PartialInverseOperator(C, (0, bandwidth(L, 1) + bandwidth(R, 1) + bandwidth(C, 2))))
        A = R'D1*P*L*D2*R
        B = R'R

        n = 100
        SA = Symmetric(A[1:n,1:n], :L)
        SB = Symmetric(B[1:n,1:n], :L)
        λ = eigvals(SA, SB)

        @test λ[1] ≈ parse(BigFloat, "2.19503852085715200848808942880214615154684642693583513254593767079468401198338e+01")
    end

    @testset "Schrödinger with piecewise-constant potential with Dirichlet boundary conditions" begin
        #
        # [-𝒟² + V] u = λu,  u(±1) = 0,
        #
        # where V = 1000[χ_[-1,-1/2](x) + χ_[1/2,1](x)].
        #
        d = Segment(-1..(-0.5))∪Segment(-0.5..0.5)∪Segment(0.5..1)
        S = PiecewiseSpace(Ultraspherical.(0.5, d.domains))
        NS = PiecewiseSpace(NormalizedUltraspherical.(0.5, d.domains))
        V = Fun(x->abs(x) ≥ 1/2 ? 1000 : 0, S)
        L = -Derivative(S, 2) + V
        C = Conversion(domainspace(L), rangespace(L))
        B = [Dirichlet(S); continuity(S, 0:1)]
        QS = QuotientSpace(B)
        Q = Conversion(QS, S)
        D1 = Conversion(S, NS)
        D2 = Conversion(NS, S)
        R = D1*Q
        P = cache(PartialInverseOperator(C, (0, bandwidth(L, 1) + bandwidth(R, 1) + bandwidth(C, 2))))
        A = R'D1*P*L*D2*R
        B = R'R

        n = 150
        SA = Symmetric(A[1:n,1:n], :L)
        SB = Symmetric(B[1:n,1:n], :L)
        λ = eigvals(SA, SB)
        # From Lee--Greengard (1997).
        λtrue = [2.95446;5.90736;8.85702;11.80147].^2
        @test norm((λ[1:4] - λtrue)./λ[1:4]) < 1e-5
    end

    @testset "Schrödinger with linear + Dirac potential with Robin boundary conditions" begin
        #
        # [-𝒟² + V] u = λu,  u(-1) = u(1) + u'(1) = 0,
        #
        # where V = x + 100δ(x-0.25).
        #
        d = Segment(-1..0.25)∪Segment(0.25..1)
        S = PiecewiseSpace(Ultraspherical.(0.5, d.domains))
        NS = PiecewiseSpace(NormalizedUltraspherical.(0.5, d.domains))
        V = Fun(identity, S)
        L = -Derivative(S, 2) + V
        C = Conversion(domainspace(L), rangespace(L))
        B4 = zeros(Operator{ApproxFunBase.prectype(S)}, 1, 2)
        B4[1, 1] = -Evaluation(component(S, 1), rightendpoint, 1) - 100*0.5*Evaluation(component(S, 1), rightendpoint)
        B4[1, 2] = Evaluation(component(S, 2), leftendpoint, 1)  - 100*0.5*Evaluation(component(S, 2), leftendpoint)
        B4 = ApproxFunBase.InterlaceOperator(B4, PiecewiseSpace, ApproxFunBase.ArraySpace)
        B = [Evaluation(S, -1); Evaluation(S, 1) + Evaluation(S, 1, 1); continuity(S, 0); B4]
        QS = QuotientSpace(B)
        Q = Conversion(QS, S)
        D1 = Conversion(S, NS)
        D2 = Conversion(NS, S)
        R = D1*Q
        P = cache(PartialInverseOperator(C, (0, bandwidth(L, 1) + bandwidth(R, 1) + bandwidth(C, 2))))
        A = R'D1*P*L*D2*R
        B = R'R

        n = 100
        SA = Symmetric(A[1:n,1:n], :L)
        SB = Symmetric(B[1:n,1:n], :L)

        k = 3

        λ, Q = eigen(SA, SB);
        u_QS = Fun(QS, Q[:, k])
        u_S = Fun(u_QS, S)
        u = Fun(u_S, PiecewiseSpace(Chebyshev.(d.domains)))
        u /= sign(u'(-1))
        u1, u2 = components(u)

        @test norm(u(-1)) < 100eps()
        @test u(1) ≈ -u'(1)
        @test u1(0.25) ≈ u2(0.25)
        @test u2'(0.25) - u1'(0.25) ≈ 100*u(0.25)
        @test -u1'' + component(V, 1)*u1 ≈ λ[k]*u1
        @test -u2'' + component(V, 2)*u2 ≈ λ[k]*u2
    end

    @testset "BigFloat negative Laplacian with Dirichlet boundary conditions" begin
        #
        # -𝒟² u = λu,  u(±1) = 0.
        #
        d = Segment(big(-1.0)..big(1.0))
        S = Ultraspherical(big(0.5), d)
        NS = NormalizedPolynomialSpace(S)
        L = -Derivative(S, 2)
        C = Conversion(domainspace(L), rangespace(L))
        B = Dirichlet(S)
        QS = QuotientSpace(B)
        Q = Conversion(QS, S)
        D1 = Conversion(S, NS)
        D2 = Conversion(NS, S)
        R = D1*Q
        P = cache(PartialInverseOperator(C, (0, bandwidth(L, 1) + bandwidth(R, 1) + bandwidth(C, 2))))
        A = R'D1*P*L*D2*R
        B = R'R

        n = 300
        SA = Symmetric(A[1:n,1:n], :L)
        SB = Symmetric(B[1:n,1:n], :L)
        BSA = BandedMatrix(SA)
        BSB = BandedMatrix(SB)
        begin
            v = zeros(BigFloat, n)
            v[1] = 1
            v[3] = 1/256
            λ = big(0.0)
            for _ = 1:7
                λ = dot(v, BSA*v)/dot(v, BSB*v)
                OP = Symmetric(SA.data-λ*SB.data, :L)
                F = ldlt!(OP)
                ldiv!(F, v)
                normalize!(v)
            end
            @test λ ≈ big(π)^2/4
        end
    end

    @testset "Skew differentiation matrices" begin
        #
        # 𝒟 u = λ u,  u(1) + u(-1) = 0.
        #
        d = Segment(-1..1)
        S = Ultraspherical(0.5, d)
        NS = NormalizedPolynomialSpace(S)
        Lsk = Derivative(S)
        Csk = Conversion(domainspace(Lsk), rangespace(Lsk))
        B = Evaluation(S, -1) + Evaluation(S, 1)
        QS = PathologicalQuotientSpace(B)
        Q = Conversion(QS, S)
        D1 = Conversion(S, NS)
        D2 = Conversion(NS, S)
        R = D1*Q
        Psk = cache(PartialInverseOperator(Csk, (0, 4 + bandwidth(Lsk, 1) + bandwidth(R, 1) + bandwidth(Csk, 2))))
        Ask = R'D1*Psk*Lsk*D2*R
        Bsk = R'R

        n = 100
        λim = imag(sort!(eigvals(Matrix(tril(Ask[1:n,1:n], 1)), Matrix(tril(Bsk[1:n,1:n], 2))), by = abs))

        @test abs.(λim[1:2:round(Int, 2n/5)]) ≈ π.*(0.5:round(Int, 2n/5)/2)
        @test abs.(λim[2:2:round(Int, 2n/5)]) ≈ π.*(0.5:round(Int, 2n/5)/2)
    end

    @testset "Complex spectra of principal finite sections of an ultraspherical discretization of a self-adjoint problem" begin
        #
        # -𝒟² u = λ u,  u'(±1) = 0.
        #
        S = Chebyshev()
        L = -Derivative(S, 2)
        B = Neumann(S)
        C = Conversion(domainspace(L), rangespace(L))
        n = 10 # ≥ 10 appears to do the trick
        λ = eigvals(Matrix([B;L][1:n,1:n]), Matrix([B-B;C][1:n,1:n]))
        @test eltype(λ) == Complex{Float64}
    end
end


text:
module Python

using PyCall
using REPL
import PyCall: pyimport, pygui_start, PyObject, pycall, pyeval, pyexists
import REPL:LineEdit

export  @py, @pyput, @pyget, py_choosegui, py, pymain

global const pymain = PyNULL() #Ref{PyObject}()
global const py=PyNULL()

function __init__()
	active_repl=Base.active_repl;
    main_mode=active_repl.interface.modes[1]
    main_mode.keymap_dict = LineEdit.keymap_merge(main_mode.keymap_dict,pykeys)
	copy!(pymain, pyimport("__main__") )
	copy!(py, pyimport("__main__") )
	pymain[:juliatemp]="import matplotlib.pyplot as plt\nfrom matplotlib.pylab import *\nplt.ion()\n"
	py"exec(juliatemp)"
    pymain[:juliagui]="qt5"
    pygui_start(:qt5)
	nothing
end

function py_choosegui(gui=:qt5)
    try
       pygui_start(gui)
	catch
	   print("please install qt5 for python: pip3 install pyqt5\n")
    end
end

 macro pyput(args...)
     for a in args
          eval(Meta.parse("pymain[:$a]=Main.$a"))
     end
 end

 # will complete @pyget. You can put this part into startup.jl to use these two functions
 macro pyget(args...)
     for a in args
          Base.eval(Meta.parse("Main.$a=Main.deepcopy(pymain[:$a])"))
     end
 end

macro py(args...)
    script=join([string(i) for i in args]," ")
      try
         if occursin(r"^\w*$",script)
             pymain[:juliatemp]=string("print(",script,")")
             py"exec(juliatemp)"
        elseif occursin("\$", script)
		     script2=string(args...)
             script2=replace(script2,r"\(Expr\(\:\$, :(?<arg>\w*)\)\)"=>s"\g<1>")
             reg=r"\$(\w*)"
             vars=String[]
             m=collect(eachmatch(reg, script2))
             vars=[replace(x.match, "\$"=>"")  for x in m]
             for x in vars
                   eval(Meta.parse("pymain[:$x]=Main.$x"))
             end
             pymain[:juliatemp]=replace(script2,"\$"=>"")
             py"exec(juliatemp)"
             for x in vars
                   pymain[:juliatemp]="del $x"
                   py"exec(juliatemp)"
             end
        else
             pymain[:juliatemp]=script
             py"exec(juliatemp)"
        end
      catch err
          print(err.val)
      end
end

function parse_status(script::String)
    status = :ok
    status
end

# See: https://github.com/JuliaInterop/RCall.jl/blob/master/src/RPrompt.jl
function bracketed_paste_callback(s, o...)
    input = LineEdit.bracketed_paste(s)
    sbuffer = LineEdit.buffer(s)
    curspos = position(sbuffer)
    seek(sbuffer, 0)
    shouldeval = (bytesavailable(sbuffer) == curspos && search(sbuffer, UInt8('\n')) == 0)
    seek(sbuffer, curspos)
    if curspos == 0
        input = lstrip(input)
    end

    if !shouldeval
        LineEdit.edit_insert(s, input)
        return
    end

    LineEdit.edit_insert(sbuffer, input)
    input = String(take!(sbuffer))

    oldpos = start(input)
    nextpos = 0
    while !done(input, oldpos)
        nextpos = search(input, '\n', nextpos+1)
        if nextpos == 0
            nextpos = endof(input)
        end
        block = input[oldpos:nextpos]
        status = parse_status(block)

        if status == :error  || (status == :incomplete && done(input, nextpos+1)) ||
                (done(input, nextpos+1) && !endswith(input, '\n'))
            LineEdit.replace_line(s, input[oldpos:end])
            LineEdit.refresh_line(s)
            break
        elseif status == :incomplete && !done(input, nextpos+1)
            continue
        end

        if !isempty(strip(block))
            LineEdit.replace_line(s, strip(block))
            LineEdit.commit_line(s)
            terminal = LineEdit.terminal(s)
            REPL.raw!(terminal, false) && LineEdit.disable_bracketed_paste(terminal)
            LineEdit.mode(s).on_done(s, LineEdit.buffer(s), true)
            REPL.raw!(terminal, true) && LineEdit.enable_bracketed_paste(terminal)
        end
        oldpos = nextpos + 1
    end
    LineEdit.refresh_line(s)
end

mutable struct PyCompletionProvider <: LineEdit.CompletionProvider
    py::REPL.LineEditREPL
end

function create_py_repl(repl,main)
    py_mode = LineEdit.Prompt("Python> ";
                 prompt_prefix=Base.text_colors[:blue],
                 prompt_suffix=main.prompt_suffix,
                 sticky=true)
    hp = main.hist
    hp.mode_mapping[:py] = py_mode
    py_mode.hist = hp
    py_mode.complete = PyCompletionProvider(repl)
    py_mode.on_enter = (s) -> begin
            status = parse_status(String(take!(copy(LineEdit.buffer(s)))))
            status == :ok || status == :error
    end
    py_mode.on_done = (s, buf, ok) -> begin
        if !ok
            return REPL.transition(s, :abort)
        end
        script = String(take!(buf))
        if !isempty(strip(script))
	REPL.reset(repl)
        try
             if occursin('$', script)
                  reg=r"\$(\w*)"
                  vars= String[]
                  m=collect(eachmatch(reg, script))
                  vars=[replace(x.match, "\$"=>"")  for x in m]
                  for x in vars
                       eval(Meta.parse("pymain[:$x]=Main.$x"))
                  end
                  pymain[:juliatemp]=replace(script,"\$"=>"")
                  py"exec(juliatemp)"
                  for x in vars
                        pymain[:juliatemp]="del $x"
                        py"exec(juliatemp)"
                  end
             elseif occursin(r"^\w*$",script)
                  pymain[:juliatemp]=string("print(",script,")")
                  py"exec(juliatemp)"
             else
                  pymain[:juliatemp]=script
                  py"exec(juliatemp)"
             end
          catch err
              print(err)
          end
        end
		REPL.prepare_next(repl)
        REPL.reset_state(s)
        s.current_mode.sticky || REPL.transition(s,main)
    end

    bracketed_paste_mode_keymap = Dict{Any,Any}(
        "\e[200~" => bracketed_paste_callback
    )

    search_prompt, skeymap = LineEdit.setup_search_keymap(hp)
    prefix_prompt, prefix_keymap = LineEdit.setup_prefix_keymap(hp, py_mode)

	mk = REPL.mode_keymap(main)
    delete!(mk, "^C")

    b = Dict{Any,Any}[
        bracketed_paste_mode_keymap,
        skeymap, mk, prefix_keymap, LineEdit.history_keymap,
        LineEdit.default_keymap, LineEdit.escape_defaults
    ]
    py_mode.keymap_dict = LineEdit.keymap(b)

    py_mode
end

const pykeys = Dict{Any,Any}(
    ")"=> (s,o...)->(
	     if isempty(s) || position(LineEdit.buffer(s)) == 0
                  repl = Base.active_repl
                  mirepl = isdefined(repl,:mi) ? repl.mi : repl
                  main_mode = mirepl.interface.modes[1]
                  py_mode = create_py_repl(repl,main_mode)
                  buf = copy(LineEdit.buffer(s))
                  LineEdit.transition(s,py_mode) do
                  LineEdit.state(s,py_mode).input_buffer = buf
                 end
           else
              LineEdit.edit_insert(s, ')')
           end
		  ),
)

function customize_keys(repl)
    repl.interface = REPL.setup_interface(repl; extra_repl_keymap = pykeys)
end

#atreplinit(customize_keys)  if you run codes in startup.jl

end # module


text:
using ArrayIteration
using SparseArrays

using Test
using Base.PermutedDimsArrays: PermutedDimsArray

const AI = ArrayIteration
const CCI = AI.ContigCartIterator

include("array_types.jl")  # just for testing

takebuf_string(io::IO) = String(take!(io))

@testset "ArrayIteration" begin
@testset "index" begin

A = zeros(2,3)
@test inds(A, 1) == 1:2
@test inds(A, 2) == 1:3
@test inds(A, 3) == 1:1
@test inds(A) == (1:2, 1:3)
B = ATs.OA(Array{Int}(undef,2,2), (-1,2))
@test inds(B) == (0:1, 3:4)

io = IOBuffer()
show(io, index(A))
@test takebuf_string(io) == "iteration hint over indexes of a "*summary(A)*" over the region (Base.Slice(Base.OneTo(2)), Base.Slice(Base.OneTo(3)))"
io = IOBuffer()
show(io, index(A, :, 2:3))
@test takebuf_string(io) == "iteration hint over indexes of a "*summary(A)*" over the region (Base.Slice(Base.OneTo(2)), 2:3)"
io = IOBuffer()
show(io, stored(A, 1, 2:3))
@test takebuf_string(io) == "iteration hint over stored values of a "*summary(A)*" over the region (1, 2:3)"
io = IOBuffer()
show(io, index(stored(A, 1:2, :)))
@test takebuf_string(io) == "iteration hint over indexes of stored values of a "*summary(A)*" over the region (1:2, Base.Slice(Base.OneTo(3)))"
io = IOBuffer()
show(io, stored(index(A, 1:2, :)))
@test takebuf_string(io) == "iteration hint over indexes of stored values of a "*summary(A)*" over the region (1:2, Base.Slice(Base.OneTo(3)))"

end # testset index

@testset "internal" begin include("internal.jl") end
@testset "dense" begin include("dense.jl") end
@testset "sparse" begin include("sparse.jl") end

end # testset


text:
module MyPackage2

export add_func, subtract_func

#这种注释方式，推荐大家使用，支持在vscode中悬停查看函数帮助
"""
    add_func(x,y)

Returns `x` + `y`.
"""
add_func(x,y) = x + y

"""
    subtract_func(x,y)

Returns `x` - `y`.
"""
subtract_func(x,y) = x - y

include("math.jl")

end


text:
#=
  AR(2) in Turing.jl

  From BLOG example/ar2.blog

  Note: Using
     true ~ Dirac(x[2] == 1.0)
  takes too long for NUTS() and HMC(). Instead I hardwired x[2] as
       x[t] ~ Dirac(1.0) (for t == 2)

  This might be considered cheating...

  NUTS: (58s)
  """
  Summary Statistics
  parameters      mean       std   naive_se      mcse       ess      rhat   ess_per_sec
      Symbol   Float64   Float64    Float64   Float64   Float64   Float64       Float64

        x[1]    0.0000    0.0000     0.0000    0.0000       NaN       NaN           NaN
        x[2]    1.0000    0.0000     0.0000    0.0000       NaN       NaN           NaN
        x[3]   -1.2907    0.0000     0.0000    0.0000   20.5530    0.9999        0.3713
        x[4]    0.5053    0.0000     0.0000    0.0000   20.5530    0.9999        0.3713

  Quantiles
  parameters      2.5%     25.0%     50.0%     75.0%     97.5%
      Symbol   Float64   Float64   Float64   Float64   Float64

        x[1]    0.0000    0.0000    0.0000    0.0000    0.0000
        x[2]    1.0000    1.0000    1.0000    1.0000    1.0000
        x[3]   -1.2907   -1.2907   -1.2907   -1.2907   -1.2907
        x[4]    0.5053    0.5053    0.5053    0.5053    0.5053
   """

  HMC(0.01,5) (3,6s)
  """
  Summary Statistics
  parameters      mean       std   naive_se      mcse       ess      rhat   ess_per_sec
      Symbol   Float64   Float64    Float64   Float64   Float64   Float64       Float64

        x[1]    0.0000    0.0000     0.0000    0.0000       NaN       NaN           NaN
        x[2]    1.0000    0.0000     0.0000    0.0000       NaN       NaN           NaN
        x[3]    1.5492    0.0000     0.0000    0.0000   20.5530    0.9999        9.6674
        x[4]    0.1999    0.0000     0.0000    0.0000   20.5530    0.9999        9.6674

  Quantiles
  parameters      2.5%     25.0%     50.0%     75.0%     97.5%
      Symbol   Float64   Float64   Float64   Float64   Float64

        x[1]    0.0000    0.0000    0.0000    0.0000    0.0000
        x[2]    1.0000    1.0000    1.0000    1.0000    1.0000
        x[3]    1.5492    1.5492    1.5492    1.5492    1.5492
        x[4]    0.1999    0.1999    0.1999    0.1999    0.1999
   """

   Cf ~/blog/ar2.blog
      ~/webppl/ar2.wppl

=#

using Turing
include("jl_utils.jl")

@model function ar2()
    beta = [0.2,0.8]
    sigma = 0.1
    # sigma ~ Uniform(0.0,1.0)
    # beta1 ~ Uniform(0,1)
    # beta2 ~ Uniform(0,1)

    # n = length(ys)
    n = 4
    # Note: using tzeros give strange error. Use Vector{Real} instead!
    # tzeros(Float64,n)
    x = Vector{Real}(undef, n)
    for t in 1:n
        if t == 1
            x[t] ~ Dirac(0.0)
        elseif t == 2
            # With this NUTS() take an awful long time
            # x[t] ~ Normal(0.0,sigma)
            # This is much faster but might be considered cheating...
            x[t] ~ Dirac(1.0)
        else
            x[t] ~ Normal(beta[1]*x[t-2] + beta[2]*x[t-1],sigma)
        end
    end

    # This takes too long!
    # true ~ Dirac(x[2] == 1.0)

end

ys = [0,1,2,3]
# model = ar2(ys)
model = ar2()
num_chains = 4
# chs = sample(model, Prior(), 1000)
# chs = sample(model, MH(), 10_000)
# chs = sample(model, PG(15), 10_000)
# chs = sample(model, IS(), 10_000)
# chs = sample(model, SMC(), 10_000)
# chs = sample(model, SMC(), MCMCThreads(), 10_000, num_chs)

# chs = sample(model, SGLD(), 10_000)
# chs = sample(model,NUTS(), 10_000)
chs = sample(model,HMC(0.01,5), 10_000)

display(chs)
# display(plot(chs))

max_stars_repo_name: tias/hakank

max_issues_repo_name: tias/hakank

max_forks_repo_name: tias/hakank