## dist_zef-antononcube-Lingua-NumericWordForms.md
# Raku Lingua::NumericWordForms

[![MacOS](https://github.com/antononcube/Raku-Lingua-NumericWordForms/actions/workflows/macos.yml/badge.svg)](https://github.com/antononcube/Raku-Lingua-NumericWordForms/actions/workflows/macos.yml)
[![Linux](https://github.com/antononcube/Raku-Lingua-NumericWordForms/actions/workflows/linux.yml/badge.svg)](https://github.com/antononcube/Raku-Lingua-NumericWordForms/actions/workflows/linux.yml)
[![Win64](https://github.com/antononcube/Raku-Lingua-NumericWordForms/actions/workflows/windows.yml/badge.svg)](https://github.com/antononcube/Raku-Lingua-NumericWordForms/actions/workflows/windows.yml)
[![](https://raku.land/zef:antononcube/Lingua::NumericWordForms/badges/version)](https://raku.land/zef:antononcube/Lingua::NumericWordForms)
[![](https://raku.land/zef:antononcube/Lingua::NumericWordForms/badges/downloads)](https://raku.land/zef:antononcube/Lingua::NumericWordForms)
[![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0)

🇦🇲 🇦🇿 🇧🇬 🇨🇿 🇬🇧 🇫🇷 🇩🇪 🇬🇷 🇮🇷 🇯🇵 🇰🇿 🇵🇱 🇵🇹 🇷🇴 🇷🇺 🇪🇸 🇺🇦

## Introduction

This repository provides a Raku package with functions for the
generation, parsing, and interpretation of numeric word forms in different languages.

The initial versions of the code in this repository can be found in the GitHub repository [AAr1].

The Raku package
[`Lingua::Number`](https://github.com/labster/p6-Lingua-Number), [BL1],
provides word forms (cardinal, ordinal, etc.) generation in many languages.
(But at least for one language the produced forms are incorrect.)

The Raku package
[`Lingua::EN::Numbers`](https://github.com/labster/p6-Lingua-Number), [SS1],
also provides word forms (cardinal, ordinal, etc.) generation in English.

The parsers and interpreters of this package can be seen as complementary
to the functions in [BL1, SS1].

**Remark:** Maybe a more complete version of this package should be merged with
[`Lingua::Number`](https://github.com/labster/p6-Lingua-Number), [BL1].

**Remark:** I can judge the quality of the results only of the languages:
Bulgarian, English, and Russian. The numeric word form interpreters for the rest of the languages
pass testing, but they might have potentially many deficiencies.
(That are easily detected by people who have mastered those languages.)

**Remark:** The package also "understands" (i.e. parses and translates to)
[Koremutake](https://shorl.com/koremutake.php).

---

## Installation

Package installations from both sources use [zef installer](https://github.com/ugexe/zef)
(which should be bundled with the "standard" [Rakudo](https://rakudo.org) installation file.)

To install the package via Zef's ecosystem use the shell command:

```
zef install Lingua::NumericWordForms

```

To install the package from the GitHub repository use the shell command:

```
zef install https://github.com/antononcube/Raku-Lingua-NumericWordForms.git

```

---

## Examples

### Generation

The generation of numeric word forms is a *secondary* goal of this package.
Currently only generation of Bulgarian, English, [Koremutake](https://shorl.com/koremutake.php), and Russian
numeric word forms are implemented.
Here are examples:

```
use Lingua::NumericWordForms;
say to-numeric-word-form(8093);
say to-numeric-word-form(8093, 'Bulgarian');
say to-numeric-word-form(8093, 'Koremutake');
say to-numeric-word-form(8093, 'Russian');

```

```
# eight thousand, ninety three
# осем хиляди и деветдесет и три
# pohy
# восемь тысяч девяносто три

```

The first argument of `to-numeric-word-form` can be:

* An integer
* A string that can be parsed into an integer
* A string of numbers separated by ";"
* A list of numbers or strings

Here are examples of the latter two:

```
to-numeric-word-form('123; 232; 898_934').join('; ');

```

```
# one hundred twenty three; two hundred thirty two; eight hundred ninety eight thousand, nine hundred thirty four

```

```
to-numeric-word-form([321, '992', 100_904]).join('; ');

```

```
# three hundred twenty one; nine hundred ninety two; one hundred thousand, nine hundred four

```

### Interpretation

Interpretation of numeric word forms is the *primary* goal of this package.
Multiple language are supported. Here are examples:

```
use Lingua::NumericWordForms;
say from-numeric-word-form('one thousand and twenty three');
say from-numeric-word-form('хиляда двадесет и три', 'Bulgarian');
say from-numeric-word-form('tysiąc dwadzieścia trzy', 'Polish');
say from-numeric-word-form('одна тысяча двадцать три', lang => 'Russian');
say from-numeric-word-form('mil veintitrés', lang => 'Spanish');

```

```
# 1023
# 1023
# 1023
# 1023
# 1023

```

The function `from-numeric-word-form` can take as a first argument:

* A string that is a numeric word form
* A string comprised of numeric word forms separated by ";"
* A list or an array of strings

The language can be specified as a second positional argument or with the named argument "lang".
In addition to the names of the supported languages the value of the language argument can be also `Whatever` or "Automatic".

Here are corresponding examples:

```
from-numeric-word-form('twenty six');

```

```
# 26

```

```
from-numeric-word-form(['mil veintitrés', 'dos mil setenta y dos']);

```

```
# (1023 2072)

```

```
from-numeric-word-form('two hundred and five; триста четиридесет и две; 二十万六十五'):p;

```

```
# (english => 205 bulgarian => 342 japanese => 200065)

```

For more examples see the file
[NumericWordForms-examples.raku](examples/NumericWordForms-parsing-examples.raku).

Here we retrieve a list of all supported languages:

```
from-numeric-word-form('languages').sort

```

```
# (armenian azerbaijani azərbaycan bulgarian czech deutsch english español français french german greek japanese kazakh korean koremutake persian polish polski portuguese português qazaq romanian română russian spanish ukrainian český ελληνικά български казак руский український қазақ հայերեն 日本語 한국어)

```

**Remark:** In the list above some languages appear twice, with both their English and native names.

#### Type of the result

The returned result can be an `Int` object or a `Str` object -- that is controlled with
the adverb `number` (which by default is `True`.) Here is an example:

```
my $res = from-numeric-word-form('one thousand and twenty three');
say $res, ' ', $res.WHAT;

```

```
# 1023 (Int)

```

```
$res = from-numeric-word-form('one thousand and twenty three', :!number);
say $res, ' ', $res.WHAT;

```

```
# 1023 (Str)

```

#### Automatic language detection

Automatic language detection is invoked if the second argument is `Whatever` or "Automatic":

```
say from-numeric-word-form('tysiąc dwadzieścia trzy', Whatever):p;
say from-numeric-word-form('триста двадесет и три', lang => 'Automatic'):p;

```

```
# polish => 1023
# bulgarian => 323

```

```
say from-numeric-word-form(['tysiąc dwadzieścia trzy', 'twenty three']):p;

```

```
# (polish => 1023 english => 23)

```

The adverb `:pairs` (`:p`) specifies whether the result should be a `Pair` object or a `List` of `Pair` objects
with the detected languages as keys.

### Translation

Translation from one language to another:

```
translate-numeric-word-form('хиляда двадесет и три', 'Bulgarian' => 'English');

```

```
# one thousand, twenty three

```

```
translate-numeric-word-form('two hundred thousand and five', 'English' => 'Bulgarian');

```

```
# двеста хиляди и пет

```

**Remark:** Currently that function translates to Bulgarian, English,
[Koremutake](https://shorl.com/koremutake.php), and Russian.
only (from any of the package languages.)

Here is a Spanish to Koremutake example:

```
my $numForm = "tres mil ochocientos noventa";
my $trRes = translate-numeric-word-form($numForm, 'Automatic' => 'Koremutake');
say "Given           : $numForm";
say "To Koremutake   : $trRes";
say "From Koremutake : {from-numeric-word-form($trRes)}";

```

```
# Given           : tres mil ochocientos noventa
# To Koremutake   : jami
# From Koremutake : 3890

```

The named arguments "from" and "to" can be also used:

```
translate-numeric-word-form($numForm, from => Whatever, to => 'English');

```

```
# three thousand, eight hundred ninety

```

---

## Roles

This package provides (exports) roles that can be used in grammars or roles in other packages, applications, etc.

For example, see the roles:

```
Lingua::NumericWordForms::Roles::Bulgarian::WordedNumberSpec
Lingua::NumericWordForms::Roles::English::WordedNumberSpec

```

A grammar or role that does the roles above should use the rule:

```
<numeric-word-form>

```

For code examples see the file
[Parsing-examples.raku](./examples/Parsing-examples.raku).

**Remark:** The role `Lingua::NumericWordForms::Roles::WordedNumberSpec` and the corresponding
actions class `Lingua::NumericWordForms::Actions::WordedNumberSpec` are "abstract".
They were introduced in order to have simpler roles and actions code
(and non-duplicated implementations.) Hence, that role and class *should not* be used in
grammars and roles outside of this package.

---

## CLI

The package provides two Command Line Interface (CLI) functions:
`from-numeric-word-form` and `to-numeric-word-form`.

Corresponding usage messages and examples are given below.

### `from-numeric-word-form`

#### Usage message

```
from-numeric-word-form --help

```

```
# Usage:
#   from-numeric-word-form <text> [-l|--lang=<Str>] [-p|--pairs] [-f|--format=<Str>] -- Interprets numeric word forms into numbers.
#   from-numeric-word-form [<words> ...] [-l|--lang=<Str>] [-p|--pairs] [-f|--format=<Str>] -- Takes a list of words to be a numeric word form and interprets it into a number.
#   from-numeric-word-form [-l|--lang=<Str>] [-p|--pairs] [-f|--format=<Str>] -- Interprets numeric word forms from a (pipeline) input.
#
#     <text>               Text to interpret to numbers.
#     -l|--lang=<Str>      Language [default: 'Automatic']
#     -p|--pairs           Should Language-number pairs be returned or not? [default: False]
#     -f|--format=<Str>    Output format one of 'text', 'lines', or 'raku'. [default: 'text']
#     [<words> ...]        Text to interpret to numbers.

```

#### Example

```
from-numeric-word-form two hundred and five

```

```
# 205

```

### `to-numeric-word-form`

#### Usage message

```
to-numeric-word-form --help

```

```
# Usage:
#   to-numeric-word-form <text> [-l|--lang=<Str>] [-f|--format=<Str>] -- Coverts numbers into numeric word forms.
#   to-numeric-word-form [<words> ...] [-l|--lang=<Str>] [-f|--format=<Str>] -- Takes a list of numbers and converts it into a list of numeric word forms.
#   to-numeric-word-form [-l|--lang=<Str>] [-f|--format=<Str>] -- Converts numbers from a (pipeline) input into numeric word forms.
#
#     <text>               String of one or more numbers to convert into numeric word forms. (Multiple numbers can be separated with ';'.)
#     -l|--lang=<Str>      Language (one of 'Bulgarian', 'English', or 'Koremutake'.) [default: 'English']
#     -f|--format=<Str>    Output format one of 'text', 'lines', or 'raku'. [default: 'text']
#     [<words> ...]        Number strings to be converted into numeric word forms.

```

#### Example

```
to-numeric-word-form 33 124 99832 --lang Bulgarian

```

```
# тридесет и три; сто двадесет и четири; деветдесет и девет хиляди осемстотин тридесет и две

```

---

## TODO

The following TODO items are ordered by priority, the most important are on top.

1. TODO Expand parsing beyond trillions
2. DONE Automatic determination of the language
3. DONE Word form generation:

   * DONE Bulgarian
   * DONE English
   * DONE Koremutake
   * DONE Russian
   * CANCELED General algorithm
     * Canceled because it is a hard problem and Large Language Models (LLMs) can do it.
4. TODO Documentation of the general programming approach.

   * TODO What are the main challenges?
   * TODO How the chosen software architecture decisions address them?
   * TODO Concrete implementations walk-through.
   * TODO How to implement / include a new language?
   * TODO How the random numbers test files were made?
   * TODO Profiling, limitations, alternatives.
   * TODO Comparison with LLM-based conversions.
5. TODO Full, consistent Persian numbers parsing.

   * Currently, Persian number parsing works only for numbers less than 101.
6. DONE General strategy for parsing and interpretation of
   numeric word forms of East Asia languages

   * Those languages use groupings based on 10^4 instead of 10^3.
   * DONE Implementation for Japanese.
7. TODO Implement parsing of ordinal numeric word forms

   * DONE English, French, Greek, and Spanish
   * DONE Bulgarian
   * DONE Czech, Russian, Ukrainian, Polish
   * DONE Japanese
   * DONE Koremutake
   * DONE Portuguese
   * DONE Azerbaijani
   * DONE Kazakh

     * Very similar to Azerbaijani.
       * The Kazakh action class should inherit the Azerbaijani one.
   * DONE German

     * As expected, required some refactoring to handle the agglutinative word forms.
   * DONE Romanian
   * DONE Armenian
   * TODO Korean

     * Implemented to a point.
   * TODO Persian

     * Implemented to a point.
   * TODO Sanskrit
8. TODO Implement parsing of year "shortcut" word forms, like "twenty o three"
9. TODO Implement parsing of numeric word forms for rationals, like "five twelfths"
10. DONE Translation function (from one language to another)

---

# Collaboration notes

* The **main rule** is that the main branch should always be installable and pass all of its tests.
* From the main rule it follows that new features are developed in separate branches or forks.
* The easiest way to collaborate is to create and commit new test files or corrections
  to existing test files.

  * Then I would change the corresponding grammars rules and actions
    in order the package to pass the tests.
* Please use [*Conventional Commits* (CC)](https://www.conventionalcommits.org/en/v1.0.0/).

  * Here is the CC short form stencil (in Raku):
    `<type> ['(' <scope> ')']? ':' <description>`.
  * See the recent commits in this repository for examples.
  * Here are additional examples of CC messages (each line is a separate message):

```
feat:Implemented the parsing of Danish numeric word forms.
docs:Added documentation of right-to-left word forms parsing.
fix(Persian):Corrected tests for numbers larger that 1000.
test:Added new corner cases tests.
test(Ukrainian):Added new tests.

```

---

## Acknowledgements

* Thanks to [spyrettas](https://github.com/spyrettas) for:
  * Riding "shotgun" during the initial implementation of the Greek role, actions, and tests
  * Proofreading and correcting Greek tests and role
* Thanks to [Denis](https://github.com/DenisVCode) for:
  * Proofreading the Czech language unit tests and suggesting corrections.
* Thanks to Aikerim Belispayeva, [aikerimbelis](https://github.com/aikerimbelis), for:
  * Proofreading the Kazah language unit tests and suggesting corrections.
* Thanks to Herbert Breunung, [lichtkind](https://github.com/lichtkind), for:
  * Proofreading the German language unit tests
  * Suggesting corrections and extensions
  * Verifying the German numeric word forms parsing with the [DSL Translations](https://antononcube.shinyapps.io/DSL-evaluations/) interface
* Thanks to Nora Popescu for:
  * Bug reporting and suggestions for the Romanian language parser
  * Verifying the Romanian numeric word forms parsing with the [DSL Translations](https://antononcube.shinyapps.io/DSL-evaluations/) interface

---

## References

[AAr1] Anton Antonov,
[Raku::DSL::Shared](https://github.com/antononcube/Raku-DSL-Shared).

[BL1] Brent "Labster" Laabs,
[`Lingua::Number`](https://github.com/labster/p6-Lingua-Number).

[SS1] Larry Wall, Steve Schulze,
[Lingua::EN::Numbers](https://github.com/thundergnat/Lingua-EN-Numbers).

---

Anton Antonov
Florida, USA
April-May, 2021
October, 2022 (updated, separate executable doc)
March, 2023 (updated, Azerbaijani parsing)
June, 2024 (updated, Bulgarian generation)
March-April, 2025 (updated; Kazakh, German, and Romanian parsing; Russian generation)


## dist_cpan-TYIL-Grammar-DiceRolls.md
# NAME

Grammar::DiceRolls

# VERSION

0.3.1

# AUTHOR

Patrick Spek [p.spek@tyil.nl](mailto:p.spek@tyil.nl)

# LICENSE

Copyright © 2020

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.


## temporal.md
role X::Temporal

Error related to DateTime or Date

```raku
role X::Temporal is Exception { }
```

A common exception type for all errors related to [`DateTime`](/type/DateTime) or [`Date`](/type/Date).


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

# NAME

Raku port of Perl's Sub::Name module

# SYNOPSIS

```
use Sub::Name;

subname $name, $callable;

$callable = subname foo => { ... };

```

# DESCRIPTION

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

This module has only one function, which is also exported by default:

subname NAME, CALLABLE

Assigns a new name to referenced Callable. If package specification is omitted in the name, then the current package is used. The return value is the Callable.

The name is only used for informative routines. You won't be able to actually invoke the Callable by the given name. To allow that, you need to do assign it to a &-sigilled variable yourself.

Note that for anonymous closures (Callables that reference lexicals declared outside the Callable itself) you can name each instance of the closure differently, which can be very useful for debugging.

# AUTHOR

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

Re-imagined from the Perl version as part of the CPAN Butterfly Plan. Perl version originally developed by Matthijs van Duin.

# COPYRIGHT AND LICENSE

Copyright 2018, 2019, 2020, 2021 Elizabeth Mattijsen

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


## nodemap.md
nodemap

Combined from primary sources listed below.

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

See primary documentation
[in context](/type/Any#method_nodemap)
for **method nodemap**.

```raku
method nodemap(&block --> List) is nodal
```

`nodemap` will apply `&block` to each element and return a new [`List`](/type/List) with the return values of `&block`. In contrast to [deepmap](/routine/deepmap) it will **not** descend recursively into sublists if it finds elements which [do](/routine/does) the [`Iterable`](/type/Iterable) role.

```raku
say [[1,2,3], [[4,5],6,7], 7].nodemap(*+1);
# OUTPUT: «(4, 4, 8)␤»

say [[2, 3], [4, [5, 6]]]».nodemap(*+1)
# OUTPUT: «((3 4) (5 3))␤»
```

The examples above would have produced the exact same results if we had used [map](/routine/map) instead of `nodemap`. The difference between the two lies in the fact that [map](/routine/map) flattens out [`Slip`](/type/Slip)s while `nodemap` doesn't.

```raku
say [[2,3], [[4,5],6,7], 7].nodemap({.elems == 1 ?? $_ !! slip});
# OUTPUT: «(() () 7)␤»
say [[2,3], [[4,5],6,7], 7].map({.elems == 1 ?? $_ !! slip});
# OUTPUT: «(7)␤»
```

When applied to [`Associative`](/type/Associative)s, it will act on the values:

```raku
{ what => "is", this => "thing" }.nodemap( *.flip ).say;
# OUTPUT: «{this => gniht, what => si}␤»
```


## dist_cpan-BDUGGAN-Terminal-ANSI.md
## Terminal::ANSI

This is a library of ANSI escape sequences.

### Example

```
use Terminal::ANSI;

save-screen;
clear-screen;
home;

hide-cursor;

sub scroll($row,$col = 1, $height = 7) {
  print-at $row,$col, "━" x 20;
  print-at $row + $height,$col, "━" x 20;
  my $on = $row;
  for 20000, 19999 ... 0 {
    atomically {
      set-scroll-region($row + 1,$row + $height - 1);
      scroll-up if $on >= $row + $height - 1;
      print-at ++$on min $row + $height - 1, $col, "counting down..$_";
    }
  }
}

my $p1 = start scroll(2);
my $p2 = start scroll(12,10,10);
my $p3 = start scroll(24);
await Promise.allof($p1,$p2,$p3);
sleep 1;

reset-scroll-region;
show-cursor;
restore-screen;

```

See the [eg/](https://git.sr.ht/~bduggan/raku-terminal-ansi/tree/master/eg) directory for more examples.

## Description

The functions in this module print ANSI escape sequences to stdout.
There are functions for cursor movement, scroll regions, colors, and
other screen functionality. There aren't functions for any of the
esoteric escape codes.

The `atomically` function suppresses printing, and instead concatenates
the output and emits the entire line at the end. This is helpful for
multi-threaded situations, where the output of several functions needs
to be in one piece.

There is also an OO interface, as well as a virtual screen, to mock
emitting of escape codes (useful for testing).

## Documentation

* This README can be found online here:

  <https://man.sr.ht/~bduggan/raku-terminal-ansi/README.md>
* [Terminal::ANSI](https://man.sr.ht/~bduggan/raku-terminal-ansi/lib/Terminal/ANSI.md) has documentation for all of the available functions.
* [Terminal::ANSI:OO](https://man.sr.ht/~bduggan/raku-terminal-ansi/lib/Terminal/ANSI/OO.md) has the OO interface.

## Bugs

Feel free to email bug reports to the author, or you can file a ticket at

<https://todo.sr.ht/~bduggan/raku-terminal-ansi>

## Author

Brian Duggan (bduggan at matatu.org)


## dist_zef-tbrowder-GNU-Time.md
[![Actions Status](https://github.com/tbrowder/GNU-Time/workflows/test/badge.svg)](https://github.com/tbrowder/GNU-Time/actions)

# NAME

**GNU::Time** - Provides an easy interface for the GNU `time` command on Linux and OSX hosts (usually installed as '/bin/time' or '/usr/bin/time') to time user commands.

NOTE: This module replaces the time-related routines in module **Proc::More** (which is now deprecated).

Of course one can use the Raku `now` routine before and after a command to achieve calculating the total wall clock time, but sometimes one may be interested in the actual process time without including the times of other processes on the host computer.

# SYNOPSIS

```
use GNU::Time;
# get the proces times (in seconds) for a system command:
say time-command "locate lib"; # OUTPUT: «real 0.23␤user 0.22␤sys 0.01␤»

```

# DESCRIPTION

Raku module **GNU::Time** provides the `time-command` subroutine for easy access to the GNU `time` command on Linux and OSX hosts. The default is to return the same output format as running the following command at the host's command line interface:

```
$ /bin/time -p locate lib 1>/tmp/stdout
real 0.23
user 0.22
sys 0.01

```

Note the `TIME` environment variable format, if defined, is ignored.

# INSTALLATION

First, ensure the GNU `time` command is installed on your host. If required, you may install it from source.

## Getting the `time` command

On Debian and other Linux hosts the `time` command may not be installed by default, but it is available in package `time`. It can also be built from source available at the *Free Software Foundation*'s git site. Clone the source repository:

```
    $ git clone https://git.savannah.gnu.org/git/time.git

```

The build and install instructions are in the repository along with the source code. Details of the GNU `time` command may be seen by executing `man 1 time` at the command line.

Unfortunately, there is no equivalent command available for Windows unless you install Cygwin or an equivalent system. (The author has seen Windows command scripts posted on Stack Overflow but has not tried any himself.)

## sub time-command

Purpose : Collect the process times for a system or user command (using the GNU `time` command). Runs the input command using the Raku `run` routine and returns the process times shown below (all times are in seconds):

* `real` - real (wall clock) time
* `user` - user time
* `system` - system time

### Signature:

```
sub time-command(Str:D $cmd,
                 :$typ where { !$typ.defined || $typ ~~ &typ },
                 :$fmt where { !$fmt.defined || $fmt ~~ &fmt },
                 :$rtn where { !$rtn.defined || $rtn ~~ &rtn },
		 :$dir,
                ) is export {...}

```

### Parameters:

* `$cmd` - The command as a string. Note special characters are not recognized by Raku's `run` routine, so results may not be as expected if they are part of the command.
* `:$typ` - Type of time values to return (see token `typ` definition)
* `:$fmt` - Desired format of returned time values (see token `fmt` definition)
* `:$rth` - Desired return type (see token `rtn` definition)
* `:$dir` - Directory in which to execute the command

### The `typ`, `fmt`, and `rtn` tokens:

Note the user should either use the single-character form of the token or at least two characters of the multi-character form to ensure proper disambiguation of the desired token. For example, the character 'u' alone is taken to be the 'user' type while 'u+' is the "sum" type. In all cases, the canonical name of each token is the single-character shown for each token.

```
my token typ { ^ :i
    # the desired time(s) to return:
              # [default: all are returned]
    r|real|   # show real (wall clock) time only
    u|user|   # show the user time only
    s|sys|    # show the system time only
    '+'|'u+s' # show sum of user and system time
$ }

my token fmt { ^ :i
    # the desired format for the time(s)
                # [default: raw seconds]
    s|seconds|  # time in seconds with an appended
                #   's': "30.42s"
    h|hms|      # time in hms format: "0h00m30.42s"
    ':'|'h:m:s' # time in h:m:s format: "0:00:30.42"
$ }

my token rtn { ^ :i
    # the desired type of return:
    # [default: string]
    l|list|
    h|hash|
$ }

```

### Returns one of:

* A string consisting of real (wall clock), user, **and** system times [default]
* A string consisting in one of real (wall clock), user, **or** system times
* A list consisting of real (wall clock), user, and system times (in that order)
* A hash of all of real (wall clock), user, and system times keyed by 'real', 'user', and 'system'

All returned time values are in the default or the selected format.

### `GNU_Time_Format` environment variable

The user may set the desired default type, format, and return type by setting the **GNU\_Time\_Format** environment variable as in the following example

```
export GNU_Time_Format='typ(u)' # returns the user time in seconds

```

where 'typ()', 'fmt()', and 'rtn()' are "tokens" with values within their trailing parentheses. The values within parentheses are expected to be the appropriate ones for the signature tokens. Multiple tokens may be separated by semicolons, whitespace, or commas. Whitespace is ignored. Missing values and tokens are ignored as are malformed or unrecognized tokens or values.

# AUTHOR

Tom Browder [tbrowder@cpan.org](mailto:tbrowder@cpan.org)

# COPYRIGHT and LICENSE

Copyright © 2021 Tom Browder

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


## dist_zef-bduggan-Geo-Polyline.md
[![Actions Status](https://github.com/bduggan/raku-geo-polyline/actions/workflows/linux.yml/badge.svg)](https://github.com/bduggan/raku-geo-polyline/actions/workflows/linux.yml)
[![Actions Status](https://github.com/bduggan/raku-geo-polyline/actions/workflows/macos.yml/badge.svg)](https://github.com/bduggan/raku-geo-polyline/actions/workflows/macos.yml)

# NAME

Geo::Polyline - Encode and decode Google Maps polyline strings

# SYNOPSIS

```
use Geo::Polyline;

my $polyline = polyline-encode([ [ 38.5, -120.2 ], [ 40.7, -120.95 ], [ 43.252, -126.453 ] ]);
my @coords = polyline-decode($polyline);
my $geojson = polyline-to-geojson($polyline);

my $polyline6 = polyline6-encode([ [ 38.5, -120.2 ], [ 40.7, -120.95 ], [ 43.252, -126.453 ] ]);
my @coords6 = polyline6-decode($polyline6);
my $geojson6 = polyline6-to-geojson($polyline6);

```

# DESCRIPTION

Encode and decode polyline strings using the google polyline algorithm.

The algorithm is described here: <https://developers.google.com/maps/documentation/utilities/polylinealgorithm>

Polyline6 is a variant of the algorithm that uses 6 decimals of precision instead of 5. These variants can be used by either passing :v6, or using the polyline6- functions.

# FUNCTIONS

## polyline-encode, polyline6-encode

Encode an array of lon/lat coordinate pairs into a polyline string.

## polyline-decode, polyline6-decode

Decode a polyline string into an array of lon/lat coordinate pairs.

## polyline-to-geojson, polyline6-to-geojson

Convert a polyline string into a GeoJSON object.

## polyline-encode-coordinate, polyline-decode-coordinate, polyline6-encode-coordinate, polyline6-decode-coordinate

Also exported; these encode an individual coordinate number to/from a string.

# AUTHOR

Brian Duggan


## hyperwhatever.md
class HyperWhatever

Placeholder for multiple unspecified values/arguments

```raku
class HyperWhatever { }
```

`HyperWhatever` is very similar in functionality to [`Whatever`](/type/Whatever). The difference lies in `HyperWhatever` standing in for *multiple* values, rather than a single one.

# [Standalone term](#class_HyperWhatever "go to top of document")[§](#Standalone_term "direct link")

Just like with [`Whatever`](/type/Whatever), if a `HyperWhatever` is used as a term on its own, no priming is done and the `HyperWhatever` object will be used as-is:

```raku
sub foo ($arg) { say $arg.^name }
foo **; # OUTPUT: «HyperWhatever␤»
```

You can choose to interpret such a value as standing for multiple values in your own routines. In core, a `HyperWhatever` can be used with this meaning when smartmatching with [`List`](/type/List)s:

```raku
say (1, 8)                ~~ (1, **, 8); # OUTPUT: «True␤»
say (1, 2, 4, 5, 6, 7, 8) ~~ (1, **, 8); # OUTPUT: «True␤»
say (1, 2, 8, 9)          ~~ (1, **, 8); # OUTPUT: «False␤»
```

Wherever a `HyperWhatever` appears in the list on the right-hand side means any number of elements can fill that space in the list being smartmatched.

# [Priming](#class_HyperWhatever "go to top of document")[§](#Priming "direct link")

When it comes to priming, the `HyperWhatever` follows the same rules as [`Whatever`](/type/Whatever). The only difference is `HyperWhatever` produces a [`Callable`](/type/Callable) with a [`*@` slurpy](/language/signatures#Flattened_slurpy) as a signature:

```raku
say (**²)(1, 2, 3, 4, 5); # OUTPUT: «(1 4 9 16 25)␤»
```

A `HyperWhatever` closure can be imagined as a [`WhateverCode`](/type/WhateverCode) with **another** sub wrapped around it that simply maps each element in the arguments over:

```raku
my &hyper-whatever = sub (*@args) { map *², @args }
say hyper-whatever(1, 2, 3, 4, 5); # OUTPUT: «(1 4 9 16 25)␤»
```

When priming, mixing `HyperWhatever` with [`Whatever`](/type/Whatever) is not permitted.

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

Type relations for `HyperWhatever`

raku-type-graph

HyperWhatever
HyperWhatever

Any
Any

HyperWhatever->Any

Mu
Mu

Any->Mu

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


## pred.md
pred

Combined from primary sources listed below.

# [In enum Bool](#___top "go to top of document")[§](#(enum_Bool)_routine_pred "direct link")

See primary documentation
[in context](/type/Bool#routine_pred)
for **routine pred**.

```raku
method pred(--> Bool:D)
```

Returns `False`.

```raku
say True.pred;                                    # OUTPUT: «False␤»
say False.pred;                                   # OUTPUT: «False␤»
```

`pred` is short for "predecessor"; it returns the previous enum value. Bool is a special enum with only two values, `False` and `True`. When sorted, `False` comes first, so `False` is the predecessor to `True`. And since `False` is the "lowest" Bool enum value, its own predecessor is also `False`.

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

See primary documentation
[in context](/type/Str#method_pred)
for **method pred**.

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

Returns the string decremented by one.

String decrementing is "magical" just like string increment (see [succ](/routine/succ)). It fails on underflow

```raku
'b0'.pred;           # OUTPUT: «a9»
'a0'.pred;           # OUTPUT: Failure
'img002.png'.pred;   # OUTPUT: «img001.png»

```

# [In role Enumeration](#___top "go to top of document")[§](#(role_Enumeration)_method_pred "direct link")

See primary documentation
[in context](/type/Enumeration#method_pred)
for **method pred**.

```raku
method pred(::?CLASS:D:)
```

```raku
say Freija.pred;  # OUTPUT: «Oðin␤»

```

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

See primary documentation
[in context](/type/IO/Path#method_pred)
for **method pred**.

```raku
method pred(IO::Path:D: --> IO::Path:D)
```

Returns a new `IO::Path` constructed from the invocant, with [`.basename`](/routine/basename) changed by calling [`Str.pred`](/type/Str#method_pred) on it.

```raku
"foo/file02.txt".IO.pred.say; # OUTPUT: «"foo/file01.txt".IO␤»
```

# [In role Numeric](#___top "go to top of document")[§](#(role_Numeric)_method_pred "direct link")

See primary documentation
[in context](/type/Numeric#method_pred)
for **method pred**.

```raku
method pred(Numeric:D:)
```

Returns the number decremented by one (predecessor).

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

See primary documentation
[in context](/type/Allomorph#method_pred)
for **method pred**.

```raku
method pred(Allomorph:D:)
```

Calls [`Numeric.pred`](/type/Numeric#method_pred) on the invocant's numeric value.

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

See primary documentation
[in context](/type/Date#method_pred)
for **method pred**.

```raku
method pred(Date:D: --> Date:D)
```

Returns a `Date` of the previous day. "pred" is short for "predecessor".

```raku
say Date.new("2016-01-01").pred;   # OUTPUT: «2015-12-31␤»
```


## threadpoolscheduler.md
class ThreadPoolScheduler

Scheduler that distributes work among a pool of threads

```raku
class ThreadPoolScheduler does Scheduler {}

```

The `ThreadPoolScheduler` has a range of number of threads that it maintains, and it distributes work among those threads. When the upper limit of threads isn't reached yet, and there is work pending, it spawns new threads to handle the work.

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

## [new](#class_ThreadPoolScheduler "go to top of document")[§](#new "direct link")

```raku
method new(Int :$initial_threads = 0, Int :$max_threads = 8 * Kernel.cpu-cores)

```

Creates a new `ThreadPoolScheduler` object with the given range of threads to maintain.

The default value for `:initial_threads` is **0**, so no threads will be started when a `ThreadPoolScheduler` object is created by default.

The default value for `:max_threads` is **64**, unless there appear to be more than 8 CPU cores available. In that case the default will be 8 times the number of CPU cores.

See also the [RAKUDO\_MAX\_THREADS](/programs/03-environment-variables#Other) environment variable to set the default maximum number of threads.

As of release 2022.06 of the Rakudo compiler, it is also possible to specify `Inf` or `*` as a value for `:max_threads`, indicating that the maximum number of threads allowed by the operating system, will be used.

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

Type relations for `ThreadPoolScheduler`

raku-type-graph

ThreadPoolScheduler
ThreadPoolScheduler

Any
Any

ThreadPoolScheduler->Any

Scheduler
Scheduler

ThreadPoolScheduler->Scheduler

Mu
Mu

Any->Mu

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


## invocantmarker.md
class X::Syntax::Signature::InvocantMarker

Compilation error due to a misplaced invocant marker in a signature

```raku
class X::Syntax::Signature::InvocantMarker does X::Syntax { }
```

Syntax error when the invocant in a signature is anywhere else than after the first parameter.

For example

```raku
:($a, $b: $c);

```

dies with

｢text｣ without highlighting

```

```

===SORRY!===
Can only use : as invocant marker in a signature after the first parameter

```

```

See also: [`Signature`](/type/Signature).


## dist_zef-jnthn-Badger.md
# Badger

Badger, not an ORM (a snake).

### What's Badger?

Badger is a SQL library that allows you to invoke SQL snippets as function as
if it was Raku code. This way you can keep writing your SQL queries by hand
for performance and tweakability, and your tools still recognize the `.sql`
files to help you work with them.

### What does a Badger SQL file look like?

A badger-compatible SQL file is just a normal SQL file, with signature headers.
These signatures are intended to look like Raku signatures.

The most basic example:

```
-- sub my-query()
SELECT;

```

### How do I feed Badger my SQL?

You have to pass the .sql file(s) to the `use Badger` statement:

```
use Badger <sql/my-query.sql>; # The file in the previous code block

```

This will generate this function Raku-side:

```
sub my-query(Database $db --> Int) { ... }

```

Which you can call just like any other Raku subs, by passing any object that
has an interface similar to `DB::Pg` (for now at least) as the connection.

For parameters and return values, see below.

## Parameters

A Badger SQL sub can have arguments that you can use in the SQL body.
Interpolation works for sigilled variables:

```
-- sub query-with-params($a, $b)
SELECT $a + $b, @c

```

This will generate a prepared query with `$a` and `$b` replaced `$1`, `$2`
(or with `?`s depending on the RDBMS).

### Parameter Sigils

The Raku allowed sigils are `$` and `@`.

### Parameter typing

You can put type annotations on the parameters:

```
-- sub query-with-params(Int $x, Int @xs)
SELECT $x = ANY(@xs)

```

If a parameter is typed, Badger will try to help you by inserting coercions in the generated SQL.
This is what the executed SQL looks like:

```
SELECT ($1::int) = ANY(($2::int[]))

```

### Named Parameters

Parameters can be named, just like in Raku:

```
-- sub query-nameds(Int :$a, :$b)
SELECT $a + $b

```

Just like in Raku, you can't have a positional parameter after a named one.

### Mandatory Named Parameters

Also just like in Raku, named parameters can be marked mandatory:

```
-- sub query-nameds(:$mandatory!)
SELECT $a * 2

```

## Return Sigils

### `+` (default)

The default one -- in you don't specify a return sigil, you get this.
Returns the number of affected rows (as an `Int`).

```
-- sub count-unnests(--> +)
-- ... or ...
-- sub count-unnests()
UPDATE products
   SET price = 999
   WHERE price IS NULL

```

### `$`

Returns a single value. `Nil` is returned otherwise:

```
-- sub get-username(Str $token --> $)
SELECT username
FROM users
WHERE token = $token

```

### Typed `$`

Calls `.new` on the given type with all the data returned from the SQL query:

```
-- sub get-user(Int $id --> MyApp::Models::User)
SELECT 1 AS id, 'steve' AS username

```

You'll usually need to import type module that provides the type, by placing
a `use` at the top of the SQL file:

```
-- use MyApp::Models;

```

```
class MyApp::Models::User {
  has Int $.id;
  has Str $.username;
}
...
my MyApp::Models::User $user = get-user(db, 1);
# Result: `MyApp::Models::User.new(id => 1, :username<steve>);`

```

### `%`

Returns a hash.

```
-- sub get-hash(--> %)
SELECT 'comment' as type, 'Hello world!' as txt

```

```
my %h = get-hash($db);
# Result: `%(type => "comment", txt => "Hello world!")`

```

If the database doesn't return anything, Badger gives you an empty hash back.

### `@`

Returns an array of hashes.

```
-- sub get-hashes(--> @)
SELECT 'comment' as type, txt
FROM unnest(array['Hello', 'world!']) txt

```

```
my @hashes = get-hashes($db);
# Result: `%(type => "comment", txt => "Hello"), %(type => "comment", txt => "world!")`

```

### Typed `@`

Calls `.new` on the given type on each row of the data returned from the SQL query:

```
-- sub get-data(--> Datum @)
SELECT row_number() OVER () as id
     , unnest(ARRAY['a','b']) as value

```

```
class Datum {
  has Int $.id;
  has Str $.value;
}
...
my Datum @data = get-data($db);
# Result: `Datum.new(id => 1, :value<a>), Datum.new(id => 2, :value<b>)`

```


## dist_zef-2colours-HTML-Tag.md
# NAME

HTML::Tag - Simple HTML Tag Generators

# SYNOPSIS

```
    use HTML::Tag::Tags;

    say HTML::Tag::p.new(:text('This is my paragraph'), :class('pretty')).render;

    # <p class="pretty">This is my paragraph</p>

    my $link = HTML::Tag::a.new(:text('paragraph'),
                                :href('http://dom.com'));
    say HTML::Tag::p.new(:text("This is my ", $link, "."),
                         :class('pretty')).render;

    # <p class="pretty">This is my <a href="http://dom.com">paragraph</a>.</p>

```

# DESCRIPTION

HTML::Tag::Tags provides little objects to generate HTML tags. Tags
that support :text have their string text encoded for HTML special
characters.

Tags that support :text also support "embedding" other tags inside
their :text by passing alternating string text and tag objects as a
list. Tag objects passed this way *should not* have `.render` called
on them first to avoid the HTML special characters being escaped.

Not all attributes of every HTML tag is supported, just the most
common. It enforces very little. It is meant to help minimize clutter
in code for those who are not using html template classes or who wish
to dynamically generate segments of html code.

Please see the POD documentation for each macro for more details on
macro use.

Also, an HTML::Tag::Exports can be used to export the symbol "tag"
into your scope which shortens `HTML::Tag::<thing>` creation to
`tag('thing', %opts)`

# TAGS

HTML::Tag::Tags will give you all tag classes defined. They can be
instantiated with HTML::Tag::.new and take options matching
their normal html attributes.

Tags can be combined into one another by placing them into another
tag's :text attribute. Tags are then recursively rendered when .render
is called on the furthest-outward containing tag (such as
HTML::Tag::html which represents an entire page).

`HTML::Tag::Raw` represents raw HTML text that renders as its content itself.

`HTML::Tag::Macro::CSS` will generate a CSS link.

`HTML::Tag::Macro::Table` will help generate tables.

`HTML::Tag::Macro::List` will help generate lists.

`HTML::Tag::Macro::Form` will help generate form and do some form
variable handling.

# MACROS

Please see individual macro files for more thorough documentation on
each macro.

## HTML::Tag::Macro::CSS

Renders a normal CSS file link that can be wrapped into a html head element:

```
HTML::Tag::Macro::CSS.new(:href('/css/mycssfile.css')).render;

```

## HTML::Tag::Macro::Table

A HTML::Tag::Macro::Table object gets fed rows one after the
other. These rows contain arrays of data that will be surrounded by
td's.

```
    my $table = HTML::Tag::Macro::Table.new;
    my @data = $var1, $var2, $var3;
    $table.row(@data);
    @data = $var4, $var5, $var6;
    $table.row(@data);
    $table.render;

```

The `.row` method takes `Bool :$header` which will generated th tags
instead of td tags for each array element (representing a table header
row).

The `.row` method takes `Map :$tr-opts` which will apply normal
`HTML::Tag::tr` options to that row, as specified in :$tr-opts.

The `.row` method takes `Map :$td-opts` which will apply normal
`HTML::Tag::td` options to td tags that are generated for that
row. **$td-opts is keyed by the td array element** (see td-opts example
code below).

```
    $table = HTML::Tag::Macro::Table.new(:table-opts(id =>'myID'));
    @data = 'Col1', 'Col2', 'Col3';
    $table.row(:header(True), @data);
    @data = 11, 22, 33;
    $table.row(@data);
    @data = 111, 222, 333;
    my $td-opts = %(1 => {class => 'pretty'},
                    2 => {class => 'pretty',
                          id    => 'lastone'});
    $table.row(:$td-opts, @data);

```

As you can see the new constructor takes :$table-opts that will be
passed along to the normal HTML::Tag::table object.

NO CHECKING IS PERFORMED FOR A CONSISTENT NUMBER OF ELEMENTS IN EACH
ROW

## HTML::Tag::Macro::List

Generates an ordered or unordered HTML list from a supplied array, or
constructs the array for you by repeated calling of the item() method.

```
    my $list = HTML::Tag::Macro::List.new;
    $list.link(:to('http://somewhere'), :text('rainbows'));
    $list.link(:to('http://elsewhere'), :text('snails'),
	                                    :class('highlight'));
    $list.render;

    # .. or ..

    my @fruit = 'fingers', 'sofa', 'airliner';
    my $html = HTML::Tag::Macro::List.new(:items(@fruit)).render;

```

The lists have a special method called link() that makes `HTML::Tag::a`
links that are surrounded by list elements since this is a common way
to generate HTML menus.

## HTML::Tag::Macro::Form

Generates forms based upon a definition variable passed in. This
variable must be an array of hashes.

## The array of hashes represents one form element per hash in the array. Labels are automatically generated for all form elements by default.

The hash key represents the HTML name of the hash by default, and the
input variable if given, etc. That key's value represents options for
that form element.

```
    use HTML::Tag::Macro::Form;

    my $form = HTML::Tag::Macro::Form.new(:action('/hg/login/auth'),
                                          :input(%.input));
    $form.def = ({username => {}},
                 {password => { type => 'password' }},
                 {submit   => { value => 'Login',
                                type  => 'submit',
                                label => '' }}
                );

    $form.render;

```

Most certainly a work in progress.

# AUTHOR

Current maintenance: Polgár, Márton [ersterpleghthome@gmail.com](mailto:ersterpleghthome@gmail.com)

Author of the original module: Rushing, Mark [mark@orbislumen.net](mailto:mark@orbislumen.net)

# LICENSE

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


## dist_cpan-KAIEPI-Type-EnumHOW.md
[![Build Status](https://travis-ci.org/Kaiepi/p6-Type-EnumHOW.svg?branch=master)](https://travis-ci.org/Kaiepi/p6-Type-EnumHOW)

# NAME

Type::EnumHOW - Sugar for enum's meta-object protocol

# SYNOPSIS

```
use Type::EnumHOW;

BEGIN {
    my Str @ranks   = 'Unranked', 'Voice', 'Half-Operator', 'Operator', 'Administrator', 'Owner';
    my Str %symbols = %(
        @ranks[0] => ' ',
        @ranks[1] => '+',
        @ranks[2] => '%',
        @ranks[3] => '@',
        @ranks[4] => '&',
        @ranks[5] => '~'
    );

    my constant Rank = Type::EnumHOW.new_type: :name<Rank>, :base_type(Int);
    Rank.^set_package: OUR;
    Rank.^add_attribute_with_values: '$!symbol', %symbols, :type(Str);
    Rank.^compose;
    Rank.^add_enum_values: @ranks;
    Rank.^compose_values;
};

say Owner;        # OUTPUT: Owner
say Owner.symbol; # OUTPUT: ~

```

# DESCRIPTION

Enums are not straightforward to create using their meta-object protocol since a large chunk of the work the runtime does to create enums is handled during precompilation. Type::EnumHOW extends Metamodel::EnumHOW to provide methods that both do the work normally done during precompilation and to provide sugar for customizing enum behaviour without the need to import nqp.

It is recommended to declare enums at compile-time rather than at runtime so enums and their values can have their serialization context set. This can be done by either using `constant` in combination with `do` or using `BEGIN`.

Type::EnumHOW extends Metamodel::EnumHOW. Refer to [its documentation](https://docs.perl6.org/type/Metamodel::EnumHOW) for more information.

# METHODS

* **^new\_type**(\*\*%named\*)

Creates a new enum type. Named arguments are the same as those taken by `Metamodel::EnumHOW.new_type`. If you plan on calling `^add_enum_values` with a list of keys, ensure you pass `:base_type(Int)`.

* **^package**()

Returns the package set by `^set_package`.

* **^set\_package**(*$package* where \*.WHO ~~ Stash | PseudoStash)

Sets the package in which the enum and its values' symbols will be installed. This must be called before calling `^compose` or `^add_enum_values`.

If `MY` is given, the enum must be created during compilation. Any other package can be used during runtime.

Do not pass `MY` packages in other lexpads to this method, such as `OUTER::MY` or `CALLER::MY`; enum and enum value symbols will get installed in the wrong lexpad. To the best of my knowledge, there isn't a good way to properly detect when they get passed when `BEGIN`/`constant` are involved.

* **^add\_attribute\_with\_values**(str *$name*, %values, Mu:U *:$type* = Any, Bool *:$private* = False)

Adds an attribute with the name `$name` to the enum. `%values` is a hash of enum value keys to attribute values that is used to bind the attribute values to their respective enum values when calling `^compose_values`. `$type` is the type of the attribute values. If the attribute should be private, set `$private` to `True`, otherwise a getter will automatically be added.

* **^compose**()

Composes the enum type. Call this after adding enum attributes and methods, but before adding enum values.

If no package has been set using `^set_package`, an `X::Type::EnumHOW::MissingPackage` exception will be thrown.

If the package was set to `MY` and this wasn't called during compilation, an `X::Type::EnumHOW::PostCompilationMY` exception will be thrown.

* **^add\_enum\_values**(*%values*)
* **^add\_enum\_values**(*@keys*)

Batch adds a list of enum values to an enum and installs them both in the package set and the enum's package. `^compose` must be called before calling this. Calling this with a hash will warn about the enum values' order not necessarily being the same as when they were defined in the hash. This may also be called with either a list of keys or a list of pairs.

If no package has been set using `^set_package`, an `X::Type::EnumHOW::MissingPackage` exception will be thrown.

If the package was set to `MY` and this wasn't called during compilation, an `X::Type::EnumHOW::PostCompilationMY` exception will be thrown.

# AUTHOR

Ben Davies (Kaiepi)

# COPYRIGHT AND LICENSE

Copyright 2019 Ben Davies

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


## dist_zef-lizmat-MoarVM-Bytecode.md
[![Actions Status](https://github.com/lizmat/MoarVM-Bytecode/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/MoarVM-Bytecode/actions) [![Actions Status](https://github.com/lizmat/MoarVM-Bytecode/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/MoarVM-Bytecode/actions) [![Actions Status](https://github.com/lizmat/MoarVM-Bytecode/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/MoarVM-Bytecode/actions)

# NAME

MoarVM::Bytecode - Provide introspection into MoarVM bytecode

# SYNOPSIS

```
use MoarVM::Bytecode;

my $M = MoarVM::Bytecode.new($filename);  # or letter or IO or Blob

say $M.hll-name;     # most likely "Raku"

say $M.strings[99];  # the 100th string on the string heap

```

# DESCRIPTION

MoarVM::Bytecode provides an object oriented interface to the MoarVM bytecode format, based on the information provided in [docs/bytecode.markdown](https://github.com/MoarVM/MoarVM/blob/main/docs/bytecode.markdown#bytecode).

# CLASS METHODS

## new

```
my $M = MoarVM::Bytecode.new("c");             # the 6.c setting

my $M = MoarVM::Bytecode.new("foo/bar");       # path as string

my $M = MoarVM::Bytecode.new($filename.IO);    # path as IO object

my $M = MoarVM::Bytecode.new($buf);            # a Buf object

```

Create an instance of the `MoarVM::Bytecode` object from a letter (assumed to be a Raku version letter such as "c", "d" or "e"), a filename, an `IO::Path` or a `Buf`/`Blob` object.

## files

```
.say for MoarVM::Bytecode.files;

.say for MoarVM::Bytecode.files(:instantiate);

```

Returns a sorted list of paths of MoarVM bytecode files that could be found in the installation of the currently running `rakudo` executable.

Optionally accepts a `:instantiate` named argument to return a sorted list of instantiated `MoarVM::Bytecode` objects instead of just paths.

## root

```
my $rootdir = MoarVM::Bytecode.rootdir;

```

Returns an `IO::Path` of the root directory of the installation of the currently running `rakudo` executable.

## setting

```
my $setting = MoarVM::Bytecode.setting;

my $setting = MoarVM::Bytecode.setting("d");

```

Returns an `IO::Path` of the bytecode file of the given setting letter. Assumes the currently lowest supported setting by default.

# HELPER SCRIPTS

## bceval

```
$ bceval c '.strings.grep(*.contains("zip"))'
&zip
zip
zip-latest

```

Helper script to allow simple actions on a `MoarVM::Bytecode` object from the command line. The first argument indicates the bytecode file to load (either a `use` target, setting letter or path. The second argument indicates the code to be executed.

The topic `$_` is set with the `MoarVM::Bytecode` object upon entry.

If the result is an `Iterable`, then each iteration will be shown on a separate line. Otherwise the return value will be shown.

## bcinfo

```
$ bcinfo --help
Usage:
  bin/bcinfo <file> [--filename=<Str>] [--name=<Str>] [--opcode=<Str>] [--header] [--decomp] [--hexdump] [--verbose]

    <file>              use target, setting letter or bytecode path
    --filename=<Str>    select frames with given filename
    --name=<Str>        select frames with given name
    --opcode=<Str>      select frames containing opcode
    --header            show header information
    --decomp            de-compile file / selected frames
    --hexdump           show hexdump of selected frames
    --verbose           be verbose when possible

```

Produces various types of information about the given bytecode file, specified by either a `use` target, setting letter or path.

## csites

```
$ csites c 12
 12 $, $, N

```

Helper code to show the callsite info of the given callsite number.

## opinfo

```
$ opinfo if_i unless_i
 24 if_i r(int64),ins (8 bytes)
 25 unless_i r(int64),ins (8 bytes)

$ opinfo 42 666
 42 bindlex_nn str,r(num64) (8 bytes)
666 atpos2d_s w(str),r(obj),r(int64),r(int64) (10 bytes)

```

Helper script to show the gist of the given op name(s) or number(s).

## sheap

```
$ sheap e 3 4 5
    3 SETTING::src/core.e/core_prologue.rakumod
    4 language_revision_type
    5 lang-meth-call

$ sheap e byte
   42 byte
 2844 bytecode-size

```

Helper script for browsing the string heap of a given bytecode file (specified by either a `use` target, setting letter, or a path of a bytecode file).

String arguments are interpreted as a key to do a .grep on the whole string heap. Numerical arguments are interpreted as indices into the string heap. If no arguments are given, the entire string heap will be produced.

Shown are the string index and the string.

# INSTANCE METHODS

## coverables

```
# Show all files and number of lines in that file
say .key ~ ": " ~ +.value ~ "  lines"
  for $M.coverables.sort(*.key);

```

Returns a `Map` with the filename(s) as keys, and a list of line numbers in that file that have code in them that `can` be produced in a coverage report.

## callsites

```
.say for $M.callsites[^10];  # show the first 10 callsites

```

Returns a list of [Callsite](#Callsite) objects, which contains information about the arguments at a given callsite.

## de-compile

Returns a string with the opcodes and their arguments.

## extension-ops

```
.say for $M.extension-ops;  # show all extension ops

```

Returns a list of NQP extension operators that have been added to this bytecode. Each element consists of an <ExtensionOp> object.

## frames

```
.say for $M.frames[^10];  # show the first 10 frames on the frame heap

my @frames := $M.frames.reify-all;

```

Returns a <Frames> object that serves as a `Positional` for all of the frames on the frame heap. Since the reification of a [Frame](#Frame) object is rather expensive, this is done lazily on each access.

To reify all `Frame` objects at once, one can call the `reify-all` method, which also returns a list of the reified `Frame` objects.

## hll-name

```
say $M.hll-name;     # most likely "Raku"

```

Returns the HLL language name for this bytecode. Most likely "Raku", or "nqp".

## op

```
say $M.op(0x102);     #  102 istype       w(int64),r(obj),r(obj)

say $M.op("istype");  #  102 istype       w(int64),r(obj),r(obj)

```

Attempt to create an opcode object for the given name or opcode number. Also includes any extension ops that may be defined in the bytecode itself.

## opcodes

A `Buf` with the actual opcodes.

## sc-dependencies

```
.say for $M.sc-dependencies;  # identifiers for Serialization Context

```

Returns a list of strings of the Serialization Contexts on which this bytecode depends.

## strings

```
.say for $M.strings[^10];  # The first 10 strings on the string heap

```

Returns a <Strings> object that serves as a `Positional` for all of the strings on the string heap.

## version

```
say $M.version;     # most likely 7

```

Returns the numeric version of this bytecode. Most likely "7".

# PRIMITIVES

## bytecode

```
my $b = $M.bytecode;

```

Returns the `Buf` with the bytecode.

## hexdump

```
say $M.hexdump($M.string-heap-offset);  # defaults to 256

say $M.hexdump($M.string-heap-offset, 1024);

```

Returns a hexdump representation of the bytecode from the given byte offset for the given number of bytes (256 by default).

## slice

```
dd $M.slice(0, 8).chrs;     # "MOARVM\r\n"

```

Returns a `List` of unsigned 32-bit integers from the given offset and number of bytes. Basically a shortcut for `$M,bytecode[$offset ..^ $offset + $bytes]`. The number of bytes defaults to `256` if not specified.

## str

```
say $M.str(76);  # Raku or nqp

```

Returns the string of which the index is the given offset.

## subbuf

```
dd $M.subbuf(0, 8).decode;  # "MOARVM\r\n"

```

Calls `subbuf` on the `bytecode` and returns the result. Basically a shortcut for `$M.bytecode.subbuf(...)`.

## uint16

```
my $i = $M.uint16($offset);

```

Returns the unsigned 16-bit integer value at the given offset in the bytecode.

## uint16s

```
my @values := = $M.uint16s($M.string-heap-offset);  # 16 entries

my @values := $M.uint16s($M.string-heap-offset, $entries);

```

Returns an unsigned 16-bit integer array for the given number of entries at the given offset in the bytecode. The number of entries defaults to 16 if not specified.

## uint32

```
my $i = $M.uint32($offset);

```

Returns the unsigned 32-bit integer value at the given offset in the bytecode.

## uint32s

```
my @values := = $M.uint32s($offset);  # 16 entries

my @values := $M.uint32s($offset, $entries);

```

Returns an unsigned 32-bit integer array for the given number of entries at the given offset in the bytecode. The number of entries defaults to 16 if not specified.

# HEADER SHORTCUTS

The following methods provide shortcuts to the values in the bytecode header. They are explained in the [MoarVM documentation](https://github.com/MoarVM/MoarVM/blob/main/docs/bytecode.markdown#bytecode).

`sc-dependencies-offset`, `sc-dependencies-entries`, `extension-ops-offset`, `extension-ops-entries`, `frames-data-offset`, `frames-data-entries`, `callsites-data-offset`, `callsites-data-entries`, `string-heap-offset`, `string-heap-entries`, `sc-data-offset`, `sc-data-length`, `opcodes-offset`, `opcodes-length`, `annotation-data-offset`, `annotation-data-length`, `main-entry-frame-index`, `library-load-frame-index`, `deserialization-frame-index`

# SUBCLASSES

Instances of these classes are usually created automatically.

## Argument

The `Argument` class provides these methods:

### flags

The raw 8-bit bitmap of flags. The following bits have been defined:

* 1 - object
* 2 - native integer, signed
* 4 - native floating point number
* 8 - native NFG string (MVMString REPR)
* 16 - literal
* 32 - named argument
* 64 - flattened argument
* 128 - native integer, unsigned

### is-flattened

Returns 1 if the argument is flattened, else 0.

### is-literal

Returns 1 if the argument is a literal value, else 0.

### name

The name of the argument if it is a named argument, else the empty string.

### type

The type of the argument: possible values are `Mu` (indicating a HLL object of some kind), or any of the basic native types: `str`, `int`, `uint` or `num`.

## Callsite

The `Callsite` class provides these methods:

### arguments

The list of <Argument> objects for this callsite, if any.

### bytes

The number of bytes this callsite needs.

### has-named-arg

Returns `True` if the call site has a named argument with the given name, else `False`.

### named

A `Map` of named arguments, keyed by name.

## ExtensionOp

The `ExtensionOp` class provides these methods:

### adverbs

Always an empty `Map`.

### annotation

Always the empty string.

### bytes

The number of bytes this opcode uses.

### name

The name with which the extension op can be called.

### descriptor

An 8-byte `Buf` with descriptor information.

### is-sequence

Always `False`.

## Frame

The `Frame` class provides these methods:

### is-inlineable

Return `Bool` whether the current frame is considered to be inlineable.

### cuid

A string representing the compilation unit ID.

### de-compile

Returns a string with the opcodes and their arguments of this frame.

### flags

A 16-bit unsigned integer bitmap with flags of this frame.

### handlers

A list of [Handler](#Handler) objects, representing the handlers in this frame.

### has-exit-handler

1 if this frame has an exit handler, otherwise 0.

### hexdump

Return a hexdump of the opcodes of this frame. Optionally takes a named argument `:highlight` which will highlight the bytes of the actual opcodes (excluding any argument bytes following them).

### index

A 16-bit unsigned integer indicating the frame index of this frame.

### is-thunk

1 if this frame is a thunk (as opposed to a real scope), otherwise 0.

### lexicals

A list of [Lexical](#Lexical) objects, representing the lexicals in this frame.

### locals

A list of [Local](#Local) objects, representing the locals in this frame.

### name

The name of this frame, if any.

### no-outer

1 if this frame has no outer, otherwise 0.

### opcodes

A `Buf` with the actual bytecode of this frame.

### outer-index

A 16-bit unsigned integer indicating the frame index of the outer frame.

### sc-dependency-index

A 32-bit unsigned integer index into

### sc-object-index

A 32-bit unsigned integer index into

### statements

A list of [Statement](#Statement) objects for this frame, may be empty.

## Handler

### start-protected-region

### end-protected-region

### category-mask

### action

### register-with-block

### handler-goto

## Lexical

### name

The name of this lexical, if any.

### type

The type of this lexical.

### flags

A 16-bit unsigned integer bitmap for this lexical.

### sc-dependency-index

Index of into the `sc-dependencies` list.

### sc-object-index

Index of into the `sc-dependencies` list.

## Local

### name

The name of this local, if any.

### type

The type of this local.

## Statement

### line

The line number of this statement.

### offset

The opcode offset of this statement.

## Op

### all-adverbs

Return a `List` of all possible adverbs.

### all-ops

Return a `List` of all possible ops.

### annotation

The annotation of this operation. Currently recognized annotations are:

* dispatch
* jump
* parameter
* return
* spesh

Absence of annotation if indicated by the empty string. See also [is-sequence](#is-sequence).

### adverbs

A `Map` of additional adverb strings.

### bytes

```
my $bytes := $op.bytes($frame, $offset);

```

The number of bytes this op occupies in memory. Returns **0** if the op has a variable size.

Some ops have a variable size depending on the callsite in the frame it is residing. For those cases, one can call the `bytes` method with the [Frame](#Frame) object and the offset in the opcodes of that frame to obtain the number of bytes for that instance.

### index

The numerical index of this operation.

### is-sequence

True if this op is the start of a sequence of ops that share the same annotation.

### name

The name of this operation.

### new

```
my $op = MoarVM::Op.new(0);

my $op = MoarVM::Op.new("no_op");

```

Return an instantiated `MoarVM::Op` object from the given name or opcode number.

### not-inlineable

Returns `True` if the op causes the frame to which it belongs to be not inlineable. Otherwise returns `False`.

### operands

A `List` of operands, if any.

# AUTHOR

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

# COPYRIGHT AND LICENSE

Copyright 2024, 2025 Elizabeth Mattijsen

Source can be located at: <https://github.com/lizmat/MoarVM-Bytecode> . 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!

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


## notandthen.md
notandthen

Combined from primary sources listed below.

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

See primary documentation
[in context](/language/operators#infix_notandthen)
for **infix notandthen**.

The `notandthen` operator returns [`Empty`](/type/Slip#constant_Empty) upon encountering the first [defined](/routine/defined) argument, otherwise the last argument. Last argument is returned as-is, without being checked for definedness at all. Short-circuits. The result of the left side is bound to `$_` for the right side, or passed as arguments if the right side is a [`Callable`](/type/Callable), whose [count](/routine/count) must be `0` or `1`.

At first glance, [notandthen](/routine/notandthen) might appear to be the same thing as the [orelse](/routine/orelse) operator. The difference is subtle: [notandthen](/routine/notandthen) returns [`Empty`](/type/Slip#constant_Empty) when it encounters a [defined](/routine/defined) item (that isn't the last item), whereas [orelse](/routine/orelse) returns that item. In other words, [notandthen](/routine/notandthen) is a means to act when items aren't defined, whereas [orelse](/routine/orelse) is a means to obtain the first defined item:

```raku
sub all-sensors-down     { [notandthen] |@_, True             }
sub first-working-sensor { [orelse]     |@_, 'default sensor' }

all-sensors-down Nil, Nil, Nil
  and say 'OMG! All sensors are down!'; # OUTPUT:«OMG! All sensors are down!␤»
say first-working-sensor Nil, Nil, Nil; # OUTPUT:«default sensor␤»

all-sensors-down Nil, 42, Nil
  and say 'OMG! All sensors are down!'; # No output
say first-working-sensor Nil, 42, Nil;  # OUTPUT:«42␤»

```

The `notandthen` operator is a close relative of the [`without` statement modifier](/language/control#with_orwith_without), and some compilers compile `without` to `notandthen`, meaning these two lines have equivalent behavior:

```raku
sub good-things { fail }

'boo'.say without good-things;
good-things() notandthen 'boo'.say;

```


## dist_zef-vrurg-WWW-GCloud-API-Vision.md
# NAME

`WWW::GCloud::API::Vision` - `WWW::GCloud` implementation of [Google Vision API](https://cloud.google.com/vision/docs/reference/rest)

# SYNOPSIS

```
use v6.e.PREVIEW;
use WWW::GCloud;
use WWW::GCloud::API::Vision;
use WWW::GCloud::API::Vision::Types;

my $gcloud = WWW::GCloud.new;
my $images = $gcloud.vision.images;

my $queue = $images.annotation-queue;
given $queue {
    .project("my-project-id");
    # Create a new request to OCR-annotate an image. Subsequent calls to .request will queue new requests.
    .request(
        :file("my-image.ext"), # Can be a PNG, TIFF, GIF.
        feature => ( :type(GCVFDocument), :model<builtin/latest> ),
        # If several features to be added at once:
        # features => [...],
        -> $request {
            # Here we can do things with the request object itself.
            $request.feature(GCVFLogo); # Also search the image for logos.
            # If there is something special about the input config...
            # $request.set-input-config(...);

            # If the image is a multi-page one. .pages is an Array[UInt:D] attribute.
            # $request.pages = 1,3;
        }
    );
}

await $queue
        .start
        .andthen({
            say "Annotate completed."
            # .result is an instance of WWW::GCloud::R::Vision::BatchAnnotateImagesResponse
        });

```

# DESCRIPTION

This module lacks complete documentation due to me not currently able to write it. Please, see some notes for [`WWW::GCloud`](https://raku.land/zef:vrurg/WWW::GCloud) framework. And look into *exmaples/* where I tried to provide meaningful code to follow.

## Status

This module is pre-beta, pre-anything. It is incomplete and likely not well thought out at places. But it already lets you do a lot with your storages.

If there is anything you need but it is missing then, please, consider implementing it and submitting a PR. Any other approach would barely proces any outcome for what I do apologize!

Either way, this module can be used as a reference implementation for a `WWW::GGCloud` API.

Do not hesitate to get in touch with me would you need any help. I know it could be annoying when a complex module has little to none docs. I'll do my best to fix the situation. But until then feel free to open an issue in the [GitHub repository](https://github.com/vrurg/raku-WWW-GCloud-API-Vision/issues), even if it's just a question.

# COPYRIGHT

(c) 2023, Vadim Belman [vrurg@cpan.org](mailto:vrurg@cpan.org)

# LICENSE

Artistic License 2.0

See the [*LICENSE*](LICENSE) file in this distribution.


## dist_cpan-JFORGET-Date-Calendar-Hebrew.md
# NAME

Date::Calendar::Hebrew - Conversions from / to the Hebrew calendar

# SYNOPSIS

Converting a Gregorian date (e.g. 16th June 2019) into Hebrew

```
use Date::Calendar::Hebrew;
my Date                   $TPC2019-Pittsburgh-grg;
my Date::Calendar::Hebrew $TPC2019-Pittsburgh-heb;

$TPC2019-Pittsburgh-grg .= new(2019, 6, 16);
$TPC2019-Pittsburgh-heb .= new-from-date($TPC2019-Pittsburgh-grg);

say $TPC2019-Pittsburgh-heb;
# --> 5779-03-13
say "{.day-name} {.day} {.month-name} {.year}" with $TPC2019-Pittsburgh-heb;
# --> Yom Rishon 13 Sivan 5779

```

Converting a Hebrew date (e.g. 6 Av 5779) into Gregorian

```
use Date::Calendar::Hebrew;
my Date::Calendar::Hebrew $Perlcon-Riga-heb;
my Date                   $Perlcon-Riga-grg;

$Perlcon-Riga-heb .= new(year  => 5779
                       , month =>    5
                       , day   =>    6);
$Perlcon-Riga-grg = $Perlcon-Riga-heb.to-date;

say $Perlcon-Riga-grg;

```

# INSTALLATION

```
zef install Date::Calendar::Hebrew

```

or

```
git clone https://github.com/jforget/raku-Date-Calendar-Hebrew.git
cd raku-Date-Calendar-Hebrew
zef install .

```

# DESCRIPTION

Date::Calendar::Hebrew is a class representing dates in the Hebrew
calendar. It allows you to convert an Hebrew date into Gregorian (or
possibly other) calendar and the other way.

# AUTHOR

Jean Forget [JFORGET@cpan.org](mailto:JFORGET@cpan.org)

# COPYRIGHT AND LICENSE

Copyright © 2019, 2020 Jean Forget, all rights reserved

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


## dist_zef-FCO-Protocol.md
[![Build Status](https://travis-ci.org/FCO/Protocol.svg?branch=master)](https://travis-ci.org/FCO/Protocol)

# Potocol

## Description

The idea here is to have a "set of methods". So, you can test a *class* based on that set of methods. But different from *roles* with stubbed methods it doesn't need do be "*does*ed" to be matched. It does create a subset but using a different syntax, and will check the methods.

## Synopsis

```
use Protocol;

protocol Writer {               # creates a Writer protocol that have a write method
    method write { ... }
}

sub write(Writer $w) {          # accepts a Writer
    $w.write
}

class JustAGreeter {            # no roles, parents nor protocols declared on the class
    method write {              # it has the write method, so it attends to the protocol
        say "Hello protocol!"
    }
}

write JustAGreeter.new;         # prints: Hello protocol!

```


## dist_zef-sumankhanal-Statistics.md
[![Linux](https://github.com/sumanstats/Statistics/actions/workflows/linux.yml/badge.svg)](https://github.com/sumanstats/Statistics/actions/workflows/linux.yml)
[![Win64](https://github.com/sumanstats/Statistics/actions/workflows/windows-spec.yml/badge.svg)](https://github.com/sumanstats/Statistics/actions/workflows/windows-spec.yml)
[![MacOS](https://github.com/sumanstats/Statistics/actions/workflows/macos.yml/badge.svg)](https://github.com/sumanstats/Statistics/actions/workflows/macos.yml)
[![Build status](https://ci.appveyor.com/api/projects/status/8k6m9d1e7lcby5bm/branch/main?svg=true)](https://ci.appveyor.com/project/sumanstats/statistics/branch/main)

[![Lifecycle](https://img.shields.io/badge/lifecycle-experimental-brightgreen.svg)](https://github.com/sumanstats/Statistics)

```
  _____ _        _   _     _   _
 / ____| |      | | (_)   | | (_)
| (___ | |_ __ _| |_ _ ___| |_ _  ___ ___
 \___ \| __/ _` | __| / __| __| |/ __/ __|
 ____) | || (_| | |_| \__ \ |_| | (__\__ \
|_____/ \__\__,_|\__|_|___/\__|_|\___|___/v0.0.6

```

# NAME

Statistics - Raku module for doing statistics

# SYNOPSIS

```
use Statistics;

my @data1 = [6,6,4,6,8,6,8,4,4,6,6,8,8,8,8,8,8,4,4,4,4,8,8,8,8,4,4,4,8,6,8,4];
my @data2 = [160.0,160.0,108.0,258.0,360.0,225.0,360.0,146.7,140.8,167.6,167.6,
            275.8,275.8,275.8,472.0,460.0,440.0,78.7,75.7,71.1,120.1,318.0,304.0,
            350.0,400.0,79.0,120.3,95.1,351.0,145.0,301.0,121.0];

# central tendency
mean(@data1); # 6.1875
median(@data1); # 6

# sample standard deviation
sd(@data1); # 1.7859216469465444

# population standard deviation
sd(@data1, sample => False); # 1.757795138803154

# Coefficient of variation
coef_variation(@data2); # 53.71779066522493

# Five number summary
fivenum(@data2); # (71.1 120.65 196.3 334 472)

# correlation coefficients
pearson_cor_coef(@data1, @data2); # 0.9020328721469989
spearman_cor_coef(@data1, @data2); # 0.9276515785415314
kendall_cor_coef(@data1, @data2); # 0.8144262510988963

# Biweight_midcorrelation
# more robust, less sensitive to outliers
bi_cor_coef(@data1, @data2); # 0.9146470012038392

# numpy linspace
linspace(2.1, 3.2, 5, endpoint => False, retstep => False); # [2.1, 2.32, 2.54, 2.76, 2.98]
linspace(1, 3, 3, endpoint => False, retstep => True); # ([1, 1.666667, 2.333333], 0.666667)

# pdf of normal distribution
raku_dnorm(5); # 1.4867195147342977e-06
raku_dnorm(3, mean => 2, sd => 1); # 0.24197072451914337
raku_dnorm(3, mean => 2, sd => -1); # NaN;
raku_dnorm(3, mean => 2, sd => 0); # 0;

# cdf of normal distribution
raku_pnorm(5); # 0.9999997133484281
raku_pnorm(4, mean => 2, sd => 3); # 0.7475074624530771
raku_pnorm(4, mean => 2, sd => 3, log_p => True) # -0.29101099055230867

raku_qnorm(5); # NaN

# Random number generator for normal distribution
set_seed(111,222);
raku_rnorm(12) # (0.2933064931910023 -0.43157564134676835 0.1280404124560668 -1.001461811038476 -0.9219453227924342 1.2988990178409578 -0.46867271131577315 -1.2678609176619775 0.3596981905325252 0.35262105537769173 0.5770092689090144 -1.0392300758070165)

# Multinomial coefficients
multinomial_coef([3,1,1,3,4.2, 8, 90, 40]); # 2.717246116384229e+69;
multinomial_coef([3,1,1,3,4.2, 8, 90, 140]); # 1.0317825100856673e+106;
multinomial_coef([2,4,5,7]); # 220540320

multinomial_coef_excel([3,1.9,1,3,4.2]); # 554400;

```

# DESCRIPTION

Statistics is a module to make it easier to do statistics in Raku programming language.

## Features

* descriptive statistics
* correlation coefficients
* pdf, cdf of probability distributions
* random number generators
* parametric tests
* non-parametric tests

### INSTALLATION

The module contains **compiled** code. `gcc`, `cmake` and `ninja`
are required for compilation and should be available in `PATH`.

### ISSUES

<https://github.com/sumanstats/Statistics/issues>

### PULL REQUESTS

Improvement of the code base and efficient implementation of the algorithms are welcome.

# AUTHOR

Dr Suman Khanal [suman81765@gmail.com](mailto:suman81765@gmail.com)

# COPYRIGHT AND LICENSE

Copyright 2022 Dr Suman Khanal

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


## 101-basics.md
Raku by example 101

A basic introductory example of a Raku program

Suppose that you host a table tennis tournament. The referees tell you the results of each game in the format `Player1 Player2 | 3:2`, which means that `Player1` won against `Player2` by 3 to 2 sets. You need a script that sums up how many matches and sets each player has won to determine the overall winner.

The input data (stored in a file called `scores.txt`) looks like this:

｢data｣ without highlighting

```

```

Beth Ana Charlie Dave
Ana Dave | 3:0
Charlie Beth | 3:1
Ana Beth | 2:3
Dave Charlie | 3:0
Ana Charlie | 3:1
Beth Dave | 0:3

```

```

The first line is the list of players. Every subsequent line records a result of a match.

Here's one way to solve that problem in Raku:

```raku
use v6;

# start by printing out the header.
say "Tournament Results:\n";

my $file  = open 'scores.txt'; # get filehandle and...
my @names = $file.get.words;   # ... get players.

my %matches;
my %sets;

for $file.lines -> $line {
    next unless $line; # ignore any empty lines

    my ($pairing, $result) = $line.split(' | ');
    my ($p1, $p2)          = $pairing.words;
    my ($r1, $r2)          = $result.split(':');

    %sets{$p1} += $r1;
    %sets{$p2} += $r2;

    if $r1 > $r2 {
        %matches{$p1}++;
    } else {
        %matches{$p2}++;
    }
}

my @sorted = @names.sort({ %sets{$_} }).sort({ %matches{$_} }).reverse;

for @sorted -> $n {
    my $match-noun = %matches{$n} == 1 ?? 'match' !! 'matches';
    my $set-noun   = %sets{$n} == 1 ?? 'set' !! 'sets';
    say "$n has won %matches{$n} $match-noun and %sets{$n} $set-noun";
}

```

This produces the output:

｢text｣ without highlighting

```

```

Tournament Results:

Ana has won 2 matches and 8 sets
Dave has won 2 matches and 6 sets
Charlie has won 1 match and 4 sets
Beth has won 1 match and 4 sets

```

```

# [`v6`](#Raku_by_example_101 "go to top of document")[§](#Pragma_v6 "direct link")

```raku
use v6;

```

Every Raku program should begin with a line similar to `use v6;`. This line tells the compiler which version of Raku the program expects. For instance, 6.c is an example of a Raku version. Should you accidentally run the file with Perl, you'll get a helpful error message.

# [Statements](#Raku_by_example_101 "go to top of document")[§](#Statements "direct link")

```raku
# start by printing out the header.
say "Tournament Results:\n";

```

A Raku program consists of zero or more statements. A *statement* ends with a semicolon or a curly brace at the end of a line.

In Raku, single line comments start with a single hash character `#` and extend until the end of the line. Raku also supports [multi-line/embedded comments](/language/syntax#Multi-line_/_embedded_comments). The compiler doesn't evaluate comments as program text and they're only intended for human readers.

# [Lexical scope](#Raku_by_example_101 "go to top of document")[§](#Lexical_scope_and_block "direct link")

```raku
my $file = open 'scores.txt';

```

`my` declares a lexical variable, which are visible only in the current block from the point of declaration to the end of the block. If there's no enclosing block, it's visible throughout the remainder of the file (which would effectively be the enclosing block). A block is any part of the code enclosed between curly braces `{ }`.

## [Sigils](#Raku_by_example_101 "go to top of document")[§](#Sigils_and_identifiers "direct link")

A variable name begins with a *sigil*, which is a non-alpha-numeric symbol such as `$`, `@`, `%`, or `&` — or occasionally the double colon `::`. Sigils indicate the structural interface for the variable, such as whether it should be treated as a single value, a compound value, a subroutine, etc. After the sigil comes an *identifier*, which may consist of letters, digits and the underscore. Between letters you can also use a dash `-` or an apostrophe `'`, so `isn't` and `double-click` are valid identifiers.

## [Scalar](#Raku_by_example_101 "go to top of document")[§](#Scalar "direct link")

Sigils indicate the default access method for a variable. Variables with the `@` sigil are accessed positionally; variables with the `%` sigil are accessed by string key. The `$` sigil, however, indicates a general scalar container that can hold any single value and be accessed in any manner. A scalar can even contain a compound object like an [`Array`](/type/Array) or a [`Hash`](/type/Hash); the `$` sigil signifies that it should be treated as a single value, even in a context that expects multiple values (as with an [`Array`](/type/Array) or [`Hash`](/type/Hash)).

## [Filehandle](#Raku_by_example_101 "go to top of document")[§](#Filehandle_and_assignment "direct link")

The built-in function `open` opens a file, here named `scores.txt`, and returns a *filehandle* — an object representing that file. The assignment operator `=` *assigns* that filehandle to the variable on the left, which means that `$file` now stores the filehandle.

## [String literals](#Raku_by_example_101 "go to top of document")[§](#String_literals "direct link")

`'scores.txt'` is a *string literal*. A string is a piece of text, and a string literal is a string which appears directly in the program. In this line, it's the argument provided to `open`.

# [Arrays](#Raku_by_example_101 "go to top of document")[§](#Arrays,_methods_and_invocants "direct link")

```raku
my @names = $file.get.words;

```

The right-hand side calls a *method* — a named group of behavior — named `get` on the filehandle stored in `$file`. The `get` method reads and returns one line from the file, removing the line ending. If you print the contents of `$file` after calling `get`, you will see that the first line is no longer in there. `words` is also a method, called on the string returned from `get`. `words` decomposes its *invocant* — the string on which it operates — into a list of words, which here means strings separated by whitespace. It turns the single string `'Beth Ana Charlie Dave'` into the list of strings `'Beth', 'Ana', 'Charlie', 'Dave'`.

Finally, this list gets stored in the [`Array`](/type/Array) `@names`. The `@` sigil marks the declared variable as an [`Array`](/type/Array). Arrays store ordered lists.

# [Hashes](#Raku_by_example_101 "go to top of document")[§](#Hashes "direct link")

```raku
my %matches;
my %sets;

```

These two lines of code declare two hashes. The `%` sigil marks each variable as a [`Hash`](/type/Hash). A [`Hash`](/type/Hash) is an unordered collection of key-value pairs. Other programming languages call that a *hash table*, *dictionary*, or *map*. You can query a hash table for the value that corresponds to a certain `$key` with `%hash{$key}`.

In the score counting program, `%matches` stores the number of matches each player has won. `%sets` stores the number of sets each player has won. Both of these hashes are indexed by the player's name.

# [`for`](#Raku_by_example_101 "go to top of document")[§](#for_and_blocks "direct link")

```raku
for $file.lines -> $line {
    ...
}

```

`for` produces a loop that runs the *block* delimited by curly braces once for each item of the list, setting the variable `$line` to the current value of each iteration. `$file.lines` produces a list of the lines read from the file `scores.txt`, starting with the second line of the file since we already called `$file.get` once, and going all the way to the end of the file.

During the first iteration, `$line` will contain the string `Ana Dave | 3:0`; during the second, `Charlie Beth | 3:1`, and so on.

```raku
my ($pairing, $result) = $line.split(' | ');

```

`my` can declare multiple variables simultaneously. The right-hand side of the assignment is a call to a method named `split`, passing along the string `' | '` as an argument.

`split` decomposes its invocant into a list of strings, so that joining the list items with the separator `' | '` produces the original string.

`$pairing` gets the first item of the returned list, and `$result` the second.

After processing the first line, `$pairing` will hold the string `Ana Dave` and `$result` will hold `3:0`.

The next two lines follow the same pattern:

```raku
my ($p1, $p2) = $pairing.words;
my ($r1, $r2) = $result.split(':');

```

The first extracts and stores the names of the two players in the variables `$p1` and `$p2`. The second extracts the results for each player and stores them in `$r1` and `$r2`.

After processing the first line of the file, the variables contain the values:

|  |  |
| --- | --- |
| Variable | Contents |
| $line | 'Ana Dave | 3:0' |
| $pairing | 'Ana Dave' |
| $result | '3:0' |
| $p1 | 'Ana' |
| $p2 | 'Dave' |
| $r1 | '3' |
| $r2 | '0' |

The program then counts the number of sets each player has won:

```raku
%sets{$p1} += $r1;
%sets{$p2} += $r2;

```

The above two statements involve the `+=` compound assignment operator. They are a variant of the following two statements that use the simple assignment operator `=` and that may be easier to understand at first sight:

```raku
%sets{$p1} = %sets{$p1} + $r1;
%sets{$p2} = %sets{$p2} + $r2;

```

For your program, the shorthand version using the `+=` compound assignment operator is preferred over the longhand version using the simple assignment operator `=`. This is not only because the shorter version requires less typing, but also because the `+=` operator silently initializes undefined values of the hash's key-value pairs to zero. In other words: by using `+=`, there is no need to include a separate statement like `%sets{$p1} = 0` before you can meaningfully add `$r1` to it. We'll look at this is behavior in a bit more detail below.

## [`Any`](#Raku_by_example_101 "go to top of document")[§](#Any_and_+= "direct link")

```raku
%sets{$p1} += $r1;
%sets{$p2} += $r2;

```

`%sets{$p1} += $r1` means *increase the value in the variable on the left by $r1*. In the first iteration `%sets{$p1}` is not yet defined, so it defaults to a special value called [`Any`](/type/Any). The `+=` operator conveniently treats the undefined value [`Any`](/type/Any) as a number with the value `0`, allowing it to sensibly add some other value to it. To perform the addition, the strings `$r1`, `$r2`, etc. are automatically converted to numbers, as addition is a numeric operation.

## [Fat arrow](#Raku_by_example_101 "go to top of document")[§](#Fat_arrow,_pairs_and_autovivification "direct link")

Before these two lines execute, `%sets` is empty. Adding to an entry that is not in the hash yet will cause that entry to spring into existence just-in-time, with a value starting at zero. This behavior is known as *autovivification*. After these two lines have run for the first time, `%sets` contains `'Ana' => 3, 'Dave' => 0`. (The fat arrow `=>` separates the key and the value in a [`Pair`](/type/Pair).)

## [Postincrement](#Raku_by_example_101 "go to top of document")[§](#Postincrement_and_preincrement "direct link")

```raku
if $r1 > $r2 {
    %matches{$p1}++;
} else {
    %matches{$p2}++;
}

```

If `$r1` is numerically larger than `$r2`, `%matches{$p1}` increments by one. If `$r1` is not larger than `$r2`, `%matches{$p2}` increments. Just as in the case of `+=`, if either hash value did not exist previously, it is autovivified by the increment operation.

`$thing++` is a variant of `$thing += 1`; it differs from the latter in that the return value of the expression is `$thing` *before* the increment, and not the incremented value. As in many other programming languages, you can use `++` as a prefix. Then it returns the incremented value: `my $x = 1; say ++$x` prints `2`.

# [Topic variable](#Raku_by_example_101 "go to top of document")[§](#Topic_variable "direct link")

```raku
my @sorted = @names.sort({ %sets{$_} }).sort({ %matches{$_} }).reverse;

```

This line consists of three individually simple steps. An array's `sort` method returns a sorted version of the array's contents. However, the default sort on an array sorts by its contents. To print player names in winner-first order, the code must sort the array by the *scores* of the players, not their names. The `sort` method's argument is a *block* used to transform the array elements (the names of players) to the data by which to sort. The array items are passed in through the *topic variable* `$_`.

## [Blocks](#Raku_by_example_101 "go to top of document")[§](#Blocks "direct link")

You have seen blocks before: both the `for` loop `-> $line { ... }` and the `if` statement worked on blocks. A block is a self-contained piece of Raku code with an optional signature (the `-> $line` part).

The simplest way to sort the players by score would be `@names.sort({ %matches{$_} })`, which sorts by number of matches won. However Ana and Dave have both won two matches. That simple sort doesn't account for the number of sets won, which is the secondary criterion to decide who has won the tournament.

## [Stable sort](#Raku_by_example_101 "go to top of document")[§](#Stable_sort "direct link")

When two array items have the same value, `sort` leaves them in the same order as it found them. Computer scientists call this a *stable sort*. The program takes advantage of this property of Raku's `sort` to achieve the goal by sorting twice: first by the number of sets won (the secondary criterion), then by the number of matches won (the primary criterion).

After the first sorting step, the names are in the order `Beth Charlie Dave Ana`. After the second sorting step, it's still the same, because no one has won fewer matches but more sets than someone else. Such a situation is entirely possible, especially at larger tournaments.

`sort` sorts in ascending order, from smallest to largest. This is the opposite of the desired order. Therefore, the code calls the `.reverse` method on the result of the second sort, and stores the final list in `@sorted`.

# [Standard output](#Raku_by_example_101 "go to top of document")[§](#Standard_output "direct link")

```raku
for @sorted -> $n {
    my $match-noun = %matches{$n} == 1 ?? 'match' !! 'matches';
    my $set-noun   = %sets{$n} == 1 ?? 'set' !! 'sets';
    say "$n has won %matches{$n} $match-noun and %sets{$n} $set-noun";
}

```

To print out the players and their scores, the code loops over `@sorted`, setting `$n` to the name of each player in turn. Read this code as "For each element of sorted, set `$n` to the element, then execute the contents of the following block." The variable `$match-noun` will store either the string *match* if the player has won a single match or *matches* if the player has won zero or more matches. In order to do this, the *ternary* operator (`?? !!`) is used. If `%matches{$n} == 1` evaluates to `True`, then *match* is returned. Otherwise, *matches* is returned. Either way, the returned value is stored in `$match-noun`. The same approach applies to `$set-noun`.

The statement `say` prints its arguments to the standard output (the screen, normally), followed by a newline. (Use `print` if you don't want the newline at the end.)

Note that `say` will truncate certain data structures by calling the `.gist` method so `put` is safer if you want exact output.

## [Variable interpolation](#Raku_by_example_101 "go to top of document")[§](#Variable_interpolation "direct link")

When you run the program, you'll see that `say` doesn't print the contents of that string verbatim. In place of `$n` it prints the contents of the variable `$n` — a player's name stored in `$n`. This automatic substitution of code with its contents is called *interpolation*. This interpolation happens only in strings delimited by double quotes `"..."`. Single quoted strings `'...'` do not interpolate:

## [Double-quoted strings](#Raku_by_example_101 "go to top of document")[§](#Double-quoted_strings_and_single-quoted_strings "direct link")

```raku
my $names = 'things';
say 'Do not call me $names'; # OUTPUT: «Do not call me $names␤»
say "Do not call me $names"; # OUTPUT: «Do not call me things␤»

```

Double quoted strings in Raku can interpolate variables with the `$` sigil as well as blocks of code in curly braces. Since any arbitrary Raku code can appear within curly braces, [`Array`](/type/Array)s and [`Hash`](/type/Hash)es may be interpolated by placing them within curly braces.

Arrays within curly braces are interpolated with a single space character between each item. Hashes within curly braces are interpolated as a series of lines. Each line will contain a key, followed by a tab character, then the value associated with that key, and finally a newline.

Let's see an example of this now.

In this example, you will see some special syntax that makes it easier to make a list of strings. This is the `<...>` [quote-words](/language/operators#index-entry-qw-quote-words-quote-words) construct. When you put words in between the `<` and `>` they are all assumed to be strings, so you do not need to wrap them each in double quotes `"..."`.

```raku
say "Math: { 1 + 2 }";
# OUTPUT: «Math: 3␤»

my @people = <Luke Matthew Mark>;
say "The synoptics are: {@people}";
# OUTPUT: «The synoptics are: Luke Matthew Mark␤»

say "{%sets}";
# OUTPUT (From the table tennis tournament):

# Charlie 4
# Dave    6
# Ana     8
# Beth    4

```

When array and hash variables appear directly in a double-quoted string (and not inside curly braces), they are only interpolated if their name is followed by a postcircumfix operator — a bracketing pair that follows a statement. It's also ok to have a method call between the variable name and the postcircumfix.

# [Zen slices](#Raku_by_example_101 "go to top of document")[§](#Zen_slices "direct link")

```raku
my @flavors = <vanilla peach>;

say "we have @flavors";           # OUTPUT: «we have @flavors␤»
say "we have @flavors[0]";        # OUTPUT: «we have vanilla␤»
# so-called "Zen slice"
say "we have @flavors[]";         # OUTPUT: «we have vanilla peach␤»

# method calls ending in postcircumfix
say "we have @flavors.sort()";    # OUTPUT: «we have peach vanilla␤»

# chained method calls:
say "we have @flavors.sort.join(', ')";
                                  # OUTPUT: «we have peach, vanilla␤»

```

# [Exercises](#Raku_by_example_101 "go to top of document")[§](#Exercises "direct link")

**1.** The input format of the example program is redundant: the first line containing the name of all players is not necessary, because you can find out which players participated in the tournament by looking at their names in the subsequent rows, so in principle we could safely remove it.

How can you make the program run if you do not use the `@names` variable? Hint: `%hash.keys` returns a list of all keys stored in `%hash`.

**Answer:** After removing the first line in `scores.txt`, remove the line `my @names = $file.get.words;` (which would read it), and change:

```raku
my @sorted = @names.sort({ %sets{$_} }).sort({ %matches{$_} }).reverse;

```

... into:

```raku
my @sorted = %sets.keys.sort({ %sets{$_} }).sort({ %matches{$_} }).reverse;

```

**2.** Instead of deleting the redundant `@names` variable, you can also use it to warn if a player appears that wasn't mentioned in the first line, for example due to a typo. How would you modify your program to achieve that?

Hint: Try using [membership operators](/language/operators#infix_(elem),_infix_∈).

**Answer:** Change `@names` to `@valid-players`. When looping through the lines of the file, check to see that `$p1` and `$p2` are in `@valid-players`. Note that for membership operators you can also use `(elem)` and `!(elem)`.

```raku
...;
my @valid-players = $file.get.words;
...;

for $file.lines -> $line {
    my ($pairing, $result) = $line.split(' | ');
    my ($p1, $p2)          = $pairing.split(' ');
    if $p1 ∉ @valid-players {
        say "Warning: '$p1' is not on our list!";
    }
    if $p2 ∉ @valid-players {
        say "Warning: '$p2' is not on our list!";
    }
    ...
}

```