text:
# Thanks to load order issues, we have to do the documentation seperately

Base.Docs.catdoc(org::Org...) = *(org...)

# ---------------------
# Elements, Sectioning
# ---------------------

@doc org"""
*Org Syntax Reference*: \S3.1.1 \\
*Org Component Type*: Element

* Form

#+begin_example
STARS KEYWORD PRIORITY TITLE TAGS
#+end_example

+ STARS :: A string consisting of one or more asterisks (up to
  ~org-inlinetask-min-level~ if the =org-inlinetask= library is loaded)
  and ended by a space character.  The number of asterisks is used to
  define the level of the heading.

+ KEYWORD (optional) :: A string which is a member of
  ~org-todo-keywords-1~[fn:otkw1:By default, ~org-todo-keywords-1~ only
  contains =TODO= and =DONE=, however this is liable to change.].  Case is
  significant.  This is called a "TODO keyword".

+ PRIORITY (optional) :: A single alphanumeric character preceded by a
  hash sign =#= and enclosed within square brackets (e.g. =[#A]= or =[#1]=).  This
  is called a "priority cookie".

+ TITLE (optional) :: A series of objects from the standard set,
  excluding line break objects.  It is matched after every other part.

+ TAGS (optional) :: A series of colon-separated strings consisting of
  alpha-numeric characters, underscores, at signs, hash signs, and
  percent signs (=_@#%=).

If the first word appearing in the title is =COMMENT=, the heading
will be considered as "commented".  Case is significant.

If its title is the value of ~org-footnote-section~ (=Footnotes= by
default), it will be considered as a "footnote section".  Case is
significant.

If =ARCHIVE= is one of the tags given, the heading will be considered as
"archived".  Case is significant.

A heading contains directly one *section* (optionally), followed by
any number of deeper level headings.

* Examples

#+begin_src org
,* A simple heading
,** A second-level heading, with a :tag:
,*** TODO [#A] Finish the Org parser :julia:org:
#+end_src

* Fields

#+begin_src julia
level::Integer
keyword::Union{AbstractString, Nothing}
priority::Union{AbstractString, Nothing}
title::Vector{Object}
tags::Vector{AbstractString}
section::Union{Section, Nothing}
planning::Union{Planning, Nothing}
properties::Union{PropertyDrawer, Nothing}
#+end_src
""" Heading

@doc org"""
*Org Syntax Reference*: \S3.1.2 \\
*Org Component Type*: Element

* Form

Sections contain one or more non-*heading* elements.  With the exception
of the text before the first heading in a document (which is
considered a section), sections only occur within headings.

* Fields

#+begin_src julia
content::Vector{Element}
#+end_src

* The top level section

All elements before the first heading in a document lie in a special
section called the /top level section/.  It may be preceded by blank
lines.  Unlike a normal section, the top level section can immediately
contain a *property drawer*, optionally preceded by *comments*.  It cannot
however, contain *planning*.
""" Section

@doc org"""
*Org Syntax Reference*: \S3.2 \\
*Org Component Type*: Element

With the exception of *comments*, *clocks*, *headings*, *inlinetasks*,
*items*, *node properties*, *planning*, *property drawers*, *sections*, and
*table rows*, every other element type can be assigned attributes.

This is done by adding specific *keywords*, named /affiliated/ keywords,
immediately above the element considered (a blank line cannot lie
between the affiliated keyword and element). Structurally, affiliated
keyword are not considered an element in their own right but a
property of the element they apply to.

* Form

#+begin_example
,#+KEY: VALUE
,#+KEY[OPTVAL]: VALUE
,#+attr_BACKEND: VALUE
#+end_example

+ KEY :: A string which is a member of
  ~org-element-affiliated-keywords~[fn:oeakw:By default,
  ~org-element-affiliated-keywords~ contains =CAPTION=, =DATA=, =HEADERS=,
  =LABEL=, =NAME=, =PLOT=, =RESNAME=, =RESULT=, =RESULTS=, =SOURCE=, =SRCNAME=, and
  =TBLNAME=.].
+ BACKEND :: A string consisting of alphanumeric characters, hyphens,
  or underscores (=-_=).
+ OPTVAL (optional) :: A string consisting of any characters but a
  newline.  Opening and closing square brackets must be balanced.
  This term is only valid when KEY is a member of
  ~org-element-dual-keywords~[fn:oedkw:By default,
  ~org-element-dual-keywords~ contains =CAPTION= and =RESULTS=.].
+ VALUE :: A string consisting of any characters but a newline, except
  in the case where KEY is member of
  ~org-element-parsed-keywords~[fn:oepkw:By default,
  ~org-element-parsed-keywords~ contains =CAPTION=.] in which case VALUE
  is a series of objects from the standard set, excluding footnote
  references.

Repeating an affiliated keyword before an element will usually result
in the prior VALUEs being overwritten by the last instance of KEY.
There are two situations under which the VALUEs will be concatenated:
1. If KEY is a member of ~org-element-dual-keywords~[fn:oedkw].
2. If the affiliated keyword is an instance of the patten
   =#+attr_BACKEND: VALUE=.

* Example

The following example contains three affiliated keywords:

#+begin_example
,#+name: image-name
,#+caption: This is a caption for
,#+caption: the image linked below
[[file:some/image.png]]
#+end_example

* Fields

#+begin_src julia
key::AbstractString
optval::Union{<:AbstractString, Vector{Object}, Nothing}
value::Union{<:AbstractString, Vector{Object}, Nothing}
#+end_src
""" AffiliatedKeyword

@doc org"""
A wrapper for a collection of *affiliated keywords* and an *element*.

See the docstring for ~AffiliatedKeyword~ for more
information of affiliated keywords.

* Fields

#+begin_src julia
element::Element
keywords::Vector{AffiliatedKeyword}
#+end_src
""" AffiliatedKeywordsWrapper

# ---------------------
# Greater Elements
# ---------------------

@doc org"""
*Org Syntax Reference*: \S3.3 \\

Unless specified otherwise, greater elements can contain directly
any greater or *lesser element* except:
+ Elements of their own type.
+ *Planning*, which may only occur in a *heading*.
+ *Property drawers*, which may only occur in a *heading* or the *top level
  section*.
+ *Node properties*, which can only be found in *property drawers*.
+ *Items*, which may only occur in *plain lists*.
+ *Table rows*, which may only occur in *tables*.
""" GreaterElement

@doc org"""
*Org Syntax Reference*: \S3.3.1 \\
*Org Component Type*: Element/Greater Element

* Form

#+begin_example
,#+begin_NAME PARAMETERS
CONTENTS
,#+end_NAME
#+end_example

+ NAME :: A string consisting of any non-whitespace characters, which
  is not the NAME of a *lesser block*.  Greater blocks are treated
  differently based on their subtype, which is determined by the NAME
  as follows:
  - =center=, a "center block"
  - =quote=, a "quote block"
  - any other value, a "special block"
+ PARAMETERS (optional) :: A string consisting of any characters other
  than a newline.
+ CONTENTS :: A collection of zero or more elements, subject to two
  conditions:
  - No line may start with =#+end_NAME=.
  - Lines beginning with an asterisk must be quoted by a comma (=,*=).
  Furthermore, lines starting with =#+= may be quoted by a comma (=,#+=).

* Examples

#+begin_src org
TODO?
#+end_src

* Fields

#+begin_src julia
TODO
#+end_src
""" GreaterBlock

@doc org"""
*Org Syntax Reference*: \S3.3.2 \\
*Org Component Type*: Element/Greater Element

* Form

#+begin_example
:NAME:
CONTENTS
:end:
#+end_example

+ NAME :: A string consisting of word-constituent characters, hyphens
  and underscores (=-_=).
+ CONTENTS :: A collection of zero or more elements, except another drawer.

* Examples

#+begin_src org
TODO?
#+end_src

* Fields

#+begin_src julia
name::AbstractString
contents::Vector{Element}
#+end_src
""" Drawer

@doc org"""
*Org Syntax Reference*: \S3.3.3 \\
*Org Component Type*: Element/Greater Element

* Form

Dynamic blocks are structured according to the following pattern:
#+begin_example
,#+begin: NAME PARAMETERS
CONTENTS
,#+end:
#+end_example

+ NAME :: A string consisting of non-whitespace characters.
+ PARAMETERS (optional) :: A string consisting of any characters but a newline.
+ CONTENTS :: A collection of zero or more elements, except another
  dynamic block.

* Examples

#+begin_src org
TODO?
#+end_src

* Fields

#+begin_src julia
name::AbstractString
parameters::Union{AbstractString, Nothing}
contents::Vector{Element}
#+end_src
""" DynamicBlock

@doc org"""
*Org Syntax Reference*: \S3.3.4 \\
*Org Component Type*: Element/Greater Element

* Form

Footnote definitions must occur at the start of an /unindented/ line,
and are structured according to the following pattern:
#+begin_example
[fn:LABEL] CONTENTS
#+end_example

+ LABEL :: Either a number or an instance of the pattern =fn:WORD=, where
  =WORD= represents a string consisting of word-constituent characters,
  hyphens and underscores (=-_=).

+ CONTENTS (optional) :: A collection of zero or more elements.  It
  ends at the next footnote definition, the next heading, two
  consecutive blank lines, or the end of buffer.

* Examples

#+begin_example
[fn:1] A short footnote.

[fn:2] This is a longer footnote.

It even contains a single blank line.
#+end_example

* Fields
#+begin_src julia
label::AbstractString
definition::Vector{Element}
#+end_src
""" FootnoteDefinition

@doc org"""
*Org Syntax Reference*: \S3.3.5 \\
*Org Component Type*: Element/Greater Element

* Form

Inlinetasks are syntactically a *heading* with a level of at least
~org-inlinetask-min-level~[fn:oiml:The default value of
~org-inlinetask-min-level~ is =15=.], i.e. starting with at least that
many asterisks.

Optionally, inlinetasks can be ended with a second heading with a
level of at least ~org-inlinetask-min-level~[fn:oiml], with no optional
components (i.e. only STARS and TITLE provided) and the string =END= as
the TITLE. This allows the inlinetask to contain elements.

* Examples

#+begin_example
,*************** TODO some tiny task
This is a paragraph, it lies outside the inlinetask above.
,*************** TODO some small task
                 DEADLINE: <2009-03-30 Mon>
                 :PROPERTIES:
                   :SOMETHING: or other
                 :END:
                 And here is some extra text
,*************** END
#+end_example

* Fields

#+begin_src org
TODO?
#+end_src
""" InlineTask

@doc org"""
*Org Syntax Reference*: \S3.3.6 \\
*Org Component Type*: Element/Greater Element

* Form

#+begin_example
BULLET COUNTER-SET CHECK-BOX TAG CONTENTS
#+end_example

+ BULLET :: One of the two forms below, followed by either a
  whitespace character or line ending.
  - An asterisk, hyphen, or plus sign character (i.e., =*=, =-=, or =+=).
  - Either the pattern =COUNTER.= or =COUNTER)=.
    + COUNTER :: Either a number or a single letter (a-z).
+ COUNTER-SET (optional) :: An instance of the pattern =[@COUNTER]=.
+ CHECK-BOX (optional) :: A single whitespace character, an =X=
  character, or a hyphen enclosed by square brackets (i.e. =[ ]=, =[X]=, or =[-]=).
+ TAG (optional) :: An instance of the pattern =TAG-TEXT ::= where
  =TAG-TEXT= represents a string consisting of non-newline characters
  that does not contain the substring "\nbsp{}::\nbsp{}" (two colons surrounded by
  whitespace).
+ CONTENTS (optional) :: A collection of zero or more elements, ending
  at the first instance of one of the following:
  - The next item.
  - The first line less or equally indented than the starting line,
    not counting lines within other elements or *inlinetask* boundaries.
  - Two consecutive blank lines.

* Examples
#+begin_src org
- item
3. [@3] set to three
+ [-] tag :: item contents
#+end_src

* Fields
#+begin_src julia
bullet::AbstractString
counterset::Union{AbstractString, Nothing}
checkbox::Union{Char, Nothing}
tag::Union{AbstractString, Nothing}
contents::Vector{OrgComponent}
#+end_src
""" Item

@doc org"""
*Org Syntax Reference*: \S3.3.7 \\
*Org Component Type*: Element/Greater Element

* Form

A /plain list/ is a set of consecutive *items* of the same indentation.

If first item in a plain list has a COUNTER in its BULLET, the plain
list will be an "ordered plain-list".  If it contains a TAG, it will
be a "descriptive list".  Otherwise, it will be an "unordered list".
List types are mutually exclusive.

For example, consider the following excerpt of an Org document:

#+begin_example
1. item 1
2. [X] item 2
   - some tag :: item 2.1
#+end_example

Its internal structure is as follows:

#+begin_example
(ordered-plain-list
 (item)
 (item
  (descriptive-plain-list
   (item))))
#+end_example

* Fields
#+begin_src org
items::Vector{Item}
#+end_src
""" List

@doc org"""
*Org Syntax Reference*: \S3.3.8 \\
*Org Component Type*: Element/Greater Element

Property drawers are a special type of *drawer* containing properties
attached to a *heading* or *inlinetask*.  They are located right after a heading
and its *planning* information, as shown below:

#+begin_example
HEADLINE
PROPERTYDRAWER

HEADLINE
PLANNING
PROPERTYDRAWER
#+end_example

* Forms

#+begin_example
:properties:
CONTENTS
:end:
#+end_example

+ CONTENTS :: A collection of zero or more *node properties*, not
  separated by blank lines.

* Example

#+begin_src org
:PROPERTIES:
:CUSTOM_ID: someid
:END:
#+end_src

* Fields
#+begin_src julia
contents::Vector{NodeProperty}
#+end_src
""" PropertyDrawer

@doc org"""
*Org Syntax Reference*: \S3.3.9 \\
*Org Component Type*: Element/Greater Element

* Form

Tables are started by a line beginning with either:
+ A vertical bar (=|=), forming an "org" type table.
+ The string =+-= followed by a sequence of plus (=+=) and minus (=-=)
  signs, forming a "table.el" type table.

Tables cannot be immediately preceded by such lines, as the current
line would the be part of the earlier table.

Org tables contain table rows, and end at the first line not starting
with a vertical bar. An Org table can be followed by a number of
=#+TBLFM: FORMULAS= lines, where =FORMULAS= represents a string consisting
of any characters but a newline.

Table.el tables end at the first line not starting with either
a vertical line or a plus sign.

*Note*
table.el style tables are currently not supported.

* Examples
#+begin_src org
| Name  | Phone | Age |
|-------+-------+-----|
| Peter |  1234 |  24 |
| Anna  |  4321 |  25 |
#+end_src

* Fields
#+begin_src julia
rows::Vector{Union{TableRow, TableHrule}}
formulas::Vector{AbstractString}
#+end_src
""" Table

# ---------------------
# Lesser Elements
# ---------------------

@doc org"""
Lesser elements cannot contain any other element.

Only *keywords* which are a member of ~org-element-parsed-keywords~[fn:oepkw], *verse
blocks*, *paragraphs* or *table rows* can contain objects.
""" OrgLesserElement

@doc org"""
*Org Syntax Reference*: \S3.4.1 \\
*Org Component Type*: Element/Lesser Element

* Form

#+begin_example
,#+call: NAME(ARGUMENTS)
,#+call: NAME[HEADER1](ARGUMENTS)
,#+call: NAME(ARGUMENTS)[HEADER2]
,#+call: NAME[HEADER1](ARGUMENTS)[HEADER2]
#+end_example

+ NAME :: A string consisting of any non-newline characters except for
  square brackets, or parentheses (=[]()=).
+ ARGUMENTS (optional) :: A string consisting of any non-newline
  characters.  Opening and closing parenthesis must be balanced.
+ HEADER1 (optional), HEADER2 (optional) :: A string consisting of any
  non-newline characters.  Opening and closing square brackets must be
  balanced.

*Note*
Only NAME is currently implemented.

* Fields

#+begin_src julia
name::AbstractString
#+end_src
""" BabelCall

@doc org"""
*Org Syntax Reference*: \S3.4.2 \\
*Org Component Type*: Element/Lesser Element

* Form

#+begin_example
,#+begin_NAME DATA
CONTENTS
,#+end_NAME
#+end_example

+ NAME :: A string consisting of any non-whitespace characters.  The
  type of the block is determined based on the value as follows:
  - =comment=, a "comment block",
  - =example=, an "example block",
  - =export=, an "export block",
  - =src=, a "source block",
  - =verse=, a "verse block".
    The NAME must be one of these values.  Otherwise, the pattern
    forms a greater block.
+ DATA (optional) :: A string consisting of any characters but a newline.
  - In the case of an export block, this is mandatory and must be a
    single word.
  - In the case of a source block, this is mandatory and must follow
    the pattern =LANGUAGE SWITCHES ARGUMENTS= with:
    + LANGUAGE :: A string consisting of any non-whitespace characters
    + SWITCHES :: Any number of SWITCH patterns, separated by a single
      space character
      - SWITCH :: Either the pattern =-l "FORMAT"= where =FORMAT=
        represents a string consisting of any characters but a double
        quote (="=) or newline, or the pattern =-S= or =+S= where =S=
        represents a single alphabetic character
    + ARGUMENTS :: A string consisting of any character but a newline.
+ CONTENTS (optional) :: A string consisting of any characters
  (including newlines) subject to the same two conditions of greater
  block's CONTENTS, i.e.
  - No line may start with =#+end_NAME=.
  - Lines beginning with an asterisk must be quoted by a comma (=,*=).
  As with greater blocks, lines starting with =#+= may be quoted by a
  comma (=,#+=).
  CONTENTS will contain Org objects when the block is a verse block,
  it is otherwise not parsed.

* Examples

#+begin_src org
,#+begin_verse
    There was an old man of the Cape
   Who made himself garments of crepe.
       When asked, “Do they tear?”
      He replied, “Here and there,
 But they’re perfectly splendid for shape!”
,#+end_verse
#+end_src

* Fields

#+begin_src julia
name::AbstractString
data::Union{AbstractString, Nothing}
contents::AbstractString
#+end_src
""" Block

# Clock

# DiarySexp

@doc org"""
*Org Syntax Reference*: \S3.4.5 \\
*Org Component Type*: Element/Lesser Element

* Form

#+begin_example
HEADING
PLANNING
#+end_example

+ HEADING :: A *heading* element.
+ PLANNING :: A line consisting of a series of =KEYWORD: TIMESTAMP=
  patterns (termed "info" patterns).
  - KEYWORD :: Either the string =DEADLINE=, =SCHEDULED=, or =CLOSED=.
  - TIMESTAMP :: A *timestamp* object.

It is not permitted for any blank lines to lie between HEADING and
PLANNING.

* Fields

#+begin_src julia
deadline::Union{Timestamp, Nothing}
scheduled::Union{Timestamp, Nothing}
closed::Union{Timestamp, Nothing}
#+end_src
""" Planning

@doc org"""
*Org Syntax Reference*: \S3.4.6 \\
*Org Component Type*: Element/Lesser Element

* Form

A "comment line" starts with a hash character (=#=) and either a whitespace
character or the immediate end of the line.

Comments consist of one or more consecutive comment lines.

* Examples

#+begin_src org
# Just a comment
#
# Over multiple lines
#+end_src

* Fields

#+begin_src julia
contents::AbstractString
#+end_src
""" Comment

@doc org"""
*Org Syntax Reference*: \S3.4.7 \\
*Org Component Type*: Element/Lesser Element

* Form

A "fixed-width line" starts with a colon character (=:=) and either a whitespace
character or the immediate end of the line.

Fixed-width areas consist of one or more consecutive fixed-width lines.

* Examples

#+begin_src org
: This is a
: fixed width area
#+end_src

* Fields

#+begin_src julia
contents::AbstractString
#+end_src
""" FixedWidth

@doc org"""
*Org Syntax Reference*: \S3.4.8 \\
*Org Component Type*: Element/Lesser Element

* Form

A horizontal rule is formed by a line consisting of at least five
consecutive hyphens (=-----=).
""" HorizontalRule

@doc org"""
*Org Syntax Reference*: \S3.4.9 \\
*Org Component Type*: Element/Lesser Element

* Form

#+begin_example
,#+KEY: VALUE
#+end_example

+ KEY :: A string consisting of any non-whitespace characters, other
  than =call= (which would forms a *babel call* element).
+ VALUE :: A string consisting of any characters but a newline.

When KEY is a member of ~org-element-parsed-keywords~[fn:oepkw], VALUE can contain
the standard set objects, excluding footnote references.

Note that while instances of this pattern are preferentially parsed as
*affiliated keywords*, a keyword with the same KEY as an affiliated
keyword may occur so long as it is not immediately preceding a valid
element that can be affiliated.  For example, an instance of
=#+caption: hi= followed by a blank line will be parsed as a keyword,
not an affiliated keyword.

* Examples

#+begin_src org
,#+title: Document title
#+end_src

* Fields

#+begin_src julia
key::AbstractString
value::Union{<:AbstractString, Vector{Object}, Nothing}
#+end_src
""" Keyword

@doc org"""
*Org Syntax Reference*: \S3.4.10 \\
*Org Component Type*: Element/Lesser Element

* Form

#+begin_example
\begin{NAME}
CONTENTS
\end{NAME}
#+end_example

+ NAME :: A string consisting of alphanumeric or asterisk characters
+ CONTENTS (optional) :: A string which does not contain the substring
  =\end{NAME}=.

* Examples

#+begin_example
\begin{align*}
2x - 5y &= 8 \\
3x + 9y &= -12
\end{align*}
#+end_example

* Fields

#+begin_src julia
name::AbstractString
contents::AbstractString
#+end_src
""" LaTeXEnvironment

@doc org"""
*Org Syntax Reference*: \S3.4.11 \\
*Org Component Type*: Element/Lesser Element

* Forms
#+begin_example
:NAME: VALUE
:NAME:
:NAME+: VALUE
:NAME+:
#+end_example

+ NAME :: A non-empty string containing any non-whitespace characters
  which does not end in a plus characters (=+=).
+ VALUE (optional) :: A string containing any characters but a newline.

* Examples
#+begin_src org
TODO?
#+end_src

* Fields
#+begin_src julia
name::AbstractString
additive::Bool
value::AbstractString
#+end_src
""" NodeProperty

@doc org"""
*Org Syntax Reference*: \S3.4.12 \\
*Org Component Type*: Element/Lesser Element

* Form

Paragraphs are the default element, which means that any
unrecognized context is a paragraph.

Empty lines and other elements end paragraphs.

Paragraphs can contain the standard set of objects.

* Examples
#+begin_src org
Hey look, it's just some text.
#+end_src

* Fields
#+begin_src julia
objects::Vector{Object}
#+end_src
""" Paragraph

@doc org"""
*Org Syntax Reference*: \S3.4.13 \\
*Org Component Type*: Element/Lesser Element

* Forms

A table row consists of a vertical bar (=|=) followed by:
+ Any number of *table cells*, forming a "standard" type row.
+ A hyphen (=-=), forming a "rule" type row.  Any non-newline characters
  can follow the hyphen and this will still be a "rule" type row

Table rows can only exist in *tables*.

* Fields
#+begin_src julia
cells::Vector{TableCell}
#+end_src
""" TableRow

# ---------------------
# Objects
# ---------------------

@doc org"""
Objects can only be found in the following elements:

- *keywords* or *affiliated keywords* VALUEs, when KEY is a member of
  ~org-element-parsed-keywords~[fn:oepkw],
- *heading* TITLEs,
- *inlinetask* TITLEs,
- *item* TAGs,
- *clock* INACTIVE-TIMESTAMP and INACTIVE-TIMESTAMP-RANGE, which can
  only contain inactive timestamps,
- *planning* TIMESTAMPs, which can only be timestamps,
- *paragraphs*,
- *table cells*,
- *table rows*, which can only contain table cell objects,
- *verse blocks*.

Most objects cannot contain objects.  Those which can will be
specified.  Furthermore, while many objects may contain newlines, a
blank line often terminates the element that the object is a part of,
such as a paragraph.
""" Object

@doc org"""
*Org Syntax Reference*: \S4.1 \\
*Org Component Type*: Object

* Form

#+begin_example
\NAME POST
#+end_example

Where NAME and POST are not separated by a whitespace character.

+ NAME :: A string with a valid association in either
  ~OrgMode.Entities~ or ~org-entities-user~.
+ POST :: Either:
  - The end of line.
  - The string ={}=.
  - A non-alphabetic character.

* Examples
#+begin_example
\cent
#+end_example

* Fields

#+begin_src julia
name::AbstractString
#+end_src
""" Entity

@doc org"""
*Org Syntax Reference*: \S4.2 \\
*Org Component Type*: Object

* Forms

#+begin_example
\NAME BRACKETS
\(CONTENTS\)
\[CONTENTS\]
#+end_example

+ NAME :: A string consisting of alphabetic characters which does not
  have an association in either ~org-entities~ or ~org-entities-user~.
+ BRACKETS (optional) :: An instance of one of the following patterns,
  not separated from NAME by whitespace.
  #+begin_example
[CONTENTS1]
{CONTENTS1}
  #+end_example
  - CONTENTS1 :: A string consisting of any characters but ={=, =}=, =[=,
    =]=, or a newline.
  - CONTENTS2 :: A string consisting of any characters but ={=, =}=, or a newline.
+ CONTENTS :: A string consisting of any characters, so long as it does
  not contain the substring =\)= in the case of the
  second template, or =\]= in the case of the third template.

Org also supports TeX-style inline LaTeX fragments, but I don't like them.

* Examples

#+begin_example
\enlargethispage{2\baselineskip}
\(e^{i \pi}\)
#+end_example

* Fields

#+begin_src julia
contents::AbstractString
delimiters::Union{Tuple{AbstractString, AbstractString}, Nothing}
#+end_src
""" LaTeXFragment

@doc org"""
*Org Syntax Reference*: \S4.3 \\
*Org Component Type*: Object

* Form

#+begin_example
@@BACKEND:VALUE@@
#+end_example

+ BACKEND :: A string consisting of alphanumeric characters and hyphens.
+ VALUE (optional) :: A string containing anything but the string =@@=.

* Fields
#+begin_src julia
backend::AbstractString
snippet::AbstractString
#+end_src
""" ExportSnippet

@doc org"""
*Org Syntax Reference*: \S4.4 \\
*Org Component Type*: Object

* Forms

#+begin_example
[fn:LABEL]
[fn:LABEL:DEFINITION]
[fn::DEFINITION]
#+end_example

+ LABEL :: A string containing one or more word constituent characters,
  hyphens and underscores (=-_=).
+ DEFINITION (optional) :: A series of objects from the standard set,
  so long as opening and closing square brackets are balanced within
  DEFINITION.

If the reference follows the second pattern, it is called an "inline
footnote".  If it follows the third pattern, i.e. if LABEL is omitted,
it is called an "anonymous footnote".

Note that the first pattern may not occur on an /unindented/ line, as it
is then a *footnote definition*.

* Fields

#+begin_src julia
label::Union{AbstractString, Nothing}
definition::Union{Vector{Object}, Nothing}
#+end_src
""" FootnoteReference

@doc org"""
*Org Syntax Reference*: \S4.6 \\
*Org Component Type*: Object

* Forms

#+begin_example
KEYPREFIX @KEY KEYSUFFIX
#+end_example
Where KEYPREFIX, @KEY, and KEYSUFFIX are not separated by whitespace.

+ KEYPREFIX (optional) :: A series of objects from the minimal set,
  so long as all square brackets are balanced within KEYPREFIX, and
  it does not contain any semicolons (=;=) or subsequence that matches
  =@KEY=.
+ KEY :: A string made of any word-constituent character, =-=, =.=, =:=,
  =?=, =!=, =`=, ='=, =/=, =*=, =@=, =+=, =|=, =(=, =)=, ={=, =}=, =<=, =>=, =&=, =_=, =^=, =$=, =#=, =%=, or
  =~=.
+ KEYSUFFIX (optional) :: A series of objects from the minimal set,
  so long as all square brackets are balanced within KEYPREFIX, and
  it does not contain any semicolons (=;=).

* Fields

#+begin_src julia
prefix::Vector{Object}
key::AbstractString
suffix::Vector{Object}
#+end_src
""" CitationReference

@doc org"""
*Org Syntax Reference*: \S4.5 \\
*Org Component Type*: Object

* Forms

#+begin_example
[cite CITESTYLE: GLOBALPREFIX REFERENCES GLOBALSUFFIX]
#+end_example

Where "cite" and =CITESTYLE=, =KEYCITES= and =GLOBALSUFFIX= are /not/
separated by whitespace.  =KEYCITES=, =GLOBALPREFIX=, and =GLOBALSUFFIX=
must be separated by semicolons.  Whitespace after the leading colon
or before the closing square bracket is not significant.  All other
whitespace is significant.

+ CITESTYLE (optional) :: An instance of either the pattern =/STYLE= or =/STYLE/VARIANT=
  - STYLE :: A string made of any alphanumeric character, =_=, or =-=.
  - Variant :: A string made of any alphanumeric character, =_=, =-=, or =/=.
+ GLOBALPREFIX (optional) :: A series of objects from the standard set,
  so long as all square brackets are balanced within GLOBALPREFIX, and
  it does not contain any semicolons (=;=) or subsequence that matches
  =@KEY=.
+ REFERENCES :: One or more *citation reference* objects, separated by
  semicolons (=;=).
+ GLOBALSUFFIX (optional) :: A series of objects from the standard set,
  so long as all square brackets are balanced within GLOBALSUFFIX, and
  it does not contain any semicolons (=;=) or subsequence that matches
  =@KEY=.

* Examples

#+begin_example
[cite:@key]
[cite/t:see;@foo p. 7;@bar pp. 4;by foo]
[cite/a/f:c.f.;the very important @@atkey @ once;the crucial @baz vol. 3]
#+end_example

* Fields

#+begin_src julia
style::Tuple{Union{AbstractString, Nothing},
              Union{AbstractString, Nothing}}
globalprefix::Vector{Object}
citerefs::Vector{CitationReference}
globalsuffix::Vector{Object}
#+end_src
""" Citation

@doc org"""
*Org Syntax Reference*: \S4.7 \\
*Org Component Type*: Object

* Forms

#+begin_example
call_NAME(ARGUMENTS)
call_NAME[HEADER1](ARGUMENTS)
call_NAME(ARGUMENTS)[HEADER2]
call_NAME[HEADER1](ARGUMENTS)[HEADER2]
#+end_example

+ NAME :: A string consisting of any non-whitespace characters except
  for square brackets or parentheses (=[]()=).
+ ARGUMENTS (optional), HEADER1 (optional), HEADER2 (optional) :: A
  string consisting of any characters but a newline.  Opening and
  closing square brackets must be balanced.

* Fields
#+begin_src julia
name::AbstractString
header::Union{AbstractString, Nothing}
arguments::Union{AbstractString, Nothing}
#+end_src
""" InlineBabelCall

@doc org"""
*Org Syntax Reference*: \S4.8 \\
*Org Component Type*: Object

* Forms

#+begin_example
src_LANG{BODY}
src_LANG[HEADERS]{BODY}
#+end_example

+ LANG :: A string consisting of any non-whitespace characters.
+ HEADERS (optional), BODY (optional) :: A string consisting of any
  characters but a newline.  Opening and closing square brackets must
  be balanced.

* Fields

#+begin_src julia
lang::AbstractString
options::Union{AbstractString, Nothing}
body::AbstractString
#+end_src
""" InlineSourceBlock

@doc org"""
*Org Syntax Reference*: \S4.9 \\
*Org Component Type*: Object

* Forms
#+begin_example
\\SPACE
#+end_example

+ SPACE :: Zero or more tab and space characters.

This pattern must occur at the end of any otherwise non-empty line.
""" LineBreak

@doc org"""
*Org Syntax Reference*: \S4.10 \\
*Org Component Type*: Object

Links come in four subtypes:
+ ~RadioLink~
+ ~PlainLink~
+ ~AngleLink~
+ ~RegularLink~

Each of those have dedicated docstrings.
""" Link

@doc org"""
*Org Syntax Reference*: \S4.10.1 \\
*Org Component Type*: Object

* Form

#+begin_example
PRE RADIO POST
#+end_example

+ PRE :: A non-alphanumeric character.
+ RADIO :: A series of objects matched by some *radio target*.  It can
  contain the minimal set of objects.
+ POST :: A non-alphanumeric character.

* Example

#+begin_example
This is some <<<*important* information>>> which we refer to lots.
Make sure you remember the *important* information.
#+end_example

The first instance of =*important* information= defines a radio target,
which is matched by the second instance of =*important* information=,
forming a radio link.

* Fields

#+begin_src julia
radio::RadioTarget
#+end_src
""" RadioLink

@doc org"""
*Org Syntax Reference*: \S4.10.4 \\
*Org Component Type*: Object

* Forms
#+begin_src org
PROTOCOL:PATH
PROTOCOL://PATH
id::ID
#CUSTOM-ID
(CODEREF)
FUZZY
#+end_src

+ =PROTOCOL= is any recognised protocol string
+ =PATH=, =CUSTOM-ID=, =CODEREF=, and =FUZZY= can contain any character besides "[" or "]"
+ =ID= is a hexidecimal string seperated by hyphens

* Fields
#+begin_src julia
protocol::Union{Symbol, AbstractString}
path::AbstractString
#+end_src
""" LinkPath

@doc org"""
*Org Syntax Reference*: \S4.10.2 \\
*Org Component Type*: Object

* Form

#+begin_example
PRE PROTOCOL:PATHPLAIN POST
#+end_example

+ PRE :: A non word constituent character.
+ PROTOCOL :: A string which is one of the link type strings in
  ~org-link-parameters~[fn:olp:By default, ~org-link-parameters~ defines
  links of type =file+sys=, =file+emacs=, =shell=, =news=, =mailto=, =https=,
  =http=, =ftp=, =help=, =file=, and =elisp=.].
+ PATHPLAIN :: A string containing any non-whitespace character but =(=, =)=,
  =<=, or =>=.  It must end with a word-constituent character, or any
  non-whitespace non-punctuation character followed by =/=.
+ POST :: A non word constituent character.

* Example

#+begin_example
Be sure to look at https://orgmode.org.
#+end_example

* Fields

#+begin_src julia
path::LinkPath
#+end_src
""" PlainLink

@doc org"""
*Org Syntax Reference*: \S4.10.3 \\
*Org Component Type*: Object

Angle-type essentially provide a method to disambiguate plain links
from surrounding text.

* Form

#+begin_example
<PROTOCOL:PATHANGLE>
#+end_example

+ PROTOCOL :: A string which is one of the link type strings in
  ~org-link-parameters~[fn:olp]
+ PATHANGLE :: A string containing any character but =]=, =<=, =>= or =\n=.

The angle brackets allow for a more permissive PATH syntax, without
accidentally matching surrounding text.

* Fields

#+begin_src julia
path::LinkPath
#+end_src
""" AngleLink

@doc org"""
*Org Syntax Reference*: \S4.10.4 \\
*Org Component Type*: Object

* Forms

#+begin_example
[[PATHREG]]
[[PATHREG][DESCRIPTION]]
#+end_example

+ PATHREG :: An instance of one of the seven following annotated patterns:
  #+begin_example
FILENAME               ("file" type)
PROTOCOL:PATHINNER     ("PROTOCOL" type)
PROTOCOL://PATHINNER   ("PROTOCOL" type)
id:ID                  ("id" type)
#CUSTOM-ID             ("custom-id" type)
(CODEREF)              ("coderef" type)
FUZZY                  ("fuzzy" type)
  #+end_example
  - FILENAME :: A string representing an absolute or relative file path.
  - PROTOCOL :: A string which is one of the link type strings in
    ~org-link-parameters~[fn:olp]
  - PATHINNER :: A string consisting of any character besides square brackets.
  - ID :: A string consisting of hexadecimal numbers separated by hyphens.
  - CUSTOM-ID :: A string consisting of any character besides square brackets.
  - CODEREF :: A string consisting of any character besides square brackets.
  - FUZZY :: A string consisting of any character besides square brackets.
  Square brackets and backslashes can be present in PATHREG so long as
  they are escaped by a backslash (i.e. =\]=, =\\=).
+ DESCRIPTION (optional) :: A series of objects enclosed by square
  brackets.  It can contain the minimal set of objects as well as
  *export snippets*, *inline babel calls*, *inline source blocks*, *macros*,
  and *statistics cookies*.  It can also contain another link, but only
  when it is a plain or angle link.  It can contain square brackets,
  so long as they are balanced.

* Examples

#+begin_example
[[https://orgmode.org][The Org project homepage]]
[[file:orgmanual.org]]
[[Regular links]]
#+end_example

* Fields

#+begin_src julia
path::LinkPath
description::Union{Vector{Object}, Nothing}
#+end_src
""" RegularLink

@doc org"""
*Org Syntax Reference*: \S4.11 \\
*Org Component Type*: Object

* Forms

#+begin_example
{{{NAME}}}
{{{NAME(ARGUMENTS)}}}
#+end_example

+ NAME :: A string starting with a alphabetic character followed by
  any number of alphanumeric characters, hyphens and underscores (=-_=).
+ ARGUMENTS (optional) :: A string consisting of any characters, so
  long as it does not contain the substring =}}}=.  Values within
  ARGUMENTS are separated by commas.  Non-separating commas have to be
  escaped with a backslash character.

* Examples
#+begin_example
{{{title}}}
{{{one_arg_macro(1)}}}
{{{two_arg_macro(1, 2)}}}
{{{two_arg_macro(1\,a, 2)}}}
#+end_example

* Fields

#+begin_src julia
name::AbstractString
arguments::Vector{AbstractString}
#+end_src
""" Macro

@doc org"""
*Org Syntax Reference*: \S4.12 \\
*Org Component Type*: Object

* Forms

#+begin_example
<<<CONTENTS>>>
#+end_example

+ CONTENTS :: A series of objects from the minimal set, starting and
  ending with a non-whitespace character, and containing any character
  but =<=, =>=, or =\n=.

* Fields

#+begin_src julia
contents::Vector{Object}
#+end_src
""" RadioTarget

@doc org"""
*Org Syntax Reference*: \S4.12 \\
*Org Component Type*: Object

* Forms

#+begin_example
<<TARGET>>
#+end_example

+ TARGET :: A string containing any character but =<=, =>=, or =\n=.  It
  cannot start or end with a whitespace character.

* Fields

#+begin_src julia
contents::AbstractString
#+end_src
""" Target

@doc org"""
*Org Syntax Reference*: \S4.13 \\
*Org Component Type*: Object

* Forms

#+begin_example
[PERCENT%]
[NUM1/NUM2]
#+end_example

+ PERCENT (optional) :: A number.
+ NUM1 (optional) :: A number.
+ NUM2 (optional) :: A number.

* Fields

The subtype =StatisticsCookiePercent= has the following structure:
#+begin_src julia
percentage::AbstractString
#+end_src

The subtype =StatisticsCookieFraction= has the following structure:
#+begin_src julia
complete::Union{Integer, Nothing}
total::Union{Integer, Nothing}
#+end_src
""" StatisticsCookie

@doc org"""
See =StatisticsCookie=.
"""
StatisticsCookiePercent

@doc org"""
See =StatisticsCookie=.
"""
StatisticsCookieFraction

@doc org"""
*Org Syntax Reference*: \S4.14 \\
*Org Component Type*: Object

* Forms
#+begin_src org
CHAR_SCRIPT
CHAR^SCRIPT
#+end_src

+ CHAR :: Any non-whitespace character.
+ SCRIPT :: One of the following constructs:
  - A single asterisk character (=*=).
  - An expression enclosed in curly brackets (={=, =}=), which may itself
    contain balanced curly brackets.
  - An instance of the pattern:
    #+begin_example
SIGN CHARS FINAL
    #+end_example
    With no whitespace between SIGN, CHARS and FINAL.
    + SIGN :: Either a plus sign character (=+=), a minus sign character
      (=-=), or the empty string.
    + CHARS :: Either the empty string, or a string consisting of any
      number of alphanumeric characters, commas, backslashes, and
      dots.
    + FINAL :: An alphanumeric character.

* Fields

Each of the subtypes, =Subscript= and =Superscript= are of the form:
#+begin_src
char::Char
script::AbstractString
#+end_src
""" Script

@doc org"""
*Org Syntax Reference*: \S4.15 \\
*Org Component Type*: Object

* Forms

#+begin_example
CONTENTS SPACES|
#+end_example

+ CONTENTS :: A series of objects not containing the vertical bar
  character (=|=).  It can contain the minimal set of objects,
  *citations*, *export snippets*, **footnote references*, *links*, *macros*,
  *radio targets*, *targets*, and *timestamps*.
+ SPACES :: A string consisting of zero or more of space characters,
  used to align the table columns.

The final vertical bar (=|=) may be omitted in the last cell of a row.

* Fields

#+begin_src julia
contents::Vector{Object}
#+end_src
""" TableCell

@doc org"""
*Org Syntax Reference*: \S4.16 \\
*Org Component Type*: Object

* Forms

#+begin_example
<%%(SEXP)>                                                     (diary)
<DATE TIME REPEATER-OR-DELAY>                                  (active)
[DATE TIME REPEATER-OR-DELAY]                                  (inactive)
<DATE TIME REPEATER-OR-DELAY>--<DATE TIME REPEATER-OR-DELAY>   (active range)
<DATE TIME-TIME REPEATER-OR-DELAY>                             (active range)
[DATE TIME REPEATER-OR-DELAY]--[DATE TIME REPEATER-OR-DELAY]   (inactive range)
[DATE TIME-TIME REPEATER-OR-DELAY]                             (inactive range)
#+end_example

+ SEXP :: A string consisting of any characters but =>= and =\n=.
+ DATE :: An instance of the pattern:
  #+begin_example
YYYY-MM-DD DAYNAME
  #+end_example
  - Y, M, D :: A digit.
  - DAYNAME (optional) :: A string consisting of non-whitespace
    characters except =+=, =-=, =]=, =>=, a digit, or =\n=.
+ TIME (optional) :: An instance of the pattern =H:MM= where =H= represents a one to
  two digit number (and can start with =0=), and =M= represents a single
  digit.
+ REPEATER-OR-DELAY (optional) :: An instance of the following pattern:
  #+begin_example
MARK VALUE UNIT
  #+end_example
  Where MARK, VALUE and UNIT are not separated by whitespace characters.
  - MARK :: Either the string =+= (cumulative type), =++= (catch-up type),
    or =.+= (restart type) when forming a repeater, and either =-= (all
    type) or =--= (first type) when forming a warning delay.
  - VALUE :: A number
  - UNIT :: Either the character =h= (hour), =d= (day), =w= (week), =m=
    (month), or =y= (year)

There can be two instances of =REPEATER-OR-DELAY= in the timestamp: one
as a repeater and one as a warning delay.

* Examples
#+begin_example
<1997-11-03 Mon 19:15>
<%%(diary-float t 4 2)>
[2004-08-24 Tue]--[2004-08-26 Thu]
<2012-02-08 Wed 20:00 ++1d>
<2030-10-05 Sat +1m -3d>
#+end_example

* Fields

There are a large number of subtypes.\\
TODO fill in more info
""" Timestamp

@doc org"""
*Org Syntax Reference*: \S4.17 \\
*Org Component Type*: Object

There are six text markup objects: bold, italic, underline,
verbatim, code, and strike-through.  They are all shadowed
by this type.

* Forms

#+begin_example
PRE MARKER CONTENTS MARKER POST
#+end_example

Where PRE, MARKER, CONTENTS, MARKER and /POST/ are not separated by
whitespace characters.

+ PRE :: Either a whitespace character, =-=, =(=, ={=, ='=, ="=, or the beginning
  of a line.
+ MARKER :: A character that determines the object type, as follows:
  - =*=, a /bold/ object,
  - =/=, an /italic/ object,
  - =_= an /underline/ object,
  - ===, a /verbatim/ object,
  - =~=, a /code/ object
  - =+=, a /strike-through/ object.
+ CONTENTS :: An instance of the pattern:
  #+begin_example
BORDER BODY BORDER
  #+end_example
  Where BORDER and BODY are not separated by whitespace.
  - BORDER :: Any non-whitespace character.
  - BODY ::  Either a string (when MARKER represents code or verbatim)
    or a series of objects from the standard set, not spanning more
    than three lines.
+ POST :: Either a whitespace character, =-=, =.=, =,=, =;=, =:=, =!=, =?=, ='=, =)=, =}=,
  =[=, ="=, or the end of a line.

* Fields
#+begin_src julia
formatting::Symbolcontents::Vector{Object}
contents::Union{Vector{Object}, <:AbstractString}
#+end_src
""" TextMarkup

@doc org"""
*Org Syntax Reference*: \S4.18 \\
*Org Component Type*: Object

Any string that doesn't match any other object can be considered a
plain text object.
Within a plain text object, all whitespace is collapsed to a single
space. For instance, =hello\n there= is equivalent to =hello there=.

* Fields

#+begin_src julia
text::AbstractString
#+end_src
""" TextPlain


text:
using KiteModels, KiteUtils
using Test

cd("..")
KiteUtils.set_data_path("")
include("test_kps3.jl")
include("test_kps4.jl")
include("bench3.jl")
include("bench4.jl")

ext: jl


text:
"""
    Absolute(x::SeaPearl.AbstractIntVar, y::SeaPearl.AbstractIntVar)

Absolute value constraint, enforcing y = |x|.
"""
struct Absolute <: Constraint
    x::AbstractIntVar
    y::AbstractIntVar
    active::StateObject{Bool}
    initialized::StateObject{Bool}

    function Absolute(x, y, trailer)
        constraint = new(x, y, StateObject(true, trailer), StateObject(false, trailer))
        addOnDomainChange!(x, constraint)
        addOnDomainChange!(y, constraint)
        return constraint
    end
end

"""
    propagate!(constraint::Absolute, toPropagate::Set{Constraint}, prunedDomains::CPModification)

"Propagate the 'Absolute' constraint.
"""
function propagate!(constraint::Absolute, toPropagate::Set{Constraint}, prunedDomains::CPModification)

    if !constraint.initialized.value
        setValue!(constraint.initialized, true)
        prunedY = removeBelow!(constraint.y.domain, 0) # y cannot take a negative value
        addToPrunedDomains!(prunedDomains, constraint.y, prunedY)
        triggerDomainChange!(toPropagate, constraint.y)
    end

    if isbound(constraint.x)
        value = abs(assignedValue(constraint.x))
        if !(value in constraint.y.domain)
            return false
        end

        prunedY = assign!(constraint.y, value)
        addToPrunedDomains!(prunedDomains, constraint.y, prunedY)
        triggerDomainChange!(toPropagate, constraint.y)
        setValue!(constraint.active, false)

    elseif isbound(constraint.y) # x is equal to y or -y
        value = assignedValue(constraint.y)
        if !(value in constraint.x.domain || -value in constraint.x.domain)
            return false
        end

        for v in minimum(constraint.x.domain):maximum(constraint.x.domain)
            if v != value && v != -value
                # remove everything in x domain except y and -y
                prunedX = remove!(constraint.x.domain,v)
                addToPrunedDomains!(prunedDomains, constraint.x, prunedX)
                triggerDomainChange!(toPropagate, constraint.x)
            end
        end
        setValue!(constraint.active, false)
    else # no variable is bound

        prunedValuesX = Int[]
        prunedValuesY = Int[]
        if minimum(constraint.x.domain) >= 0
            append!(prunedValuesY, removeBelow!(constraint.y.domain, minimum(constraint.x.domain)))
            append!(prunedValuesY, removeAbove!(constraint.y.domain, maximum(constraint.x.domain)))
            append!(prunedValuesX, removeBelow!(constraint.x.domain, minimum(constraint.y.domain)))
            append!(prunedValuesX, removeAbove!(constraint.x.domain, maximum(constraint.y.domain)))

        elseif maximum(constraint.x.domain) <= 0
            append!(prunedValuesY, removeBelow!(constraint.y.domain, -maximum(constraint.x.domain)))
            append!(prunedValuesY, removeAbove!(constraint.y.domain, -minimum(constraint.x.domain)))
            append!(prunedValuesX, removeBelow!(constraint.x.domain, -maximum(constraint.y.domain)))
            append!(prunedValuesX, removeAbove!(constraint.x.domain, -minimum(constraint.y.domain)))

        else
            maxAbs = max(maximum(constraint.x.domain), -minimum(constraint.x.domain))
            append!(prunedValuesY, removeAbove!(constraint.y.domain, maxAbs))
            append!(prunedValuesX, removeBelow!(constraint.x.domain, -maximum(constraint.y.domain)))
            append!(prunedValuesX, removeAbove!(constraint.x.domain, maximum(constraint.y.domain)))
        end
        addToPrunedDomains!(prunedDomains, constraint.x, prunedValuesX)
        addToPrunedDomains!(prunedDomains, constraint.y, prunedValuesY)
        triggerDomainChange!(toPropagate, constraint.x)
        triggerDomainChange!(toPropagate, constraint.y)
    end

    if isempty(constraint.x.domain) || isempty(constraint.y.domain)
        return false
    end

    if constraint in toPropagate
        pop!(toPropagate, constraint)
    end

    return true

end

variablesArray(constraint::Absolute) = [constraint.x, constraint.y]

function Base.show(io::IO, ::MIME"text/plain", con::Absolute)
    println(io, string(typeof(con)), ": |", con.x.id, "| = ", con.y.id, ", active = ", con.active.value)
    println(io, "   ", con.x)
    print(io, "   ", con.y)
end

function Base.show(io::IO, con::Absolute)
    print(io, string(typeof(con)), ": |", con.x.id, "| = ", con.y.id)
end


text:
start = time()
N = 100
Rows = 3
MaxValue = 10
#MaxNumProcs = 4
Reps = 10

@everywhere delay = 0.01

#times = zeros(Reps, MaxNumProcs)
times = zeros(Reps, 1)

#for numproc in 1:MaxNumProcs
  numproc = nprocs()
  #println("With $(numproc) procs")

  require("pfind_colwise.jl") # Reload to ensure it is on all procs

  @everywhere mycond(column) = fake_slow_condition(column, delay, 30)

  for rep in 1:Reps
    #println("  Rep $rep")
    array = ifloor(MaxValue * rand(Rows, N))

    # We will be looking for the first column that sums to 30. Make sure it exists.
    suma = sum(array, 1)
    i = findfirst(suma, 30)
    if i == 0
      # Put it somewhere around the middle
      #i = ifloor(rand(0.45N:0.55*N))
      i = rand(1:N)
      array[:,i] = MaxValue * ones(Int, Rows, 1)
    end

    tic()
      idx, res = pfind_colwise(mycond, array)
    #times[rep, numproc] = toq()
    times[rep] = toq()
    @assert idx == i
  end

  #addprocs(1) # Add one proc for next round
#end

#println(mean(times[2:Reps,:], 2))
mean_time = mean(times[2:Reps,:])
println("Nprocs = $(nprocs()), Delay = $delay, Avg time = $(mean_time), Total time = $(time() - start)")


text:
function sort3(a,b,c)
if c > b
  tmp = c; c = b; b = tmp
end
if c > a
  tmp = a; a = c; c = tmp
end
if b > a
  tmp = b; b = a; a = tmp
end
println(a," ",b," ",c)
return
end

max_stars_repo_name: tagordon/limbdark

max_issues_repo_name: tagordon/limbdark

max_forks_repo_name: tagordon/limbdark


text:
using ESDL
using Test
using Dates
using IterTools
using WeightedOnlineStats

c=Cube()
d = getCubeData(c,variable=["air_temperature_2m", "gross_primary_productivity", "soil_moisture"],longitude=(30,31),latitude=(50,51),
              time=(Date("2002-01-01"),Date("2008-12-31")))
mytable = CubeTable(variable=d,include_axes=("lon", "lat", "time"),fastest="variable")

mytable2 = CubeTable(data=d,include_axes=("lon", "lat", "time", "variable"),fastest="variable")

@testset "cubefittable and WeightedCovMatrix fittable" begin
    covmCube = cubefittable(mytable, WeightedCovMatrix, :variable, weight=(x->cosd(x.lat)),showprog=false)
    newtab = IterTools.partition(mytable,3)
    covmVal = WeightedCovMatrix()
    for row in newtab
        obs = [row[i].variable for i in 1:length(row)]
        obslat = row[1].lat
        if !any(ismissing.(obs))
            fit!(covmVal, obs, cosd(obslat))
        end
    end
    @test all(isapprox.(covmCube.data, value(covmVal)))
end

@testset "remaining functions in tablestats.jl" begin
    meanCube = cubefittable(mytable2, WeightedMean, :data, weight=(x->cosd(x.lat)),
                            by=(:variable,))
    weightedTableMeans = fittable(mytable2, WeightedMean, :data, by=(:variable,),
                                    weight=(x -> cosd(x.lat)))
    foreach(enumerate(["air_temperature_2m", "gross_primary_productivity", "soil_moisture"])) do (i,v)
      @test isapprox(value(weightedTableMeans)[(v,)], meanCube.data[i])
    end
end


text:
__precompile__()

"""
Anonymous types are automatically generated types where the field names and field types are
based on the values provided to them.

This package provides syntax for creating instances of these types, as well as syntax for
dispatching to different methods based on their structural properties such as mutability,
field names, and field types.

The following exported macros are provided for public use.

*Type Instantiation:*

- [`@type`]({ref})
- [`@immutable`]({ref})

*Type Signatures:*

- [`@Anon`]({ref})
- [`@Type`]({ref})
- [`@Immutable`]({ref})
"""
module AnonymousTypes

using Base.Meta, Compat

# Dispatch macros.

export @Anon, @Type, @Immutable

abstract GeneratedType{mutable, fields, types}

"""
Create signature for anonymous (either mutable or immutable) types. Can be used in function
definitions as follows:

```julia
f(a :: @Anon(x, y), b :: @Anon(:: Integer, y :: Vector)) = ...
```

**Syntax**

Anonymous type with 2 fields, `a` and `b`:

```julia
@Anon(a, b)
```

Anonymous type with 3 unnamed fields of type `T_i` for `i = 1:3`:

```julia
@Anon(:: T_1, :: T_2, :: T_3)
```

Anonymous type with 1 field named `a` subtyping from `Integer`:

```julia
@Anon(a :: Integer)
```
"""
macro Anon(args...) buildsig(tvar(:M), args...) end

"Similar to [`@Anon`]({ref}) but limited to mutable types."
macro Type(args...) buildsig(true, args...) end

"Similar to [`@Anon`]({ref}) but limited to immutable types."
macro Immutable(args...) buildsig(false, args...) end

function buildsig(mutable, args...)
    fields, types = Any[], Any[]
    for (i, x) in enumerate(args)
        f, t = term(x, i)
        push!(fields, f)
        push!(types, t)
    end
    fields, types = map(esc, fields), map(esc, types)
    :(GeneratedType{$mutable, Tuple{$(fields...)}, Tuple{$(types...)}})
end

function term(x, n)
    F_n, T_n = symbol("F_", n), symbol("T_", n)
    isexpr(x, :(::), 1) ? (tvar(F_n),       xtvar(T_n, x.args[1])) :
    isexpr(x, :(::), 2) ? (quot(x.args[1]), xtvar(T_n, x.args[2])) :
    error("invalid syntax. $x")
end
term(s :: Symbol, n) = (quot(s), tvar(symbol("T_", n)))

tvar(s) = TypeVar(s, Any, true)

xtvar(s, x) = :(TypeVar($(quot(s)), $x, true))

# Construction macros.

export @type, @immutable

@eval macro $(:type)(args...) buildcall(:m, args...) end
"""
Create an anonymous mutable type instance.

**Examples**

```julia
t = @type x = 1 y = 2
t.x + t.y == 3
```

Variables may be used in place of `=` expressions:

```julia
x = 1
t = @type x y = 2
t.x + t.y == 3
```
"""
:(@type)

@eval macro $(:immutable)(args...) buildcall(:i, args...) end
"""
Create an anonymous immutable type instance.

See [`@type`]({ref}) for examples of use since, apart from their names, both macros support
the same set of features.
"""
:(@immutable)

function buildcall(kind, args...)
    # Types are generated on a per-module basis.
    modname = Val{hash(fullname(current_module()))}()
    names, values = Expr(:tuple), Expr(:tuple)
    for a in args
        addfields!(names.args, values.args, a)
    end
    :($(symbol(kind, "_struct"))($(esc(modname)), $(esc(names)), $(esc(values))...))
end

function addfields!(n, v, x)
    if isexpr(x, [:(=), :kw])
        push!(n, Val{x.args[1]}())
        push!(v, x.args[2])
    else
        error("invalid '@type'/'@immutable' syntax: '$x'")
    end
end
addfields!(n, v, s::Symbol) = (push!(n, Val{s}()); push!(v, s))

@generated m_struct(::Val, fields, args...) = struct(true,  fields, args...)
@generated i_struct(::Val, fields, args...) = struct(false, fields, args...)

function struct{T}(ismutable, ::Type{T}, args...)
    # Build type expression.
    fields = [x.parameters[1] for x in T.parameters]
    name   = typename(ismutable, fields, args)
    super  = GeneratedType{ismutable, Tuple{fields...}, Tuple{args...}}
    expr   = Expr(:type, ismutable, Expr(:(<:), name, super), quote end)

    expr.args[end].args = [:($x :: $y) for (x, y) in zip(fields, args)]

    # Avoid redefining the type if `struct` is run multiple times.
    isdefined(current_module(), name) || eval(current_module(), expr)

    # Return a new instance of the generated type.
    :($(current_module()).$(name)(args...))
end

function typename(ismutable, fields, args)
    id = join(["$f::$t" for (f, t) in zip(fields, args)], ", ")
    symbol("[generated $(ismutable ? "type" : "immutable")]#{$(id)}")
end

end # module

max_stars_repo_name: MichaelHatherly/AnonymousTypes

max_issues_repo_name: MichaelHatherly/AnonymousTypes

max_forks_repo_name: MichaelHatherly/AnonymousTypes


text:
@testset "Basis" begin include("./basis/basis.jl") end

@testset "Basis Generators" begin
   @variables u[1:3]
   @test all(isequal.(sin_basis(u, 1), sin.(1 .* u)))
   @test all(isequal.(cos_basis(u, 2), vcat(cos.(1 .* u), cos.(2 .*u))))
   @test all(isequal.(chebyshev_basis(u, 1), cos.( 1 .* acos.(u))))
   @test all(isequal.(fourier_basis(u, 1), sin.(1 .* u ./2)))
   @test all(isequal.(monomial_basis(u, 1), u.^1))
   @test all(isequal.(polynomial_basis(u, 2), [1; u[1]^1; u[1]^2; u[2]^1; u[1]^1*u[2]^1; u[2]^2; u[3]^1; u[1]^1*u[3]^1; u[2]^1*u[3]^1; u[3]^2]))

   @test all(isequal.(sin_basis(u, 1:2), vcat([sin.(i .* u) for i in 1:2]...)))
   @test all(isequal.(cos_basis(u, 1:5), vcat([cos.(i .* u) for i in 1:5]...)))
   @test all(isequal.(chebyshev_basis(u, [1;2]), vcat([cos.(i .* acos.(u)) for i in 1:2]...)))
   @test all(isequal.(fourier_basis(u, 1:2), vcat(sin.(1 .* u ./2), cos.( 2 .* u ./ 2))))
end


text:
using Test, MIDatasets

@test length(midatasets()) == 29

X, y = midataset("Musk1")
@test length(X) == length(y)

X, y, f = midataset("Musk1", folds=true)
@test length(f) == 5
@test length(f[1]) == 10
@test length(f[1][1]) == length(X)

@test_broken midataset("non-existing-dataset")


text:
using JuMP, DataStructures

mutable struct nodo
  nivel::Int64
  Model::JuMP.Model
  inf::Float64
  sup::Float64
  x_relax::Vector{Float64}
  frac::Vector{Float64}
  x_int::Vector{Float64}
  status::Symbol
end

function fractional(x,var_bin)
  s = length(var_bin)
  frac = Array{Float64,1}(s)

  for i=1:s
    frac[i] = modf(x[var_bin[i]])[1]
  end
  return frac
end

function branch(x,var_bin)
  f,i = findmin(abs(x-0.5))
  return var_bin[i]
end

function poda(lista_,sense,liminf,limsup, P)
  L = size(lista_)[1]
  erase = []
  P_ = 0
  for l=1:L
    if lista_[l].status == :Infeasible
      erase = copy([erase;[l]])
      P_ = P_ + 1
    elseif lista_[l].frac == 0
      erase = copy([erase;[l]])
      P_ = P_ + 1
    elseif (sense == :Max && lista_[l].sup <= liminf) ||(sense == :Min && lista_[l].inf >= limsup)
       erase = copy([erase;[l]])
       P_ = P_ + 1
    end
  end
  P =copy(P + P_)
  deleteat!(lista_,erase)
  return  P
end

function deep(m::JuMP.Model,var_bin,frac, solver::MathProgBase.AbstractMathProgSolver = JuMP.UnsetSolver())
    m_ = deepcopy(m)
    N = 1
    liminf = []
    limsup = []
    obj = []
    x_best = []
    x = []
    k = 1
    sense = m.objSense
    status1 = []
    status2 = []
   time = 0

    while frac != zeros(length(var_bin))
      tic()
      m1 = deepcopy(m_)
      m2 = deepcopy(m_)
      i_ = branch(frac,var_bin)
      if mod(k,2) == 0

         m1.colUpper[i_] = 0
         status1 = solve(m1, relaxation=true)
         x = copy(m1.colVal)
         obj = copy(m1.objVal)
         frac = fractional(x,var_bin)
         m_ = deepcopy(m1)
      elseif  mod(k,2) == 1

        m2.colLower[i_] = 1
        status2 = solve(m2, relaxation=true)
        x = copy(m2.colVal)
        obj = copy(m2.objVal)
        frac = fractional(x,var_bin)
        m_ = deepcopy(m2)
      end
     time_aux = toc()
     time = time + time_aux
      if status1 == :Infeasible && status2 == :Optimal
        m_ = deepcopy(m2)
      elseif status2 == :Infeasible && status1 == :Optimal
        m_ = deepcopy(m1)
      elseif  status1 == :Infeasible && status2 == :Infeasible
      break
      end
      if time >= 120
        break
      end
      k = k + 1
      N = N + 1
    end

  if sense == :Max
    if frac == zeros(length(var_bin))
     liminf = copy(obj)
     x_best = copy(x)
    else
     liminf = -Inf
     N = Inf
   end
  else
    if frac == zeros(length(var_bin))
       limsup = copy(obj)
       x_best = copy(x)
    else
       limsup = Inf
       N = Inf
   end
  end

return liminf, limsup, x_best,N
end

function largura(lista,sense,var_bin,liminf,limsup)
  liminf_ = copy(liminf)
  limsup_ = copy(limsup)
  Podas_aux = 0
  AUX = []
  int_sol = []
  x_best = []
  IntSol = 0
  lista_aux = copy(lista)
  Nivel = 5000
  k = 1
  time = 0
  sol = []
  time_aux = 0
  Visit_ = 0
  Visit_aux = 0
   while k <= Nivel && IntSol == 0
     tic()
     L = length(lista_aux)
     Visit_aux = copy(L)
     for l=1:L
        filhos(lista_aux[l],lista_aux,var_bin,sense,liminf_,limsup_)
     end
     L = length(lista_aux)
     erase = []
     for l=1:L
       if lista_aux[l].nivel == k - 1
         erase = copy([erase;[l]])
       end
     end
     deleteat!(lista_aux,erase)
     liminf_, limsup_, AUX, int_sol, IntSol  = gap(lista_aux,sense,liminf_,limsup_,AUX,int_sol,IntSol)
     Podas_aux = poda(lista_aux,sense,liminf,limsup,Podas_aux)
     k = k + 1
     time_aux = toc()
     time = time + time_aux
     Visit_ = Visit_ + Visit_aux
     if time >= 350
       break
     end
   end
   if AUX != []
     if sense == :Max
         t,r = size(AUX)
         for i=1:t
           if liminf_ == AUX[i,1]
             x_best = AUX[i,2:end]
             sol = liminf_
           end
         end
       else
         t,r = size(AUX)
         for i=1:t
           if limsup_ == AUX[i,1]
             x_best = AUX[i,2:end]
             sol = limsup_
           end
         end
     end
   end
   if sense == :Max
     if IntSol == 0
        liminf_ = -Inf
    end
   else
     if IntSol == 0
        limsup_ = Inf
    end
   end
   return liminf_, limsup_, x_best, time, Podas_aux, k, sol, Visit_, IntSol
end

function filhos(pai,lista_,var_bin,sense,liminf,limsup)
  #############################################################################
  # Nodo filho 1
  #############################################################################
    m1 = deepcopy(pai.Model)
    frac = copy(pai.frac)
    i_ = branch(frac,var_bin)
    m1.colUpper[i_] = 0
    status = solve(m1, relaxation=true)
    x = copy(m1.colVal)
    obj = copy(m1.objVal)
    frac = fractional(x,var_bin)

    if sense == :Max
      sup = copy(obj)
      inf = liminf
    else
      inf = copy(obj)
      sup = limsup
    end

    if frac == zeros(length(var_bin))
      x_int = copy(x)
    else
      x_int = []
    end
  nivel = pai.nivel + 1
  filho1 = nodo(nivel,m1,inf,sup,x,frac,x_int,status)
  push!(lista_,filho1)

  #############################################################################
  # Nodo filho 2
  #############################################################################
  m2 = deepcopy(pai.Model)
  m2.colLower[i_] = 1
  status = solve(m2, relaxation=true)
  x = copy(m2.colVal)
  obj = copy(m2.objVal)
  frac = fractional(x,var_bin)

  if sense == :Max
    sup = copy(obj)
    inf = copy(liminf)
  else
    inf = copy(obj)
    sup = copy(limsup)
  end

  if frac  == zeros(length(var_bin))
    x_int = copy(x)
  else
    x_int = []
  end

  filho2 = nodo(nivel,m2,inf,sup,x,frac,x_int,status)
  push!(lista_,filho2)
return nothing
end

function selection(lista,sense,liminf,limsup)
  pai = []
  l = []
  L = length(lista)
  for i=1:L
    if sense == :Max && lista[i].sup == limsup
       pai = lista[i]
       l = i
    elseif sense == :Min && lista[i].inf == liminf
      pai = lista[i]
      l = i
    end
  end
  return pai, l
end

function gap(lista,sense,liminf,limsup,AUX,int_sol,IntSol)
  ##############################################################################
  # Gap
  ##############################################################################

  SUP = []
  INFI = []

  L = length(lista)
    if sense ==:Max
      for l=1:L
        if  lista[l].status != :Infeasible && lista[l].status != :Unbounded
          SUP = copy([SUP;[lista[l].sup]])
        end
        if lista[l].x_int != []
            int_sol = copy([int_sol;[lista[l].sup]])
            IntSol = IntSol + 1
            AUX = copy([AUX;Matrix([lista[l].sup lista[l].x_relax'])])
          else
            int_sol = copy([int_sol;[liminf]])
        end
      end
      limsup = maximum(SUP)
      liminf = maximum(int_sol)
    else
      for l=1:L
        if lista[l].status != :Infeasible && lista[l].status != :Unbounded
         INFI = copy([INFI;[lista[l].inf]])
       end
        if lista[l].x_int != []
          int_sol = copy([int_sol;[lista[l].inf]])
          IntSol = IntSol + 1
          AUX = copy([AUX;Matrix([lista[l].inf lista[l].x_relax'])])
        else
          int_sol = copy([int_sol;[limsup]])
        end
      end
      liminf = minimum(INFI)
      limsup = minimum(int_sol)
    end
    return liminf, limsup, AUX, int_sol,IntSol
end

function BNB(m::JuMP.Model, solver::MathProgBase.AbstractMathProgSolver = JuMP.UnsetSolver())

  #-----------------------------------------------------------------------------
  # Nodo raiz
  #-----------------------------------------------------------------------------
  # inicialização da Lista
  m.ext[:time] = []
  m.ext[:status] = []
  m.ext[:nodes] = []
  m.ext[:Podas] = []
  m.ext[:Iter] = []
  m.ext[:intsols] = []
  Tempo = 0
  lista = []
  sol = []
  x_best = []
  IntSol = 0
  AUX = []
  # Relaxação linear

  m_ = deepcopy(m)
  status = solve(m_, relaxation=true)
  x = copy(m_.colVal)
  obj = copy(m_.objVal)

  sense = m_.objSense

  index = m_.colCat
  var_bin = []
  for  i =1:size(index)[1]
    if index[i] == :Bin
      var_bin = copy([var_bin;[i]])
    end
  end

  frac = fractional(x,var_bin)

  if frac == zeros(length(var_bin))
    m.objVal = copy(obj)
    m.colVal = copy(x)
    m.objBound = copy(obj)
    m.ext[:time] = 0
    m.ext[:status] = status
    m.ext[:nodes] = 0
    m.ext[:Podas] = 0
    m.ext[:Iter] = 0
    m.ext[:intsols] = 1
    return nothing
  end

  if status == :Infeasible
    m.objVal = NaN
    m.colVal = []
    m.objBound = NaN
    m.ext[:time] = 0
    m.ext[:status] = status
    m.ext[:nodes] = 0
    m.ext[:Podas] = 0
    m.ext[:Iter] = 0
    m.ext[:intsols] = 0
    return nothing
  end

 liminf, limsup, x_best, Max_nivel = deep(m_,var_bin,frac)

 if x_best != []
   IntSol = 1
 end

  if sense == :Max
    sup = copy(obj)
    inf = copy(liminf)
    limsup = copy(obj)
  else
    inf = copy(obj)
    sup = copy(limsup)
    liminf = copy(obj)
  end

raiz = nodo(0,m_,inf,sup,x,frac,[],status)

# Dados iniciais
nivel = 1
ϵ = limsup - liminf
iter = 1

push!(lista, raiz)

Visit_ = 0
if x_best ==[]
  liminf_, limsup_, x_best, time, Podas_aux, iter_aux, sol, Visit_, IntSol = largura(lista,sense,var_bin,liminf,limsup)
  ϵ_aux = limsup_ - liminf_
  if x_best !=[] && ϵ_aux <= 1.0e-1
      m.objVal = sol
      m.colVal = x_best
      if sense == :Max
        m.objBound = limsup_
      else
        m.objBound = liminf_
      end
      m.ext[:time] = time
      m.ext[:status] = status
      m.ext[:nodes] = Visit_
      m.ext[:Podas] = Podas_aux
      m.ext[:Iter] = iter_aux
      m.ext[:intsols] = IntSol
      return nothing
  elseif x_best !=[] && ϵ_aux > 1.0e-1
      if sense == :Max
        liminf = copy(liminf_)
      else
        limsup = copy(limsup_)
      end
  end
end

L = 1
int_sol = []

ϵ = limsup - liminf
iter = 1
Visit = 0
Podas = 0

tempo_aux = 0

Max_iter =5000

while ϵ >= 1.0e-1 && iter <= Max_iter
  tic()
  #############################################################################
  # Seleção do problema da lista para fazer branch
  #############################################################################
  pai, l = selection(lista,sense,liminf,limsup)
  deleteat!(lista,l)
  Visit = Visit + 1 # Número do nós onde se fez branch
  #############################################################################
  # Adicionar os nós filhos do problema selecionado da lista
  #############################################################################
  filhos(pai,lista,var_bin,sense,liminf,limsup)
  #############################################################################
  # Atualização do lowere (upper bound) para o problema de Min (Max)
  #############################################################################
  liminf, limsup, AUX, int_sol, IntSol = gap(lista,sense,liminf,limsup,AUX,int_sol,IntSol)
  #############################################################################
  # Podas da árvore
  #############################################################################
  Podas = poda(lista,sense,liminf,limsup,Podas)
  #############################################################################
  # Atualização do upper (lower) bound pra o problema de Min (Max)
  #############################################################################
   L = size(lista)[1]
   ϵ = limsup - liminf # Atualização do ϵ e do x_best (melhor solução inteira)

    if AUX != []
      if sense == :Max
          t,r = size(AUX)
          for i=1:t
            if liminf == AUX[i,1]
              x_best = AUX[i,2:end]
              sol = liminf
            end
          end
        else
          t,r = size(AUX)
          for i=1:t
            if limsup == AUX[i,1]
              x_best = AUX[i,2:end]
              sol = limsup
            end
          end
      end
    end
    tempo_aux = toc()
    Tempo = Tempo + tempo_aux
    iter = copy(iter) + 1
    if Tempo >= 300
      break
    end
end

if iter - 1 == Max_iter &&  ϵ > 1.0e-1 && x_best != []
  status = :Subotimal
  if sense == :Max
    sol = copy(liminf)
  else
    sol = copy(limsup)
  end
elseif iter - 1 == Max_iter && x_best == []
  status = :unsolved
  sol = NaN
elseif lista == [] && x_best == []
  status = :Infeasible
  sol = NaN
else
  status = :Optimal
end
#############################################################################
# Prenchimento dos outputs
#############################################################################
m.objVal = sol
m.colVal = x_best
if sense == :Max
  m.objBound = limsup
else
  m.objBound = liminf
end
m.ext[:time] = Tempo
m.ext[:status] = status
m.ext[:nodes] = Visit
m.ext[:Podas] = Podas
m.ext[:Iter] = iter
m.ext[:intsols] = IntSol

return nothing

end


text:
using Images, Test, Colors, Graphics

global checkboard

@testset "Edge" begin

    @testset "imedge" begin
        img = zeros(8, 10)
        img[:, 5] .= 1
        grad_y, grad_x, mag, orient = imedge(img)
        @test all(x->x==0, grad_y)
        target_x = zeros(8, 10); target_x[:, 4] .= 0.5; target_x[:, 6] .= -0.5
        @test grad_x == target_x
        @test mag == abs.(grad_x)
        target_orient = zeros(8, 10); target_orient[:, 6] .= pi
        @test orient ≈ target_orient
    end

    EPS = 1e-14

    kernelmethods = (KernelFactors.sobel, KernelFactors.prewitt, KernelFactors.ando3,
                     KernelFactors.ando4, KernelFactors.ando5)

    ## Checkerboard array, used to test image gradients
    white(::Type{T}) where {T} = oneunit(T)
    black(::Type{T}) where {T} = zero(T)
    white(::Type{T}) where {T<:Unsigned} = typemax(T)
    black(::Type{T}) where {T<:Unsigned} = typemin(T)

    function checkerboard(::Type{T}, sq_width::Integer, count::Integer) where T
        wh = fill(white(T), (sq_width,sq_width))
        bk = fill(black(T), (sq_width,sq_width))
        bw = [wh bk; bk wh]
        vert = repeat(bw, (count>>1), 1)
        isodd(count) && (vert = vcat(vert, [wh bk]))
        cb = repeat(vert, 1, (count>>1))
        isodd(count) && (cb = hcat(cb, vert[:,1:sq_width]))
        cb
    end

    checkerboard(sq_width::Integer, count::Integer) = checkerboard(UInt8, sq_width, count)

    #Canny Edge Detection
    @testset "Canny Edge Detection" begin
        #General Checks
        img = zeros(10, 10)
        edges = canny(img, (0.8, 0.2))
        @test eltype(edges) == Bool
        @test all(.!edges)

        #Box Edges

        img[2:end-1, 2:end-1] .= 1
        edges = canny(img, (Percentile(80), Percentile(20)))
        @test all(edges[2:end-1, 2])
        @test all(edges[2:end-1, end-1])
        @test all(edges[2, 2:end-1])
        @test all(edges[end-1, 2:end-1])
        @test all(.!edges[3:end-2, 3:end-2])

        edges = canny(img, (0.9/8, 0.2/8), 1.4)
        @test all(edges[2:end-1, 2])
        @test all(edges[2:end-1, end-1])
        @test all(edges[2, 2:end-1])
        @test all(edges[end-1, 2:end-1])
        @test all(.!edges[3:end-2, 3:end-2])

        #Checkerboard - Corners are not detected as Edges!
        img = checkerboard(Gray, 5, 3)
        edges = canny(img, (Percentile(80), Percentile(20)), 1.4)
        @test eltype(edges) == Bool
        id = [1,2,3,4,6,7,8,9,10,12,13,14,15]
        @test all(.!edges[id, id])
        id = [5, 11]
        id2 = [1,2,3,4,7,8,9,12,13,14,15]
        id3 = [5,6,10,11]
        @test all(edges[id, id2])
        @test all(edges[id2, id])
        @test all(.!edges[id, id3])
        @test all(.!edges[id3, id])

        #Diagonal Edge
        img = zeros(10,10)
        img[diagind(img)] .= 1
        img[diagind(img, 1)] .= 1
        img[diagind(img, -1)] .= 1
        edges = canny(img, (Percentile(80),Percentile(20)))
        @test eltype(edges) == Bool
        @test all(edges[diagind(edges, 2)])
        @test all(edges[diagind(edges, -2)])
        nondiags = setdiff(1:1:100, union(diagind(edges, 2), diagind(edges, -2)))
        @test all(.!edges[nondiags])

        #Checks Hysteresis Thresholding
        img = fill(oneunit(Gray{N0f8}), (10, 10))
        img[3:7, 3:7] .= 0.0
        img[4:6, 4:6] .= 0.7
        thresholded = Images.hysteresis_thresholding(img, 0.9, 0.8)
        @test all(thresholded[3:7, 3:7] .== 0.0)
        @test all(thresholded[1:2, :] .== 0.9)
        @test all(thresholded[:, 1:2] .== 0.9)
        @test all(thresholded[8:10, :] .== 0.9)
        @test all(thresholded[:, 8:10] .== 0.9)

        thresholded = Images.hysteresis_thresholding(img, 0.9, 0.6)
        @test all(thresholded[4:6, 4:6] .== 0.5)
        @test all(thresholded[3:7, 3:7] .< 0.9)
        @test all(thresholded[1:2, :] .== 0.9)
        @test all(thresholded[:, 1:2] .== 0.9)
        @test all(thresholded[8:10, :] .== 0.9)
        @test all(thresholded[:, 8:10] .== 0.9)

        img[3, 5] = 0.7
        thresholded = Images.hysteresis_thresholding(img, 0.9, 0.6)
        @test all(thresholded[4:6, 4:6] .== 0.9)
        @test all(thresholded[3:7, 3] .== 0.0)
        @test all(thresholded[3:7, 7] .== 0.0)
        @test all(thresholded[7, 3:7] .== 0.0)
        @test all(vec(thresholded[3, 3:7]) .== [0.0, 0.0, 0.9, 0.0, 0.0])
        @test all(thresholded[1:2, :] .== 0.9)
        @test all(thresholded[:, 1:2] .== 0.9)
        @test all(thresholded[8:10, :] .== 0.9)
        @test all(thresholded[:, 8:10] .== 0.9)

        # Issue #665
        @test_throws MethodError canny(rand(4, 5))
        @test isa(canny(rand(4, 5), (0.8, 0.2)), Matrix{Bool})
    end

    SZ=5
    cb_array    = checkerboard(SZ,3)

    cb_gray = Gray.(normedview(cb_array))
    cb_rgb = convert(Array{RGB}, cb_gray)
    cb_rgbf64 = convert(Array{RGB{Float64}}, cb_gray)

    # TODO: now that all of these behave nearly the same, put in a
    # loop over the array type (only have to adjust tests for `red`)
    @testset "Checkerboard" begin
        for method in kernelmethods
            ## Checkerboard array

            (agy, agx) = imgradients(cb_array, method)
            amag = magnitude(agx, agy)
            agphase = phase(agx, agy)
            @test (amag, agphase) == magnitude_phase(agx, agy)

            @test agx[1,SZ] < 0
            @test agx[1,2*SZ] > 0
            @test agy[SZ,1] < 0
            @test agy[2*SZ,1] > 0

            # Test direction of increasing gradient
            @test cos(agphase[1,SZ])   - (-1.0) < EPS  # increasing left  (=  pi   radians)
            @test cos(agphase[1,2*SZ]) -   1.0  < EPS  # increasing right (=   0   radians)
            @test sin(agphase[SZ,1])   -   1.0  < EPS  # increasing up    (=  pi/2 radians)
            @test sin(agphase[2*SZ,1]) - (-1.0) < EPS  # increasing down  (= -pi/2 radians)

            # Test that orientation is perpendicular to gradient
            aorient = orientation(agx, agy)
            @test all((cos.(agphase) .* cos.(aorient) .+
                       sin.(agphase) .* sin.(aorient) .< EPS) .|
                      ((agphase .== 0.0) .& (aorient .== 0.0)))
                      # this part is where both are zero because there is no gradient

            ## Checkerboard with Gray pixels

            (gyg, gxg) = imgradients(cb_gray, method)
            magg = magnitude(gxg, gyg)
            gphaseg = phase(gxg, gyg)
            @test (magg, gphaseg) == magnitude_phase(gxg, gyg)
            @test gyg[SZ,1]   < 0     # white to black transition
            @test gyg[2*SZ,1] > 0  # black to white transition
            @test gxg[1,SZ]   < 0     # white to black transition
            @test gxg[1,2*SZ] > 0  # black to white transition

            @test cos(gphaseg[1,SZ])   - (-1.0) < EPS  # increasing left  (=  pi   radians)
            @test cos(gphaseg[1,2*SZ]) -   1.0  < EPS  # increasing right (=   0   radians)
            @test sin(gphaseg[SZ,1])   -   1.0  < EPS  # increasing up    (=  pi/2 radians)
            @test sin(gphaseg[2*SZ,1]) - (-1.0) < EPS  # increasing down  (= -pi/2 radians)

            # Test that orientation is perpendicular to gradient
            orientg = orientation(gxg, gyg)
            @test all((cos.(gphaseg) .* cos.(orientg) .+
                       sin.(gphaseg) .* sin.(orientg) .< EPS) .|
                      ((gphaseg .== 0.0) .& (orientg .== 0.0)))
                      # this part is where both are zero because there is no gradient

            ## Checkerboard with RBG pixels

            (gy_rgb, gx_rgb) = imgradients(cb_rgb, method)
            mag_rgb = magnitude(gx_rgb, gy_rgb)
            gphase_rgb = phase(gx_rgb, gy_rgb)
            @test (mag_rgb, gphase_rgb) == magnitude_phase(gx_rgb, gy_rgb)
            @test red(gy_rgb[SZ,1])   < 0     # white to black transition
            @test red(gy_rgb[2*SZ,1]) > 0  # black to white transition
            @test red(gx_rgb[1,SZ])   < 0     # white to black transition
            @test red(gx_rgb[1,2*SZ]) > 0  # black to white transition

            @test cos(gphase_rgb[1,SZ])   - (-1.0) < EPS  # increasing left  (=  pi   radians)
            @test cos(gphase_rgb[1,2*SZ]) -   1.0  < EPS  # increasing right (=   0   radians)
            @test sin(gphase_rgb[SZ,1])   -   1.0  < EPS  # increasing up    (=  pi/2 radians)
            @test sin(gphase_rgb[2*SZ,1]) - (-1.0) < EPS  # increasing down  (= -pi/2 radians)

            # Test that orientation is perpendicular to gradient
            orient_rgb = orientation(gx_rgb, gy_rgb)
            @test all((cos.(gphase_rgb) .* cos.(orient_rgb) .+
                       sin.(gphase_rgb) .* sin.(orient_rgb) .< EPS) .|
                      ((gphase_rgb .== 0.0) .& (orient_rgb .== 0.0)))
                      # this part is where both are zero because there is no gradient

            ## Checkerboard Image with RBG{Float64} pixels

            (gy_rgb, gx_rgb) = imgradients(cb_rgbf64, method)
            mag_rgb = magnitude(gx_rgb, gy_rgb)
            gphase_rgb = phase(gx_rgb, gy_rgb)
            @test (mag_rgb, gphase_rgb) == magnitude_phase(gx_rgb, gy_rgb)
            @test red(gy_rgb[SZ,1])   < 0     # white to black transition
            @test red(gy_rgb[2*SZ,1]) > 0  # black to white transition
            @test red(gx_rgb[1,SZ])   < 0     # white to black transition
            @test red(gx_rgb[1,2*SZ]) > 0  # black to white transition

            @test cos(gphase_rgb[1,SZ])   - (-1.0) < EPS  # increasing left  (=  pi   radians)
            @test cos(gphase_rgb[1,2*SZ]) -   1.0  < EPS  # increasing right (=   0   radians)
            @test sin(gphase_rgb[SZ,1])   -   1.0  < EPS  # increasing up    (=  pi/2 radians)
            @test sin(gphase_rgb[2*SZ,1]) - (-1.0) < EPS  # increasing down  (= -pi/2 radians)

            # Test that orientation is perpendicular to gradient
            orient_rgb = orientation(gx_rgb, gy_rgb)
            @test all((cos.(gphase_rgb) .* cos.(orient_rgb) .+
                       sin.(gphase_rgb) .* sin.(orient_rgb) .< EPS) .|
                      ((gphase_rgb .== 0.0) .& (orient_rgb .== 0.0)))
                      # this part is where both are zero because there is no gradient
        end
    end

    @testset "Diagonals" begin
        # Create an image with white along diagonals -2:2 and black elsewhere
        m = zeros(UInt8, 20,20)
        for i = -2:2; m[diagind(m,i)] .= 0xff; end

        for method in kernelmethods
            ## Diagonal array

            (agy, agx) = imgradients(m, method)
            amag = magnitude(agx, agy)
            agphase = phase(agx, agy)
            @test magnitude_phase(agx, agy) == (amag, agphase)
            @test agx[7,9]  < 0     # white to black transition
            @test agx[10,8] > 0  # black to white transition
            @test agy[10,8] < 0     # white to black transition
            @test agy[7,9]  > 0  # black to white transition

            # Test direction of increasing gradient
            @test abs(agphase[10,8] -    pi/4 ) < EPS  # lower edge (increasing up-right  =   pi/4 radians)
            @test abs(agphase[7,9]  - (-3pi/4)) < EPS  # upper edge (increasing down-left = -3pi/4 radians)

            # Test that orientation is perpendicular to gradient
            aorient = orientation(agx, agy)
            @test all((cos.(agphase) .* cos.(aorient) .+
                       sin.(agphase) .* sin.(aorient) .< EPS) .|
                      ((agphase .== 0.0) .& (aorient .== 0.0)))
                    # this part is where both are zero because there is no gradient
        end
    end

    # Nonmaximal suppression

    function thin_edges(img)
        # Get orientation
        gy,gx = imgradients(img, KernelFactors.ando3)
        orient = phase(gx,gy)

        # Do NMS thinning
        thin_edges_nonmaxsup_subpix(img, orient, radius=1.35)
    end

    function nms_test_horiz_vert(img, which)
        ## which = :horizontal or :vertical

        # Do NMS thinning
        t,s = thin_edges(img)

        # Calc peak location by hand

        # Interpolate values 1.35 pixels left and right
        # Orientation is zero radians -> to the right
        v1 = 6 - 0.35   # slope on right is 1
        v2 = 5 - 0.35*2 # slope on left is 2
        c = 7.0         # peak value

        # solve v = a*r^2 + b*r + c
        a = (v1 + v2)/2 - c
        b = a + c - v2
        r = -b/2a

        @test abs(r - 1/6) < EPS
        # Location and value at peak
        peakloc = r*1.35 + 3
        peakval = a*r^2 + b*r + c

        horizontal = which == :horizontal

        if !horizontal
            @test all(t[:,[1,2,4,5]] .== 0)
            @test all(t[:,3]   .== peakval)
            @test all(map(x->x==zero(Graphics.Point), s[:,[1,2,4,5]]))
        else
            @test all(t[[1,2,4,5],:] .== 0)
            @test all(t[3,:]   .== peakval)
            @test all(map(x->x==zero(Graphics.Point), s[[1,2,4,5],:]))
        end

        if which == :horizontal
            @test     [pt.x for pt in s[3,:]]  == [1:5;]
            @test all([pt.y for pt in s[3,:]] .== peakloc)
        else
            @test all([pt.x for pt in s[:,3]] .== peakloc)
            @test     [pt.y for pt in s[:,3]]  == [1:5;]
        end
    end

    @testset "Nonmax suppression vertical edge" begin
        # Test image: vertical edge
        m = [3.0  5.0  7.0  6.0  5.0
             3.0  5.0  7.0  6.0  5.0
             3.0  5.0  7.0  6.0  5.0
             3.0  5.0  7.0  6.0  5.0
             3.0  5.0  7.0  6.0  5.0]

        nms_test_horiz_vert(m, :vertical)
    end

    @testset "Nonmax suppression horizontal edge" begin
        # Test image: horizontal edge
        m = [3.0  5.0  7.0  6.0  5.0
             3.0  5.0  7.0  6.0  5.0
             3.0  5.0  7.0  6.0  5.0
             3.0  5.0  7.0  6.0  5.0
             3.0  5.0  7.0  6.0  5.0]
        m = m'

        nms_test_horiz_vert(m, :horizontal)
    end

function nms_test_diagonal(img)
    # Do NMS thinning
    t,s = thin_edges(img)

    # Calc peak location by hand

    # Interpolate values 1.35 pixels up and left, down and right
    # using bilinear interpolation
    # Orientation is π/4 radians -> 45 degrees up
    fr = 1.35*cos(π/4)
    lower = (7 + fr*(6-7))
    upper = (6 + fr*(5-6))
    v1 = lower + fr*(upper-lower)

    lower = (7 + fr*(5-7))
    upper = (5 + fr*(3-5))
    v2 = lower + fr*(upper-lower)

    c = 7.0         # peak value

    # solve v = a*r^2 + b*r + c
    a = (v1 + v2)/2 - c
    b = a + c - v2
    r = -b/2a

    @test (r - 1/6) < EPS

    # Location and value at peak

    x_peak_offset, y_peak_offset = r*fr, -r*fr
    peakval = a*r^2 + b*r + c

    @test all(diag(t)[2:4] .== peakval)
    @test all(t - diagm(0 => diag(t)) .== 0)

    diag_s = diagm(0 => diag(s))
    @test s == diag_s

    @test all([pt.x for pt in diag(s)[2:4]] - ((2:4) .+ x_peak_offset) .< EPS)
    @test all([pt.y for pt in diag(s)[2:4]] - ((2:4) .+ y_peak_offset) .< EPS)

end

    @testset "Nonmax suppression diagonal" begin
        # Test image: diagonal edge
        m = [7.0  6.0  5.0  0.0  0.0
             5.0  7.0  6.0  5.0  0.0
             3.0  5.0  7.0  6.0  5.0
             0.0  3.0  5.0  7.0  6.0
             0.0  0.0  3.0  5.0  7.0]

        nms_test_diagonal(m)
    end

end

nothing


text:
#=
WE estimation of the probability of for a diffusion with X(0) = x₀ satisfying
X(T) ∈ B for the Muller potential.
=#

using Statistics
using Printf

include("muller_setup.jl");
using WeightedEnsemble

# number of coarse steps in WE
n_we_steps = 10;
# number of time steps during mutation step
nΔt_coarse = Int(nΔt / n_we_steps);
# number of samples in coarse matrix
n_samples_per_bin = 10^2;
# ensemble size
n_particles = 10^2;

# define bin structure using Voronoi
xc = LinRange(-1.5, 1, 7)
yc = LinRange(-0.5, 2, 7)
voronoi_pts = Array{Float64,1}[];
for x in xc, y in yc
    # only include points that are likely to be accessed
    if (V([x, y]) < 250)
        push!(voronoi_pts, [x, y])
    end
end
B₀, bin_id, rebin! = setup_Voronoi_bins(voronoi_pts);

opts = MDOptions(n_iters = nΔt_coarse, n_save_iters = nΔt_coarse)
mutation! = x -> sample_trajectory!(x, sampler, options = opts);

# construct coarse model
Random.seed!(100);
x0_vals = copy(voronoi_pts);
n_bins = length(B₀);
K̃ = WeightedEnsemble.build_coarse_transition_matrix(mutation!, bin_id, x0_vals, n_bins, n_samples_per_bin);

# define coarse observable as a bin function
f̃ = f.(voronoi_pts);
_, v²_vectors = WeightedEnsemble.build_coarse_vectors(n_we_steps, K̃, float.(f̃));
v² = (x, t) -> v²_vectors[t+1][bin_id(x)]
# define selection function
selection! = (E, B, t)-> optimal_selection!(E, B, v², t)
# selection! = (E, B, t)-> uniform_selection!(E, B, t)

we_sampler = WEsampler(mutation!, selection!, rebin!);

# set up ensemble
E₀ = Dirac_to_Ensemble(x₀, n_particles);
rebin!(E₀, B₀, 0);

# run
E = deepcopy(E₀);
B = deepcopy(B₀);
Random.seed!(200)
run_we!(E, B, we_sampler, n_we_steps);
p_est = f.(E.ξ) ⋅ E.ω
@printf("WE Estimate = %g\n", p_est)

max_stars_repo_name: gideonsimpson/JuWeightedEnsemble

max_issues_repo_name: gideonsimpson/JuWeightedEnsemble

max_forks_repo_name: gideonsimpson/JuWeightedEnsemble


text:
# elastic-net regularization

"""
  ElasticNet(λ::Real=1.0, μ::Real=1.0)

Returns the function `g(x) = μ||x||_1 + (λ/2)||x||²`, for a real parameters `μ, λ ⩾ 0`.
"""

immutable ElasticNet{R <: Real} <: ProximableFunction
  mu::R
  lambda::R
  function ElasticNet(mu::R, lambda::R)
    if lambda < 0 || mu < 0
      error("parameters μ, λ must be nonnegative")
    else
      new(mu, lambda)
    end
  end
end

ElasticNet{R <: Real}(mu::R=1.0, lambda::R=1.0) = ElasticNet{R}(mu, lambda)

function (f::ElasticNet){T <: RealOrComplex}(x::AbstractArray{T})
  return f.mu*vecnorm(x,1) + (f.lambda/2)*vecnorm(x,2)^2
end

function prox!{T <: Real}(f::ElasticNet, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)
  sqnorm2x = zero(Float64)
  norm1x = zero(Float64)
  gm = gamma*f.mu
  gl = gamma*f.lambda
  for i in eachindex(x)
    y[i] = (x[i] + (x[i] <= -gm ? gm : (x[i] >= gm ? -gm : -x[i])))/(1 + gl)
    sqnorm2x += abs2(y[i])
    norm1x += abs(y[i])
  end
  return f.mu*norm1x + (f.lambda/2)*sqnorm2x
end

function prox!{T <: Complex}(f::ElasticNet, x::AbstractArray{T}, y::AbstractArray{T}, gamma::Real=1.0)
  sqnorm2x = zero(Float64)
  norm1x = zero(Float64)
  gm = gamma*f.mu
  gl = gamma*f.lambda
  for i in eachindex(x)
    y[i] = sign(x[i])*max(0, abs(x[i]) - gm)/(1 + gl)
    sqnorm2x += abs2(y[i])
    norm1x += abs(y[i])
  end
  return f.mu*norm1x + (f.lambda/2)*sqnorm2x
end

fun_name(f::ElasticNet) = "elastic-net regularization"
fun_dom(f::ElasticNet) = "AbstractArray{Real}, AbstractArray{Complex}"
fun_expr(f::ElasticNet) = "x ↦ μ||x||_1 + (λ/2)||x||²"
fun_params(f::ElasticNet) = "μ = $(f.mu), λ = $(f.lambda)"

function prox_naive{T <: RealOrComplex}(f::ElasticNet, x::AbstractArray{T}, gamma::Real=1.0)
  uz = max.(0, abs.(x) - gamma*f.mu)/(1 + f.lambda*gamma);
  return sign.(x).*uz, f.mu*vecnorm(uz,1) + (f.lambda/2)*vecnorm(uz)^2
end


text:
__precompile__()

module ECharts

	using JSON, DataFrames

	import Base.print, Base.show

	include("constructors.jl")
	include("render.jl")

end


text:
using DelimitedFiles
using PGFPlotsX

loadcsv(n) = (
	open(n) do f
	    return readdlm(f, skipstart=1)
	end)
table(data) = Table([:x => vec(7:length(data)), :y => vec(data[7:end])])
addtoitems!(items, n, color, mark, style) = begin
	t = table(loadcsv(n))
	options = [color, "only marks", style, "mark=$mark"]
	_p = Plot(@pgf({options...}), t)
    push!(items, _p)
    options = [color, style]
    _p = Plot(@pgf({options...}), t)
    push!(items, _p)
    return items
end
styles = vec(["solid"
"densely dashed"
"dashed"
"densely dotted"
"dotted"
"loosely dotted"])
colors = vec(["red" "green" "blue" "magenta" "black" "yellow"  "brown"  "teal"  "orange"  "violet"  "cyan"  "gray"])
marks = vec(["*" "square*" "triangle*" "star" "pentagon*" "diamond*" "otimes*" "p" "a"])

items = []

# ["bend_hex_spectrum_full", "bend_hex_spectrum_underintegrated", "bend_hex_spectrum_ms", "bend_hex_spectrum_im"]
for (j, basen) in enumerate(["bend_hex_spectrum_full", "bend_hex_spectrum_im"])
	for (i, aspect) in enumerate([1.0 10.0 100.0 1000.0])
		tag = "aspect=$(aspect)"
		n = "$(basen)-$(tag).csv"
		addtoitems!(items, n, colors[j], marks[j], styles[i])
	end
end

@pgf _a = SemiLogYAxis({
	xlabel = "Mode [ND]",
	ylabel = "Generalized stiffness [N/m]",
	grid="major",
	legend_pos  = "north west"
	},
	items...)
display(_a)


text:
export  calculateMultiIndices,
        findUnivariateIndices

function calculateMultiIndices(d::Int, n::Int)
    # d denotes dimension of random variables/number of sources of uncertainty,
    # n the maximum degree of multivariate basis
    # function to calculate indices of multivariate basis following the algorithm
    # from "Spectral Methods for Uncertainty Quantiﬁcation; Le Maitre, Knio;2014" p.516-517
    # No::BigInt = factorial(BigInt(d+n))/(factorial(Bigint(d))*factorial(BigInt(n)));  #number of polynomials of multivariate basis
  n < 0 && throw(DomainError(n, "maximum degree must be non-negative"))
  d <= 0 && throw(DomainError(d, "number of uncertainties must be positive"))
  # catch case n == 0 --> No-d==0
  n == 0 && return zeros(Int64,1,d)
  # non-pathological cases begin here
  No = numberPolynomials(d,n)
  inds = vcat(zeros(Int64,1,d),Matrix(1I,d,d),zeros(Int64, No-d-1, d));  #initiate index matrix for basis
  pi=ones(Int64,No,d);

  for k in 2:No
    g = 0;
    for l in 1:d
      pi[k,l]=sum(pi[k-1,:])-g;
      g=g+pi[k-1,l];
    end
  end

  P = d + 1;
  for k in 2:n
    L = P;
    for j in 1:d, m in L-pi[k,j]+1:L
        P += 1;
        inds[P,:] = inds[m,:];
        inds[P,j] = inds[P,j]+1;
    end
  end

  return inds
end

"""
    computes the number of polynomials with a multivariate basis
    `(d+n)!/(d!+n!)`
"""

function numberPolynomials(d::Int64, n::Int64)
    x, y = max(d,n), min(d,n)
    return UInt128(prod(UInt128(x+1):UInt128(d+n)) ÷ factorial(UInt128(y)))
end

"""
    findUnivariateIndices(i::Int,ind::AbstractMatrix{Int64,2})
Given the multi-index `ind` this function returns all entries of the multivariate basis
that correspond to the `i`th univariate basis.
"""
function findUnivariateIndices(i::Int,ind::AbstractMatrix{Int})
  l,p = size(ind)
  i > p && throw(DomainError((i,p), "basis is $p-variate, you requested $i-variate"))
  deg = ind[end,end]
  deg < 0 && throw(DomainError(deg, "invalid degree"))
  col = ind[:,i]
  myind = zeros(Int64,deg)
  for deg_ in 1:deg
      myind[deg_] = findfirst(x->x==deg_,col)
  end
  pushfirst!(myind,1)
end


text:
using SafeTestsets

@safetestset "Dummy testing" begin include("dummy_tests.jl") end
@safetestset "Core" begin include("core_test.jl") end


text:
"""

    ObjectIndexableArray{T, N, A, O} <: AbstractArray{T, N}

An instance of `ObjectIndexableArray`, referred to as `object_indexable_array` here, simply wraps an `array` (whose type is captured by the type parameter `A` above) and allows us to index its first dimension using a [singleton](https://docs.julialang.org/en/v1/manual/types/#man-singleton-types) object or an array of singleton objects (in addition to all the other ways of indexing the wrapped `array`). Information about the objects is stored in the type parameter `O` above which is essentially the type of tuple of objects along the `num_objects` dimension. Note that `size(object_indexable_array, 1)` should be equal to the number of elements in the type parameter `O`.

"""
struct ObjectIndexableArray{T, N, A, O} <: AbstractArray{T, N}
    array::A
end

get_objects_type(::ObjectIndexableArray{T, N, A, O}) where {T, N, A, O} = O
get_objects(object_indexable_array::ObjectIndexableArray) = Tuple(object_type() for object_type in get_objects_type(object_indexable_array).parameters)

Base.size(object_indexable_array::ObjectIndexableArray, args...; kwargs...) = Base.size(object_indexable_array.array, args..., kwargs...)

# regular indexing (indexing without using objects)
Base.getindex(object_indexable_array::ObjectIndexableArray, args...; kwargs...) = Base.getindex(object_indexable_array.array, args..., kwargs...)
Base.setindex!(object_indexable_array::ObjectIndexableArray, args...; kwargs...) = Base.setindex!(object_indexable_array.array, args..., kwargs...)

# indexing using a single object
@generated function Base.to_index(object_indexable_array::ObjectIndexableArray{T, N, A, O}, object::X) where {T, N, A, O, X <: AbstractObject}
    i = findfirst(X .=== O.parameters)
    isnothing(i) && error("Object $object is not present in $object_indexable_array")
    return :($i)
end

Base.getindex(object_indexable_array::ObjectIndexableArray, object::AbstractObject, args...; kwargs...) = getindex(object_indexable_array.array, Base.to_index(object_indexable_array, object), args..., kwargs...)
Base.setindex!(object_indexable_array::ObjectIndexableArray, value::Bool, object::AbstractObject, args...; kwargs...) = setindex!(object_indexable_array.array, value, Base.to_index(object_indexable_array, object), args..., kwargs...)

# indexing using an array of objects
Base.to_index(object_indexable_array::ObjectIndexableArray, objects::AbstractArray{<:AbstractObject}) = map(object -> Base.to_index(object_indexable_array, object), objects)
Base.getindex(object_indexable_array::ObjectIndexableArray, objects::AbstractArray{<:AbstractObject}, args...; kwargs...) = getindex(object_indexable_array.array, map(object -> Base.to_index(object_indexable_array, object), objects), args..., kwargs...)


text:
module Dialogs

using Genie, Stipple, StippleUI, StippleUI.API
import Genie.Renderer.Html: HTMLString, normal_element, register_normal_element

export dialog

register_normal_element("q__dialog", context = @__MODULE__)

function dialog(fieldname::Symbol, args...; kwargs...)
  q__dialog(args...; kw([:fieldname => fieldname, kwargs...])...)
end

# for compatibility reason with earlier versions
function dialog(args...; kwargs...)
  q__dialog(args...; kw(kwargs)...)
end

end