## dist_zef-FRITH-Math-Libgsl-LinearAlgebra.md
## Chunk 3 of 3
 right element of $A is used to store the matrix 1-norm, used later by cholesky-band-rcond() to calculate the reciprocal condition number. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### cholesky-band-solve(Math::Libgsl::Matrix $LLT where \*.matrix.size1 == $LLT.matrix.size2, Math::Libgsl::Vector $b where \*.vector.size == $LLT.matrix.size1 --> Math::Libgsl::Vector)

This function is available only from the C library v2.6. This function solves the symmetric banded system Ax = b using the Cholesky decomposition of A held in the matrix $LLT which must have been previously computed by cholesky-band-decomp. The function returns the Math::Libgsl::Vector solution $x. In case of error a failure object is returned.

### cholesky-band-svx(Math::Libgsl::Matrix $LLT where \*.matrix.size1 == $LLT.matrix.size2, Math::Libgsl::Vector $x where \*.vector.size == $LLT.matrix.size1 --> Int)

This function is available only from the C library v2.6. This function solves the symmetric banded system Ax = b using the Cholesky decomposition of A held in the matrix $LLT which must have been previously computed by cholesky-band-decomp. On input $x should contain the right-hand side b, which is replaced by the solution on output. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### cholesky-band-invert(Math::Libgsl::Matrix $LLT where \*.matrix.size1 == $LLT.matrix.size2 --> Math::Libgsl::Matrix)

This function is available only from the C library v2.6. This function computes the inverse of a symmetric banded matrix from its Cholesky decomposition $LLT, which must have been previously computed by cholesky-band-decomp. The function returns the inverse matrix as a Math::Libgsl::Matrix solution object. In case of error a failure object is returned.

### cholesky-band-unpack(Math::Libgsl::Matrix $LLT where \*.matrix.size1 == $LLT.matrix.size2 --> Math::Libgsl::Matrix)

This function is available only from the C library v2.6. This function unpacks the lower triangular Cholesky factor from $LLT, which returns as a Math::Libgsl::Matrix object. In case of error a failure object is returned.

### cholesky-band-rcond(Math::Libgsl::Matrix $LLT where \*.matrix.size1 == $LLT.matrix.size2 --> Num)

This function is available only from the C library v2.6. This function estimates the reciprocal condition number (using the 1-norm) of the symmetric banded positive definite matrix A, using its Cholesky decomposition provided in $LLT. The reciprocal condition number estimate, defined as 1/(||A||₁ · ||A⁻¹||₁), is returned.

### ldlt-band-decomp(Math::Libgsl::Matrix $A where \*.matrix.size1 == $A.matrix.size2 --> Int)

This function is available only from the C library v2.6. This function factorizes the symmetric, non-singular square matrix $A into the decomposition A = LDT(L). The input matrix $A is given in symmetric banded format, and has dimensions N-by-(p + 1), where p is the lower bandwidth of the matrix. On output, the entries of $A are replaced by the entries of the matrices D and L in the same format. If the matrix is singular then the decomposition will fail, returning the error code GSL\_EDOM . This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### ldlt-band-solve(Math::Libgsl::Matrix $LDLT where \*.matrix.size1 == $LDLT.matrix.size2, Math::Libgsl::Vector $b where \*.vector.size == $LDLT.matrix.size1 --> Math::Libgsl::Vector)

This function is available only from the C library v2.6. This function solves the symmetric banded system Ax = b using the LDT(L) decomposition of A held in the matrix $LDLT which must have been previously computed by ldlt-band-decomp. The function returns the Math::Libgsl::Vector solution $x. In case of error a failure object is returned.

### ldlt-band-svx(Math::Libgsl::Matrix $LDLT where \*.matrix.size1 == $LDLT.matrix.size2, Math::Libgsl::Vector $x where \*.vector.size == $LDLT.matrix.size1 --> Int)

This function is available only from the C library v2.6. This function solves the symmetric banded system Ax = b using the LDT(L) decomposition of A held in the matrix $LDLT which must have been previously computed by ldlt-band-decomp. On input $x should contain the right-hand side b, which is replaced by the solution on output. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### ldlt-band-unpack(Math::Libgsl::Matrix $LDLT where \*.matrix.size1 == $LDLT.matrix.size2 --> List)

This function is available only from the C library v2.6. This function unpacks the unit lower triangular factor L from $LDLT. This function returns a Math::Libgsl::Matrix object, which holds the lower triangular portion of the matrix L, and a Math::Libgsl::Vector object, which contains the diagonal matrix D. In case of error a failure object is returned.

### ldlt-band-rcond(Math::Libgsl::Matrix $LDLT where \*.matrix.size1 == $LDLT.matrix.size2 --> Num)

This function is available only from the C library v2.6. This function estimates the reciprocal condition number (using the 1-norm) of the symmetric banded nonsingular matrix A, using its LDT(L) decomposition provided in $LDLT. The reciprocal condition number estimate, defined as 1/(||A||₁ · ||A⁻¹||₁), is returned.

### balance-matrix(Math::Libgsl::Matrix $A --> Math::Libgsl::Vector)

This function replaces the matrix $A with its balanced counterpart and returns the diagonal elements of the similarity transformation as a Math::Libgsl::Vector object. In case of error a failure object is returned.

## Complex

### LU-cdecomp(Math::Libgsl::Matrix::Complex64 $A where \*.matrix.size1 == $A.matrix.size2 --> List)

This function factorizes the matrix A into the LU decomposition PA = LU. The factorization is done in place, so on output the diagonal and upper triangular (or trapezoidal) part of the input matrix A contain the matrix U. The lower triangular (or trapezoidal) part of the input matrix (excluding the diagonal) contains L. The diagonal elements of L are unity, and are not stored. The return value is a List: the sign of the permutation and a permutation object, which encodes the permutation matrix P. In case of error a failure object is returned.

### LU-csolve(Math::Libgsl::Matrix::Complex64 $LU where \*.matrix.size1 == $LU.matrix.size2, Math::Libgsl::Permutation $p where \*.size == $LU.matrix.size1, Math::Libgsl::Vector::Complex64 $b where \*.vector.size == $LU.matrix.size1 --> Math::Libgsl::Vector::Complex64)

This function solves the square system Ax = b using the LU decomposition of A into (LU, p) given by the output of LU-decomp. In case of error a failure object is returned.

### LU-csvx(Math::Libgsl::Matrix::Complex64 $LU where \*.matrix.size1 == $LU.matrix.size2, Math::Libgsl::Permutation $p where \*.size == $LU.matrix.size1, Math::Libgsl::Vector::Complex64 $x where \*.vector.size == $LU.matrix.size1 --> Int)

This function solves the square system Ax = b in-place using the precomputed LU decomposition of A into (LU, p). On input $x should contain the right-hand side b, which is replaced by the solution on output. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### LU-crefine(Math::Libgsl::Matrix::Complex64 $A where \*.matrix.size1 == $A.matrix.size2, Math::Libgsl::Matrix::Complex64 $LU where { $LU.matrix.size1 == $LU.matrix.size2 && $A.matrix.size1 == $LU.matrix.size2 }, Math::Libgsl::Permutation $p where \*.size == $LU.matrix.size1, Math::Libgsl::Vector::Complex64 $b where \*.vector.size == $LU.matrix.size1, Math::Libgsl::Vector::Complex64 $x where \*.vector.size == $LU.matrix.size1 --> Int)

This function applies an iterative improvement to x, the solution of Ax = b, from the precomputed LU decomposition of A into (LU, p). This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### LU-cinvert(Math::Libgsl::Matrix::Complex64 $LU, Math::Libgsl::Permutation $p where \*.size == $LU.matrix.size1 --> Math::Libgsl::Matrix::Complex64)

This function computes the inverse of a matrix A from its LU decomposition (LU, p), returning the matrix inverse. In case of error a failure object is returned.

### LU-cdet(Math::Libgsl::Matrix::Complex64 $LU, Int $signum where \* ~~ -1|1 --> Complex)

This function computes the determinant of a matrix A from its LU decomposition, $LU, and the sign of the permutation, $signum. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### LU-clndet(Math::Libgsl::Matrix::Complex64 $LU --> Num)

This function computes the determinant the logarithm of the absolute value of the determinant of a matrix A, ln |det(A)|, from its LU decomposition, $LU. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### LU-csgndet(Math::Libgsl::Matrix::Complex64 $LU, Int $signum where \* ~~ -1|1 --> Complex)

This function computes the sign or phase factor of the determinant of a matrix A, det(A)/|det(A)| from its LU decomposition, $LU. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### cholesky-cdecomp(Math::Libgsl::Matrix::Complex64 $A where \*.matrix.size1 == $A.matrix.size2 --> Int)

This function factorizes the symmetric, positive-definite square matrix $A into the Cholesky decomposition A = LT(L). On input, the values from the diagonal and lower-triangular part of the matrix $A are used (the upper triangular part is ignored). On output the diagonal and lower triangular part of the input matrix $A contain the matrix L, while the upper triangular part contains the original matrix. If the matrix is not positive-definite then the decomposition will fail, returning the error code GSL\_EDOM. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### cholesky-csolve(Math::Libgsl::Matrix::Complex64 $A where \*.matrix.size1 == $A.matrix.size2, Math::Libgsl::Vector::Complex64 $b where \*.vector.size == $A.matrix.size1 --> Math::Libgsl::Vector::Complex64)

These functions solve the system Ax = b using the Cholesky decomposition of $A which must have been previously computed by cholesky-cdecomp. The function returns the Math::Libgsl::Vector::Complex64 $x. In case of error a failure object is returned.

### cholesky-csvx(Math::Libgsl::Matrix::Complex64 $A where \*.matrix.size1 == $A.matrix.size2, Math::Libgsl::Vector::Complex64 $x where \*.vector.size == $A.matrix.size1 --> Int)

This function solves the system Ax = b in-place using the Cholesky decomposition of $A which must have been previously computed by cholesky-cdecomp. On input $x should contain the right-hand side b, which is replaced by the solution on output. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### cholesky-cinvert(Math::Libgsl::Matrix::Complex64 $A where \*.matrix.size1 == $A.matrix.size2 --> Int)

These functions compute the inverse of a matrix from its Cholesky decomposition $A, which must have been previously computed by cholesky-cdecomp. On output, the inverse is stored in-place in $A. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### hermtd-cdecomp(Math::Libgsl::Matrix::Complex64 $A where \*.matrix.size1 == $A.matrix.size2 --> Math::Libgsl::Vector::Complex64)

This function factorizes the hermitian matrix $A into the symmetric tridiagonal decomposition UTT(U). On output the diagonal and subdiagonal part of the input matrix $A contain the tridiagonal matrix T. The remaining lower triangular part of the input matrix contains the Householder vectors which, together with the Householder coefficients tau returned as a Math::Libgsl::Vector::Complex64 object, encode the orthogonal matrix U. The upper triangular part of $A and the imaginary parts of the diagonal are not referenced. In case of error a failure object is returned.

### hermtd-cunpack(Math::Libgsl::Matrix::Complex64 $A where \*.matrix.size1 == $A.matrix.size2, Math::Libgsl::Vector::Complex64 $tau where \*.vector.size == $A.matrix.size1 - 1 --> List)

This function unpacks the encoded symmetric tridiagonal decomposition ($A, $tau) obtained from hermtd-cdecomp. The function returns a List: the unitary matrix $U as a Math::Libgsl::Matrix::Complex64, the real vector of diagonal elements $diag as a Math::Libgsl::Vector, and the real vector of subdiagonal elements $subdiag as a Math::Libgsl::Vector. In case of error a failure object is returned.

### hermtd-cunpack-T(Math::Libgsl::Matrix::Complex64 $A where \*.matrix.size1 == $A.matrix.size2 --> List)

This function unpacks the diagonal and subdiagonal of the encoded symmetric tridiagonal decomposition ($A, $tau) obtained from hermtd-cdecomp. The function returns a List of two real Math::Libgsl::Vector: $diag and $subdiag. In case of error a failure object is returned.

### householder-ctransform(Math::Libgsl::Vector::Complex64 $w --> Complex)

This function prepares a Householder transformation H = I − τvT(v) which can be used to zero all the elements of the input vector $w except the first. On output the Householder vector v is stored in $w and the scalar τ is returned. The householder vector v is normalized so that v[0] = 1, however this 1 is not stored in the output vector. Instead, $w[0] is set to the first element of the transformed vector, so that if u = Hw, w[0] = u[0] on output and the remainder of u is zero. This function returns a Complex: $τ.

### householder-chm(Complex $tau, Math::Libgsl::Vector::Complex64 $v, Math::Libgsl::Matrix::Complex64 $A --> Int)

This function applies the Householder matrix H defined by the scalar $tau and the vector $v to the left-hand side of the matrix $A. On output the result HA is stored in $A. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### householder-cmh(Complex $tau, Math::Libgsl::Vector::Complex64 $v, Math::Libgsl::Matrix::Complex64 $A --> Int)

This function applies the Householder matrix H defined by the scalar $tau and the vector $v to the right-hand side of the matrix $A. On output the result AH is stored in $A. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### householder-chv(Complex $tau, Math::Libgsl::Vector::Complex64 $v, Math::Libgsl::Vector::Complex64 $w --> Int)

This function applies the Householder transformation H defined by the scalar $tau and the vector $v to the vector $w. On output the result Hw is stored in w. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### tri-cinvert(Int $Uplo, Int $Diag, Math::Libgsl::Matrix::Complex64 $A --> Int)

This function is available only from the C library v2.6. This function computes the in-place inverse of the triangular matrix $T, stored in the lower triangle when $Uplo = CblasLower and upper triangle when $Uplo = CblasUpper. The parameter $Diag = CblasUnit, CblasNonUnit specifies whether the matrix is unit triangular. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### tri-cLHL(Math::Libgsl::Matrix::Complex64 $L --> Int)

This function is available only from the C library v2.6. This function computes the product LT(L) in-place and stores it in the lower triangle of $L on output. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

### tri-cUL(Math::Libgsl::Matrix::Complex64 $LU --> Int)

This function is available only from the C library v2.6. This function compute the product $UL where U is upper triangular and L is unit lower triangular, stored in $LU, as computed by LU-cdecomp. This function returns GSL\_SUCCESS if successful, or one of the error codes listed in Math::Libgsl::Constants::gsl-error.

# C Library Documentation

For more details on libgsl see <https://www.gnu.org/software/gsl/>. The excellent C Library manual is available here <https://www.gnu.org/software/gsl/doc/html/index.html>, or here <https://www.gnu.org/software/gsl/doc/latex/gsl-ref.pdf> in PDF format.

# Prerequisites

This module requires the libgsl library to be installed. Please follow the instructions below based on your platform:

## Debian Linux and Ubuntu 20.04+

```
sudo apt install libgsl23 libgsl-dev libgslcblas0

```

That command will install libgslcblas0 as well, since it's used by the GSL.

## Ubuntu 18.04

libgsl23 and libgslcblas0 have a missing symbol on Ubuntu 18.04. I solved the issue installing the Debian Buster version of those three libraries:

* <http://http.us.debian.org/debian/pool/main/g/gsl/libgslcblas0_2.5+dfsg-6_amd64.deb>
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl23_2.5+dfsg-6_amd64.deb>
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl-dev_2.5+dfsg-6_amd64.deb>

# Installation

To install it using zef (a module management tool):

```
$ zef install Math::Libgsl::LinearAlgebra

```

# AUTHOR

Fernando Santagata [nando.santagata@gmail.com](mailto:nando.santagata@gmail.com)

# COPYRIGHT AND LICENSE

Copyright 2020 Fernando Santagata

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_zef-antononcube-Markdown-Grammar.md
# Raku Markdown::Grammar

## In brief

Markdown parser suitable for making converters of Markdown files into files of different kind of formats:

* DONE Mathematica notebook
* TODO RMarkdown notebook
* DONE Jupyter notebook
* DONE Pod6 file
* DONE Org-mode file
* DONE HTML file
* DONE Raku data structure

See the video
["Markdown to Mathematica converter (CLI and StackExchange examples)"](https://www.youtube.com/watch?v=39ekokgnoqE), [AAv1],
for a (quick, 7.5 min) demo.
The video [AAv2] shows the conversion of a Jupyter notebook into a Mathematica notebook via Markdown representation.
The video [AAv3] shows conversions to POD6, Mathematica, and Jupyter and evaluations of those documents.
(The evaluations are done with
["Text::CodeProcessing"](https://raku.land/zef:antononcube/Text::CodeProcessing), [AAp1].)

### Motivation

#### Mathematica notebooks

I am most interested in generating Mathematica notebooks from Markdown.

I have written a fair amount of Raku-related Markdown documents. Many of those Markdown documents
were generated from Mathematica notebooks using
[M2MD](https://github.com/kubaPod/M2MD), [JPp1].
But of course, most of the time, further changes and embellishments were made over those Markdown documents.
Hence it would be very nice to be able to go back to Mathematica.

**Remark:** Raku can be used in Mathematica via the so called `RakuMode` -- see [AA1].

**Remark:** Markdown documents with Raku code cells can be evaluated with Command Line Interface (CLI)
scripts of the package
["Text::CodeProcessing"](https://raku.land/cpan:ANTONOV/Text::CodeProcessing), [AAp1].
For more details see the article
["Connecting Mathematica and Raku"](https://rakuforprediction.wordpress.com/2021/12/30/connecting-mathematica-and-raku/), [AA1].

Here is a flowchart that gives better idea of the workflow outlined above:

```
graph TD
    Rnb[Make Raku notebook in Mathematica]-->LT
    LT[Literate programming]-->GE
    GE{Good enough?}-->|yes|CN
    CN[Convert notebook to Markdown]-->P
    P["Publish (GitHUb/WordPress)"]-->SP
    SP-->|yes|R
    R[Review and modify]-->P
    GE-->|no|LT
    SP{Needs <br /> refinement?}-->|no|SD
    SD{Significantly <br /> different?}-->|yes|CM
    SD-->|no|PC
    CM[Convert Markdown document to notebook]-->PC
    PC["Publish to notebook Community.wolfram.com"]

```

#### Pod6

The notebook formats have syntax that makes it hard to evaluate the conversions visually.
That is why I use Pod6 -- during development it is much easier to evaluate the Pod6 interpretations
produced by the package.
(I.e. no need to use another tool to open and evaluate the obtained conversion artifact.)

---

## Installation

From Zef ecosystem:

```
zef install Markdown::Grammar

```

From GitHub:

```
zef install https://github.com/antononcube/Raku-Markdown-Grammar.git

```

---

## Round trip translation

Consider the following round trip translation experiment:

1. Make a Mathematica notebook
2. Convert WL notebook into Markdown file with the Mathematica package [M2MD](https://github.com/kubaPod/M2MD)
3. Convert the obtained Markdown file into Mathematica notebook using the Raku package "Markdown::Grammar"
4. Compare the notebooks

Here is the corresponding flowchart:

```
graph TD
    WL[Make a Mathematica notebook] --> E
    E["Examine notebook(s)"] --> M2MD
    M2MD["Convert to Markdown with M2MD"] --> MG
    MG["Convert to Mathematica with Markdown::Grammar"] --> |Compare|E

```

---

## Related work

Here is a table of converters from- or to Markdown:

| From \ To | HTML | Jupyter | Markdown | Mathematica | Pod6 | Org-mode | Raku |
| --- | --- | --- | --- | --- | --- | --- | --- |
| HTML |  | [pandoc](https://pandoc.org) | [pandoc](https://pandoc.org) |  |  | [pandoc](https://pandoc.org) |  |
| Jupyter | [Jupyter](https://jupyter.org) |  | [Jupyter](https://jupyter.org), [jupytext](https://jupytext.readthedocs.io) |  |  |  |  |
| Markdown | [pandoc](https://pandoc.org), [Markit](https://raku.land/cpan:UZLUISF/Markit), [Text::Markdown](https://raku.land/zef:JJMERELO/Text::Markdown), [Markdown::Grammar](https://raku.land/zef:antononcube/Markdown::Grammar) | [jupytext](https://jupytext.readthedocs.io), [Markdown::Grammar](https://raku.land/zef:antononcube/Markdown::Grammar) |  | [Markdown2WL](https://github.com/dishmint/Markdown2WL), [md2nb](https://github.com/ConnorGray/md2nb), [Markdown::Grammar](https://raku.land/zef:antononcube/Markdown::Grammar) | [Markdown::Grammar](https://raku.land/zef:antononcube/Markdown::Grammar) | [pandoc](https://pandoc.org), [Markdown::Grammar](https://raku.land/zef:antononcube/Markdown::Grammar) | [Markdown::Grammar](https://raku.land/zef:antononcube/Markdown::Grammar) |
| Mathematica |  |  | [M2MD](https://github.com/kubaPod/M2MD) |  |  |  |  |
| Pod6 |  |  | [Pod::To::Markdown](https://raku.land/cpan:SOFTMOTH/Pod::To::Markdown) |  |  |  |  |
| Org-mode | [pandoc](https://pandoc.org), [Org-mode](https://orgmode.org) |  | [pandoc](https://pandoc.org), [Org-mode](https://orgmode.org) |  |  |  |  |

**Remark:** [Pandoc](https://pandoc.org) attempts to be an universal converter, applicable for all couples of formats.

**Remark:** Except
["this package"](https://github.com/antononcube/Raku-Markdown-Grammar)
there are no other converters from Markdown to
[Pod6](https://docs.raku.org/language/pod).

**Remark:** In general I like the idea of a Markdown-to-Mathematica converter written in Mathematica.
The package
["Markdown2WL"](https://github.com/dishmint/Markdown2WL)
attempts that, but unfortunately it is fairly incomplete.

**Remark:** When starting this project I did not know about Connor's package
["md2nb"](https://github.com/ConnorGray/md2nb). (Written in Rust.)
If I knew about it, most likely, I would have not written this package.

---

## Command line interface

The package provides a Command Line Interface (CLI) script, `from-markdown`. Here is its usage message:

```
from-markdown --help

```

```
# Usage:
#   from-markdown <text> [-f|--flavor=<Str>] [-t|--to=<Str>] [-l|--default-language=<Str>] [-r|--raku-code-cell-name=<Str>] [-d|--docked-cells] [-o|--output=<Str>] -- Converts Markdown files into Jupyter and Mathematica notebooks, and HTML, Org-mode, and Pod6 files.
#
#     <text>                            Input file or Markdown text.
#     -f|--flavor=<Str>                 Markdown flavor. (One of 'obsidian' or 'Whatever'.) [default: 'Whatever']
#     -t|--to=<Str>                     Format to convert to. (One of 'html', 'jupyter', 'mathematica', 'org', 'pod6', or 'Whatever'.) [default: 'Whatever']
#     -l|--default-language=<Str>       Default code blocks language. [default: 'Whatever']
#     -r|--raku-code-cell-name=<Str>    Raku code cell name. (Mathematica only.) [default: 'Whatever']
#     -d|--docked-cells                 Should formula conversion button be added as a docked cell or not? (Mathematica only.) [default: False]
#     -o|--output=<Str>                 Output file; if an empty string then the result is printed to stdout. [default: '']

```

The CLI script `from-markdown` takes both file names and (Markdown) text. Here is an usage example for the latter:

```
from-markdown -to=pod6 'Here is data wrangling code:

    obj = dfTitanic;
    obj = GroupBy[ obj, #["passengerSex"]& ];
    Echo[Map[ Length, obj], "counts:"]

## References'

```

```
# =begin pod
# =begin para
# Here is data wrangling code:
# =end para
# =begin code
# obj = dfTitanic;
# obj = GroupBy[ obj, #["passengerSex"]& ];
# Echo[Map[ Length, obj], "counts:"]
# =end code
# =begin head2
# References
# =end head2
# =end pod

```

**Remark:** Using the CLI script with the option setting `--raku-cell-code-name=RakuInputExecute` produces
Raku cells that require the Mathematica package "RakuMode.m", [AAp2], to be loaded and the command `RakuMode[]`
to be executed in the result notebook.

**Remark:** If CLI script's argument `--output` is a non-empty string and `--format` is "whatever" or "automatic",
then an attempt is made to conclude the format to convert to from the extension of the file name given to `--output`.

---

## Usage examples

### Conversion of text

Consider the following Markdown text:

```
my $mtext = q:to/END/;
Here is data wrangling code:

    obj = dfTitanic;
    obj = GroupBy[ obj, #["passengerSex"]& ];
    Echo[Map[ Length, obj], "counts:"]

## References

### Articles

[AA1] Anton Antonov,
["Introduction to data wrangling with Raku"](https://rakuforprediction.wordpress.com/2021/12/31/introduction-to-data-wrangling-with-raku/),
(2021),
[RakuForPrediction at WordPress](https://rakuforprediction.wordpress.com).
END

say $mtext.chars;

```

```
# 410

```

Here is the corresponding Mathematica notebook:

```
use Markdown::Grammar;

from-markdown($mtext, to => 'mathematica')

```

```
# Notebook[{Cell[TextData[{"Here", " ", "is", " ", "data", " ", "wrangling", " ", "code:"}], "Text"], Cell[ BoxData["obj = dfTitanic;
# obj = GroupBy[ obj, #[\"passengerSex\"]& ];
# Echo[Map[ Length, obj], \"counts:\"]
# "], "Input"], Cell[TextData[{"References"}], "Section"], Cell[TextData[{"Articles"}], "Subsection"], Cell[TextData[{"[AA1]", " ", "Anton", " ", "Antonov,", " ", ButtonBox["\"Introduction to data wrangling with Raku\"", BaseStyle -> "Hyperlink", ButtonData -> { URL["https://rakuforprediction.wordpress.com/2021/12/31/introduction-to-data-wrangling-with-raku/"], None}], " ", ",", " ", "(2021),", " ", ButtonBox["RakuForPrediction at WordPress", BaseStyle -> "Hyperlink", ButtonData -> { URL["https://rakuforprediction.wordpress.com"], None}], " ", "."}], "Text"]}]

```

Here is the corresponding Pod6 text:

```
from-markdown($mtext, to => 'pod6')

```

```
# =begin pod
# =begin para
# Here is data wrangling code:
# =end para
# =begin code
# obj = dfTitanic;
# obj = GroupBy[ obj, #["passengerSex"]& ];
# Echo[Map[ Length, obj], "counts:"]
# =end code
# =begin head2
# References
# =end head2
#
# =begin head3
# Articles
# =end head3
#
# =para
# [AA1] Anton Antonov,
# L<"Introduction to data wrangling with Raku"|https://rakuforprediction.wordpress.com/2021/12/31/introduction-to-data-wrangling-with-raku/> ,
# (2021),
# L<RakuForPrediction at WordPress|https://rakuforprediction.wordpress.com> .
# =end pod

```

### Section tree

The function `md-section-tree` extracts the Markdown blocks into a Hash-based tree that
corresponds to the hierarchical sections structure of the Markdown document:

```
use Data::Translators;
md-section-tree($mtext) ==> data-translation(field-names => <type level name content>)

```

| type | level | name | content |
| --- | --- | --- | --- |
| md-text-block | 7 | (Whatever) | Here is data wrangling code: |
| md-code-indented-block | 7 | (Whatever) | obj = dfTitanic; obj = GroupBy[ obj, #["passengerSex"]& ]; Echo[Map[ Length, obj], "counts:"] |
| md-header2 | 2 | References | ## References |
| md-text-block | 7 | (Whatever) |  |
| md-header3 | 3 | Articles | ### Articles |
| md-text-block | 7 | (Whatever) | [AA1] Anton Antonov, ["Introduction to data wrangling with Raku"](https://rakuforprediction.wordpress.com/2021/12/31/introduction-to-data-wrangling-with-raku/), (2021), [RakuForPrediction at WordPress](https://rakuforprediction.wordpress.com). |

Here we just get the code blocks:

```
md-section-tree($mtext, modifier => 'code')

```

```
# [
#     obj = dfTitanic;
#     obj = GroupBy[ obj, #["passengerSex"]& ];
#     Echo[Map[ Length, obj], "counts:"]
#
# ]

```

---

## Parsing Markdown flavors

### Obsidian

The parsing and interpretation of Obsidian flavor Markdown files is specified with the option "flavor".
Here is an invocation within a Raku session:

```
from-markdown($mtext2, flavor => 'obsidian', to => 'jupyter');

```

Here is one of the ways to specify Obsidian file conversion via the CLI script:

```
from-markdown myObsidianFile.md -f obsidian -o myObsidianFile.ipynb

```

Other examples are given in the test file
["07-Jupyter-Obsidian.rakutest"](https://github.com/antononcube/Raku-Markdown-Grammar/blob/main/t/07-Jupyter-Obsidian.rakutest).

See also the dedicated GitHub repository: ["obsidian-2-jupyter"](https://github.com/rcmlz/obsidian-2-jupyter), [RMr1].

---

## TODOs

The most important items are placed first.

* DONE Parsing bold, italic, code "words."
* TODO Parsing bold, italic, code "phrases."
* DONE Parsing blocks with bold, italic formatting specs
* DONE Parsing code blocks given with indentation.
* DONE Parsing and interpretation of "deferred" links. E.g. `[![enter image description here][1]][1]`.

  * This is somewhat complicated, needing a "second pass" interpreter.
  * The "second pass" is handled in the TOP action methods.
* DONE Parsing quote lines and quote blocks
* DONE Parsing tables
* DONE Parsing LaTeX and/or [math blocks](https://github.com/fletcher/MultiMarkdown/wiki/MultiMarkdown-Syntax-Guide#math-support)
* DONE Parsing inlined LaTeX code.
* DONE Parsing LaTeX code with a docked cell button in the generated Mathematica notebook.
* DONE Have option(s) for default language for code cells.
* DONE Have option(s) for Raku code cell name.
* TODO Have option(s) for skipping horizontal line specs.
* TODO Parsing alternate syntax for heading 1 and 2
* TODO Parsing escaping characters
* TODO Parsing HTML
* TODO Parsing most or all of the elements of the [extended syntax](https://www.markdownguide.org/extended-syntax/), [MC1]

---

## Acknowledgments

Many thanks to Jakub (Kuba) Podkalicki for programming the package "M2MD", and helping me to understand
a fair amount of Mathematica's
[low-Level notebook programming](https://reference.wolfram.com/language/guide/LowLevelNotebookProgramming.html).

Thanks to Rc Mlz for his request and guidance for parsing the Obsidian Markdown flavor and
creating the dedicated [Obsidian-to-Jupyter conversion repository](https://github.com/rcmlz/obsidian-2-jupyter), [RMr1].

---

## References

### Articles

[AA1] Anton Antonov,
["Connecting Mathematica and Raku"](https://rakuforprediction.wordpress.com/2021/12/30/connecting-mathematica-and-raku/),
(2021),
RakuForPrediction at WordPress.

[FZ1] Faizon Zaman,
["Parsing markdown files"](https://community.wolfram.com/groups/-/m/t/2142852),
(2021),
[Community.wolfram.com](https://community.wolfram.com).

### Guides

[JG1] John Gruber, [Markdown: Syntax](https://daringfireball.net/projects/markdown/).

[MC1] Matt Cone, [Markdown Guide](https://www.markdownguide.org).

[RC1] Raku Community, [Raku Pod6](https://docs.raku.org/language/pod).

### Packages, paclets

[AAp1] Anton Antonov
[Text::CodeProcessing Raku package](https://github.com/antononcube/Raku-Text-CodeProcessing),
(2021-2022),
[GitHub/antononcube](https://github.com/antononcube).

[AAp2] Anton Antonov
[RakuMode Wolfram Language paclet](https://resources.wolframcloud.com/PacletRepository/resources/AntonAntonov/RakuMode/),
(2023),
[Wolfram Language Paclet Repository](https://resources.wolframcloud.com/PacletRepository).

[FZp1] Faizon Zaman,
[Markdown2WL Mathematica package](https://github.com/dishmint/Markdown2WL),
(2021),
[GitHub/dishmint](https://github.com/dishmint/Markdown2WL).

[JPp1] Jakub Podkalicki,
[M2MD](https://github.com/kubaPod/M2MD),
(2018-2022),
[GitHub/kubaPod](https://github.com/kubaPod).

[RMr1] Rc Mlz,
[obsidian-2-jupyter](https://github.com/rcmlz/obsidian-2-jupyter),
(2024),
[GitHub/rcmlz](https://github.com/rcmlz).

### Videos

[AAv1] Anton Antonov,
["Markdown to Mathematica converter (CLI and StackExchange examples)"](https://www.youtube.com/watch?v=39ekokgnoqE),
(2022),
[Anton A. Antonov's channel at YouTube](https://www.youtube.com/channel/UC5qMPIsJeztfARXWdIw3Xzw).

[AAv2] Anton Antonov,
["Markdown to Mathematica converter (Jupyter notebook example)"](https://www.youtube.com/watch?v=Htmiu3ZI05w),
(2022),
[Anton A. Antonov's channel at YouTube](https://www.youtube.com/channel/UC5qMPIsJeztfARXWdIw3Xzw).

[AAv3] Anton Antonov,
["Conversion and evaluation of Raku files"](https://www.youtube.com/watch?v=GJO7YqjGn6o),
(2022),
[Anton A. Antonov's channel at YouTube](https://www.youtube.com/channel/UC5qMPIsJeztfARXWdIw3Xzw).


## roundrobin.md
roundrobin

Combined from primary sources listed below.

# [In List](#___top "go to top of document")[§](#(List)_routine_roundrobin "direct link")

See primary documentation
[in context](/type/List#routine_roundrobin)
for **routine roundrobin**.

```raku
sub roundrobin(+list-of-lists --> Seq)
```

Builds a 'list of lists', returned as a sequence, from multiple input lists or other [`Iterable`](/type/Iterable)s. `roundrobin` returns an identical result to that of [zip](/type/List#routine_zip), except when the input lists are allowed to have an unequal number of elements.

```raku
say roundrobin <a b c>, <d e f>, <g h i>;
# OUTPUT: «((a d g) (b e h) (c f i))␤»

say .join(",") for roundrobin([1, 2], [2, 3], [3, 4]);
# OUTPUT: «1,2,3␤2,3,4␤»
```

`roundrobin` does not terminate once one or more of the input lists become exhausted, but proceeds until all elements from all lists have been processed.

```raku
say roundrobin <a b c>, <d e f m n o p>, <g h i j>;
# OUTPUT: «((a d g) (b e h) (c f i) (m j) (n) (o) (p))␤»

say .join(",") for roundrobin([1, 2], [2, 3, 57, 77], [3, 4, 102]);
# OUTPUT: «1,2,3␤2,3,4␤57,102␤77␤»
```

Therefore no data values are lost due in the 'zipping' operation. A record of which input list provided which element cannot be gleaned from the resulting sequence, however.

`roundrobin` can be useful in combining messy data to the point where a manual post-processing step can then be undertaken.

```raku
sub roundrobin(+list-of-lists, :$slip --> Seq)
```

As of release 2022.02 of the Rakudo compiler, it is also possible to specify a `:slip` named argument. If specified with a true value, will [slip](/language/list#Slips) the produced values.

```raku
say roundrobin <a b c>, <d e f m n o p>, <g h i j>, :slip;
# OUTPUT: «(a d g b e h c f i m j n o p)␤»
```


## quanthash.md
role QuantHash

Object hashes with a limitation on the type of values

```raku
role QuantHash does Associative { }
```

The `QuantHash` role provides the basic functionality shared by the [`Setty`](/type/Setty), [`Baggy`](/type/Baggy) and [`Mixy`](/type/Mixy) roles. These provide object hashes whose values are limited in some way.

`QuantHashes` are what [set operators](/language/setbagmix) use internally.

# [Methods](#role_QuantHash "go to top of document")[§](#Methods "direct link")

## [method hash](#role_QuantHash "go to top of document")[§](#method_hash "direct link")

```raku
method hash()
```

Coerces the `QuantHash` object to a [`Hash`](/type/Hash) (by stringifying the objects for the keys) with the values of the hash limited to the same limitation as `QuantHash`, and returns that.

## [method Hash](#role_QuantHash "go to top of document")[§](#method_Hash "direct link")

```raku
method Hash()
```

Coerces the `QuantHash` object to a [`Hash`](/type/Hash) (by stringifying the objects for the keys) without any limitations on the values, and returns that.

## [method Map](#role_QuantHash "go to top of document")[§](#method_Map "direct link")

```raku
method Map()
```

Available as of the 2021.02 release of the Rakudo compiler.

Coerces the `QuantHash` object to a [`Map`](/type/Map) (by stringifying the objects for the keys) without any limitations on the values, and returns that.

## [method of](#role_QuantHash "go to top of document")[§](#method_of "direct link")

```raku
method of()
```

Returns the type of value a value of this `QuantHash` may have. This is typically [`Bool`](/type/Bool) for [`Setty`](/type/Setty), [`UInt`](/type/UInt) for [`Baggy`](/type/Baggy) or [`Real`](/type/Real) for [`Mixy`](/type/Mixy) roles.

## [method keyof](#role_QuantHash "go to top of document")[§](#method_keyof "direct link")

```raku
method keyof()
```

Returns the type of value a key of this subclass of `QuantHash` may have. This is typically [`Mu`](/type/Mu), which is also the default for punned QuantHashes.

## [method Capture](#role_QuantHash "go to top of document")[§](#method_Capture "direct link")

```raku
method Capture()
```

Returns the object as a [`Capture`](/type/Capture) by previously coercing it to a [`Hash`](/type/Hash).

## [method list](#role_QuantHash "go to top of document")[§](#method_list "direct link")

```raku
multi method list(QuantHash:D:)
```

Returns a list of [`Pair`](/type/Pair) objects of all keys and values in the QuantHash.

## [method Setty](#role_QuantHash "go to top of document")[§](#method_Setty "direct link")

```raku
method Setty(--> Setty:D)
```

Coerce the `QuantHash` object to the equivalent object that uses the [`Setty`](/type/Setty) role. Note that for [`Mixy`](/type/Mixy) type coercion items with negative values will be skipped.

```raku
my %b is Bag = one => 1, two => 2;
say %b.Setty; # OUTPUT: «Set(one two)␤»
my %m is Mix = one => 1, minus => -1;
say %m.Setty; # OUTPUT: «Set(one)␤»
```

## [method Baggy](#role_QuantHash "go to top of document")[§](#method_Baggy "direct link")

```raku
method Baggy(--> Baggy:D)
```

Coerce the `QuantHash` object to the equivalent object that uses the [`Baggy`](/type/Baggy) role. Note that for [`Mixy`](/type/Mixy) type coercion items with negative values will be skipped.

```raku
my %s is Set = <one two>;
say %s.Baggy; # OUTPUT: «Bag(one two)␤»
my %m is Mix = one => 1, minus => -1;
say %m.Baggy; # OUTPUT: «Bag(one)␤»
```

## [method Mixy](#role_QuantHash "go to top of document")[§](#method_Mixy "direct link")

```raku
method Mixy(--> Mixy:D)
```

Coerce the `QuantHash` object to the equivalent object that uses the [`Mixy`](/type/Mixy) role.

```raku
my %s is Set = <one two>;
say %s.Mixy; # OUTPUT: «Mix(one two)␤»
my %b is Bag = one => 1, two => 2;
say %b.Mixy; # OUTPUT: «Mix(one two(2))␤»
```

# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")

Type relations for `QuantHash`

raku-type-graph

QuantHash
QuantHash

Associative
Associative

QuantHash->Associative

Setty
Setty

Setty->QuantHash

Baggy
Baggy

Baggy->QuantHash

Mu
Mu

Any
Any

Any->Mu

Set
Set

Set->Setty

Set->Any

SetHash
SetHash

SetHash->Setty

SetHash->Any

Bag
Bag

Bag->Baggy

Bag->Any

BagHash
BagHash

BagHash->Baggy

BagHash->Any

Mixy
Mixy

Mixy->Baggy

Mix
Mix

Mix->Any

Mix->Mixy

MixHash
MixHash

MixHash->Any

MixHash->Mixy

[Expand chart above](/assets/typegraphs/QuantHash.svg)


## trim-trailing.md
trim-trailing

Combined from primary sources listed below.

# [In Allomorph](#___top "go to top of document")[§](#(Allomorph)_method_trim-trailing "direct link")

See primary documentation
[in context](/type/Allomorph#method_trim-trailing)
for **method trim-trailing**.

```raku
method trim-trailing(Allomorph:D:)
```

Calls [`Str.trim-trailing`](/type/Str#method_trim-trailing) on the invocant's [`Str`](/type/Str) value.

# [In Str](#___top "go to top of document")[§](#(Str)_method_trim-trailing "direct link")

See primary documentation
[in context](/type/Str#method_trim-trailing)
for **method trim-trailing**.

```raku
method trim-trailing(Str:D: --> Str)
```

Removes the whitespace characters from the end of a string. See also [trim](/routine/trim).

# [In Cool](#___top "go to top of document")[§](#(Cool)_routine_trim-trailing "direct link")

See primary documentation
[in context](/type/Cool#routine_trim-trailing)
for **routine trim-trailing**.

```raku
sub trim-trailing(Str(Cool))
method trim-trailing()
```

Coerces the invocant (or in sub form, its argument) to [`Str`](/type/Str), and returns the string with trailing whitespace stripped.

```raku
my $stripped = '  abc '.trim-trailing;
say "<$stripped>";          # OUTPUT: «<  abc>␤»
```


## dist_github-shantanubhadoria-CompUnit-Search.md
# NAME

CompUnit::Search - Search through compunits

# SYNOPSIS

## Search through compunits

```
    use CompUnit::Search;

    my @modules = installed-compunits({$_ ~~ /Test\:\:.*/});

    for @modules -> $module {
      say $module;
    }

```

# METHODS

## search-compunits

Gets a list of all installed compunits from the repositories(optional filter can be passed to show a subset of the installed compunits). Note that at the moment this only searches in repositories of type CompUnit::Repository::Installation, as these are the only ones which provide a quick meta to search for installed modules. If you install anything through `panda install` it should show up in the list. Once there is a good way to search through other repositories I will implement it here.

Returns a lazy list of Pair(s) with compunits as key and a Seq of its provides as the value.

```
use CompUnit::Search;

my @compUnits = search-compunits(* ~~ /JSON\:\:.*/); # Whatever code as a parameter to filter the compunits by name
                                                     # You may also use a block with one parameter(compunit name)
                                                     # instead for filtering purposes.

for @compUnits -> $compUnit {
  say $compUnit;
}

```

Output:

```
JSON::Unmarshal => (JSON::Unmarshal)
JSON::Marshal => (JSON::Marshal)
JSON::Tiny => (JSON::Tiny JSON::Tiny::Actions JSON::Tiny::Grammar)
JSON::Pretty => (JSON::Pretty)
JSON::Class => (JSON::Class)
JSON::Infer => (JSON::Infer)
JSON::RPC => (JSON::RPC::Server X::JSON::RPC JSON::RPC::Client)
JSON::Name => (JSON::Name)
JSON::Fast => (JSON::Fast)

```

## search-provides

Gets a list of provides and the compunits that provide them. This function filters based on the provides' name. Provide can be a package, class, role, module, grammar etc. as specified in the Meta file for the compunit. Returns a lazy list of Pair(s) with a provide as the key and the compunit that provides that provide as the value.

```
use CompUnit::Search;

my @compUnits = search-provides(* ~~ /JSON\:\:.*/);

for @compUnits -> $compUnit {
  say $compUnit;
}

```

Output:

```
JSON::Unmarshal => JSON::Unmarshal
JSON::Marshal => JSON::Marshal
JSON::Tiny => JSON::Tiny
JSON::Tiny::Actions => JSON::Tiny
JSON::Tiny::Grammar => JSON::Tiny
JSON::Pretty => JSON::Pretty
JSON::Class => JSON::Class
JSON::Infer => JSON::Infer
JSON::RPC::Server => JSON::RPC
X::JSON::RPC => JSON::RPC
JSON::RPC::Client => JSON::RPC
JSON::Name => JSON::Name
JSON::Fast => JSON::Fast

```

# REFERENCE

Compilation Units <http://design.perl6.org/S11.html>

# SUPPORT

## Bugs / Feature Requests

Please report any bugs or feature requests through github at <https://github.com/shantanubhadoria/p6-CompUnit-Search/issues>. You will be notified automatically of any progress on your issue.

## Source Code

This is open source software. The code repository is available for public review and contribution under the terms of the license.

<https://github.com/shantanubhadoria/p6-CompUnit-Search>

```
git clone git://github.com/shantanubhadoria/p6-CompUnit-Search.git

```

# AUTHOR

Shantanu Bhadoria [shantanu@cpan.org](mailto:shantanu@cpan.org) <https://www.shantanubhadoria.com>

# COPYRIGHT AND LICENSE

This software is copyright (c) 2016 by Shantanu Bhadoria.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 6 programming language system itself.


## dist_zef-raku-community-modules-Log-Timeline.md
[![Actions Status](https://github.com/raku-community-modules/Log-Timeline/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Log-Timeline/actions) [![Actions Status](https://github.com/raku-community-modules/Log-Timeline/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Log-Timeline/actions) [![Actions Status](https://github.com/raku-community-modules/Log-Timeline/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Log-Timeline/actions)

# NAME

Log::Timeline - Log tasks with start/end periods and phases, as well as individual events

# DESCRIPTION

When building an application with many ongoing, potentially overlapping, tasks, we may find ourselves wishing to observe what is going on. We'd like to log, but with a focus on things that happen over time rather than just individual events. The `Log::Timeline` module provides a means to do that.

As well as annotating your own applications with `Log::Timeline` tasks and events, the module can provide various events relating to the Raku standard library, and has already been integrated in some modules, such as `Cro`.

# Key features

* Log tasks with start and end times
* Log individual events
* Tasks and events can be associated with an enclosing parent task
* Include data (keys mapped to values) with the logged tasks and events
* Have data logged to a file (JSON or CBOR), or exposed over a socket
* Visualize task timelines in [Comma](https://commaide.com/)
* Support by [Cro](https://cro.services/), to offer insight into client and server request processing pipelines
* Enable logging of various Raku standard library events: the start and end times of `start` blocks and `await` statements, socket connections, files being open, and more

Planned:

* Introspect what tasks and events a given distribution can log
* Log tasks indicating when GC happens
* Turn on/off what is logged at runtime (socket mode only)

# Turning on Raku built-ins logging

Set the `LOG_TIMELINE_RAKU_EVENTS` environment variable to a comma-separated list of events to log. For example:

```
LOG_TIMELINE_RAKU_EVENTS=file,thread,socket,process,start,await

```

The events available are:

* `await` - logs tasks showing time spent in an `await`
* `file` - logs tasks showing the time files are open
* `process` - logs tasks showing the time that a sub-process is running (the logging is done on `Proc::Async`, which covers everything since the synchronous process API is a wrapper around the asynchronous one)
* `socket` - logs a task when a listening asynchornous socket is listening, and child tasks for each connection it receives; for connections, the connection is logged along with a child task for the time taken for the initial connection establishment
* `start` - logs tasks showing the time that `start` blocks are "running" (however, they may within that time be suspended due to an `await`)
* `thread` - logs creation of Raku `Thread`s. These are typically created by the thread pool when using Raku's high-level concurrency features.

# Providing tasks and events in a distribution

Providing tasks and events in your application involves the following steps:

* 1. Make sure that your `META6.json` contains a `depends` entry for `Log::Timeline`
* 1. Create one or more modules whose final name part is `LogTimelineSchema`, which declares the available tasks and events. This will be used for tools to introspect the available set of tasks and events that might be logged, and to provide their metadata
* 1. Use the schema module and produce timeline tasks and events in your application code

## The schema module

Your application or module should specify the types of tasks and events it wishes to log. These are specified in one or more modules, which should be registered in the `provides` section of the `META6.json` file. The **module name's final component** should be `LogTimelineSchema`. For example, `Cro::HTTP` provides `Cro::HTTP::LogTimelineSchema`. You may provide more than one of these per distribution.

Every task or event has a 3-part name:

* **Module** - for example, `Cro HTTP`
* **Category** - for example, `Client` and `Server`
* **Name** - for example, `HTTP Request`

These are specified when doing the role for the event or task.

To declare an event (something that happens at a single point in time), do the `Log::Timeline::Event` role. To declare a task (which happens over time) do the `Log::Timeline::Task` role.

```
unit module MyApp::Log::LogTimelineSchema;
use Log::Timeline;

class CacheExpired
  does Log::Timeline::Event['MyApp', 'Backend', 'Cache Expired'] { }

class Search
  does Log::Timeline::Task['MyApp', 'Backend', 'Search'] { }

```

## Produce tasks and events

Use the module in which you placed the events and/or tasks you wish to log.

```
use MyApp::Log::LogTimelineSchema;

```

To log an event, simply call the `log` method:

```
MyApp::Log::LogTimelineSchema::CacheExpired.log();

```

Optionally passing extra data as named arguments:

```
MyApp::Log::LogTimelineSchema::CacheExpired.log(:$cause);

```

To log a task, also call `log`, but pass a block that will execute the task:

```
MyApp::Log::LogTimelineSchema::Search.log: -> {
    # search is performed here
}

```

Named parameters may also be passed to provide extra data:

```
MyApp::Log::LogTimelineSchema::Search.log: :$query -> {
    # search is performed here
}

```

# Collecting data

## Logging to a file in JSON lines format

Set the `LOG_TIMELINE_JSON_LINES` environment variable to the name of a file to log to. Each line is an object with the following keys:

* `m` - module
* `c` - category
* `n` - name
* `t` - timestamp
* `d` - data (an object with any extra data)
* `k` - kind (0 = event, 1 = task start, 2 = task end)

A task start (kind 1) and task end (2) will also have:

* `i` - a unique ID for the task, starting from 1, to allow starts and ends to be matched up

An event (kind 0) or task start (kind 1) may also have:

* `p` - the parent task ID

## Logging to a file as a CBOR sequence

Set the `LOG_TIMELINE_CBOR_SEQUENCE` environment variable to the name of a file to log into. The schema matches that of the JSON lines output.

## Socket logging

Set the `LOG_TIMELINE_SERVER` environment variable to either:

* A port number, to bind to `localhost` on that port
* A string of the form `host:port`, e.g. `127.0.0.1:5555`

**Warning:** Don't expose the socket server to the internet directly; there is no authentication or encryption. If really wishing to expose it, bind it to a local port and then use an SSH tunnel.

## Handshake

Upon connection the client `must` send a JSON line consisting of an object that includes the keys:

* `min` - the minimum protocol version that the client understands
* `max` - the maximum protocol version that the client understands

The client *may* include other keys in the object speculatively (for example, if protocol version 3 supports a key "foo", but it speaks anything from 1 to 3, then it may include the key "foo", knowing that a previous version of the server will simply ignore it).

In response to this, the server *must* send a JSON line consisting of an object that includes *at most one of the following*:

* `ver` - the version number of the protocol that the server will speak, if it is understands any of the versions in the range the client proposed
* `err` - an error string explaining why it will not accept the request

In the case of sending an `err`, the server *should* close the connection.

If the initial communication from the client to the server:

* Does not start with a `{`
* Does not reach a complete line within 1 megabyte of data

Then the server may send a JSON line with an object containing `err` and then close the connection.

## Protocol version 1

No additional configuration keys from the client are recognized in this version of the protocol.

Beyond the initial handshake line, the client should not send anything to the server. The client may close the connection at any time.

The server sends JSON lines to the client. This lines are the same as specified for the JSON lines file format.

## Checking if logging is active

Call `Log::Timeline.has-output` to see if some kind of logging output is set up in this process, This is useful for avoiding introducing logging if it will never take place.

# AUTHOR

Jonathan Worthington

# COPYRIGHT AND LICENSE

Copyright 2019 - 2024 Jonathan Worthington

Copyright 2024 Raku Community

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_zef-lizmat-Rakudo-Version.md
[![Actions Status](https://github.com/lizmat/Rakudo-Version/actions/workflows/test.yml/badge.svg)](https://github.com/lizmat/Rakudo-Version/actions)

# NAME

Rakudo::Version - provide a "rakudo version" pragma

# SYNOPSIS

```
# Exactly this version
use rakudo v2022.01;

# From this version onward
use rakudo v2023.02+;

# More elaborate checks with a Callable
use rakudo { $_ ~~ v2022.01 || $_ ~~ v2022.07+ }

# Custom error message
use rakudo {
    $_ ~~ v2022.07+ || die "$_ is not recent enough for this"
}

```

# DESCRIPTION

The Rakudo::Version distribution provides a `use rakudo` pragma that allows one to specify with which version of Rakudo a program is supposed to run.

Version checking occurs either by specifying a `Version` value (which will be smart-matched with the current compiler `Version`), or it can be a `Callable` which will be given the current `Version` value, and which should return a `Bool` indicating whether or not the Rakudo release is acceptable.

# PRIOR ART

The [RakudoPrereq](https://raku.land/zef:raku-community-modules/RakudoPrereq) module, originally by `Zoffix Znet`, provides a more general approach to the problem of limiting a program to a specific release.

# AUTHOR

Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)

Source can be located at: <https://github.com/lizmat/Rakudo-Version> . Comments and Pull Requests are welcome.

If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!

# COPYRIGHT AND LICENSE

Copyright 2023 Elizabeth Mattijsen

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_zef-jonathanstowe-XDG-BaseDirectory.md
# XDG::BaseDirectory

Raku access to path information provided by the xdg base directory specfication <http://www.freedesktop.org/wiki/Specifications/basedir-spec/>

![Build Status](https://github.com/jonathanstowe/XDG-BaseDirectory/workflows/CI/badge.svg)

## Synopsis

```

    use XDG::BaseDirectory;

    my $bd = XDG::BaseDirectory.new

    for $bd.load-config-paths('mydomain.org', 'MyProg', 'Options') -> $d {
        say $d;
    }

    # Directories can be made available as terms as well
    use XDG::BaseDirectory :terms;

    say config-home;

```

## Description

This is loosely based on the interface of python module pyxdg. But
due to the differences between Python and Raku it may do some things
differently.

It provides a set of facilities for discovering the location of the
configuration and data of applications.

I split this out from the XDG module as it has more general usefulness
and no external dependencies.

## Installation

Assuming you have a working Rakudo installation with *zef* installed you can install from a copy of the source directory:

```
 zef install .

```

or remotely:

```
 zef install XDG::BaseDirectory

```

## Support

Suggestions/patches are welcomed via github at:

<https://github.com/jonathanstowe/XDG-BaseDirectory/issues>

I'm not able to test on a wide variety of platforms so any help there would be appreciated.

## Licence

This module is Free Software please see the <LICENCE> file in the distribution for the exact terms.

© Jonathan Stowe 2015-2021


## dist_cpan-KBUCHELI-Text-VimColour.md
# p6-Text-VimColour

Converts language source code into colour syntax HTML using vim.

Idea was shamelessly stolen from the original Perl 5 Text::VimColor

Pull requests welcome.

## Installation

To install this module, you'll need `vim` version at least 7.4.

An optional step for the best syntax colouring results is to
also install updated
[Perl 6 vim syntax files](https://github.com/vim-perl/vim-perl)

## Synopsis

```
    use Text::VimColour;
    Text::VimColour.new(
        lang => "perl6",
        in   => "file-to-highlight.p6",
        out  => '/tmp/out.html'
    );

```

## Methods

### new

```
    Text::VimColour.new(
        lang    => 'perl6',
        in      => 'file-to-highlight.p6'
        code    => 'say $foo;',
        out     => '/tmp/out.html',
    );

```

#### in

Specifies the input file with the code to highlight. You **must** specify
either `in` or `code`.

#### code

Specifies the code to highlight. You **must** specify either `in` or `code`.

#### lang

Optional. Specifies the language to use for highlighting. Defaults to `c`

#### out

Optional. Specifies the path to a file to output highlighted HTML into

### html-full-page

```
    say Text::VimColour.new( lang => 'perl6', in => 'file-to-highlight.p6')
        .html-full-page;

```

Takes no arguments. Returns the full HTML page with highlighted code
and styling CSS.

### html

```
    say Text::VimColour.new( lang => 'perl6', in => 'file-to-highlight.p6')
        .html;

```

Same as `html-full-page`, but returns only the highlighted code HTML.

### css

```
    say Text::VimColour.new( lang => 'perl6', in => 'file-to-highlight.p6')
        .css;

```

Same as `html-full-page`, but returns only the styling CSS code.


## dist_zef-raku-community-modules-Acme-Anguish.md
[![Actions Status](https://github.com/raku-community-modules/Acme-Anguish/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Acme-Anguish/actions) [![Actions Status](https://github.com/raku-community-modules/Acme-Anguish/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Acme-Anguish/actions) [![Actions Status](https://github.com/raku-community-modules/Acme-Anguish/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Acme-Anguish/actions)

# NAME

Acme::Anguish - Use Anguish programming language in your Raku programs

# SYNOPSIS

```
use Acme::Anguish;

anguish "\x2061" x 72 ~ "\x2063"; # prints "H"

```

# DESCRIPTION

*Anguish* is a [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck) variant that uses invisible Unicode characters instead of traditional Brainfuck's ones.

Here's the mapping of Brainfuck operators to *Anguish*:

|  |  |  |
| --- | --- | --- |
| > | [] | U+2060 WORD JOINER [Cf] |
| < | [] | U+200B ZERO WIDTH SPACE [Cf] |
| + | [] | U+2061 FUNCTION APPLICATION [Cf] |
| - | [] | U+2062 INVISIBLE TIMES [Cf] |
| . | [] | U+2063 INVISIBLE SEPARATOR [Cf] |
| , | [] | U+FEFF ZERO WIDTH NO-BREAK SPACE [Cf] |
| [ | [] | U+200C ZERO WIDTH NON-JOINER [Cf] |
| ] | [] | U+200D ZERO WIDTH JOINER [Cf] |

All other characters are silently ignored.

The meaning of original Brainfuck characters are as follows:

|  |  |
| --- | --- |
| > | increment the data pointer (to point to the next cell to the right). |
| < | decrement the data pointer (to point to the next cell to the left). |
| + | increment (increase by one) the byte at the data pointer. |
| - | decrement (decrease by one) the byte at the data pointer. |
| . | output the byte at the data pointer. |
| , | accept one byte of input, storing its value in the byte at the data pointer. |
| [ | if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching ] command. |
| ] | if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching [ command. |

# SUBROUTINES

## anguish

Takes a single positional argument: string of *Anguish* code to evaluate.

# EXAMPLES

See `examples` directory of this distribution for example *Anguish* programs.

# BUGS AND CAVEATS

The `U-FEFF` character also serves as a file [BOM](https://en.wikipedia.org/wiki/Byte_order_mark), so avoid using it as the first character in your file.

# AUTHOR

Zoffix Znet

# COPYRIGHT AND LICENSE

Copyright 2017 Zoffix Znet

Copyright 2018 - 2022 Raku Community

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_cpan-WBIKER-Module2Rpm-Spec.md
# NAME

App::Module2Rpm

# SYNOPSIS

```
# Download the source of a Raku module, write the spec file and upload them to OBS.
module2rpm --module=Module::Name

# Download the source, write the spec file and upload them to OBS for each line in a file.
module2rm --file=filePath

```

# DESCRIPTION

Please, note: This is still not a 1.0 release. Modules with certain dependencies might fail.

This program downloads the source of a given Raku module, writes the spec file with the module
metadata and uploaded them to Open Build Service (OBS).
There are two commandline parameter:

* `--module=Module::Name` Looks for the metadata of the given name to find the
  source download url and metadata.
* `--file=FilePath` Handles each line in the file as either module name or metadata
  download url.

# AUTHOR

wbiker [wbiker@gmx.at](mailto:wbiker@gmx.at)


## dist_zef-jonathanstowe-Object-Permission.md
# Object::Permission

Experimental method (and public attribute accessor,) level authorisation for Raku objects.

![Build Status](https://github.com/jonathanstowe/Object-Permission/workflows/CI/badge.svg)

## Synopsis

```
use Object::Permission;

class Foo {
	has $.baz is authorised-by('baz');

	method bar() is authorised-by('barbar') {
		...
	}
}

# Object::Permission::User is a role, just use type pun
$*AUTH-USER = Object::Permission::User.new(permissions => <barbar zub>);

my $foo = Foo.new;

$foo.bar();   # Executes okay
say $foo.baz; # Throws X::NotAuthorised

```

## Description

This is an experimental module to provide a rudimentary authorisation
mechanism for classes whereby selected methods or public attribute
accessors can require a named permission to execute, the permissions
associated with the dynamic variable `$*AUTH-USER` being checked
at invocation and an exception being thrown if the User object does not
have the required permission.

The intent is that `$*AUTH-USER` is initialised with an object
of some class that does the role `Object::Permission::User` which
populates the permissions as per the application logic.

## Installation

Assuming you have a working Rakudo installation you should be able to install this with *zef* :

```
# From the source directory

zef install .

# Remote installation

zef install Object::Permission

```

## Support

Suggestions/patches are welcomed via [github](https://github.com/jonathanstowe/Object-Permission/issues)

## Licence

This is free software.

Please see the <LICENCE> file in the distribution

© Jonathan Stowe 2015 - 2021


## dist_cpan-JGOFF-CommonMark.md
[![Build Status](https://travis-ci.org/drforr/perl6-CommonMark.svg?branch=master)](https://travis-ci.org/drforr/perl6-CommonMark)

# CommonMark

Interface to the <libcmark> CommonMark parser

# Synopsis

```
use CommonMark;

say CommonMark.to-html("Hello, world!");
# "<p>Hello, world!</p>"

say CommonMark.version-string;
# 0.28.3

```

# Documentation

CommonMark is Markdown with a proper spec - It should render most Markdown files the same; it nails down some edge cases, and specifies byte encodings.

You'll want to call `.to-html($text)` to convert markdown to HTML. The library itself also supports XML, LaTeX, and nroff/troff formats, but I haven't seen where it's tested. Check out the Perl 6 source for more details there.

# CommonMark class

## METHODS

* to-html( $common-mark )

Return HTML from CommonMark format. This is likely the only method you'll use. There's a lower-level interface that'll let you interrogate the library at the individual node level, look at the source for more inspiration.

* version()

Returns a 32-bit int containing the version number.

From the documetation:

```
* Bits 16-23 contain the major version.
* Bits 8-15 contain the minor version.
* Bits 0-7 contain the patchlevel.

```

* version-string()

Returns the library version in text form.

* parse-document( Str $buffer, int32 $options )

Returns a CommonMark::Node root of the document.

# CommonMark::Node class

* new( :$type )

Create a new CommonMark node with the specified type - this isn't well-documented in the library, so please read the source.

* next()

Return this node's successor in the multiply-linked list

* previous()

Return this node's predecessor in the multiply-linked list

* parent()

Return this node's parent in the multiply-linked list

* first-child()

Return this node's first child within the multiply-linked list

* last-child()

Return this node's last child within the multiply-linked list

* user-data()

Return this node's user data (generic pointer)

* user-data( Pointer $ptr )

Set user data pointer

* type()

Return this node's type number

* type-string()

Return this node's type as a string

* literal()

Return this node's literal string

* literal( Str $str )

Set this node's literal string

* heading-level()

Return this node's heading level

* heading-level( int32 $level )

Set this node's heading level

* list-type()

Return this node's list type

* list-type( int32 $level )

Set this node's list type

* list-delim()

Return this node's list delimiter

* list-delim( int32 $level )

Set this node's list delimiter

* list-start()

Return this node's list start

* list-start( int32 $level )

Set this node's list start

* list-tight()

Return this node's list tightness

* list-tight( int32 $level )

Set this node's list tightness

* fence-info()

Return this node's fence information

* fence-info( Str $info )

Set this node's fence information

* url()

Return this node's URL content

* url( Str $url )

Set this node's URL content

* title()

Return this node's title

* title( Str $title )

Set this node's title

* on-enter()

Return this node's on-enter string

* on-enter( Str $title )

Set this node's on-enter string

* on-exit()

Return this node's on-exit string

* on-exit( Str $title )

Set this node's on-exit string

* start-line()

Return this node's starting line

* start-column()

Return this node's starting column

* end-line()

Return this node's end line

* end-column()

Return this node's end column

* unlink()

Unlink this node from the tree.

* insert-before( CommonMark::Node $node )

Insert `$node` before this node

* insert-after( CommonMark::Node $node )

Insert `$node` after this node

* replace( CommonMark::Node $node )

Replace this node with `$node`

* prepend-child( CommonMark::Node $node )

Prepend `$node` below this node

* append-child( CommonMark::Node $node )

Append `$node` below this node

* consolidate-text-nodes()

Consolidate the text nodes in this node

* render-xml( int32 $options )

Render this node as XML, with the appropriate options `$options`

* render-html( int32 $options )

Render this node as HTML, with the appropriate options `$options`

* render-man( int32 $options, int32 $width )

Render this node as a manpage, with the appropriate options `$options`, `$width`

* render-commonmark( int32 $options, int32 $width )

Render this node as the original CommonMark text, with the appropriate options `$options` and `$idth`

* render-latex( int32 $options, int32 $width )

Render this node as LaTeX, with the appropriate options `$options`, `$width`

* check( int32 $file-ID )

Check this node with file descriptor $file-ID

# CommonMark::Iterator class

* next()

Return the next item in this iterator

* node()

Return the current node for the iterator

* event-type()

Return the current event type

* root()

Return the root for the iterator

* reset( CommonMark::Node $current, int32 $event-type )

Reset the iterator to node `$current`, type `$event-type`

# CommonMark::Parser class

* feed( Str $buffer )

Feed the buffer to the parser

* finish()

Finish parsing the document


## dist_github-ramiroencinas-System-Stats-NETUsage.md
# System::Stats::NETUsage

[![Build Status](https://travis-ci.com/ramiroencinas/System-Stats-NETUsage.svg?branch=master)](https://travis-ci.com/github/ramiroencinas/System-Stats-NETUsage)

Raku module - Provides Network Usage Stats.

## OS Supported:

* GNU/Linux by /proc/net/dev
* Win32 by netstat command

## Installing the module

```
zef update
zef install System::Stats::NETUsage

```

## Example Usage:

```
use v6;
use System::Stats::NETUsage;

my %netUsage = NET_Usage();

say "\nNetwork Usage per second:\n";

say "Bytes received: " ~ %netUsage<bytesReceivedPerSecond>;
say "    Bytes sent: " ~ %netUsage<bytesSentPerSecond>;

```


## dist_zef-lizmat-Net-protoent.md
[![Actions Status](https://github.com/lizmat/Net-protoent/workflows/test/badge.svg)](https://github.com/lizmat/Net-protoent/actions)

# NAME

Raku port of Perl's Net::protoent module

# SYNOPSIS

```
use Net::protoent;
my $p = getprotobyname('tcp') || die "no proto";
printf "proto for %s is %d, aliases are %s\n",
   $p.name, $p.proto, "$p.aliases()";

use Net::protoent qw(:FIELDS);
getprotobyname('tcp')         || die "no proto";
print "proto for $p_name is $p_proto, aliases are @p_aliases\n";

```

# DESCRIPTION

This module tries to mimic the behaviour of Perl's `Net::protoent` module as closely as possible in the Raku Programming Language.

This module's exports `getprotobyname`, `getprotobynumber`, and `getprotoent` functions that return `Netr::protoent` objects. This object has methods that return the similarly named structure field name from the C's protoent structure from netdb.h, stripped of their leading "p\_" parts, namely name, aliases, and proto.

You may also import all the structure fields directly into your namespace as regular variables using the :FIELDS import tag. Access these fields as variables named with a preceding p\_ in front their method names. Thus, $proto\_obj.name corresponds to $p\_name if you import the fields.

The `getproto` function is a simple front-end that forwards a numeric argument to `getprotobynumber` and the rest to `getprotobyname`.

# PORTING CAVEATS

This module depends on the availability of POSIX semantics. This is generally not available on Windows, so this module will probably not work on Windows.

# AUTHOR

Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks)

Source can be located at: <https://github.com/lizmat/Net-protoent> . Comments and Pull Requests are welcome.

# COPYRIGHT AND LICENSE

Copyright 2018, 2019, 2020, 2021 Elizabeth Mattijsen

Re-imagined from Perl as part of the CPAN Butterfly Plan.

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## what.md
what

Combined from primary sources listed below.

# [In X::Undeclared](#___top "go to top of document")[§](#(X::Undeclared)_method_what "direct link")

See primary documentation
[in context](/type/X/Undeclared#method_what)
for **method what**.

Returns the kind of symbol that was not declared (for example variable, type, routine).

Since The symbol wasn't declared, the compiler sometimes has to guess (or rather disambiguate) what kind of symbol it encounter that wasn't declared. For example if you write

```raku
say a;

```

Then the disambiguation defaults to reporting a missing subroutine, even though declaring a `constant a = 'a'` would also make the error go away.

# [In X::Cannot::Lazy](#___top "go to top of document")[§](#(X::Cannot::Lazy)_method_what "direct link")

See primary documentation
[in context](/type/X/Cannot/Lazy#method_what)
for **method what**.

```raku
method what()
```

Returns the type that was the target of the action, if it was not the lazy list itself.

# [In X::Syntax::Missing](#___top "go to top of document")[§](#(X::Syntax::Missing)_method_what "direct link")

See primary documentation
[in context](/type/X/Syntax/Missing#method_what)
for **method what**.

```raku
method what(--> Str:D)
```

Returns a string description of the missing syntax element.

# [In IO::Special](#___top "go to top of document")[§](#(IO::Special)_method_what "direct link")

See primary documentation
[in context](/type/IO/Special#method_what)
for **method what**.

```raku
say $*IN.path.what;  # OUTPUT: «<STDIN>␤»
say $*OUT.path.what; # OUTPUT: «<STDOUT>␤»
say $*ERR.path.what; # OUTPUT: «<STDERR>␤»
```

Returns one of the strings `'<STDIN>'`, `'<STDOUT>'`, or `'<STDERR>'`, specifying the type of the special IO device.

# [In X::Cannot::Empty](#___top "go to top of document")[§](#(X::Cannot::Empty)_method_what "direct link")

See primary documentation
[in context](/type/X/Cannot/Empty#method_what)
for **method what**.

```raku
method what()
```

Returns the type that was the target of the action.

# [In X::OutOfRange](#___top "go to top of document")[§](#(X::OutOfRange)_method_what "direct link")

See primary documentation
[in context](/type/X/OutOfRange#method_what)
for **method what**.

```raku
method what(--> Str:D)
```

Verbal description of the thing that was out of range (e.g. `"array index"`, `"month"`).

# [In X::Syntax::Malformed](#___top "go to top of document")[§](#(X::Syntax::Malformed)_method_what "direct link")

See primary documentation
[in context](/type/X/Syntax/Malformed#method_what)
for **method what**.

```raku
method what(X::Syntax::Malformed:D: --> Str)
```

Returns a description of the thing that was being parsed.

# [In X::Syntax::Variable::Numeric](#___top "go to top of document")[§](#(X::Syntax::Variable::Numeric)_method_what "direct link")

See primary documentation
[in context](/type/X/Syntax/Variable/Numeric#method_what)
for **method what**.

```raku
method what returns Str:D
```

Returns a verbal description of the kind of symbol that was declared (variable, parameter, attribute).

# [In X::Redeclaration](#___top "go to top of document")[§](#(X::Redeclaration)_method_what "direct link")

See primary documentation
[in context](/type/X/Redeclaration#method_what)
for **method what**.

Returns the kind of symbol that was redeclared. Usually `symbol`, but can also be `routine`, `type` etc.


## rational.md
role Rational

Number stored as numerator and denominator

```raku
role Rational[::NuT, ::DeT] does Real { ... }
```

`Rational` is the common role for numbers that are stored as pairs of numerator and denominator. It is parameterized by the types of the numerator (`NuT`) and denominator (`DeT`). By default, these are [`Int`](/type/Int), but other types of `Rational` are possible by using a different parameterization. In addition, `Rational` objects are immutable throughout their life.

```raku
class Positive does Rational[UInt] {};
my Positive $one-third = Positive.new(1,3);
say $one-third;                         # OUTPUT: «0.333333␤»
my Positive $fail =Positive.new(-2,3);  # OUTPUT: «Type check failed in binding to parameter 'nu'; expected UInt but got Int (-2)␤»
```

Please note that, since `DeT` is by default equal to `NuT`, in this case both are instantiated to [`UInt`](/type/UInt). Built into Raku are [`Rat`](/type/Rat) and [`FatRat`](/type/FatRat), which both do the `Rational` role.

# [Methods](#role_Rational "go to top of document")[§](#Methods "direct link")

## [method new](#role_Rational "go to top of document")[§](#method_new "direct link")

```raku
method new(NuT:D $numerator, DeT:D $denominator --> Rational:D)

```

Creates a new rational object from numerator and denominator, which it normalizes to the lowest terms. The `$denominator` can be zero, in which case the numerator is normalized to `-1`, `0`, or `1` depending on whether the original is negative, zero, or positive, respectively.

## [method Bool](#role_Rational "go to top of document")[§](#method_Bool "direct link")

```raku
multi method Bool(Rational:D: --> Bool:D)
```

Returns `False` if [numerator](/routine/numerator) is `0`, otherwise returns `True`. This applies for `<0/0>` zero-denominator <`Rational` as well, despite `?<0/0>.Num` being `True`.

## [method Bridge](#role_Rational "go to top of document")[§](#method_Bridge "direct link")

```raku
method Bridge()
```

Returns the number, converted to [`Num`](/type/Num).

## [method Int](#role_Rational "go to top of document")[§](#method_Int "direct link")

```raku
method Int(Rational:D: --> Int:D)
```

Coerces the invocant to [`Int`](/type/Int) by truncating non-whole portion of the represented number, if any. If the [denominator](/routine/denominator) is zero, will [fail](/routine/fail) with [`X::Numeric::DivideByZero`](/type/X/Numeric/DivideByZero).

## [method Num](#role_Rational "go to top of document")[§](#method_Num "direct link")

```raku
method Num(Rational:D: --> Num:D)
```

Coerces the invocant to [`Num`](/type/Num) by dividing [numerator](/routine/numerator) by [denominator](/routine/denominator). If [denominator](/routine/denominator) is `0`, returns `Inf`, `-Inf`, or `NaN`, based on whether [numerator](/routine/numerator) is a positive number, negative number, or `0`, respectively.

## [method ceiling](#role_Rational "go to top of document")[§](#method_ceiling "direct link")

```raku
method ceiling(Rational:D: --> Int:D)
```

Return the smallest integer not less than the invocant. If [denominator](/routine/denominator) is zero, [fails](/routine/fail) with [`X::Numeric::DivideByZero`](/type/X/Numeric/DivideByZero).

## [method floor](#role_Rational "go to top of document")[§](#method_floor "direct link")

```raku
method floor(Rational:D: --> Int:D)
```

Return the largest integer not greater than the invocant. If [denominator](/routine/denominator) is zero, [fails](/routine/fail) with [`X::Numeric::DivideByZero`](/type/X/Numeric/DivideByZero).

## [method isNaN](#role_Rational "go to top of document")[§](#method_isNaN "direct link")

```raku
method isNaN(Rational:D: --> Bool:D)
```

Tests whether the invocant's Num value is a NaN, an acronym for *Not available Number*. That is both its numerator and denominator are zero.

## [method numerator](#role_Rational "go to top of document")[§](#method_numerator "direct link")

```raku
method numerator(Rational:D: --> NuT:D)

```

Returns the numerator.

## [method denominator](#role_Rational "go to top of document")[§](#method_denominator "direct link")

```raku
method denominator(Rational:D: --> DeT:D)

```

Returns the denominator.

## [method nude](#role_Rational "go to top of document")[§](#method_nude "direct link")

```raku
method nude(Rational:D: --> Positional)
```

Returns a list of the numerator and denominator.

## [method norm](#role_Rational "go to top of document")[§](#method_norm "direct link")

```raku
method norm(Rational:D: --> Rational:D)
```

**DEPRECATED as of 6.d**. The method is no longer needed, because as of 6.d language version, it's required for `Rational` type to be normalized on creation.

Returns a normalized Rational object, i.e. with positive denominator, and numerator and denominator coprime. The denominator can also by zero, but using it in any operation or a conversion to string will result in an exception.

```raku
use v6.c;
my Rational $by-zero = 3/0;
say $by-zero.norm.raku; # OUTPUT: «<1/0>␤»

```

```raku
say $by-zero; # OUTPUT: «Attempt to divide by zero when coercing Rational to Str␤

```

## [method base-repeating](#role_Rational "go to top of document")[§](#method_base-repeating "direct link")

```raku
method base-repeating(Rational:D: Int:D() $base = 10)
```

Returns a list of two strings that, when concatenated, represent the number in base `$base`. The second element is the one that repeats. For example:

```raku
my ($non-rep, $repeating) = (19/3).base-repeating(10);
say $non-rep;                               # OUTPUT: «6.␤»
say $repeating;                             # OUTPUT: «3␤»
printf '%s(%s)', $non-rep, $repeating;      # OUTPUT: «6.(3)»
```

19/3 is 6.333333... with the 3 repeating indefinitely.

If no repetition occurs, the second string is empty:

```raku
say (5/2).base-repeating(10).raku;          # OUTPUT: «("2.5", "")␤»
```

The precision for determining the repeating group is limited to 1000 characters, above that, the second string is `???`.

`$base` defaults to `10`.

## [method Range](#role_Rational "go to top of document")[§](#method_Range "direct link")

Returns a [Range object](/type/Range) that represents the range of values supported.

# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")

Type relations for `Rational`

raku-type-graph

Rational
Rational

Real
Real

Rational->Real

Numeric
Numeric

Real->Numeric

Mu
Mu

Any
Any

Any->Mu

Cool
Cool

Cool->Any

Rat
Rat

Rat->Rational

Rat->Cool

FatRat
FatRat

FatRat->Rational

FatRat->Cool

Stringy
Stringy

Str
Str

Str->Cool

Str->Stringy

Allomorph
Allomorph

Allomorph->Str

RatStr
RatStr

RatStr->Rat

RatStr->Allomorph

[Expand chart above](/assets/typegraphs/Rational.svg)


## inet.md
class IO::Socket::INET

TCP Socket

```raku
class IO::Socket::INET does IO::Socket {}

```

`IO::Socket::INET` provides TCP sockets, both the server and the client side.

For UDP support, please see [`IO::Socket::Async`](/type/IO/Socket/Async).

Here is an example of a very simplistic "echo" server that listens on `localhost`, port `3333`:

```raku
my $listen = IO::Socket::INET.new( :listen,
                                   :localhost<localhost>,
                                   :localport(3333) );
loop {
    my $conn = $listen.accept;
    try {
        while my $buf = $conn.recv(:bin) {
            $conn.write: $buf;
        }
    }
    $conn.close;

    CATCH {
          default { .payload.say;      }
    }

}

```

And a client that connects to it, and prints out what the server answers:

```raku
my $conn = IO::Socket::INET.new( :host<localhost>,
                                 :port(3333) );
$conn.print: 'Hello, Raku';
say $conn.recv;
$conn.close;

```

Please bear in mind that this is a synchronous connection; an attempt by any of the nodes to write without the other reading will produce the error `Could not receive data from socket: Connection reset by peer`.

# [Methods](#class_IO::Socket::INET "go to top of document")[§](#Methods "direct link")

## [method new](#class_IO::Socket::INET "go to top of document")[§](#method_new "direct link")

```raku
multi method new(
        :$host,
        :$port,
        :$family = PF_INET,
        :$encoding = 'utf-8',
        :$nl-in = "\r\n",
    --> IO::Socket::INET:D)
multi method new(
        :$localhost,
        :$localport,
        :$family = PF_INET,
        :$listen,
        :$encoding = 'utf-8',
        :$nl-in = "\r\n",
    --> IO::Socket::INET:D)

```

Creates a new socket.

If `:$listen` is True, creates a new socket that listen on `:$localhost` (which can be an IP address or a domain name) on port `:$localport`; in other words the `:$listen` flag determines the *server mode* of the socket. Otherwise (i.e., `:$listen` is `False`), the new socket opens immediately a connection to `:$host` on port `:$port`.

`:$family` defaults to `PF_INET` constant for IPv4, and can be set to `PF_INET6` constant for IPv6.

For text operations (such as [method lines](#method_lines) and [method get](#method_get)), `:$encoding` specifies the encoding, and `:$nl-in` determines the character(s) that separate lines.

# [Methods](#class_IO::Socket::INET "go to top of document")[§](#Methods_0 "direct link")

## [method get](#class_IO::Socket::INET "go to top of document")[§](#method_get "direct link")

```raku
method get()
```

Reads a line from the socket and returns it as of type [`Str`](/type/Str). Return [`Nil`](/type/Nil) on end-of-file (EOF).

## [method lines](#class_IO::Socket::INET "go to top of document")[§](#method_lines "direct link")

```raku
method lines()
```

Returns a lazy list of lines read from the socket.

## [method accept](#class_IO::Socket::INET "go to top of document")[§](#method_accept "direct link")

```raku
method accept()
```

In listen/server mode, waits for a new incoming connection. Once a new connection is established, an `IO::Socket::INET` instance (or a subclass instance) for consuming the connection is returned.


## is-20cached.md
is cached

Combined from primary sources listed below.

# [In Routine](#___top "go to top of document")[§](#(Routine)_trait_is_cached "direct link")

See primary documentation
[in context](/type/Routine#trait_is_cached)
for **trait is cached**.

```raku
multi trait_mod:<is>(Routine $r, :$cached!)
```

Causes the return value of a routine to be stored, so that when subsequent calls with the same list of arguments are made, the stored value can be returned immediately instead of re-running the routine.[[1]](#fn1)

Useful when storing and returning the computed value is much faster than re-computing it every time, and when the time saved trumps the cost of the use of more memory.

Even if the arguments passed to the routine are "reference types" (such as objects or arrays), then for the purpose of caching they will only be compared based on their contents. Thus the second invocation will hit the cache in this case:

```raku
say foo( [1, 2, 3] );   # runs foo
say foo( [1, 2, 3] );   # doesn't run foo, uses cached value

```

Since it's still at the experimental stage, you will have to insert the `use experimental :cached;` statement in any module or script that uses it.

```raku
use experimental :cached;

sub nth-prime(Int:D $x where * > 0) is cached {
    say "Calculating {$x}th prime";
    return (2..*).grep(*.is-prime)[$x - 1];
}

say nth-prime(43);
say nth-prime(43);
say nth-prime(43);

```

produces this output:

｢text｣ without highlighting

```

```

Calculating 43th prime
191
191
191

```

```

**Note**: This feature is not thread-safe.


## dist_zef-antononcube-DSL-English-ClassificationWorkflows.md
# DSL::English::ClassificationWorkflows (Raku package)

## In brief

This Raku (Perl 6) package has grammar classes and action classes for the parsing and
interpretation of natural Domain Specific Language (DSL) commands that specify classification workflows.

The interpreters (actions) target different programming languages: Python, R, Raku, Wolfram Language (WL), and others.
Also, different natural languages.

Currently, the generated pipelines are for the software monad
["ClCon"](https://github.com/antononcube/MathematicaForPrediction/blob/master/MonadicProgramming/MonadicContextualClassification.m)
implemented in WL, [AAp1], and WL's built-in commands.

**Remark:** "ClCon" stands for "Classification using a Context".

**Remark:** "WL" stands for "Wolfram Language". "Mathematica" and "WL" are used as synonyms.

---

## Installation

Zef ecosystem:

```
zef install DSL::English::ClassificationWorkflows

```

GitHub:

```
zef install https://github.com/antononcube/Raku-DSL-English-ClassificationWorkflows.git

```

---

## Examples

### Programming languages

Here is a simple invocation:

```
use DSL::English::ClassificationWorkflows;

ToClassificationWorkflowCode('make a logistic regression classifier', 'WL::ClCon');

```

```
# ClConMakeClassifier[ "LogisticRegression" ]

```

Here is a more complicated pipeline specification used to generate the code
for two WL classification systems:

```
my $command = q:to/END/;
use dfTitanic;
split the data with ratio 0.73;
create a logistic regression classifier;
show precision and recall;
show top confusions, misclassified examples, least certain examples;
show ROC plots;
END

say $_.key, "\n", $_.value, "\n"  for ($_ => ToClassificationWorkflowCode($command, $_ ) for <WL::ClCon WL::System>);

```

```
# WL::ClCon
# ClConUnit[ dfTitanic ] \[DoubleLongRightArrow]
# ClConSplitData[ "TrainingFraction" -> 0.73 ] \[DoubleLongRightArrow]
# ClConMakeClassifier[ "LogisticRegression" ] \[DoubleLongRightArrow]
# ClConClassifierMeasurements[ {"Precision", "Recall"} ] \[DoubleLongRightArrow] ClConEchoValue[] \[DoubleLongRightArrow]
# ClConClassifierMeasurements[ {"TopConfusions", "MisclassifiedExamples", "LeastCertainExamples"} ] \[DoubleLongRightArrow] ClConEchoValue[] \[DoubleLongRightArrow]
# ClConROCPlot[]
#
# WL::System
# data = ClConToNormalClassifierData @ dfTitanic;
# {dataTraining, dataTesting} = TakeDrop[ RandomSample[data], Floor[ 0.73 * Length[data] ] ];
# dataValidation = Automatic;
# clObj = Classify[ dataTraining, Method -> "LogisticRegression", ValidationSet -> dataValidation ];
# Echo @ ClassifierMeasurements[clObj, dataTesting, {"Precision", "Recall"} ];
# Echo @ ClassifierMeasurements[clObj, dataTesting, {"TopConfusions", "MisclassifiedExamples", "LeastCertainExamples"} ];
# Echo @ ROCPlot[]

```

### Natural languages

```
say $_.key, "\n", $_.value, "\n"  for ($_ => ToClassificationWorkflowCode($command, $_ ) for <Bulgarian English Russian>);

```

```
# Bulgarian
# използвай данните: dfTitanic
# раздели данните с тренировъчна част 0.73
# тренирай класификатор с метод: logistic regression
# изчисли следните мерки на класификатора: "Precision", "Recall"
# изчисли следните мерки на класификатора: "TopConfusions", "MisclassifiedExamples", "LeastCertainExamples"
# покажи диаграма с приемателните операционни характеристики (ROC)
#
# English
# use the data: dfTitanic
# split data with training part 0.73
# train classifier with method: logistic regression
# compute the classifier measures: "Precision", "Recall"
# compute the classifier measures: "TopConfusions", "MisclassifiedExamples", "LeastCertainExamples"
# show Receiver Operating Characteristics (ROC) diagram
#
# Russian
# использовать данные: dfTitanic
# разделить данные с тренировочная часть 0.73
# обучить классификатор методом: logistic regression
# вычислить следующие показатели классификатора: "Precision", "Recall"
# вычислить следующие показатели классификатора: "TopConfusions", "MisclassifiedExamples", "LeastCertainExamples"
# показать диаграмму рабочих характеристик приемника (RХП)

```

---

## Command line interface

The package provides Command Line Interface (CLI) for its functionalities:

```
ToClassificationWorkflowCode --help

```

```
# Translates natural language commands into classification programming code.
# Usage:
#   ToClassificationWorkflowCode <command> [--target=<Str>] [--language=<Str>] [--format=<Str>] [-c|--clipboard-command=<Str>] -- Translates natural language commands into (machine learning) classification workflow programming code.
#   ToClassificationWorkflowCode <target> <command> [--language=<Str>] [--format=<Str>] [-c|--clipboard-command=<Str>] -- Both target and command as arguments.
#   ToClassificationWorkflowCode [<words> ...] [-t|--target=<Str>] [-l|--language=<Str>] [-f|--format=<Str>] [-c|--clipboard-command=<Str>] -- Command given as a sequence of words.
#
#     <command>                       A string with one or many commands (separated by ';').
#     --target=<Str>                  Target (programming language with optional library spec.) [default: 'WL-ClCon']
#     --language=<Str>                The natural language to translate from. [default: 'English']
#     --format=<Str>                  The format of the output, one of 'automatic', 'code', 'hash', or 'raku'. [default: 'automatic']
#     -c|--clipboard-command=<Str>    Clipboard command to use. [default: 'Whatever']
#     <target>                        Programming language.
#     [<words> ...]                   Words of a data query.
#     -t|--target=<Str>               Target (programming language with optional library spec.) [default: 'WL::ClCon']
#     -l|--language=<Str>             The natural language to translate from. [default: 'English']
#     -f|--format=<Str>               The format of the output, one of 'automatic', 'code', 'hash', or 'raku'. [default: 'automatic']
# Details:
#     If --clipboard-command is the empty string then no copying to the clipboard is done.
#     If --clipboard-command is 'Whatever' then:
#         1. It is attempted to use the environment variable CLIPBOARD_COPY_COMMAND.
#             If CLIPBOARD_COPY_COMMAND is defined and it is the empty string then no copying to the clipboard is done.
#         2. If the variable CLIPBOARD_COPY_COMMAND is not defined then:
#             - 'pbcopy' is used on macOS
#             - 'clip.exe' on Windows
#             - 'xclip -sel clip' on Linux.

```

---

## Versions

The original version of this Raku package was developed/hosted at
[ [AAp2](https://github.com/antononcube/ConversationalAgents/tree/master/Projects/ClassficationWorkflowsAgent) ].

A dedicated GitHub repository was made in order to make the installation with Raku's `zef` more direct.
(As shown above.)

---

## References

[AAp1] Anton Antonov,
[Monadic contextual classification Mathematica package](https://github.com/antononcube/MathematicaForPrediction/blob/master/MonadicProgramming/MonadicContextualClassification.m),
(2017-2022),
[MathematicaForPrediction at GitHub](https://github.com/antononcube/MathematicaForPrediction).

[AAp2] Anton Antonov,
["Classification workflows conversational agent"](https://github.com/antononcube/ConversationalAgents/tree/master/Projects/ClassficationWorkflowsAgent),
(2017),
[ConversationalAgents at GitHub](https://github.com/antononcube/ConversationalAgents).