text:
# This file is automatically generated by MLStyle Boostrap Tools.
module Infras
using MLStyle
@eval $(LineNumberNode(
  2,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(LineNumberNode(
  3,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :using,
  Expr(
    :.,
    :MLStyle,
    :MatchCore,
  ),
))
@eval $(LineNumberNode(
  4,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :using,
  Expr(
    :.,
    :MLStyle,
    :Extension,
  ),
))
@eval $(LineNumberNode(
  5,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :using,
  Expr(
    :.,
    :MLStyle,
    :Err,
  ),
))
@eval $(LineNumberNode(
  6,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :using,
  Expr(
    :(:),
    Expr(
      :.,
      :MLStyle,
      :Toolz,
    ),
    Expr(
      :.,
      :$,
    ),
  ),
))
@eval $(LineNumberNode(
  7,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :using,
  Expr(
    :(:),
    Expr(
      :.,
      :MLStyle,
      :Render,
    ),
    Expr(
      :.,
      :render,
    ),
    Expr(
      :.,
      :format,
    ),
  ),
))
@eval $(LineNumberNode(
  9,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :const,
  Expr(
    :(=),
    :__L__,
    Expr(
      :macrocall,
      Symbol("@__LINE__"),
      LineNumberNode(
        9,
        Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
      ),
    ),
  ),
))
@eval $(LineNumberNode(
  10,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :export,
  Symbol("@format"),
))
@eval $(LineNumberNode(
  11,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :macro,
  Expr(
    :call,
    :format,
    :args,
    :template,
  ),
  Expr(
    :block,
    LineNumberNode(
      12,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :(=),
      :args,
      Expr(
        :call,
        :Expr,
        QuoteNode(
          :vect,
        ),
        Expr(
          :call,
          :(=>),
          QuoteNode(
            :__L__,
          ),
          Expr(
            :call,
            :LineNumberNode,
            :__L__,
          ),
        ),
        Expr(
          :call,
          :(=>),
          QuoteNode(
            :failed,
          ),
          Expr(
            :call,
            :QuoteNode,
            Expr(
              :quote,
              Expr(
                :.,
                Expr(
                  :$,
                  :MatchCore,
                ),
                QuoteNode(
                  :failed,
                ),
              ),
            ),
          ),
        ),
        Expr(
          :...,
          Expr(
            :.,
            :args,
            QuoteNode(
              :args,
            ),
          ),
        ),
      ),
    ),
    LineNumberNode(
      13,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :call,
      :esc,
      Expr(
        :call,
        :format,
        :args,
        :template,
      ),
    ),
  ),
))
@eval $(LineNumberNode(
  16,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :export,
  Symbol("@typed_as"),
))
@eval $(LineNumberNode(
  17,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :macrocall,
  GlobalRef(
    Core,
    Symbol("@doc"),
  ),
  LineNumberNode(
    17,
    Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
  ),
  "this macro provide a convenient and type-stable way to generate\ntype checking.\n\nHowever, the generated code requires a given variable `TARGET`\nin metaprogramming level.\n\ne.g\n\nTARGET = :target_id\n(@typed_as Int) # which generates a pattern to check if type is Int.\n\n",
  Expr(
    :macro,
    Expr(
      :call,
      :typed_as,
      :t,
    ),
    Expr(
      :block,
      LineNumberNode(
        31,
        Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
      ),
      Expr(
        :call,
        :$,
        :esc,
        Expr(
          :quote,
          Expr(
            :block,
            LineNumberNode(
              32,
              Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
            ),
            Expr(
              :(=),
              :NAME,
              Expr(
                :call,
                :mangle,
                :mod,
              ),
            ),
            LineNumberNode(
              33,
              Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
            ),
            Expr(
              :(=),
              :__T__,
              Expr(
                :$,
                :t,
              ),
            ),
            LineNumberNode(
              34,
              Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
            ),
            Expr(
              :function,
              Expr(
                :tuple,
                :body,
              ),
              Expr(
                :block,
                LineNumberNode(
                  35,
                  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                ),
                Expr(
                  :macrocall,
                  Symbol("@format"),
                  LineNumberNode(
                    35,
                    Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                  ),
                  Expr(
                    :vect,
                    :body,
                    :tag,
                    :TARGET,
                    :NAME,
                    :__T__,
                  ),
                  Expr(
                    :quote,
                    Expr(
                      :block,
                      LineNumberNode(
                        37,
                        Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                      ),
                      Expr(
                        :macrocall,
                        Symbol("@inline"),
                        LineNumberNode(
                          37,
                          Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                        ),
                        :__L__,
                        Expr(
                          :function,
                          Expr(
                            :call,
                            :NAME,
                            Expr(
                              :(::),
                              :TARGET,
                              :__T__,
                            ),
                          ),
                          Expr(
                            :block,
                            LineNumberNode(
                              38,
                              Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                            ),
                            :__T__,
                            LineNumberNode(
                              39,
                              Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                            ),
                            :body,
                          ),
                        ),
                      ),
                      LineNumberNode(
                        42,
                        Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                      ),
                      Expr(
                        :macrocall,
                        Symbol("@inline"),
                        LineNumberNode(
                          42,
                          Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                        ),
                        :__L__,
                        Expr(
                          :function,
                          Expr(
                            :call,
                            :NAME,
                            :TARGET,
                          ),
                          Expr(
                            :block,
                            LineNumberNode(
                              43,
                              Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                            ),
                            :failed,
                          ),
                        ),
                      ),
                      LineNumberNode(
                        46,
                        Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                      ),
                      Expr(
                        :call,
                        :NAME,
                        :tag,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    ),
  ),
))
@eval $(LineNumberNode(
  52,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :export,
  :patternOr,
))
@eval $(LineNumberNode(
  53,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :(=),
  :patternOr,
  Expr(
    :->,
    Expr(
      :tuple,
      :p1,
      :p2,
    ),
    Expr(
      :block,
      LineNumberNode(
        53,
        Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
      ),
      Expr(
        :->,
        :body,
        Expr(
          :block,
          LineNumberNode(
            53,
            Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
          ),
          Expr(
            :let,
            Expr(
              :block,
              Expr(
                :(=),
                :p1,
                Expr(
                  :call,
                  :p1,
                  :body,
                ),
              ),
              Expr(
                :(=),
                :p2,
                Expr(
                  :call,
                  :p2,
                  :body,
                ),
              ),
            ),
            Expr(
              :block,
              LineNumberNode(
                55,
                Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
              ),
              Expr(
                :(=),
                :tmp,
                Expr(
                  :call,
                  :mangle,
                  :Infras,
                ),
              ),
              LineNumberNode(
                56,
                Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
              ),
              Expr(
                :macrocall,
                Symbol("@format"),
                LineNumberNode(
                  56,
                  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                ),
                Expr(
                  :vect,
                  :tmp,
                  :p1,
                  :p2,
                ),
                Expr(
                  :quote,
                  Expr(
                    :block,
                    LineNumberNode(
                      57,
                      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                    ),
                    Expr(
                      :(=),
                      :tmp,
                      :p1,
                    ),
                    LineNumberNode(
                      58,
                      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                    ),
                    Expr(
                      :if,
                      Expr(
                        :call,
                        :(===),
                        :tmp,
                        :failed,
                      ),
                      :p2,
                      :tmp,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    ),
  ),
))
@eval $(LineNumberNode(
  63,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :const,
  Expr(
    :(=),
    :APP_DESTRUCTORS,
    Expr(
      :call,
      Expr(
        :curly,
        :Vector,
        Expr(
          :curly,
          :Tuple,
          :Module,
          :PDesc,
        ),
      ),
    ),
  ),
))
@eval $(LineNumberNode(
  64,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :const,
  Expr(
    :(=),
    :GAPP_DESTRUCTORS,
    Expr(
      :call,
      Expr(
        :curly,
        :Vector,
        Expr(
          :curly,
          :Tuple,
          :Module,
          :PDesc,
        ),
      ),
    ),
  ),
))
@eval $(LineNumberNode(
  66,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :export,
  :def_pattern,
))
@eval $(LineNumberNode(
  67,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :function,
  Expr(
    :call,
    :def_pattern,
    Expr(
      :parameters,
      :predicate,
      :rewrite,
      Expr(
        :kw,
        :qualifiers,
        :nothing,
      ),
    ),
    :mod,
  ),
  Expr(
    :block,
    LineNumberNode(
      68,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :(=),
      :qualifiers,
      Expr(
        :if,
        Expr(
          :call,
          :(===),
          :qualifiers,
          :nothing,
        ),
        Expr(
          :call,
          :Set,
          Expr(
            :vect,
            :invasive,
          ),
        ),
        :qualifiers,
      ),
    ),
    LineNumberNode(
      69,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :(=),
      :desc,
      Expr(
        :call,
        :PDesc,
        :predicate,
        :rewrite,
        :qualifiers,
      ),
    ),
    LineNumberNode(
      70,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :call,
      :register_pattern,
      :desc,
      :mod,
    ),
  ),
))
@eval $(LineNumberNode(
  76,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :macrocall,
  GlobalRef(
    Core,
    Symbol("@doc"),
  ),
  LineNumberNode(
    76,
    Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
  ),
  " To test if an datatype can\n",
  Expr(
    :function,
    :deconstructable,
  ),
))
@eval $(LineNumberNode(
  82,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :export,
  :register_app_pattern,
))
@eval $(LineNumberNode(
  83,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :function,
  Expr(
    :call,
    :register_app_pattern,
    Expr(
      :(::),
      :pdesc,
      :PDesc,
    ),
    Expr(
      :(::),
      :def_mod,
      :Module,
    ),
  ),
  Expr(
    :block,
    LineNumberNode(
      84,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :call,
      :push!,
      :APP_DESTRUCTORS,
      Expr(
        :tuple,
        :def_mod,
        :pdesc,
      ),
    ),
  ),
))
@eval $(LineNumberNode(
  87,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :export,
  :def_app_pattern,
))
@eval $(LineNumberNode(
  88,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :function,
  Expr(
    :call,
    :def_app_pattern,
    Expr(
      :parameters,
      :predicate,
      :rewrite,
      Expr(
        :kw,
        :qualifiers,
        :nothing,
      ),
    ),
    :mod,
  ),
  Expr(
    :block,
    LineNumberNode(
      89,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :(=),
      :qualifiers,
      Expr(
        :if,
        Expr(
          :call,
          :(===),
          :qualifiers,
          :nothing,
        ),
        Expr(
          :call,
          :Set,
          Expr(
            :vect,
            :invasive,
          ),
        ),
        :qualifiers,
      ),
    ),
    LineNumberNode(
      90,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :(=),
      :desc,
      Expr(
        :call,
        :PDesc,
        :predicate,
        :rewrite,
        :qualifiers,
      ),
    ),
    LineNumberNode(
      91,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :call,
      :register_app_pattern,
      :desc,
      :mod,
    ),
  ),
))
@eval $(LineNumberNode(
  94,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :export,
  :mk_app_pattern,
))
@eval $(LineNumberNode(
  95,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :function,
  Expr(
    :call,
    :mk_app_pattern,
    :tag,
    :hd,
    :tl,
    :use_mod,
  ),
  Expr(
    :block,
    LineNumberNode(
      96,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :if,
      Expr(
        :call,
        :isdefined,
        :use_mod,
        :hd,
      ),
      Expr(
        :block,
        LineNumberNode(
          97,
          Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
        ),
        Expr(
          :(=),
          :hd,
          Expr(
            :call,
            :getfield,
            :use_mod,
            :hd,
          ),
        ),
        LineNumberNode(
          98,
          Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
        ),
        Expr(
          :for,
          Expr(
            :(=),
            Expr(
              :tuple,
              :def_mod,
              :desc,
            ),
            :APP_DESTRUCTORS,
          ),
          Expr(
            :block,
            LineNumberNode(
              99,
              Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
            ),
            Expr(
              :if,
              Expr(
                :&&,
                Expr(
                  :call,
                  :qualifier_test,
                  Expr(
                    :.,
                    :desc,
                    QuoteNode(
                      :qualifiers,
                    ),
                  ),
                  :use_mod,
                  :def_mod,
                ),
                Expr(
                  :call,
                  Expr(
                    :.,
                    :desc,
                    QuoteNode(
                      :predicate,
                    ),
                  ),
                  :hd,
                  :tl,
                ),
              ),
              Expr(
                :block,
                LineNumberNode(
                  100,
                  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                ),
                Expr(
                  :return,
                  Expr(
                    :call,
                    Expr(
                      :.,
                      :desc,
                      QuoteNode(
                        :rewrite,
                      ),
                    ),
                    :tag,
                    :hd,
                    :tl,
                    :use_mod,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    ),
    LineNumberNode(
      104,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :(=),
      :info,
      Expr(
        :call,
        :*,
        Expr(
          :call,
          :string,
          :hd,
        ),
        "(",
        Expr(
          :call,
          :join,
          Expr(
            :call,
            :map,
            :string,
            :tl,
          ),
          ", ",
        ),
        ")",
      ),
    ),
    LineNumberNode(
      105,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :call,
      :$,
      :throw,
      Expr(
        :call,
        :PatternUnsolvedException,
        Expr(
          :string,
          "invalid usage or unknown application case ",
          :info,
          ".",
        ),
      ),
    ),
  ),
))
@eval $(LineNumberNode(
  112,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :export,
  :def_gapp_pattern,
))
@eval $(LineNumberNode(
  113,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :function,
  Expr(
    :call,
    :def_gapp_pattern,
    Expr(
      :parameters,
      :predicate,
      :rewrite,
      Expr(
        :kw,
        :qualifiers,
        :nothing,
      ),
    ),
    :mod,
  ),
  Expr(
    :block,
    LineNumberNode(
      114,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :(=),
      :qualifiers,
      Expr(
        :if,
        Expr(
          :call,
          :(===),
          :qualifiers,
          :nothing,
        ),
        Expr(
          :call,
          :Set,
          Expr(
            :vect,
            :invasive,
          ),
        ),
        :qualifiers,
      ),
    ),
    LineNumberNode(
      115,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :(=),
      :desc,
      Expr(
        :call,
        :PDesc,
        :predicate,
        :rewrite,
        :qualifiers,
      ),
    ),
    LineNumberNode(
      116,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :call,
      :register_gapp_pattern,
      :desc,
      :mod,
    ),
  ),
))
@eval $(LineNumberNode(
  119,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :export,
  :register_gapp_pattern,
))
@eval $(LineNumberNode(
  120,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :function,
  Expr(
    :call,
    :register_gapp_pattern,
    Expr(
      :(::),
      :pdesc,
      :PDesc,
    ),
    Expr(
      :(::),
      :def_mod,
      :Module,
    ),
  ),
  Expr(
    :block,
    LineNumberNode(
      121,
      Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
    ),
    Expr(
      :call,
      :push!,
      :GAPP_DESTRUCTORS,
      Expr(
        :tuple,
        :def_mod,
        :pdesc,
      ),
    ),
  ),
))
@eval $(LineNumberNode(
  124,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :export,
  :mk_gapp_pattern,
))
@eval $(LineNumberNode(
  125,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :function,
  :mk_gapp_pattern,
))
@eval $(LineNumberNode(
  130,
  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
))
@eval $(Expr(
  :call,
  :def_pattern,
  :Infras,
  Expr(
    :kw,
    :predicate,
    Expr(
      :->,
      :x,
      Expr(
        :block,
        LineNumberNode(
          131,
          Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
        ),
        Expr(
          :&&,
          Expr(
            :call,
            :isa,
            :x,
            :Expr,
          ),
          Expr(
            :call,
            :(==),
            Expr(
              :.,
              :x,
              QuoteNode(
                :head,
              ),
            ),
            QuoteNode(
              :call,
            ),
          ),
        ),
      ),
    ),
  ),
  Expr(
    :kw,
    :rewrite,
    Expr(
      :->,
      Expr(
        :tuple,
        :tag,
        :case,
        :mod,
      ),
      Expr(
        :block,
        LineNumberNode(
          132,
          Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
        ),
        Expr(
          :let,
          Expr(
            :block,
            Expr(
              :(=),
              :hd,
              Expr(
                :ref,
                Expr(
                  :.,
                  :case,
                  QuoteNode(
                    :args,
                  ),
                ),
                1,
              ),
            ),
            Expr(
              :(=),
              :tl,
              Expr(
                :ref,
                Expr(
                  :.,
                  :case,
                  QuoteNode(
                    :args,
                  ),
                ),
                Expr(
                  :call,
                  :(:),
                  2,
                  :end,
                ),
              ),
            ),
          ),
          Expr(
            :block,
            LineNumberNode(
              134,
              Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
            ),
            Expr(
              :block,
              Expr(
                :block,
                Expr(
                  :let,
                  Expr(
                    :(=),
                    Symbol("##Main.MLBootstrap 1#432"),
                    :hd,
                  ),
                  Expr(
                    :block,
                    Expr(
                      :block,
                      Expr(
                        :block,
                        LineNumberNode(
                          135,
                          Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                        ),
                        Expr(
                          :(=),
                          Symbol("##Main.MLBootstrap 0#431"),
                          Expr(
                            :block,
                            Expr(
                              :function,
                              Expr(
                                :call,
                                Symbol("##Main.MLBootstrap 14#445"),
                                Expr(
                                  :(::),
                                  Symbol("##Main.MLBootstrap 13#444"),
                                  :Symbol,
                                ),
                              ),
                              Expr(
                                :block,
                                Expr(
                                  :meta,
                                  :inline,
                                ),
                                :Symbol,
                                Expr(
                                  :call,
                                  :mk_app_pattern,
                                  :tag,
                                  :hd,
                                  :tl,
                                  :mod,
                                ),
                              ),
                            ),
                            Expr(
                              :function,
                              Expr(
                                :call,
                                Symbol("##Main.MLBootstrap 14#445"),
                                Symbol("##Main.MLBootstrap 13#444"),
                              ),
                              Expr(
                                :block,
                                Expr(
                                  :meta,
                                  :inline,
                                ),
                                Expr(
                                  :.,
                                  MLStyle.MatchCore,
                                  QuoteNode(
                                    :failed,
                                  ),
                                ),
                              ),
                            ),
                            Expr(
                              :call,
                              Symbol("##Main.MLBootstrap 14#445"),
                              Symbol("##Main.MLBootstrap 1#432"),
                            ),
                          ),
                        ),
                        Expr(
                          :if,
                          Expr(
                            :call,
                            :(===),
                            Symbol("##Main.MLBootstrap 0#431"),
                            Expr(
                              :.,
                              MLStyle.MatchCore,
                              QuoteNode(
                                :failed,
                              ),
                            ),
                          ),
                          Expr(
                            :block,
                            Expr(
                              :block,
                              Expr(
                                :block,
                                LineNumberNode(
                                  136,
                                  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                                ),
                                Expr(
                                  :(=),
                                  Symbol("##Main.MLBootstrap 0#431"),
                                  Expr(
                                    :block,
                                    Expr(
                                      :function,
                                      Expr(
                                        :call,
                                        Symbol("##Main.MLBootstrap 5#436"),
                                        Expr(
                                          :(::),
                                          Symbol("##Main.MLBootstrap 2#433"),
                                          Expr,
                                        ),
                                      ),
                                      Expr(
                                        :block,
                                        Expr(
                                          :meta,
                                          :inline,
                                        ),
                                        Expr,
                                        Expr(
                                          :block,
                                          Expr(
                                            :let,
                                            Expr(
                                              :(=),
                                              Expr(
                                                :tuple,
                                                Symbol("##Main.MLBootstrap 3#434"),
                                                Symbol("##Main.MLBootstrap 4#435"),
                                              ),
                                              Expr(
                                                :tuple,
                                                Expr(
                                                  :.,
                                                  Symbol("##Main.MLBootstrap 2#433"),
                                                  QuoteNode(
                                                    :head,
                                                  ),
                                                ),
                                                Expr(
                                                  :.,
                                                  Symbol("##Main.MLBootstrap 2#433"),
                                                  QuoteNode(
                                                    :args,
                                                  ),
                                                ),
                                              ),
                                            ),
                                            Expr(
                                              :block,
                                              Expr(
                                                :block,
                                                Expr(
                                                  :if,
                                                  Expr(
                                                    :call,
                                                    ===,
                                                    Symbol("##Main.MLBootstrap 3#434"),
                                                    QuoteNode(
                                                      :curly,
                                                    ),
                                                  ),
                                                  Expr(
                                                    :block,
                                                    Expr(
                                                      :function,
                                                      Expr(
                                                        :where,
                                                        Expr(
                                                          :call,
                                                          Symbol("##Main.MLBootstrap 7#438"),
                                                          Expr(
                                                            :(::),
                                                            Symbol("##Main.MLBootstrap 6#437"),
                                                            Expr(
                                                              :curly,
                                                              AbstractArray,
                                                              Symbol("##Main.MLBootstrap 8#439"),
                                                              1,
                                                            ),
                                                          ),
                                                        ),
                                                        Symbol("##Main.MLBootstrap 8#439"),
                                                      ),
                                                      Expr(
                                                        :block,
                                                        Expr(
                                                          :meta,
                                                          :inline,
                                                        ),
                                                        Expr(
                                                          :block,
                                                          Expr(
                                                            :if,
                                                            Expr(
                                                              :call,
                                                              :>=,
                                                              Expr(
                                                                :call,
                                                                length,
                                                                Symbol("##Main.MLBootstrap 6#437"),
                                                              ),
                                                              1,
                                                            ),
                                                            Expr(
                                                              :block,
                                                              Expr(
                                                                :(=),
                                                                Symbol("##Main.MLBootstrap 9#440"),
                                                                Expr(
                                                                  :ref,
                                                                  Symbol("##Main.MLBootstrap 6#437"),
                                                                  1,
                                                                ),
                                                              ),
                                                              Expr(
                                                                :block,
                                                                Expr(
                                                                  :function,
                                                                  Expr(
                                                                    :call,
                                                                    Symbol("##Main.MLBootstrap 11#442"),
                                                                    Expr(
                                                                      :(::),
                                                                      Symbol("##Main.MLBootstrap 10#441"),
                                                                      :Symbol,
                                                                    ),
                                                                  ),
                                                                  Expr(
                                                                    :block,
                                                                    Expr(
                                                                      :meta,
                                                                      :inline,
                                                                    ),
                                                                    :Symbol,
                                                                    Expr(
                                                                      :call,
                                                                      :mk_gapp_pattern,
                                                                      :tag,
                                                                      Expr(
                                                                        :vect,
                                                                      ),
                                                                      :hd,
                                                                      :tl,
                                                                      :mod,
                                                                    ),
                                                                  ),
                                                                ),
                                                                Expr(
                                                                  :function,
                                                                  Expr(
                                                                    :call,
                                                                    Symbol("##Main.MLBootstrap 11#442"),
                                                                    Symbol("##Main.MLBootstrap 10#441"),
                                                                  ),
                                                                  Expr(
                                                                    :block,
                                                                    Expr(
                                                                      :meta,
                                                                      :inline,
                                                                    ),
                                                                    Expr(
                                                                      :.,
                                                                      MLStyle.MatchCore,
                                                                      QuoteNode(
                                                                        :failed,
                                                                      ),
                                                                    ),
                                                                  ),
                                                                ),
                                                                Expr(
                                                                  :call,
                                                                  Symbol("##Main.MLBootstrap 11#442"),
                                                                  Symbol("##Main.MLBootstrap 9#440"),
                                                                ),
                                                              ),
                                                            ),
                                                            Expr(
                                                              :.,
                                                              MLStyle.MatchCore,
                                                              QuoteNode(
                                                                :failed,
                                                              ),
                                                            ),
                                                          ),
                                                        ),
                                                      ),
                                                    ),
                                                    Expr(
                                                      :function,
                                                      Expr(
                                                        :call,
                                                        Symbol("##Main.MLBootstrap 7#438"),
                                                        :_,
                                                      ),
                                                      Expr(
                                                        :block,
                                                        Expr(
                                                          :meta,
                                                          :inline,
                                                        ),
                                                        Expr(
                                                          :.,
                                                          MLStyle.MatchCore,
                                                          QuoteNode(
                                                            :failed,
                                                          ),
                                                        ),
                                                      ),
                                                    ),
                                                    Expr(
                                                      :call,
                                                      Symbol("##Main.MLBootstrap 7#438"),
                                                      Symbol("##Main.MLBootstrap 4#435"),
                                                    ),
                                                  ),
                                                  Expr(
                                                    :.,
                                                    MLStyle.MatchCore,
                                                    QuoteNode(
                                                      :failed,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                    Expr(
                                      :function,
                                      Expr(
                                        :call,
                                        Symbol("##Main.MLBootstrap 5#436"),
                                        Symbol("##Main.MLBootstrap 2#433"),
                                      ),
                                      Expr(
                                        :block,
                                        Expr(
                                          :meta,
                                          :inline,
                                        ),
                                        Expr(
                                          :.,
                                          MLStyle.MatchCore,
                                          QuoteNode(
                                            :failed,
                                          ),
                                        ),
                                      ),
                                    ),
                                    Expr(
                                      :call,
                                      Symbol("##Main.MLBootstrap 5#436"),
                                      Symbol("##Main.MLBootstrap 1#432"),
                                    ),
                                  ),
                                ),
                                Expr(
                                  :if,
                                  Expr(
                                    :call,
                                    :(===),
                                    Symbol("##Main.MLBootstrap 0#431"),
                                    Expr(
                                      :.,
                                      MLStyle.MatchCore,
                                      QuoteNode(
                                        :failed,
                                      ),
                                    ),
                                  ),
                                  Expr(
                                    :block,
                                    Expr(
                                      :block,
                                      Expr(
                                        :block,
                                        LineNumberNode(
                                          137,
                                          Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                                        ),
                                        Expr(
                                          :(=),
                                          Symbol("##Main.MLBootstrap 0#431"),
                                          Expr(
                                            :call,
                                            :throw,
                                            Expr(
                                              :string,
                                              "Deconstructor cannot be an expression like ",
                                              Expr(
                                                :call,
                                                :string,
                                                :hd,
                                              ),
                                              ".",
                                            ),
                                          ),
                                        ),
                                        Expr(
                                          :if,
                                          Expr(
                                            :call,
                                            :(===),
                                            Symbol("##Main.MLBootstrap 0#431"),
                                            Expr(
                                              :.,
                                              MLStyle.MatchCore,
                                              QuoteNode(
                                                :failed,
                                              ),
                                            ),
                                          ),
                                          Expr(
                                            :block,
                                            Expr(
                                              :block,
                                              Expr(
                                                :block,
                                                LineNumberNode(
                                                  134,
                                                  Symbol("/home/redbq/github/MLStyle.jl/bootstrap/Infras.jl"),
                                                ),
                                                Expr(
                                                  :call,
                                                  throw,
                                                  Expr(
                                                    :call,
                                                    InternalException,
                                                    "Non-exhaustive pattern found, at #= /home/redbq/github/MLStyle.jl/bootstrap/Infras.jl:134 =#!",
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ),
                                          Expr(
                                            :block,
                                            Symbol("##Main.MLBootstrap 0#431"),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                  Expr(
                                    :block,
                                    Symbol("##Main.MLBootstrap 0#431"),
                                  ),
                                ),
                              ),
                            ),
                          ),
                          Expr(
                            :block,
                            Symbol("##Main.MLBootstrap 0#431"),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    ),
  ),
))
end


text:
using Random, Distributions, LinearAlgebra
using Plots; pyplot()

function sum_of_squares(v)
    """Computes the sum of squared elements in v"""
    return dot(v, v)
end

function difference_quotient(f, x, h)
    return (f(x + h) - f(x)) / h
end

function square(x)
    return x * x
end

function derivative(x)
    return 2 * x
end

@assert 4 <= difference_quotient(square, 2, .001) <=4.01

function squared_distance(v, w)
    """Computes (v_1 - w_1) ** 2 + ... + (v_n - w_n) ** 2"""
    return sum_of_squares((v - w))
end

function distance(v, w)
    """Computes the distance between v and w"""
    return sqrt(squared_distance(v, w))
end

function partial_difference_quotient(f, v, i, h)
        """Returns the i-th partial difference quotient of f at v"""
        # w = [v_j + (h if j == i else 0) for j, v_j in enumerate(v)]
        w = copy(v)
        for j in 1:length(v)
            v_j = v[j]
            if(j==i)
                w[j] = v_j + h
            else
                w[j] = v_j
            end
        end

        return (f(w) - f(v)) / h
end

function add(v, w)
    """Adds corresponding elements"""
    @assert length(v) == length(w)
    return v+w
end

function scalar_multiply(c, v)
    """Multiplies every element by c"""
    return [c * v_i for v_i in v]
end

function gradient_step(v, gradient, step_size)
    """Moves `step_size` in the `gradient` direction from `v`"""
    @assert length(v) == length(gradient)
    step = scalar_multiply(step_size, gradient)
    return add(v, step)
end

function sum_of_squares_gradient(v)
    return [2 * v_i for v_i in v]
end

function custom_fun(v)
    sign = -1
    if(v[2] > 4)
        sign = 1
    end
    return v[1]*v[1] + sign * v[2]*v[2] + 16
end

function estimate_gradient(f, v, h = 0.0001)
    return [partial_difference_quotient(f, v, i, h) for i in 1:length(v)]
end
# let v = [rand(-10: 10) for i in 0:2]
let v = [2.0, 2.0]
    for epoch in 1:1000
        # grad = sum_of_squares_gradient(v)    # compute the gradient at v
        grad = estimate_gradient( custom_fun,v)
        v = gradient_step(v, grad, -0.001)    # take a negative gradient step
    end

    # @assert distance(v, [0, 0]) < 0.001    # v should be close to 0
    @assert custom_fun(v) < .1
end

xs = -10: 11
actuals = [derivative(x) for x in xs]
estimates = [difference_quotient(square, x, 0.001) for x in xs]

# plot to show they're basically the same
plot(title = "Actual Derivatives vs. Estimates")
plot!(xs, actuals, label="Actual", seriestype = :scatter, color = "red", markersize = 7)       # red  x
plot!(xs, estimates, label="Estimate", seriestype = :scatter, color = "blue", markershape= :x)   # blue +
# plot(legend=loc=9)
# plot.show()

result = estimate_gradient(sum_of_squares,[2.0 2.0])
println(result) #should be equal to [4.0 4.0]

function error(v)
    x, y, slope, intercept = v
    predicted = slope * x + intercept
    error = (predicted - y)^2
    return error
end

println(error([2, 1 , 3, 5]))

ex_vector = [2.0, 1.0 , 2.0, 5.0]
println(partial_difference_quotient(error,ex_vector,3,.001))

function linear_gradient(x, y, theta)
    vector = [x,y, theta...]
    error_diff_estimate = [partial_difference_quotient(error,vector,i,.001)
                        for i in 3:4]

end
error_diff_estimate = linear_gradient(2.0,1.0, [2.0, 5.0])
println(error_diff_estimate)

inputs = [(x, 20 * x + 5) for x in -50: 49]

function vector_mean(vectors)
    """Computes the element-wise average"""
    n = length(vectors)
    return scalar_multiply(1/n, sum(vectors))
end

ud = Uniform(-1,1)
let theta = [rand(ud), rand(ud)]

learning_rate = 0.001
for epoch in 1:3000
    grad = vector_mean([linear_gradient(x,y, theta) for (x,y) in inputs])

    theta = gradient_step(theta, grad, -learning_rate)
    println(epoch, theta)
end

slope, intercept = theta
@assert 19.9 < theta[1] < 20.1
@assert 4.9 < intercept < 5.1
end

#finished

ext: jl


text:
module ProjectEuler
include("QuestionFirst100.jl")
# Write your package code here.

end


text:
using Documenter
using Pkg
using Test
using SymbolicUtils
import IfElse: ifelse

DocMeta.setdocmeta!(
    SymbolicUtils,
    :DocTestSetup,
    :(using SymbolicUtils);
    recursive=true
)

# Only test one Julia version to avoid differences due to changes in printing.
if v"1.6" ≤ VERSION < v"1.7-beta3.0"
    doctest(SymbolicUtils)
else
    @warn "Skipping doctests"
end
SymbolicUtils.show_simplified[] = false

include("utils.jl")

if haskey(ENV, "SU_BENCHMARK_ONLY")
    include("benchmark.jl")
else
    include("basics.jl")
    include("order.jl")
    include("polyform.jl")
    include("rewrite.jl")
    include("rulesets.jl")
    include("code.jl")
    include("interface.jl")
    include("fuzz.jl")
    include("adjoints.jl")
end


text:
module Algorand

# Write your package code here.

end


text:
# Configuration for running spatial simulation
#=
Recommended command line to run:
>  julia run.jl examples/example1
or
>  julia -p 4 run.jl examples/example1
=#
export simtype
@everywhere simtype = 2
const num_trials=1
@everywhere const N_list = [3]        # Meta-population size list
#@everywhere const N = 8        # Meta-population size
#const mutation_stddev = 0.05
const mutation_stddev_list = [0.04]
#const num_attributes = 2        # number attributes for quantitative representation
const num_attributes_list = [2]        # number attributes for quantitative representation
const ngens = 3       # Generations after burn-in
const num_subpops = 1
const burn_in= 3    # if integer, generations of burn in.  If float, int_burn_in=burn_in*N+50
const ideal = 1.0
const fit_slope = 1.0
const neutral = false


text:
module InputFloats

Base.Experimental.@optlevel 1

using Redux
using CImGui
import ..ReduxImGui: get_label, get_values, get_value

# actions
abstract type AbstractInputFloatAction <: AbstractSyncAction end

"""
    Rename(label, new_label)
Change label to `new_label`.
Note that renaming may also change the identifier, please refer to `help?> CImGui.PushID`.
"""
struct Rename <: AbstractInputFloatAction
    label::String
    new_label::String
end

"""
    ChangeSize(label, size)
Change widget size to `size`.
Note changing size also changes widget appearance. If the old size is bigger,
those unused states are left intact.
"""
struct ChangeSize <: AbstractInputFloatAction
    label::String
    size::Int
end

"""
    ChangeStep(label, step)
Change value's moving step to `step`.
This only takes effect when the widget size is 1.
"""
struct ChangeStep <: AbstractInputFloatAction
    label::String
    step::Cfloat
end

"""
    ChangeSpeed(label, speed)
Change value's moving speed to `speed`.
This only takes effect when the widget size is 1.
"""
struct ChangeSpeed <: AbstractInputFloatAction
    label::String
    speed::Cfloat
end

"""
    ChangeFormat(label, format)
Change value's format to `format`, e.g. "%.3f".
"""
struct ChangeFormat <: AbstractInputFloatAction
    label::String
    format::String
end

# state
struct State <: AbstractImmutableState
    label::String
    vals::Vector{Cfloat}
    size::Int
    step::Cfloat
    speed::Cfloat
    format::String
    flags::CImGui.ImGuiInputTextFlags_
end
State(
    label::AbstractString;
    vals::Vector{Cfloat} = Cfloat[0, 0, 0, 0],
    size = 1,
    step = 0.0f0,
    speed = 0.0f0,
    format = "%.3f",
    flags = CImGui.ImGuiInputTextFlags_None,
) = State(label, vals, size, step, speed, format, flags)

State(label::AbstractString, val::AbstractFloat; args...) =
    State(label; vals = Cfloat[val, 0, 0, 0], args...)

# reducers
input_float(state::AbstractState, action::AbstractAction) = state
input_float(state::Vector{<:AbstractState}, action::AbstractAction) = state
input_float(state::Dict{String,<:AbstractState}, action::AbstractAction) = state

function input_float(state::Dict{String,State}, action::AbstractInputFloatAction)
    s = Dict{String,State}()
    for (k, v) in state
        s[k] = get_label(v) == action.label ? input_float(v, action) : v
    end
    return s
end

input_float(s::State, a::Rename) = State(a.new_label, s.vals, s.size, s.step, s.speed, s.format, s.flags)
input_float(s::State, a::ChangeSize) = State(s.label, s.vals, a.size, s.step, s.speed, s.format, s.flags)
input_float(s::State, a::ChangeStep) = State(s.label, s.vals, s.size, a.step, s.speed, s.format, s.flags)
input_float(s::State, a::ChangeSpeed) = State(s.label, s.vals, s.size, s.step, a.speed, s.format, s.flags)
input_float(s::State, a::ChangeFormat) = State(s.label, s.vals, s.size, s.step, s.speed, a.format, s.flags)

# helper
"""
    InputFloat(store::AbstractStore, get_state=Redux.get_state) -> Bool
Return `true` when triggered.
"""
function InputFloat(store::AbstractStore, get_state = Redux.get_state)
    s = get_state(store)
    if s.size == 1
        is_triggered = CImGui.InputFloat(get_label(s), s.vals, s.step, s.speed, s.format, s.flags)
    elseif s.size == 2
        is_triggered = CImGui.InputFloat2(get_label(s), s.vals, s.format, s.flags)
    elseif s.size == 3
        is_triggered = CImGui.InputFloat3(get_label(s), s.vals, s.format, s.flags)
    elseif s.size == 4
        is_triggered = CImGui.InputFloat4(get_label(s), s.vals, s.format, s.flags)
    else
        is_triggered = false
    end
    return is_triggered
end

get_label(s::State) = s.label
get_values(s::State) = s.vals
get_value(s::State) = first(s.vals)

end # module


text:
#### Auxiliary function

tablify(xaxis, data) = table(collect(xaxis), data, names = [:x, :y], pkey = :x, presorted = true)

function tablify(xaxis, data::IndexedTables.AbstractIndexedTable, val = 0.0)
    extra_axis = setdiff(xaxis, columns(data, :x))
    merge(tablify(extra_axis, fill(val, length(extra_axis))), data)
end

##### List of functions to analyze data

"""
    `_locreg(df, xaxis::AbstractRange, x, y; kwargs...)`

Apply loess regression, training the regressor with `x` and `y` and
predicting `xaxis`
"""
function _locreg(::Val{:continuous}, xaxis, t; kwargs...)
    x, y = columns(t, :x), columns(t, :y)
    within = filter(t -> minimum(x)<= t <= maximum(x), xaxis)
    if length(within) > 0
        model = Loess.loess(convert(Vector{Float64},x),convert(Vector{Float64},y); kwargs...)
        prediction = Loess.predict(model,within)
    else
        prediction = Float64[]
    end
    tablify(within, prediction)
end

"""
    `_locreg(df, xaxis, x, y; estimator = mean)`

In the discrete case, the function computes the estimate of `y` for
a given value of `x` using the function `estimator` (default is mean)
"""
function _locreg(::Val{:discrete}, xaxis, t; estimator = mean)
    if column(t, :y)[1] isa ShiftedArray
        v = reduce_vec(estimator, column(t, :y), xaxis, filter = !isnan)
        inds = findall(!ismissing, v)
        table(xaxis[inds], convert(Vector{Float64}, view(v, inds)), names = [:x, :y],
            copy = false, presorted = true)
    else
        groupby((:y => estimator, ), t, :x, select = :y)
    end
end

"""
    `_density(df,xaxis::AbstractRange, x; kwargs...)`

Kernel density of `x`, computed along `xaxis`
"""
function _density(::Val{:continuous}, xaxis, t; kwargs...)
    data = KernelDensity.pdf(KernelDensity.kde(columns(t, :x); kwargs...), xaxis)
    tablify(xaxis, data)
end

"""
    `_density(df, xaxis, x)`

Normalized histogram of `x` (which is discrete: every value is its own bin)
"""
function _density(::Val{:discrete}, xaxis, t; normalize = true)
    s = normalize ? reduce(+, t, select = :y) : 1.0
    small_table = groupby((:y => v -> length(v)/s, ), t, :x, select = :y)
    tablify(xaxis, small_table, 0.0)
end

_density_axis(column, axis_type::Symbol; kwargs...) =
    if (axis_type == :discrete)
        get_axis(column)
    else
        start, stop = extrema(KernelDensity.kde(column; kwargs...).x)
        range(start, stop = stop, length = 100)
    end

"""
    `_cumulative!(df, xaxis, x) = ecdf(df[x])(xaxis)`

Cumulative density function of `x`, computed along `xaxis`
"""
function _cumulative(T, xaxis, t)
    data = ecdf(columns(t, :x))(xaxis)
    tablify(xaxis, data)
end

"""
    `_hazard(df,xaxis, x; kwargs...)`

Hazard rate of `x`, computed along `xaxis`. Keyword arguments are passed to
the function computing the density
"""
function _hazard(T, xaxis, t; kwargs...)
    data_pdf = columns(_density(T, xaxis, t; kwargs...), :y)
    data_cdf = columns(_cumulative(T, xaxis, t), :y)
    bin_size = t[1].y
    tablify(xaxis, @.(data_pdf/(1 + bin_size * data_pdf - data_cdf)))
end

#### Method to compute and plot grouped error plots using the above functions

get_axis(column::AbstractArray{<:AbstractRange}) = column[1]
get_axis(column) = sort!(union(column))
function get_axis(column, npoints::Int64)
    start, stop = extrema(column)
    range(start, stop = stop, length = npoints)
end

function get_axis(column, axis_type::Symbol, compute_axis::Symbol; kwargs...)
    if axis_type == :discrete
        return get_axis(column)
    elseif axis_type == :continuous
        return get_axis(column, 100)
    else
        error("Unexpected axis_type: only :discrete and :continuous allowed!")
    end
end

get_axis(column, axis_type::Symbol, compute_axis; kwargs...) =
    compute_axis(column, axis_type; kwargs...)

# f is the function used to analyze dataset: define it as nan when it is not defined,
# the input is: dataframe used, points chosen on the x axis, x (and maybe y) column labels
# the output is the y value for the given xvalues

builtin_funcs = Dict(zip([:locreg, :density, :cumulative, :hazard],
    [_locreg, _density, _cumulative, _hazard]))

builtin_axis = Dict(:density => _density_axis)


text:
module HoboPlot
using PyPlot, PyCall, MultivariateStats, Interpolations, GraphViz
@pyimport matplotlib.colors as mpl_colors
@pyimport matplotlib.animation as mpl_animation
export HoboPlotter, plotclusters, writegraph, finish!

function gca_size_pixels()
    bbox = gca()[:get_window_extent]()[:transformed](gcf()[:dpi_scale_trans][:inverted]())
    dpi = gcf()[:dpi]
    (ceil(Int, bbox[:width]*dpi)::Int, ceil(Int, bbox[:height]*dpi)::Int)
end

function densitymap(X, sz::Tuple{Int,Int}=gca_size_pixels(); kws...)
    width = sz[1]
    height = sz[2]

    interpolated = interpolate(X, BSpline(Linear()), OnCell())
    counts = zeros(Int, height, width)
    minval, maxval = extrema(X)
    if minval > 20 || maxval > 20
        minval = trunc(minval/10)*10-10
        maxval = trunc(maxval/10)*10+10
    else
        minval = trunc(minval)-1
        maxval = trunc(maxval)+1
    end
    ls = linspace(1, size(X, 1), width)
    for j = 1:size(X, 2)
        v = round(Int, (interpolated[1, j]-minval)/(maxval-minval)*(height-1)+1)
        counts[v, 1] += 1
        for i = 2:width
            vlast = v
            v = round(Int, (interpolated[ls[i], j]-minval)/(maxval-minval)*(height-1)+1)
            for k = min(v, vlast + sign(v - vlast)):max(v, vlast + sign(v - vlast))
                counts[k, i] += 1
            end
        end
    end
    logcounts = log10(counts)
    imshow(logcounts./maximum(logcounts), interpolation="nearest", aspect="auto",
           extent=(0.5, size(X, 1)+0.5, minval-0.5, maxval+0.5), origin="lower"; kws...)
end

function linearcmap(rgb::NTuple{3})
    cdict = Dict("red"   => ((0.0, 1.0, 1.0),
                             (1.0, rgb[1], rgb[1])),
                 "green" => ((0.0, 1.0, 1.0),
                             (1.0, rgb[2], rgb[2])),
                 "blue"  => ((0.0, 1.0, 1.0),
                             (1.0, rgb[3], rgb[3])))
    mpl_colors.LinearSegmentedColormap("linearcmap", cdict)
end

immutable HoboPlotter
    movie_writer
    function HoboPlotter(movie_file)
        figure(figsize=(18, 8))
        if movie_file != ""
            writer = mpl_animation.FFMpegWriter(fps=2, bitrate=10000, extra_args=["-vcodec", "png"])
            writer[:setup](gcf(), movie_file, gcf()[:dpi])
        else
            writer = nothing
        end
        new(writer)
    end
end

function plotclusters(hp::HoboPlotter, rg_wf, assignments_, time)
    cluster_colors = "bgrcmykbgrcmykbgrcmykbgrcmykbgrcmykbgrcmykbgrcmykbgrcmyk"
    colordict = mpl_colors.ColorConverter[:colors]
    active_indices = sort(unique(assignments_))
    cluster_indices = [find(assignments_ .== active_indices[i]) for i = 1:length(active_indices)]
    pca = fit(PCA, rg_wf, pratio=1.0, maxoutdim=2)
    proj = projection(pca)
    for i = 1:size(proj, 2)
        proj_i = proj[:, i]
        if abs(maximum(proj_i)) > abs(minimum(proj_i))
            proj[:, i] = scale!(proj_i, -1.0)
        end
    end
    pcs = transform(pca, rg_wf)

    clf()
    bax = subplot2grid((2, length(active_indices)), (0, 0), colspan=length(active_indices))
    for iclust = 1:length(active_indices)
        cluster_color = string(cluster_colors[active_indices[iclust]+1])
        inds = cluster_indices[iclust]
        sca(bax)
        scatter(pcs[1, inds], pcs[2, inds], 1, marker=".", color=cluster_color)
        subplot2grid((2, length(active_indices)), (1, iclust-1))
        densitymap(sub(rg_wf, :, inds), cmap=linearcmap(colordict[cluster_color]))
        hz = @sprintf("%0.1f", length(inds)/time)
        title("Cluster $(active_indices[iclust]) ($hz Hz)")
    end
    draw()
    if hp.movie_writer !== nothing
        hp.movie_writer[:grab_frame]()
    end
end

function writegraph(graphfile::AbstractString, connections::Vector{Tuple{Int,Int}}, nclusters::Int)
    g = Graph("""
    digraph hobograph {
        init [label="Initial Clustering"]
        $(join(["init->$i" for i = 1:nclusters], "\n"))
        $(join(["$i->$j" for (i, j) in connections], "\n"))
    }
    """)
    f = open(graphfile, "w")
    writemime(f, MIME"image/png"(), g)
    close(f)
end

finish!(hp::HoboPlotter) = hp.movie_writer != nothing && hp.movie_writer[:finish]()
end


text:
using ZeroInflation
using Documenter

DocMeta.setdocmeta!(ZeroInflation, :DocTestSetup, :(using ZeroInflation); recursive = true)

makedocs(;
    modules = [ZeroInflation],
    authors = "Philipp Gewessler <p.gewessler@gmx.at> and contributors",
    repo = "https://github.com/p-gw/ZeroInflation.jl/blob/{commit}{path}#{line}",
    sitename = "ZeroInflation.jl",
    format = Documenter.HTML(;
        prettyurls = get(ENV, "CI", "false") == "true",
        canonical = "https://p-gw.github.io/ZeroInflation.jl",
        assets = String[]
    ),
    pages = [
        "Home" => "index.md",
        "Examples" => "examples/turing.md"
    ]
)

deploydocs(;
    repo = "github.com/p-gw/ZeroInflation.jl",
    devbranch = "main"
)


text:
@testset "Neighborhoods" begin
  @testset "CubeNeighborhood" begin
    grid1D = RegularGrid{Float64}(100)
    neigh1 = CubeNeighborhood(grid1D, .5)
    @test neigh1(1) == [1]

    grid2D = RegularGrid{Float64}(100,100)
    neigh1 = CubeNeighborhood(grid2D, 1.)
    @test neigh1(1) == [1,2,101,102]
    neigh2 = CubeNeighborhood(grid2D, 2.)
    @test neigh2(1) == [1,2,3,101,102,103,201,202,203]

    grid3D = RegularGrid{Float64}(100,100,100)
    neigh1 = CubeNeighborhood(grid3D, .5)
    @test neigh1(1) == [1]

    grid4D = RegularGrid{Float64}(10,20,30,40)
    neigh1 = CubeNeighborhood(grid4D, .5)
    @test neigh1(1) == [1]

    ps2D = PointSet([0. 1. 0. 1.; 0. 0. 1. 1.])
    neigh1 = CubeNeighborhood(ps2D, 1.)
    @test neigh1(1) == [1,2,3,4]
  end

  @testset "BallNeighborhood" begin
    grid1D = RegularGrid{Float64}(100)
    neigh1 = BallNeighborhood(grid1D, .5)
    @test neigh1(1) == [1]

    grid2D = RegularGrid{Float64}(100,100)
    neigh1 = BallNeighborhood(grid2D, 1.)
    @test neigh1(1) == [1,2,101]
    neigh2 = BallNeighborhood(grid2D, .5)
    @test neigh2(1) == [1]

    grid3D = RegularGrid{Float64}(100,100,100)
    neigh1 = BallNeighborhood(grid3D, .5)
    @test neigh1(1) == [1]

    grid4D = RegularGrid{Float64}(10,20,30,40)
    neigh1 = BallNeighborhood(grid4D, .5)
    @test neigh1(1) == [1]

    ps2D = PointSet([0. 1. 0. 1.; 0. 0. 1. 1.])
    neigh1 = BallNeighborhood(ps2D, 1.)
    @test neigh1(1) == [1,2,3]
  end
end