## dist_zef-whity-Logger.md
# Logger

A simple logging class in raku.

[![test](https://github.com/whity/raku-log/actions/workflows/test.yml/badge.svg)](https://github.com/whity/raku-log/actions/workflows/test.yml)

## Usage

```
use Logger;

sub MAIN() {
    my $log = Logger.new;
    # by default the log level is INFO and the output is $*OUT (can be any IO::Handle)
    # Logger.new(level => Logger::DEBUG, output => $*ERR)

    # log a message
    $log.trace('trace message');
    $log.debug('debug message');
    $log.info('info message');
    $log.warn('warn message');
    $log.error('error message');

    # ndc
    $log.ndc.push('xxx'); # add a value to the stack
    $log.ndc.pop(); # remove the last item from the stack

    # mdc
    $log.mdc.put('key', 'value');

    # change the level
    $log.level = Logger::DEBUG;
    $log.debug('debug message');

    # checking the current log level
    say $log.is-error;
    say $log.is-info;

    # log pattern placeholders
    #   %m -> message
    #   %d -> current datetime
    #   %c -> message level
    #   %n -> new line feed '\n'
    #   %p -> process id
    #   %x -> NDC
    #   %X{key-name} -> MDC

    $log.pattern = '%X{key} %x %m%n';
    $log.info('test');

    # register log object to use in other places
    Logger.add('log-name', Logger.new);
    #Log.add(Logger.new) # register the log object as 'main'

    # get a registered log object
    my $rlog = Logger.get('log-name');
    #my $rlog = Logger.get; returns the log object 'main'

    $rlog.info('from "log-name"');

    # Set a formatter for the datetime
    my $log = Logger.new(dt-formatter => -> $dt { sprintf "%sT%s", .dd-mm-yyyy, .hh-mm-ss given $dt)});
    $log.info('test'); # prints: [20-11-2021T18:31:44][INFO] test
}

```

## Contributing

1. Fork it ( [https://github.com/[your-github-name]/raku-log/fork](https://github.com/%5Byour-github-name%5D/raku-log/fork) )
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Add some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create a new Pull Request

## Contributors

* whity(<https://github.com/whity>) André Brás - creator, maintainer


## exitcode.md
exitcode

Combined from primary sources listed below.

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

See primary documentation
[in context](/type/Proc#method_exitcode)
for **method exitcode**.

```raku
method exitcode(Proc:D: --> Int:D)
```

Returns the exit code of the external process, or -1 if it has not exited yet.


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

# NAME

String::Fields - class for setting fixed size fields in a Str

# SYNOPSIS

```
use String::Fields;

my $sf := String::Fields.new(2,3,4)
.say for $sf.set-string("abcdefghijklmnopqrstuvwxyz");
# ab
# cde
# fghi

my $sf := String::Fields.new(2 => 5, 8, 3);
my $s = "012345678901234567890";

$s.&apply-fields($sf);  # or: apply-fields($s,$sf)
say $s;            # 012345678901234567890
say $s[0];         # 23456
say $s[1];         # 78901234
say $s[2];         # 567
say $s.join(":");  # 23456:78901234:567

# one time application
$s.&apply-fields(2,3,4);  # or: apply-fields($s,2,3,4)

# using a literal string
my @fields = "abcdefg".&apply-fields(2,3);  # ["ab","cde"]

```

# DESCRIPTION

String::Fields allows one to specify fixed length fields that can be applied to a string, effectively turning it into a sequence of strings that can be individually accessed or iterated over.

When the object is loaded with a string, it can be used as a string in all the normal ways that a string would.

# METHODS

## new

```
my $sf := String::Fields.new(2,3,4)

```

The `new` method creates a new `String::Fields` object that contains the format information of the fields. It takes any number of arguments to indicate the position and width of the fields. If the argument consists of just a number, it means the width of a field from where the last field has ended (or from position 0 for the first argument). If the argument consists of a `Pair`, then the key is taken for the offset, and the value is taken to be the width.

Please note that this **just** sets the format information. This allows the same object to be used for different strings. Setting the string to be used, is either done with the `set-string` method, or by calling the `apply-fields` subroutine.

## join

```
$s.join(":");

```

Joins all fields together with the given separator.

## set-string

```
$sf.set-string($string)

```

The `set-string` method sets the string to which the format information should be applied.

# SUBROUTINES

## apply-fields

```
apply-fields($s,$sf);  # or $s.&apply-fields($sf)

# one time application
$s.&apply-fields(2,3,4);  # or: apply-fields($s,2,3,4)

# using a literal string
my @fields = "abcdefg".&apply-fields(2,3);  # ["ab","cde"]

```

If the first argument to the `apply-fields` subroutine is a variable with a string in it, then it will become a `String::Fields` object (but will still act as the original string). If it is a string literal, then the created / applied `String::Fields` object will be returned. The other arguments indicate the fields that should be applie. This can be either be a `String::Fields` object, or it can any number of field specifications, as can be passed to the `new` method.

# AUTHOR

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

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

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

# COPYRIGHT AND LICENSE

Copyright 2020, 2021, 2024 Elizabeth Mattijsen

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


## dist_github-finanalyst-Collection-Raku-Documentation.md
# Collection-based Raku Documentation

> **Description** Distribution to set up Raku Documentation website.

> **Author** Richard Hainsworth, aka finanalyst

---

## Table of Contents

[Installation](#installation)
[Raku-Doc](#raku-doc)
[Raku-Doc as a wrapper for Collection::collect](#raku-doc-as-a-wrapper-for-collectioncollect)
[More contemporary web site.](#more-contemporary-web-site)
[In the future (not now)](#in-the-future-not-now)
[Enabling Cro App](#enabling-cro-app)
[Highlighting](#highlighting)
[Problems](#problems)
[Copyright and License](#copyright-and-license)

---

This Module creates a local website of the Raku documentation. It pulls together information held in several other distributions. The main content of this distribution is the `Raku-Doc` utility. It is intended to be as simple as possible. But the documentation system is large. The following contain other requirements.

* The documentation files are held in a github repository that is maintained and updated by the Raku community. `Raku-Doc` needs to have a local clone of the repository. It can be used to refresh the documents automatically.
* `Raku-Doc` uses Collection and Raku::Pod::Render to link all the Rakudoc (aka Pod6) files together. So `Collection` needs to be installed, which will install `Raku::Pod::Render`. By installing `Raku-Pod-Render` a user can then use `Pod::To::HTML2` to render individual `.rakudoc / .pod6` files into HTML, or `Pod::To::MarkDown2` to render them into `.md` files.
* `Collection` requires over a dozen plugins, which are automatically refreshed from a github repository by `Raku-Doc`.
* The Raku documentation system can currently be visualised in two ways:

  * using the original web design started by Moritz Lenz (using the mode Website) - currently the default.
  * using a new design by OgdenWebb (using the mode OgdenWebb).
* The website is intended to be served locally with a Cro app. Since making Cro a dependency can cause problems in a testing environment, the META6.json does not have Cro as a dependency. If Cro::HTTP is not installed, the completion plugin will exit with a note.
* A website contains templates and structure documents, which describe the website into which the Raku documentation fit. This content is also held in a separate repository. This is intended to keep the development of plugins separate from the structure documents and templates, and separate from the Raku documentation content.

# Installation

```
zef install Collection-Raku-Documentation

```

This installs the `Collection` (and other) dependencies and the `Raku-Doc` executable. These in turn install the the other main distributions and `Raku::Pod::Render`. By default `Raku::Pod::Render` does not install the highlighter automatically because `node.js` and `npm` are required.

See [Highlighting](Highlighting.md) for installation of highlighter.

# Raku-Doc

On a Linux based distributions, `Raku-Doc` depends on `git` and `unzip`, which typically are installed by default, to get and unpack other files.

Under Linux, in a terminal, the following will lead to the installation of a local copy of Raku docs and start a Cro app that will make the HTML documentation available in a browser at `localhost:30000`, and produce a progress status bar for the longer stages.

```
mkdir ~/raku-collection
cd raku-collection
Raku-Doc Init

```

This sets up a Collection directory by downloading the Website mode from github, then installs the Collection plugins.

By default the `Raku/doc` repository (containing all the Raku documentation files) will be created in the next step as **local\_raku\_docs**.

If a user wants to clone the Raku docs repository elsewhere or has an existing clone of the Raku repository, then the non-default path needs to be put into the config.raku file in the `sources-obtain` and `sources-refresh` keys. See the documentation for the `Collection` distribution for more information.

At the next invocation of **Raku-Doc**, the documentation source will be cloned, cached, and rendered.

For example, to render the full Raku Docs, the following would work, where `raku-local` is a local directory.

```
- raku-collection
    - local_raku_docs # this is generated by the git clone command
    - Website # this is generated by runnng 'Raku-Doc Init' in raku-collection
    config.raku # as Website

```

After the `Init` stage, calling `Raku-Doc` without any other options implies the mode **Website** with default options.

The Raku Documentation source files are regularly updated. The **Website** mode is configured to pull the latest versions of the source files into the Collection whenever `Raku-Doc` is run, which then updates the cache for any sources that have changed, and then re-render all the html files that are affected. These stages are automatically called by running Raku-Doc with the config defaults given.

The Website mode files and plugins are being actively developed, so newer versions may be available. New versions of the plugins are automatically called on each invocation of Raku-Doc. To get new versions of the Website mode files (sources and additional plugins), use

```
Raku-Doc Update

```

`Raku-Doc` can be called with other options, which are described in the `Collection` documentation.

**Collection-Raku-Documentation** is set up with the default `mode` called **Website**.

The more contemporary web design by Ogden Webb is in a mode call **OgdenWebb**. It is generated thus:

```
Raku-Doc OgdenWebb

```

It can be made the default by changing the `mode` key in the top-level `config.raku` file.

# Raku-Doc as a wrapper for Collection::collect

With the exception of 'Init' and 'Update', `Raku-Doc` can be called with all the options listed for `Collection::collect`.

More information about these options is given in the Documentation for `Collection`.

## More contemporary web site.

A more contemporary web design by Ogden Webb is now included. It is generated by running

```
Raku-Doc OgdenWebb

```

## In the future (not now)

If `Raku-Doc` is called with a string other than 'Init' or 'Website', then the string is interpreted as another **Mode**, with its own sub-directory and [Configuration](Configuration.md) for the collection. For example,

```
Raku-Doc Book

```

would create the collection output defined by the configuration in the sub-directory `Book/config/`. This design is to allow for the creation of different Collection outputs to be defined for the same content files.

# Enabling Cro App

A Cro App is included that will run the website automatically by running `Raku-Doc`. The Cro App is called using a plugin that runs after the html files have been refreshed. The Cro App is called at completion (see Collection documentation). It contains a test to see if Cro::HTTP is installed.

Since installing Cro can cause testing problems, this distribution does not have Cro::HTTP as a dependency.

Cro in installed using zef as

```
zef install Cro::HTTP

```

Running `Raku-Doc` without options will now serve the documentation files locally on port 3000. So point your browser at `localhost:3000`

# Highlighting

The default highlighter at present is a Node based toolstack called **atom-perl-highlighter**. In order to install it automatically, `Raku::Pod::Render` requires an uptodate version of npm. The builder is known not to work with `node.js` > \*\*\*\*v13.0> and `npm` > **v14.15**.

For someone who has not installed `node` or `npm` before, or for whom they are only needed for the highlighter, the installation is ... confusing. It would seem at the time of writing that the easiest method is:

```
# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs

```

Then, **after the default installation of Raku::Pod::Render**, highlighting can be enabled by running the following in a terminal:

```
raku-render-install-highlighter

```

# Problems

Collection is still being actively developed.

* When running `Raku-Doc` with a `sources-refresh` key set to a git pull stanza, Raku-Doc teminates after a git pull. Workaround: run `Raku-Doc` again.

# Copyright and License

(c) Richard N Hainsworth, 2021-2022

**LICENSE** Artistic-2.0

---

Rendered from README at 2023-01-14T10:19:05Z


## dist_zef-Altai-man-deredere.md
# deredere

Simple scraper framework for Perl 6.

## Usage

Often we need to get some data from some web page over the Internet. Some sites provide an API, but many sites don't. This framework makes building of "data scraper" easier. You can just get the whole page, or parse it and do something with data. At this stage three basic cases are handled:

* Downloading of raw page by url.
* Downloading of raw page, data parsing and handling by default operator.
* Downloading of raw pages, where next link is extracted with outer function, data parsing and handling by custom operator.

`Parser` is just outer function, that converts an XML document to some data list.

`Operator` is just outer function, that takes data list and processes it.

`Default operator`, which is used when none passed, works like that: if parsed item is a URL, it will be downloaded, if parsed item is just some text, it will be appended to file with data.

## The real example itself

```
use deredere;
use XML;

sub src-extractor($node) {
    ($node.Str ~~ /src\=\"(.+?)\"/)[0].Str;
}

sub parser($doc) {
    $doc.lookfor(:TAG<img>).race.map(&src-extractor);
}

# Just as pure example.
scrape("konachan.net/post", &parser);

```

See other examples for more info.

## Scrapers

```
sub scrape(Str $url);
sub scrape(Str $url, &parser, Str :$filename="scraped-data.txt");
# "Next" function has a default value of empty line function, in the case if we scrape the first page only.
sub scrape(Str $url, &parser, &operator, &next?, Int $gens=1, Int $delay=0);

```

## Installation

```
$ zef update
$ zef install deredere

```

Also, you can install `IO::Sockes::SSL` to work with "https" links. You also need `XML` to build effective data parsers.

## Testing

Tests are coming.

## To-do List

* Tests.
* More cases.
* More operators.
* Speed up.


## dist_github-ccworld1000-CCLog.md
## [CCLog](https://github.com/ccworld1000/CCLog)

```
Simple and lightweight cross-platform logs,
easy-to-use simple learning,
and support for multiple languages,
such as C, C++, Perl 6, shell, Objective-C
support ios, osx, watchos, tvos
support pod, cocoapods https://cocoapods.org/pods/CCLog

```

## Perl 6

```
There are 2 (CCLog & CCLogFull) ways of binding.

```

Call CCLog.pm6

![short_perl6](https://raw.github.com/ccworld1000/CCLog/master/CCLog/doc/sceenshot/short_perl6.png)

Call CCLogFull.pm6

![full_perl6](https://raw.github.com/ccworld1000/CCLog/master/CCLog/doc/sceenshot/full_perl6.png)

## Shell

```
Provide simple commands. fg:
	ccnormal
	ccwarning
	ccerror
	cctimer
	ccloop
	ccthread
	ccprint
	ccsay
	ccdie
	ccnetwork

These commands are automatically installed locally and can be called directly.

```

Call shell

![shell](https://raw.github.com/ccworld1000/CCLog/master/CCLog/doc/sceenshot/shell.png)

## C && C++ && Objective-C

```
You can use C library or C source (CCLog.h CCLog.c) code directly.

```

Call C && C++ && Objective-C

![c](https://raw.github.com/ccworld1000/CCLog/master/CCLog/doc/sceenshot/c.png)

## Objective-C

```
Objective-C can call C directly, Or follow other ways to import.
or use pod https://github.com/ccworld1000/CCLog

pod 'CCLog'

```

## Local installation and unloading

```
zef install .
zef uninstall CCLog

```

## Network install

```
zef update
zef install CCLog

```

## Check if the installation is successful

The installation may be as follows

![check_ok](https://raw.github.com/ccworld1000/CCLog/master/CCLog/doc/sceenshot/check_ok.png)

Installation failure may be as follows, you can try again

![check_error](https://raw.github.com/ccworld1000/CCLog/master/CCLog/doc/sceenshot/check_error.png)

## Color display control

Perl6 CCLog.pm6 call ccshowColor
Perl6 CCLogFull.pm6 call CCLog\_showColor
C && C++ && Objective-C call CCLog\_showColor
fg:

![colorControl](https://raw.github.com/ccworld1000/CCLog/master/CCLog/doc/sceenshot/colorControl.png)

## Tips display control

fg:

![logTips](https://raw.github.com/ccworld1000/CCLog/master/CCLog/doc/sceenshot/logTips.png)

## Display log control

fg:

![displayLog](https://raw.github.com/ccworld1000/CCLog/master/CCLog/doc/sceenshot/displayLog.png)


## dist_zef-dwarring-PDF-Lite.md
[[Raku PDF Project]](https://pdf-raku.github.io)
/ [PDF::Lite](https://pdf-raku.github.io/PDF-Lite-raku)

[![Actions Status](https://github.com/pdf-raku/PDF-Lite-raku/workflows/test/badge.svg)](https://github.com/pdf-raku/PDF-Lite-raku/actions)

# PDF::Lite

`PDF::Lite` is a minimal class for creating or editing PDF documents, including:

* Basic Text
* Simple forms and images (GIF, JPEG & PNG)
* Graphics and Drawing
* Content reuse (Pages and form objects)

```
use v6;
use PDF::Lite;

my PDF::Lite $pdf .= new;
$pdf.media-box = 'Letter';
my PDF::Lite::Page $page = $pdf.add-page;
constant X-Margin = 10;
constant Padding = 10;

$page.graphics: {
    enum <x0 y0 x1 y1>;
    my $font = $pdf.core-font( :family<Helvetica>, :weight<bold>, :style<italic> );
    my @position = [10, 10];
    my @box = .say: "Hello World", :@position, :$font;

    my PDF::Lite::XObject $img = .load-image: "t/images/lightbulb.gif";
    .do: $img, :position[@box[x1] + Padding, 10];
}

given $pdf.Info //= {} {
    .CreationDate = DateTime.now;
}

$pdf.save-as: "examples/hello-world.pdf";

```

![example.pdf](examples/.previews/hello-world-001.png)

#### Text

`.say` and `.print` are simple convenience methods for displaying simple blocks of text with encoding, optional line-wrapping, alignment and kerning.

These methods return a rectangle given the rendered text region;

```
use PDF::Lite;
enum <x0 y0 x1 y1>;
my PDF::Lite $pdf .= new;
$pdf.media-box = [0, 0, 500, 150];
my PDF::Lite::Page $page = $pdf.add-page;
my $font = $pdf.core-font( :family<Helvetica> );
my $header-font = $pdf.core-font( :family<Helvetica>, :weight<bold> );

$page.text: -> $txt {
    $txt.font = $header-font, 16;
    $txt.text-position = 250, 112;
    $txt.say: 'Some Sample PDF::Lite Text', :align<center>, :valign<bottom>;
    my $width := 200;
    my $text = q:to"--END--";
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
    ut labore et dolore magna aliqua.
    --END--

    $txt.font = $font, 12;
    # output text with left, top corner at (20, 100)
    my @box = $txt.say: $text, :$width, :position[20, 100];
    note "text height: {@box[y1] - @box[y0]}";

    # output kerned paragraph, flow from right to left, right, top edge at (450, 100)
    $txt.say( $text, :$width, :height(150), :align<right>, :kern, :position[450, 100] );
    # add another line of text, flowing on to the next line
    $txt.font = $pdf.core-font( :family<Helvetica>, :weight<bold> ), 12;
    $txt.say( "But wait, there's more!!", :align<right>, :kern );
}

$pdf.save-as: "examples/sample-text.pdf";

```

![sample-text.pdf](examples/.previews/sample-text-001.png)

#### Images (`.load-image` and `.do` methods):

The `.load-image` method can be used to open an image.
The `.do` method can them be used to render it.

```
use PDF::Lite;
my PDF::Lite $pdf .= new;
$pdf.media-box = [0, 0, 450, 250];
my PDF::Lite::Page $page = $pdf.add-page;

$page.graphics: -> $gfx {
    my PDF::Lite::XObject $img = $gfx.load-image("t/images/snoopy-happy-dance.jpg");
    $gfx.do($img, 50, 40, :width(150) );

    # displays the image again, semi-transparently with translation, rotation and scaling

    $gfx.transform( :translate[180, 100]);
    $gfx.transform( :rotate(-.5), :scale(.75) );
    $gfx.FillAlpha = 0.5;
    $gfx.do($img, :width(150) );
}
$pdf.save-as: "examples/sample-image.pdf";

```

![sample-image.pdf](examples/.previews/sample-image-001.png)

Note: at this stage, only the `JPEG`, `GIF` and `PNG` image formats are supported.

### Text effects

To display card suits symbols, using the ZapfDingbats core-font, with diamonds and hearts colored red:

```
use PDF::Lite;
use PDF::Content::Color :rgb;
my PDF::Lite $pdf .= new;
$pdf.media-box = [0, 0, 400, 120];
my PDF::Lite::Page $page = $pdf.add-page;

$page.graphics: {

    $page.text: {
	.text-position = [20, 70];
	.font = [ $pdf.core-font('ZapfDingbats'), 24];
	.WordSpacing = 16;
	.print("♠ ♣\c[NO-BREAK SPACE]");
	.FillColor = rgb(1, .3, .3);  # reddish
	.say("♦ ♥");
    }

    # Display outline, slanted text

    my $header-font = $pdf.core-font( :family<Helvetica>, :weight<bold> );

    $page.text: {
	 use PDF::Content::Ops :TextMode;
	.font = ( $header-font, 18);
	.TextRender = TextMode::FillOutlineText;
	.LineWidth = .5;
        .text-transform( :skew[0, -6], :translate[10, 30] );
	.FillColor = rgb(.6, .7, .9);
	.print('Outline Slanted Text @(10,30)');
    }
}

$pdf.save-as: "examples/text-effects.pdf";

```

![text-effects.pdf](examples/.previews/text-effects-001.png)

## Fonts

This module has built-in support for the PDF core fonts: Courier, Times, Helvetica, ZapfDingbats and Symbol.

The companion module [PDF::Font::Loader](https://pdf-raku.github.io/PDF-Font-Loader-raku) can be used to access a wider range of fonts:

```
use PDF::Lite;
use PDF::Font::Loader :load-font;
my PDF::Lite $pdf .= new;
$pdf.media-box = [0, 0, 400, 120];
my PDF::Lite::Page $page = $pdf.add-page;
my $noto = load-font: :file<t/fonts/NotoSans-Regular.ttf>;
# or find a system font by family and attributes (also requires FontConfig)
# $noto = load-font: :family<NotoSans>, :weight<book>;

$page.text: {
    .text-position = [10,100];
    .font = $noto;
    .say: "Noto Sans Regular";
}

$pdf.save-as: "examples/fonts.pdf";

```

![example.pdf](examples/.previews/fonts-001.png)

## Page sizes

The `media-box` method is used most commonly used to set page sizes. It can be set on the `PDF::Lite` object to set a default page size.

Individual pages can be given different page sizes.

```
use v6;
use PDF::Lite;
use PDF::Content::Page :PageSizes, :&to-landscape;

my PDF::Lite $pdf .= new;
$pdf.media-box = Letter; # Set a default page size

my $page1 = $pdf.add-page;
say $page1.media-box; # [0 0 612 792]

my $page2 = $pdf.add-page;
$page2.media-box = A4;
say $page2.media-box; # [0 0 595 842]

my $page3 = $pdf.add-page;
$page3.media-box = to-landscape(A4);
say $page3.media-box; # [0 0 842 595]

```

## Forms and Patterns

Forms are a reusable graphics component. They can be used wherever
images can be used.

A pattern can be used to fill an area with a repeating graphic.

```
use PDF::Lite;
use PDF::Content::Color :rgb;
my PDF::Lite $pdf .= new;
$pdf.media-box = [0, 0, 400, 120];
my PDF::Lite::Page $page = $pdf.add-page;

$page.graphics: {
    my $font = $pdf.core-font( :family<Helvetica> );
    my PDF::Lite::XObject $form = .xobject-form(:BBox[0, 0, 95, 25]);
    $form.graphics: {
        # Set a background color
        .FillColor = rgb(.8, .9, .9);
        .Rectangle: |$form<BBox>;
        .paint: :fill;
        .font = $font;
        .FillColor = rgb(1, .3, .3);  # reddish
        .say("Simple Form", :position[2, 5]);
    }
     # display a simple form a couple of times
    .do($form, 10, 10);
    .transform: :translate(10,40), :rotate(.1), :scale(.75);
    .do($form, 10, 10);
}

$page.graphics: {
    my PDF::Lite::Tiling-Pattern $pattern = .tiling-pattern(:BBox[0, 0, 25, 25], );
    $pattern.graphics: {
        # Set a background color
        .FillColor = rgb(.8, .8, .9);
        .Rectangle: |$pattern<BBox>;
        .paint: :fill;
        # Display an image
        my PDF::Lite::XObject $img = .load-image("t/images/lightbulb.gif");
        .do($img, 6, 2 );
    }
    # fill a rectangle using this pattern
    .FillColor = .use-pattern($pattern);
    .Rectangle(125, 10, 200, 100);
    .paint: :stroke, :fill;
}

$pdf.save-as: "examples/forms-and-patterns.pdf";

```

![forms-and-patterns.pdf](examples/.previews/forms-and-patterns-001.png)

### Resources and Reuse

The `to-xobject` method can be used to convert a page to an XObject Form to lay-up one or more input pages on an output page.

```
use PDF::Lite;
my $pdf-with-images = PDF::Lite.open: "t/images.pdf";
my $pdf-with-text = PDF::Lite.open: "examples/sample-text.pdf";

my PDF::Lite $new-doc .= new;
$new-doc.media-box = [0, 0, 500, 400];

# add a page; layup imported pages and images
my PDF::Lite::Page $page = $new-doc.add-page;

my PDF::Lite::XObject $xobj-image = $pdf-with-images.page(1).images[6];
my PDF::Lite::XObject $xobj-with-text = $pdf-with-text.page(1).to-xobject;
my PDF::Lite::XObject $xobj-with-images = $pdf-with-images.page(1).to-xobject;

$page.graphics: {
    # scale up an image; use it as a semi-transparent background
    .FillAlpha = 0.5;
    .do($xobj-image, 0, 0, :width(500), :height(400) );
    };

$page.graphics: {
    # overlay pages; scale these down
    .do($xobj-with-text, 20, 100, :width(300) );
    .do($xobj-with-images, 300, 100, :width(200) );
}

# copy whole pages from a document
for 1 .. $pdf-with-text.page-count -> $page-no {
    $new-doc.add-page: $pdf-with-text.page($page-no);
}

$new-doc.save-as: "examples/reuse.pdf";

```

![reuse.pdf Page 1](examples/.previews/reuse-001.png)
![reuse.pdf Page 2](examples/.previews/reuse-002.png)

To list all images and forms for each page

```
use PDF::Lite;
my $pdf = PDF::Lite.open: "t/images.pdf";
for 1 ... $pdf.page-count -> $page-no {
    say "page: $page-no";
    my PDF::Lite::Page $page = $pdf.page: $page-no;
    # get all X-Objects (images and forms) on the page
    my PDF::Lite::XObject %object = $page.resources('XObject');

    # also report on images embedded in the page content
    my $k = "(inline-0)";

    %object{++$k} = $_
        for $page.gfx.inline-images;

    for %object.keys -> $key {
        my $xobject = %object{$key};
        my $subtype = $xobject<Subtype>;
        my $size = $xobject.encoded.codes;
        say "\t$key: $subtype {$xobject.width}x{$xobject.height} $size bytes"
    }
}

```

Resource types are: `ExtGState` (graphics state), `ColorSpace`, `Pattern`, `Shading`, `XObject` (forms and images) and `Properties`.

Resources of type `Pattern` and `XObject/Image` may have further associated resources.

Whole pages or individual resources may be copied from one PDF to another.

## Graphics Operations

A full range of general graphics is available for drawing and displaying text.

```
use PDF::Lite;
my PDF::Lite $pdf .= new;
my $page = $pdf.add-page;

# Draw a simple Bézier curve:

# ------------------------
# Alternative 1: Using operator functions (see PDF::Content)

sub draw-curve1($gfx) {
    $gfx.Save;
    $gfx.MoveTo(175, 720);
    $gfx.LineTo(175, 700);
    $gfx.CurveToInitial( 300, 800,  400, 720 );
    $gfx.ClosePath;
    $gfx.Stroke;
    $gfx.Restore;
}

draw-curve1($page.gfx);

# ------------------------
# Alternative 2: draw from content instructions string:

sub draw-curve2($gfx) {
    $gfx.ops: q:to"--END--"
        q                     % save
          175 720 m           % move-to
          175 700 l           % line-to
          300 800 400 720 v   % curve-to
          h                   % close
          S                   % stroke
        Q                     % restore
        --END--
}
draw-curve2($pdf.add-page.gfx);

# ------------------------
# Alternative 3: draw from raw data

sub draw-curve3($gfx) {
    $gfx.ops: [
         'q',               # save,
         :m[175, 720],      # move-to
         :l[175, 700],      # line-to
         :v[300, 800,
            400, 720],      # curve-to
         :h[],              # close (or equivalently, 'h')
         'S',               # stroke (or equivalently, :S[])
         'Q',               # restore
     ];
}
draw-curve3($pdf.add-page.gfx);

```

Please see [PDF::API6 Appendix I - Graphics](https://pdf-raku.github.io/PDF-API6#appendix-i-graphics) for a description of available operators and graphics.

Graphics can also be read from an existing PDF file:

```
use PDF::Lite;
my $pdf = PDF::Lite.open: "examples/hello-world.pdf";
say $pdf.page(1).gfx.ops;

```

## Graphics and Rendering

A number of variables are maintained that describe the graphics state. In many cases these may be set directly:

```
use PDF::Lite;
my PDF::Lite $pdf .= new;
my PDF::Lite::Page $page = $pdf.add-page;
$page.graphics: {
    .text: {  # start a text block
        .CharSpacing = 1.0;     # show text with wide spacing
        # Set the font to twelve point helvetica
        my $face = $pdf.core-font( :family<Helvetica>, :weight<bold>, :style<italic> );
        .font = [ $face, 10 ];
        .TextLeading = 12; # new-line advances 12 points
        .text-position = 10, 20;
        .say("Sample Text", :position[10, 20]);
        # '$gfx.say' has updated the text position to the next line
        say .text-position;
    } # restore previous text state
    say .CharSpacing; # restored to 0
}

```

A renderer callback can be specified when reading content. This will be called for each graphics operation and has access to the graphics state, via
the `$*gfx` dynamic variable.

```
use PDF::Lite;
use PDF::Content::Ops :OpCode;
my PDF::Lite $pdf .= open: "examples/hello-world.pdf";

my &callback = -> $op, *@args {
   given $op {
       when SetTextMatrix {
           say "text matrix set to: {$*gfx.TextMatrix}";
       }
   }
}
my $gfx = $pdf.page(1).render(:&callback);
# text matrix set to: 1 0 0 1 10 10

```

## See also

* [PDF::Font::Loader](https://pdf-raku.github.io/PDF-Font-Loader-raku) for using Postscript, TrueType and OpenType fonts.
* [HTML::Canvas::To::PDF](https://pdf-raku.github.io/HTML-Canvas-To-PDF-raku/) HTML Canvas renderer
* This module (PDF::Lite) is based on [PDF](https://pdf-raku.github.io/PDF-raku) and has all of it methods available. This includes:

  * `open` to read an existing PDF or JSON file
  * `save-as` to save to PDF or JSON
  * `update` to perform an in-place incremental update of the PDF
  * `Info` to access document meta-data
* [PDF::API6 Graphics Documentation](https://pdf-raku.github.io/PDF-API6#readme) for a fuller description of methods, operators and graphics variables, which are also applicable to this module. In particular:

  * [Section II: Content Methods](https://pdf-raku.github.io/PDF-API6#section-ii-content-methods-inherited-from-pdfclass) for a description of available content methods.
  * [Appendix I - Graphics](https://pdf-raku.github.io/PDF-API6#appendix-i-graphics) for a description of available operators and graphics.


## dist_zef-leont-Protocol-MQTT.md
[![Actions Status](https://github.com/Leont/raku-protocol-mqtt/workflows/test/badge.svg)](https://github.com/Leont/raku-protocol-mqtt/actions)

# NAME

Protocol::MQTT - A (sans-io) MQTT client implementation

# SYNOPSIS

```
use Protocol::MQTT;

```

# DESCRIPTION

Protocol::MQTT contains a networking and timing independent implementation of the MQTT protocol. Currently only the client side is implemented, in the form of Protocol::MQTT::Client. Net::MQTT an actual client based on `Protocol::MQTT::Client`.

# AUTHOR

Leon Timmermans [fawaka@gmail.com](mailto:fawaka@gmail.com)

# COPYRIGHT AND LICENSE

Copyright 2021 Leon Timmermans

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


## dist_zef-jnthn-DB-Migration-Declare.md
# DB::Migration::Declare

Database migrations are an ordered, append-only list of database change
operations that together bring the database up to a current schema. A table
in the database is used to track which migrations have been applied so far,
so that the database can be brought up to date by applying the latest
migrations.

This module allows one to specify database migrations using a Raku DSL. The
migrations are checked in various ways for correctness (for example, trying
to drop a table that never existed, or adding duplicate columns), and are
then translated into SQL and applied to the database.

If one is using a Raku ORM such as Red, it is probably worth looking into how
it might assist with migrations. This module is more aimed at those writing
their queries in SQL, perhaps using something like Badger to have those SQL
queries neatly wrapped up in Raku subs and thus avoid inline SQL.

**Warning**: The module should currently be considered as a BETA-quality
minimum viable product. Of note, only Postgres support is currently available,
migrations can only be applied in the "up" direction, and various kinds
of database change are not yet implemented.

## Setup

### Writing migrations

Migrations can be written in a single file or spread over multiple files in a
single directory, where the filenames will be used as the ordering. For now
we'll assume there is a single file `migrations.raku` where the migrations
will be written one after the other.

A migration file with a single migration looks like this:

```
use DB::Migration::Declare;

migration 'Setup', {
    create-table 'skyscrapers', {
        add-column 'id', integer(), :increments, :primary;
        add-column 'name', text(), :!null, :unique;
        add-column 'height', integer(), :!null;
    }
}

```

Future changes to the database are specified by writing another migration
at the end of the file. For example, after adding another migration the
file overall could look as follows:

```
use DB::Migration::Declare;

migration 'Setup', {
    create-table 'skyscrapers', {
        add-column 'id', integer(), :increments, :primary;
        add-column 'name', text(), :!null, :unique;
        add-column 'height', integer(), :!null;
    }
}

migration 'Add countries', {
    create-table 'countries', {
        add-column 'id', integer(), :increments, :primary;
        add-column 'name', varchar(255), :!null, :unique;
    }

    alter-table 'skyscrapers',{
        add-column 'country', integer();
        foreign-key table => 'countries', from => 'country', to => 'id';
    }
}

```

### Testing migrations

When a project has migrations, it is wise to write a test case to check that
the list of migrations are well-formed. This following can be placed in a
`t/migrations.rakutest`:

```
use DB::Migration::Declare::Database::Postgres;
use DB::Migration::Declare::Test;
use Test;

check-migrations
        source => $*PROGRAM.parent.parent.add('migrations.raku'),
        database => DB::Migration::Declare::Database::Postgres.new;

done-testing;

```

Which will produce the output:

```
ok 1 - Setup
ok 2 - Add countries
1..2

```

If we were to introduce an error into the migration:

```
    alter-table 'skyskrapers',{
        add-column 'country', integer();
        foreign-key table => 'countries', from => 'country', to => 'id';
    }

```

The test would fail:

```
ok 1 - Setup
not ok 2 - Add countries
# Failed test 'Add countries'
# Migration at migrations.raku:11 has problems:
#   Cannot alter non-existent table 'skyskrapers'
1..2
# You failed 1 test of 2

```

With diagnostics indicating what is wrong. (If following this getting started
guide like a tutorial, undo the change introducing an error before continuing!)

### Applying migrations

To migrate a database to the latest version, assuming we are placing this in
a `service.raku` script, do this:

```
use DB::Migration::Declare::Applicator;
use DB::Migration::Declare::Database::Postgres;
use DB::Pg;

my $conn = $pg.new(:conninfo('...write your connection string here...'));

my $applicator = DB::Migration::Declare::Applicator.new:
        schema-id => 'my-project',
        source => $*PROGRAM.parent.add('migrations.raku'),
        database => DB::Migration::Declare::Database::Postgres.new,
        connection => $conn;
my $status = $applicator.to-latest;
note "Applied $status.migrations.elems() migration(s)";

```

Depending on your situation, you might have this as a distinct script, or
place it in the startup script for a Cro service to run the migrations upon
startup.

## Migration DSL

Top-level operations supported within a migration are:

* `create-table(Str $name, &steps)`
* `alter-table(Str $name, &steps)`
* `rename-table(Str $from, Str $to)` (or `rename-table(Str :$from!, Str :$to!)` or
  `rename-table(Pair $renmaing)`)
* `drop-table(Str $name)`
* `execute(SQLLiteral :$up!, SQLLiteral :$down!)`

Within both `create-table` and `alter-table` one can use:

* `add-column(Str $name, $type, Bool :$increments, Bool :$null, Any :$default, Bool :$primary, Bool :$unique)`
* `primary-key(*@column-names)`
* `unique-key(*@column-names)`
* `foreign-key(Str :$from!, Str :$table!, Str :$to = $from, Bool :$restrict = False, Bool :$cascade = False)`
* `foreign-key(:@from!, Str :$table!, :@to = @from, Bool :$restrict = False, Bool :$cascade = False)`

Only within `alter-table` one can use:

* `rename-column(Str $from, Str $to)` (or `rename-column(Str :$from!, Str :$to!)` or
  `rename-column(Pair $renmaing)`)
* `drop-column(Str $name)`
* `drop-unique-key(*@column-names)`

Column types are specified using any of the following functions:

* `char(Int $length)`
* `varchar(Int $length)`
* `text()`
* `boolean()`
* `integer(Int $bytes = 4)` (only 2, 4, and 8 are reliably supported)
* `date()`
* `timestamp(Bool :$timezone = False)` (a date/time)
* `arr($type, *@dimensions)` (dimensions are integers for fixed size of `*`
  for variable size; specifying no dimensions results in a variable-length
  single dimensional array)
* `type(Str $name, Bool :$checked = True)` (any other type, checked by the
  database backend against a known type list by default, but trusted and
  passed along regardless if `:!checked`)

SQL literals can be constructed either:

* Database agnostic: `sql(Str $sql)`
* Database specific: `sql(*%options)` (where the named argument names are database
  IDs, such as `postgres`, and the argument value is the SQL)
* Polymorphic "now": `now()` (becomes the Right Thing depending on database and
  column type when used as the default value of a date or timestamp column)

## Planned Features

* Migration DSL
  * Indexes (currently only those implied by keys are available)
  * Key and index dropping
  * Column type and constraint alteration
  * Column type declaration using Raku types
  * Views
  * Stored procedures
  * Table-valued functions
* Tooling
  * CLI: view migration history on a database against what is applied
  * CLI: trigger up/down migrations
  * CLI: use information schema to extract an initial migration and set
    things up as if it was already applied, to ease getting started
  * Comma: add migrations dependency, tests, etc.
  * Comma: live annotation of migration problems
* Seed data insertion
* Schema export
* Down migrations
* Configurable data retention on lossy migrations in either direction
* Database support
  * SQLite
  * MySQL


## augment.md
augment

Combined from primary sources listed below.

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

See primary documentation
[in context](/language/variables#The_augment_declarator)
for **The augment declarator**.

With `augment`, you can add methods, but not attributes, to existing classes and grammars, provided you activated the `MONKEY-TYPING` pragma first.

Since classes are usually `our` scoped, and thus global, this means modifying global state, which is strongly discouraged. For almost all situations, there are better solutions.

```raku
# don't do this
use MONKEY-TYPING;
augment class Int {
    method is-answer { self == 42 }
}
say 42.is-answer;       # OUTPUT: «True␤»
```

(In this case, the better solution would be to use a [function](/language/functions)).

For a better, and safer example, this is a practical way to create a class module to extend [`IO::Path`](/type/IO/Path) by adding a currently missing method to yield the part of the `basename` left after the `extension` is removed. (Note there is no clear developer consensus about what to call that part or even how it should be constructed.)

```raku
unit class IO::Barename is IO::Path;

method new(|c) {
    return self.IO::Path::new(|c);
}

use MONKEY-TYPING;
augment class IO::Path {
    method barename {
        self.extension("").basename;
    }
}

```


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

# NAME

Cache::Async -- A Concurrent and Asynchronous Cache

# SYNOPSIS

```
my $cache = Cache::Async.new(max-size => 1000, producer => sub ($k) { ... });
say await $cache.get('key234');

```

# FEATURES

* Producer function that gets passed in on construction and that gets called by cache on misses
* Cache size and maximum entry age can be limited
* Cache allows refreshing of entries even before they have expired
* Calls producer async and returns promise to result, perfect for usage in an otherwise async or reactive system
* Transparent support for producers that return promises themselves
* Extra args can be passed through to producer easily
* Jitter for refresh and expiry to smooth out producer calls over time
* Locked internally so it can be used from multiple threads or a thread pool, but no lock help while calling the producer function.
* Propagates exceptions from producer transparently
* Get entry from cache only if present, without loading/refreshing.
* Configurably, Nil values can be passed through without caching them
* Monitoring of hit rate

## Upcoming Features

* Optimizations of the async producer case
* Object lifetimes can be restricted by producer function

# BLOG

I also have a short article that cache users might find interesting [The Surprising Sanity of Using a Cache but Not Updating It](https://github.com/Raku/CCR/blob/main/Remaster/Robert%20Lemmen/The%20Surprising%20Sanity%20of%20Using%20a%20Cache%20but%20Not%20Updating%20It.md).

# DESCRIPTION

This module tries to implement a cache that can be used easily in otherwise async or reactive system. As such it only returns Promises to results which can then be composed with other promises, or acted on directly.

It tries to be a 'transparent' cache in the sense that it will return a cached item, or a freshly produced or retrieved one without the caller being aware of the distinction. To do this, the cache is constructed over a producer sub that gets called on cache misses.

Sometimes other data that is required by the producer function can be captured at creation time, but in other cases they need to be provided at request time, e.g. credentials. Arguments like these can be passed through `Cache::Async` transparently as extra args.

All caches should have a fixed size limit, and so does Cache::Async of course. In addition a maximum global object lifetime can be specified to avoid overly old object entries. For cache eviction a LRU mechanism is used.

If caches are used in production systems, it is often desirable to monitor their hit rates. Cache::Async supports this through a method that reports hits and misses, but it does not do the monitoring itself or automatically.

# Constructor

```
new(:&producer, Int :$max-size, Duration :$max-age, Duration :$refresh-after,
    Duration :$jitter, Bool :$cache-undefined = True)

```

Creates a new cache over the provided **&producer** sub, which must take a single string as the first argument, the key used to look up items in the cache with. It can take more arguments, see **get()** below.

The **$max-size** argument can be used to limit the number of items the cache will hold at any time, the default is 1024.

**$max-age** determines the maximum age an item can live in the cache before it is expired. By default items are not expired by age.

**$refresh-after** optionally sets a time after which an item will be refreshed by the cache in parallel with returning it. This can be used to reduce latency for frequently used entries. When set (to a value lower than **$max-age** of course), the cache will upon a hit on an entry that is older than this value immediately return the existing value, but also start an asyncronous re-fetch of the item as if it had experienced a cache miss. This can be used to make frequently used items always come from the cache, rather than incurring a cache hit with the corresponding fetch latency every now and then.

**$jitter** optionally sets a maximum jitter duration. When an item is refreshed and placed in the cache, the timestamp of the item is incremented by a random interval between 0 and this duration. This can be useful if your application loads many items after boot and wants to make sure that the refresh times spread out over time and do not stay clustered together. This value needs to be smaller than **$refresh-after** (and therefore **max-age**), the default is zero.

If **$cache-undefined** is set to False, then undefined return values from the producer function (as well as Promises that are undefined when kept of course) are not cached and will be retried the next time the coresponding key is queried.

The following example will create a simple cache with up to 100 items that live for up to 10 seconds. The values returned by the cache are promises that will hold the key specified when querying the cache enclosed in square brackets.

```
$cache = Cache::Async.new(producer => sub ($k) { return "[$k]"; },
                          max-size => 100,
                          max-age => Duration.new(10));

```

# Retrieval

In order to get items from, or better through, the cache, the **get()** method is used:

```
$cache.get($key, +@args)

```

The first argument is the **$key** used to look up items in the cache, and is passed through to the producer function the cache uses. Any other arguments are also passed to the producer functions. The call returns a `Promise` to the value produced or found in the cache.

With the cache constructed above, the call below would yield "[woot]". The first time this is called the producer is called, afterwards the cached value is used (until expiry or eviction).

```
await $cache.get('woot')

```

Multiple threads can of course safely call into the cache in parallel.

The producer function can of course return a `Promise` itself! In this case `Cache::Async` will *not* return a promise containing another promise, but it will detect the case and simply return the promise from the producer directly.

# Cache Content Management

The following methods can be used to manage the contents of the cache. This can for example be used to warm the cache on startup with some values, or clear it in error cases.

```
$cache.put($key, $value);
$cache.remove($key);
$cache.clear;

```

As a special case, you can also query for contents of the cache, but without calling the producer function on a miss, and without touching any cache statistics. This is useful to check for entry existence in cache maintenance tasks, but also and primarily when doing operations that violate the LRU criteria. For example imagine a cache with limited size over a very large backing resource, but with normal operations that show strong LRU characteristics. A perfect case for a cache, and you can expect good cache hit rates. Now every now and then a maintenance task kicks in that traverses all resources. This could also benefit from the cache, but if it updates the cache it would basically replace the whole cache with the tail end of it's iteration, destroying the LRU properties of the cache and causing increased cache misses for some time afterwards, a bit like a cache that is empty. This method allows utilising entries in the cache if present, but not touching the cache otherwise. Returns Nil if no entry is found.

```
$cache.get-if-present($key);

```

# Monitoring

The behavior of the cache can be monitored, the call will return total numbers since the last time this method was called (or the cache got constructed):

```
my ($hits, $misses) = $cache.hits-misses;

```

Note that the number of hits + misses is of course the number of calls to **get()**, but that the number of calls to the producer function is not necessarily the same as the number of misses returned from this method. The reason for this is that two calls to the cache with the same key in rapid succession could both be misses, but only the first one will call the producer. The second call will simply get chained to the first producer call.

# AUTHORS

Robert Lemmen

Elizabeth Mattijsen

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

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

# COPYRIGHT AND LICENSE

Copyright 2018-2020 Robert Lemmen

Copyright 2021, 2024, 2025 Elizabeth Mattijsen

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


## dist_zef-jonathanstowe-EuclideanRhythm.md
# EuclideanRhythm

Implementation of the algorithm described in <http://cgm.cs.mcgill.ca/~godfried/publications/banff.pdf>

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

## Synopsis

```

    use EuclideanRhythm;

    my $r = EuclideanRhythm.new(slots => 16, fills => 7);

    for $r.list {
        # do something if the value is True
    }

```

## Description

This provides an implementation of the algorithm described in
<http://cgm.cs.mcgill.ca/~godfried/publications/banff.pdf>
which is in turn derived from a Euclidean algorithm. Simply put it
provides a simple method to distribute a certain number of "fills"
(hits, beats, notes or whatever you want to call them,) as evenly as
possibly among a number of "slots". The linked paper describes how, using
this method, you can approximate any number of common rhythmic patterns
(as well as not so common ones.)

You could of course use it for something other than generating musical
rhythms: any requirement where a number of events need to be distributed
over a fixed number of slots may find this useful.

## Installation

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

```
zef install EuclideanRhythm

```

or if you have a local copy of this repository:

```
zef install .

```

in the directory you found this file.

## Support

This is a fairly simple module such that the scope for any
egregious bugs is quite limited, however if you have any
suggestions, patches or comment the feel free to leave a post at
<https://github.com/jonathanstowe/EuclideanRhythm/issues>.

Because it is quite simple in both scope and implementation I would
anticipate that any higher level functionality (such as providing timing,)
would be implemented in another module.

## Licence and Copyright

This is free software. Please see the <LICENCE> file in the distribution.

© Jonathan Stowe 2016 - 2021


## notcomposed.md
class X::Inheritance::NotComposed

Error due to inheriting from a type that's not composed yet

```raku
class X::Inheritance::NotComposed is Exception {}
```

When you try to inherit from a class that hasn't been [composed](/language/mop#Composition_time_and_static_reasoning), an exception of type X::Inheritance::NotComposed is thrown.

Usually this happens because it's not yet fully parsed, or that is stubbed:

For example

```raku
class A { ... };    # literal ... for stubbing
class B is A { };

```

dies with

｢text｣ without highlighting

```

```

===SORRY!===
'B' cannot inherit from 'A' because 'A' isn't composed yet (maybe it is stubbed)

```

```

The second common way to trigger this error is by trying to inherit from a class from within the class body.

For example

```raku
class Outer {
    class Inner is Outer {
    }
}

```

dies with

｢text｣ without highlighting

```

```

===SORRY!===
'Outer::Inner' cannot inherit from 'Outer' because 'Outer' isn't composed yet (maybe it is stubbed)

```

```

# [Methods](#class_X::Inheritance::NotComposed "go to top of document")[§](#Methods "direct link")

## [method child-name](#class_X::Inheritance::NotComposed "go to top of document")[§](#method_child-name "direct link")

```raku
method child-name(X::Inheritance::NotComposed:D: --> Str:D)
```

Returns the name of the type that tries to inherit.

## [method parent-name](#class_X::Inheritance::NotComposed "go to top of document")[§](#method_parent-name "direct link")

```raku
method parent-name(X::Inheritance::NotComposed:D: --> Str:D)
```

Returns the name of the parent type that the type tries to inherit from


## dist_zef-jmaslak-IP-Random.md
[![Build Status](https://travis-ci.org/jmaslak/Raku-IP-Random.svg?branch=master)](https://travis-ci.org/jmaslak/Raku-IP-Random)

# NAME

IP::Random - Generate random IP Addresses

# SYNOPSIS

```
use IP::Random;

my $ipv4 = IP::Random::random_ipv4;
my @ips  = IP::Random::random_ipv4( count => 100, allow-dupes => False );

```

# DESCRIPTION

This provides a random IP (IPv4 only currently) address, with some extensability to exclude undesired IPv4 addresses (I.E. don't return IP addresses that are in the multicast or RFC1918 ranges).

By default, the IP returned is a valid, publicly routable IP address, but this behavior can be adjusted.

# FUNCTIONS

## default\_ipv4\_exclude

Returns the default exclude list for IPv4, as a list of CIDR strings.

Additional CIDRs may be added to future versions, but in no case will standard Unicast publicly routable IPs be added. See <named_exclude> to determine what IP ranges will be included in this list.

## exclude\_ipv4\_list($type)

When passed a `$type`, such as `'rfc1918'`, will return a list of CIDRs that match that type. See <named_exclude> for the valid types.

## random\_ipv4( :@exclude, :$count )

```
say random_ipv4;
say random_ipv4( exclude => ('rfc1112', 'rfc1122') );
say random_ipv4( exclude => ('default', '24.0.0.0/8') );
say join( ',',
    random_ipv4( exclude => ('rfc1112', 'rfc1122'), count => 2048 ) );
say join( ',',
    random_ipv4( count => 2048, allow-dupes => False ) );

```

This returns a random IPv4 address. If called with no parameters, it will exclude any addresses in the default exclude list.

If called with the exclude optional parameter, which is passed as a list, it will use the exclude types (see <named_exclude> for the types) to exclude from generation. In addition, individual CIDRs may also be passed to exclude those CIDRs. If neither CIDRs or exclude types are passed, it will use the `default` tag to exclude the default excludes. Should you want to exclude nothing, pass an empty list. If you want to exclude something in addition to the default list, you must pass the `default` tag explictly.

The count optional parameter will cause c<random\_ipv4> to return a list of random IPv4 addresses (equal to the value of `count`). If `count` is greater than 128, this will be done across multiple CPU cores. Batching in this way will yield significantly higher performance than repeated calls to the `random_ipv4()` routine.

The `allow-dupes` parameter determines whether duplicate IP addresses are allowed to be returned within a batch. The default, `True`, allows duplicate addresses to be randomly picked. Obviously unless there is an extensive exclude list or a very large batch size, the chance of randomly selecting a duplicate is very small. But with extensive excludes and large batch sizes, it is possible to have duplicates selected. If the amount of non-excluded IPv4 space is less than the batch size (the `count` argument) and this parameter is set to `False`, then you will get a list of all possible IP addresses rather than `count` elements returned.

# CONSTANTS

## named\_exclude

```
%excludes = IP::RANDOM::named_exclude

```

A hash of all the named IP exludes that this `IP::Random` is aware of. The key is the excluded IP address. The value is a list of tags that this module is aware of. For instance, `192.168.0.0/16` would be a key with the values of `( 'rfc1918', 'default' )`.

This list contains:

* `0.0.0.0/8`

  Tags: default, rfc1122

  "This" Network (RFC1122, Section 3.2.1.3).
* `10.0.0.0/8`

  Tags: default, rfc1918

  Private-Use Networks (RFC1918).
* `100.64.0.0/10`

  Shared Address Space (RFC6598)
* `127.0.0.0/8`

  Tags: default, rfc1122

  Loopback (RFC1122, Section 3.2.1.3)
* `169.254.0.0/16`

  Link Local (RFC 3927)
* `172.16.0.0/12`

  Tags: default, rfc1918

  Private-Use Networks (RFC1918)
* `192.0.0.0/24`

  IETF Protocol Assignments (RFC5736)
* `192.0.2.0/24`

  TEST-NET-1 (RFC5737)
* `192.88.99.0/24`

  6-to-4 Anycast (RFC3068)
* `192.168.0.0/16`

  Tags: default, rfc1918

  Private-Use Networks (RFC1918)
* `198.18.0.0/15`

  Network Interconnect Device Benchmark Testing (RFC2544)
* `198.51.100.0/24`

  TEST-NET-2 (RFC5737)
* `203.0.113.0/24`

  TEST-NET-3 (RFC5737)
* `224.0.0.0/4`

  Multicast (RFC3171)
* `240.0.0.0/4`

  Reserved for Future Use (RFC 1112, Section 4)

# AUTHOR

Joelle Maslak [jmaslak@antelope.net](mailto:jmaslak@antelope.net)

# CONTRIBUTORS

Elizabeth Mattijsen [liz@wenzperl.nl](mailto:liz@wenzperl.nl)

# EXPRESSING APPRECIATION

If this module makes your life easier, or helps make you (or your workplace) a ton of money, I always enjoy hearing about it! My response when I hear that someone uses my module is to go back to that module and spend a little time on it if I think there's something to improve - it's motivating when you hear someone appreciates your work!

I don't seek any money for this - I do this work because I enjoy it. That said, should you want to show appreciation financially, few things would make me smile more than knowing that you sent a donation to the Gender Identity Center of Colorado (See <http://giccolorado.org/>. This organization understands TIMTOWTDI in life and, in line with that understanding, provides life-saving support to the transgender community.

If you make any size donation to the Gender Identity Center, I'll add your name to "MODULE PATRONS" in this documentation!

# COPYRIGHT AND LICENSE

Copyright (C) 2018-2022 Joelle Maslak

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


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

# NAME

Acme::Text::UpsideDown - provide logic to turn ASCII text upside-down

# SYNOPSIS

```
use Acme::Text::UpsideDown;

say upsidedown "The quick brown fox jumps over the lazy dog";
# ɓop ʎzɐꞁ ǝɥʇ ɹǝʌo sdɯnſ̣ xoɟ uʍoɹq ʞɔᴉnb ǝɥ⊥

say uʍopǝpᴉsdn "ɓop ʎzɐꞁ ǝɥʇ ɹǝʌo sdɯnſ̣ xoɟ uʍoɹq ʞɔᴉnb ǝɥ⊥";
# The quick brown fox jumps over the lazy Dog

```

# DESCRIPTION

Acme::Text::UpsideDown provides two subroutines that can be used to create strings from ASCII texts for upside-down reading. Inspired by the Perl version called Acme::Text::Viceversa.

# SUBROUTINES

## upsidedown

```
say upsidedown "The quick brown fox jumps over the lazy dog";
# ɓop ʎzɐꞁ ǝɥʇ ɹǝʌo sdɯnſ̣ xoɟ uʍoɹq ʞɔᴉnb ǝɥ⊥

say upsidedown "ɓop ʎzɐꞁ ǝɥʇ ɹǝʌo sdɯnſ̣ xoɟ uʍoɹq ʞɔᴉnb ǝɥ⊥";
# The quick brown fox jumps over the lazy dog

```

Return the string that allows reading of the given ASCII string upside-down, and vice-versa.

## uʍopǝpᴉsdn

```
say uʍopǝpᴉsdn "ɓop ʎzɐꞁ ǝɥʇ ɹǝʌo sdɯnſ̣ xoɟ uʍoɹq ʞɔᴉnb ǝɥ⊥";
# The quick brown fox jumps over the lazy dog

say uʍopǝpᴉsdn "The quick brown fox jumps over the lazy dog";
# ɓop ʎzɐꞁ ǝɥʇ ɹǝʌo sdɯnſ̣ xoɟ uʍoɹq ʞɔᴉnb ǝɥ⊥

```

Return the string that allows normal reading of a previously upside-downed string, and vice-versa. Basically a fun alias for `upsidedown`.

# COMMAND LINE INTERFACE

This module also installs a `ud` script for easy upsidedowning of text.

When called without any parameters, it will read from STDIN and print the upsidedowned text on STDOUT.

When called with a single parameter that indicates an existing file, then it will read that file and print the upsidedowned text on STDOUT.

In all other cases, the command line parameters will be joined together with a space, and then printed upsidedowned on STDOUT.

# AUTHOR

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

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

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

# COPYRIGHT AND LICENSE

Original Perl version of Acme::Text::Viceversa: Copyright 2019 吉田勇気, Raku re-imagining: Copyright 2019, 2021, 2024 Elizabeth Mattijsen

Some additional character mappings taken from <https://github.com/mcsnolte/Text-UpsideDown>.

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


## dist_github-scovit-Scheduler-DRMAA.md
[![Build Status](https://travis-ci.org/scovit/Scheduler-DRMAA.svg?branch=master)](https://travis-ci.org/scovit/Scheduler-DRMAA)

# NAME

Scheduler::DRMAA - Bindings for the DRMAA cluster library

# SYNOPSIS

```
use DRMAA;             # Loads the high-level bindings
use DRMAA::NativeCall; # Loads the C binings

```

The `libdrmaa.so` library needs to be installed in the loader path, or the directory added to `LD_LIBRARY_PATH` environment variable.

# DESCRIPTION

Scheduler::DRMAA are the Perl 6 bindings for the DRMAA library. You can use them in order to submit pipelines of work to a supercomputer. We provide two different interfaces:

* the DRMAA C library, it can be used through the `DRMAA::NativeCall` module, it uses `NativeCall` and `NativeHelpers::CBuffer` modules
* the object interface, provided by the `DRMAA` module. It requires `v6.d.PREVIEW` and supports all the C library functionalities but also an asynchronous event-based mechanism to keep track of job events and a pluggable job-dependency pipeline genearator, reminescent of the `Promise` API.

The library has been tested on a SLURM DRMAA implementation and does not provide any warrant or guarantee to work. First thing, in order to initialize and close the DRMAA session use the following commands:

```
DRMAA::Session.init;

# code goes here

DRMAA::Session.exit;

```

## OBJECTS

### DRMAA::Session

The DRMAA session is a singleton and represent the session level API. Upon initialization it also takes care of the event loop. It provides the following methods:

```
method init(Str :$contact, DRMAA::Native-specification :native-specification(:$ns));

```

initializes the session, optional arguments are the contact code, and the Native-specification plugin: if not provided explicitly it gets autodetected through a reasonable euristics.

```
method exit()

```

closes the session.

```
method native-specification(--> DRMAA::Native-specification)

```

returns the native-specification plugin.

```
method events(--> Supply)

```

returns a Supply to the DRMAA events, mostly Job terminations events or failures

Other methods:

```
method attribute-names(--> List)
method vector-attribute-names(--> List)
method contact(--> Str)
method DRM-system(--> Str)
method implementation(--> Str)
method version(--> Version)

```

### DRMAA::Job-template

Represents a Job template, must be constructed in order to launch one, or more jobs

```
submethod BUILD(*%all)

```

Construct the object, use it as `DRMAA::Job-template.new`, named parameters corresponds to attributes and/or methods, making it straightforward to create a submission, a simple example:

```
my $template = DRMAA::Job-template.new(
   :remote-command<sleep> :argv<5>
);

```

creates a job template for something which will just sleep 5 seconds; an alternative way to do it uses heredocs:

```
my $template = DRMAA::Job-template.new(:script(q:to/⬅ 完/));
   sleep 5;
   say "Slept 5 seconds";
   ⬅ 完

```

will run the Perl 6 script, the library will exploit the following dynamic variables: `$*EXECUTABLE`, `@*ARGS` and `%*ENV`. For instance, to submit a shell script do the following:

```
my $*EXECUTABLE = "/bin/sh";
my @*ARGS = <5>;
my $template = DRMAA::Job-template.new(:script(q:to/⬅ 完/));
   sleep $1
   echo "Slept $1 seconds";
   ⬅ 完

```

Easy, isn't it?

To run a template, use one of the following methods:

```
method run(--> DRMAA::Submission)
multi method run-bulk(Int:D $start, Int:D $end, Int :$by --> List)
multi method run-bulk(Range:D $range, Int :$by --> List)
multi method run-bulk(Int:D $size --> List)

```

`run-bulk` methods are discouraged, seriously, just use `@list.map: DRMAA::Job-template.new`...

To resume, the most important attributes, which are also building parameters, are:

```
remote-command        (scalar)
argv                  (list)
env                   (list)

```

The following are other available attributes, which are also building parameters

```
block-email           (scalar)
email                 (list)
start-time            (scalar)
deadline-time         (scalar)
duration-hlimit       (scalar)
duration-slimit       (scalar)
wct-hlimit            (scalar)
wct-slimit            (scalar)
error-path            (scalar)
input-path            (scalar)
output-path           (scalar)
job-category          (scalar)
job-name              (scalar)
join-files            (scalar)
transfer-files        (scalar)
js-state              (scalar)
native-specification  (scalar)
wd                    (scalar)

```

The following extra attributes are available if the Native-plugin implement the required functionality:

```
after                 (list)
afterend              (list)
afterok               (list)
afternotok            (list)

```

Queue after the start/end/success/failure of the values: which shoud be a list of `DRMAA::Submission`. To create a `DRMAA::Submission` out of a job name, in case it doesn't come out of a `run` method just do like this: `DRMAA::Submission.new(:job-id("123456"))`.

### DRMAA::Submission

First of all: a submission is an Awaitable:

```
my $submission = $template.run;
my $result = await $submission;

```

It can be created either by the `run` method of a `DRMAA::Job-schedule` or from a job id:

```
DRMAA::Submission.new(job-id => "123456");

```

It provides the following methods

```
method suspend
method resume
method hold
method release
method terminate

method status

```

Retuns the one of the following status objects:

```
DRMAA::Submission::Status::Undetermined
DRMAA::Submission::Status::Queued-active
DRMAA::Submission::Status::System-on-hold
DRMAA::Submission::Status::User-on-hold
DRMAA::Submission::Status::User-system-on-hold
DRMAA::Submission::Status::Running
DRMAA::Submission::Status::System-suspended
DRMAA::Submission::Status::User-suspended
DRMAA::Submission::Status::User-system-suspended
DRMAA::Submission::Status::Done
DRMAA::Submission::Status::Failed
DRMAA::Submission::Status::Unimplemented

method events(--> Supply)

```

Returns a Supply with all events regarding the Submission

```
method done(--> Promise)

```

Returns a Promise which will be kept when the job is over. The result of the promise will contain one of the following:

```
class X::DRMAA::Submission::Status::Aborted is Exception {
   has Str  $.id;
   has Bool $.exited;
   has Int  $.exit-code;
   has Str  $.signal;
   has Str  $.usage;

   method message(--> Str:D) {
       "Job $.id aborted";
   }
}

class DRMAA::Submission::Status::Succeded {
   has Str  $.id;
   has Bool $.exited;
   has Int  $.exit-code;
   has Str  $.signal;
   has Str  $.usage;
}

```

The result can also be accessed through:

```
method result

```

or

```
await

```

Another handy method:

```
method then(DRMAA::Job-template $what)

```

chain the jobs, same as specify the attribute `afterend` to `$what`, and then `run`; an example:

```
DRMAA::Job-template.new( :remote-command<sleep>, :argv<20> ).run.then(
   DRMAA::Job-template.new( :remote-command<echo>, :argv<Hello world!> ));

```

the functionality should be implemented in the Native plugin, currently only works for SLURM.

# AUTHOR

Vittore F. Scolari [vittore.scolari@gmail.com](mailto:vittore.scolari@gmail.com)

# COPYRIGHT AND LICENSE

Copyright 2017 Institut Pasteur

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


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

# NAME

uniprop - Provide uniprop- subs

# SYNOPSIS

```
use uniprop;  # provide uniprop-int, uniprop-bool, unitprop-str

```

# DESCRIPTION

The `uniprop` distribution provides 3 subroutines that used to live in the Rakudo core, but were in fact implementation detail / used for testing by core developers only. These have since then been removed from Rakudo.

This distribution has captured the code of these subroutines and will export them in any version of Rakudo that has them removed.

No further documentation is provided, as originally no additional documentation was provided and it was never the intention to expose this functionality this way.

# AUTHOR

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

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

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

# COPYRIGHT AND LICENSE

Copyright 2022, 2024 Elizabeth Mattijsen

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


## dist_zef-tony-o-YAML-Parser-LibYAML.md
# YAML::Parser::LibYAML

Uses a wrapper and constructs a perl6 array/hash/whatever to represent the YAML. Use it for good (or bad, I don't care).

```

use YAML::Parser::LibYAML;

my $yaml = yaml-parse('path/to/yaml.yaml');

$yaml.perl.say;

```

Profit.

tony-o | thanks to ingy and tina for fuelling this creation with scotch and vegan pizza

If you must build this yourself, you can do

> zef build .

or

> src/build.sh


## dist_github-jsimonet-IRC-Client-Plugin-UserPoints.md
# NAME

IRC::Client::Plugin::UserPoints

# SYNOPSIS

```
    use IRC::Client;
    use IRC::Client::Plugin::UserPoints;

    IRC::Client.new(
        :nick<botte>
        :host<irc.freenode.net>
        :channels<#test>
        :plugins( IRC::Client::Plugin::UserPoints.new )
    ).run;

```

```
<jsimonet> botte++
<botte> jsimonet, Adding one point to botte in « main » category
<jsimonet> botte2++ Perl6
<botte> jsimonet, Adding one point to botte2 in « Perl6 » category
<jsimonet> jsimonet++
<botte> jsimonet, Influencing points of himself is not possible.
<jsimonet> !scores
<botte> jsimonet, « botte » has some points : 1 for main
<botte> jsimonet, « botte2 » has some points : 1 in Perl6
<jsimonet> !sum
<botte> jsimonet, Total points : 2

```

# DESCRIPTION

This module is a plugin for `IRC::Client`, which aims to count points delivered to users.

A point can be categorized, for more precision :)

Points can be listed with the `scores` command, and passing one or more users
will list only theirs points.

A sum can be printed with `sum` command, and like `scores` command, a list of users
can be used.

# Attributes

```
    IRC::Client::Plugin::UserPoints.new(
        :db-file-name( 'path/to/file.txt' ),
        :command-prefix( '!' ),
        :list-scores-max-user(5),
        :msg-confirm( '#channel1' => True )
    )

```

## db-file-name

The file name of the points database.

## command-prefix

The command prefix is used to determine the char used to trigger the bot.

## list-scores-max-user

The maximum number of users the bot can print their points. Can be used to prevent spam.

Default value: +Inf (Infinite)

## msg-confirm

Confirm on IRC when a point have been handled.

Defaults to False.

# IRC COMMANDS

```
<nickName>++         # Add a point in "main" category
<nickName>--         # Remove a point in "main" category
<nickName>++ Perl6   # Add a point in "Perl6" category
!scores              # Prints the attributed points
!scores <nickName> … # Prints the attributed points
!sum                 # Sum of all attributed points
!sum <nickName> …    # Sum of attributed points for nickName

```

# BUGS

To report bugs or request features, please use
<https://github.com/jsimonet/IRC-Client-Plugin-UserPoints/issues>

# AUTHOR

Julien Simonet


## all.md
all

Combined from primary sources listed below.

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

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

```raku
method all(--> Junction:D)
```

Interprets the invocant as a list and creates an [all](/routine/all)-[`Junction`](/type/Junction) from it.

```raku
say so 1 < <2 3 4>.all;         # OUTPUT: «True␤»
say so 3 < <2 3 4>.all;         # OUTPUT: «False␤»
```


## dist_cpan-CHSANCH-Lingua-Stem-Es.md
[![Build Status](https://travis-ci.org/chsanch/perl6-Lingua-Stem-Es.svg?branch=master)](https://travis-ci.org/chsanch/perl6-Lingua-Stem-Es)

# NAME

Lingua::Stem::Es - Porter's steming algorithm for Spanish

# SYNOPSIS

```
    use Lingua::Stem::Es

    my $stem = stem( $word );

```

# DESCRIPTION

This module uses Porter's Stemming Algorithm to return a stemmed word.
The algorithm is implemented as described in: <http://snowball.tartarus.org/algorithms/spanish/stemmer.html>

# REPOSITORY

Fork this module on GitHub:

<https://github.com/chsanch/perl6-Lingua-Stem-Es>

# BUGS

To report bugs or request features, please use:

<https://github.com/chsanch/perl6-Lingua-Stem-Es/issues>

# AUTHOR

This module was inspired by Perl 5's module [Lingua::Stem::Es](https://metacpan.org/pod/Lingua::Stem::Es).

Christian Sánchez [chsanch@cpan.org](mailto:chsanch@cpan.org).

# LICENSE

You can use and distribute this module under the terms of the
The Artistic License 2.0. See the `LICENSE` file included in this
distribution for complete details.

The `META6.json` file of this distribution may be distributed and modified
without restrictions or attribution.


## dist_zef-rbt-DBIish-Pool.md
# DBIish::Pool - Database connection pooling for DBIish

## SYNOPSIS

```
my %connection-parameters = database => 'foo', user => 'bar', password => secret();
my $pool = DBIish.new(driver => 'Pg', initial-size => 1, max-connections => 10, min-spare-connections => 1,
                     max-idle-duration => Duration.new(60), |%connection-parameters);

my $dbh = $pool.get-connection()

$dbh.do({SELECT 1});

$dbh.dispose;

```

## DESCRIPTION

This module is useful for apps supporting multiple parallel users which arrive at an inconsistent rate, such as a
web application. In addition to connection reuse it allow configuring a maximum number of simultaneous connections to
ensure the database does not go over capacity.

Database connection reuse improves performance significantly for very simple transactions, or
long distance networks using SSL encrypted connections. 300% has been seen within the same network
for web requests, where each request was establishing a new connection.

To use, create a pool, then take a connection from that pool. The connection is returned to the pool when
dispose is called. Calling dispose is important as otherwise you may exhaust the pool due to garbage collection
being unpredictable.

See your database driver for a description of the connection parameters allowed. These are the same as the
C<DBIish.connect> call.

```
my $pool = DBIish::Pool.new(driver => 'Pg', max-connections => 20, max-idle-duration => Duration.new(60),
    min-spare-connections => 3,  initial-size => 5, |%dbiish-connection-parameters);

sub do-db-work() {
  my $dbh = $pool.get-connection();

  my $sth = $dbh.prepare(q{ SELECT session_state FROM sessions WHERE session_id = ? });

  $sth.execute($session-id);
  my $ret = $sth.allrows();
  $dbh.dispose

  return $ret;
}

```

### `new`

* `min-spare-connections`

  The number of idle connections to keep around. These are ready for immediate use. Busy multi-threaded workloads
  will want to raise this above 1 as there is a short time between when a connection is disposed and when it
  will be ready for use again.
* `initial-size`

  The number of connections to create when the pool is established. This may be kept equal to `min-spare-connections`
  unless your app requires a very fast initial response time and is regularly restarted during peak periods.
* `max-idle-duration`

  Connections which have not been used in this time period will be slowly closed, unless required to meet the
  `min-spare-connections`.
* `max-connections`

  Maximum number of database connections, including those currently being scrubbed of session state for reuse.
  Overall performance is often better if the database has a consistent load and spikes are smoothed out.
* `|%dbiish-connection-parameters` are whatever `DBIish` allows. For a pool for a PostgreSQL driver might be established
  like this:

  ```
  my $pool = DBIish::Pool.new(driver => 'Pg', dbname => 'dbtest', user => 'postgres', port => 5432, max-connections => 20);

  ```

### `get-connection`

Returns a connection from the pool, establishing a new connection if necessary, when one becomes available. The
connection is checked for connectivity prior to returning it to the client.

Once `max-connections` is reached, this routine will not return a connection until one becomes available. Ensure you
call `dispose` after finished using the connection to shorten this timeframe as garbage collection is not predictable.

If preferred, you may obtain a connection asynchronously.

```
my $dbh = await $pool.get-connection(:async);

```

### Pool Statistics

A small Hash with pool connection statistics is available. This can be useful for automated monitoring purposes.

my %stats = $pool.stats();

Statistics fields include:

* inuse ➡ Number of connections currently in use.
* idle ➡ Number available for immediate use.
* starting ➡ Number starting up.
* scrub ➡ Numbers recently disposed, currently being scrubbed.
* total ➡ Total of the `inuse`, `idle`, `starting`, and `scrub` counters. Due to short race conditions, this may not add up at times.
* waiting ➡ Number of unfilled `connect` calls.


## radixoutofrange.md
class X::Syntax::Number::RadixOutOfRange

Compilation error due to an unallowed radix in a number literal

```raku
class X::Syntax::Number::RadixOutOfRange does X::Syntax { }
```

Syntax error that is thrown when the radix of a radix number is not allowed, like `:1<1>` or `:42<ouch>`.

# [Methods](#class_X::Syntax::Number::RadixOutOfRange "go to top of document")[§](#Methods "direct link")

## [method radix](#class_X::Syntax::Number::RadixOutOfRange "go to top of document")[§](#method_radix "direct link")

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

The offensive radix.


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

# NAME

HTTP::UserAgent - Web user agent class

# SYNOPSIS

```
use HTTP::UserAgent;

my $ua = HTTP::UserAgent.new;
$ua.timeout = 10;

my $response = $ua.get("URL");

if $response.is-success {
    say $response.content;
}
else {
    die $response.status-line;
}

```

# DESCRIPTION

This module provides functionality to crawling the web witha handling cookies and correct User-Agent value.

It has TLS/SSL support.

# METHODS

## method new

```
method new(HTTP::UserAgent:U: :$!useragent, Bool :$!throw-exceptions, :$!max-redirects = 5, :$!debug)

```

Default constructor.

There are four optional named arguments:

* useragent

A string that specifies what will be provided in the `User-Agent` header in the request. A number of standard user agents are described in [HTTP::UserAgent::Common](http::UserAgent::Common), but a string that is not specified there will be used verbatim.

* throw-exceptions

By default the `request` method will not throw an exception if the response from the server indicates that the request was unsuccesful, in this case you should check `is-success` to determine the status of the [HTTP::Response](http::Response) returned. If this is specified then an exception will be thrown if the request was not a success, however you can still retrieve the response from the `response` attribute of the exception object.

* max-redirects

This is the maximum number of redirects allowed for a single request, if this is exceeded then an exception will be thrown (this is not covered by `no-exceptions` above and will always be throw,) the default value is 5.

* debug

It can etheir be a Bool like simply `:debug` or you can pass it a IO::Handle or a file name. Eg `:debug($*ERR)` will ouput on stderr `:debug("mylog.txt")` will ouput on the file.

## method auth

```
method auth(HTTP::UserAgent:, Str $login, Str $password)

```

Sets username and password needed to HTTP Auth.

## method get

```
multi method get(Str $url is copy, :bin?, *%headers)
multi method get(URI $uri, :bin?, *%headers)

```

Requests the $url site, returns HTTP::Response, except if throw-exceptions is set as described above whereby an exception will be thrown if the response indicates that the request wasn't successfull.

If the Content-Type of the response indicates that the content is text the `content` of the Response will be a decoded string, otherwise it will be left as a <Blob>.

If the ':bin' adverb is supplied this will force the response `content` to always be an undecoded <Blob>

Any additional named arguments will be applied as headers in the request.

## method post

```
multi method post(URI $uri, %form, *%header ) -> HTTP::Response
multi method post(Str $uri, %form, *%header ) -> HTTP::Response

```

Make a POST request to the specified uri, with the provided Hash of %form data in the body encoded as "application/x-www-form-urlencoded" content. Any additional named style arguments will be applied as headers in the request.

An [HTTP::Response](http::Response) will be returned, except if throw-exceptions has been set and the response indicates the request was not successfull.

If the Content-Type of the response indicates that the content is text the `content` of the Response will be a decoded string, otherwise it will be left as a <Blob>.

If the ':bin' adverb is supplied this will force the response `content` to always be an undecoded <Blob>

If greater control over the content of the request is required you should create an [HTTP::Request](http::Request) directly and populate it as needed,

## method request

```
method request(HTTP::Request $request, :bin?)

```

Performs the request described by the supplied [HTTP::Request](http::Request), returns a [HTTP::Response](http::Response), except if throw-exceptions is set as described above whereby an exception will be thrown if the response indicates that the request wasn't successful.

If the response has a 'Content-Encoding' header that indicates that the content was compressed, then it will attempt to inflate the data using Compress::Zlib, if the module is not installed then an exception will be thrown. If you do not have or do not want to install Compress::Zlib then you should be able to send an 'Accept-Encoding' header with a value of 'identity' which should cause a well behaved server to send the content verbatim if it is able to.

If the Content-Type of the response indicates that the content is text the `content` of the Response will be a decoded string, otherwise it will be left as a <Blob>. The content-types that are always considered to be binary (and thus left as a <Blob> ) are those with the major-types of 'image','audio' and 'video', certain 'application' types are considered to be 'text' (e.g. 'xml', 'javascript', 'json').

If the ':bin' adverb is supplied this will force the response `content` to always be an undecoded <Blob>

You can use the helper subroutines defined in [HTTP::Request::Common](http::Request::Common) to create the [HTTP::Request](http::Request) for you or create it yourself if you have more complex requirements.

## routine get :simple

```
sub get(Str $url) returns Str is export(:simple)

```

Like method get, but returns decoded content of the response.

## routine head :simple

```
sub head(Str $url) returns Parcel is export(:simple)

```

Returns values of following header fields:

* Content-Type
* Content-Length
* Last-Modified
* Expires
* Server

## routine getstore :simple

```
sub getstore(Str $url, Str $file) is export(:simple)

```

Like routine get but writes the content to a file.

## routine getprint :simple

```
sub getprint(Str $url) is export(:simple)

```

Like routine get but prints the content and returns the response code.

# SUPPORT MODULES

## HTTP::Cookie - HTTP cookie class

This module encapsulates single HTTP Cookie.

```
use HTTP::Cookie;

my $cookie = HTTP::Cookie.new(:name<test_name>, :value<test_value>);
say ~$cookie;

```

The following methods are provided:

### method new

```
my $c = HTTP::Cookie.new(:name<a_cookie>, :value<a_value>, :secure, fields => (a => b));

```

A constructor, it takes these named arguments:

| key | description |
| --- | --- |
| name | name of a cookie |
| value | value of a cookie |
| secure | Secure param |
| httponly | HttpOnly param |
| fields | list of field Pairs (field => value) |

### method Str

Returns a cookie as a string in readable (RFC2109) form.

## HTTP::Cookies - HTTP cookie jars

This module provides a bunch of methods to manage HTTP cookies.

```
use HTTP::Cookies;
my $cookies = HTTP::Cookies.new(
  :file<./cookies>,
  :autosave
);
$cookies.load;

```

### method new

```
my $cookies = HTTP::Cookies.new(
  :file<./cookies.here>
  :autosave,
);

Constructor, takes named arguments:

```

| key | description |
| --- | --- |
| file | where to write cookies |
| autosave | save automatically after every operation on cookies or not |

### method set-cookie

```
my $cookies = HTTP::Cookies.new;
$cookies.set-cookie('Set-Cookie: name1=value1; HttpOnly');

```

Adds a cookie (passed as an argument $str of type Str) to the list of cookies.

### method save

```
my $cookies = HTTP::Cookies.new;
$cookies.set-cookie('Set-Cookie: name1=value1; HttpOnly');
$cookies.save;

```

Saves cookies to the file ($.file).

### method load

```
my $cookies = HTTP::Cookies.new;
$cookies.load;

```

Loads cookies from file specified at instantiation ($.file).

### method extract-cookies

```
my $cookies = HTTP::Cookies.new;
my $response = HTTP::Response.new(Set-Cookie => "name1=value; Secure");
$cookies.extract-cookies($response);

```

Gets cookies ('Set-Cookie: ' lines) from the HTTP Response and adds it to the list of cookies.

### method add-cookie-header

```
my $cookies = HTTP::Cookies.new;
my $request = HTTP::Request.new;
$cookies.load;
$cookies.add-cookie-header($request);

```

Adds cookies fields ('Cookie: ' lines) to the HTTP Request.

### method clear-expired

```
my $cookies = HTTP::Cookies.new;
$cookies.set-cookie('Set-Cookie: name1=value1; Secure');
$cookies.set-cookie('Set-Cookie: name2=value2; Expires=Wed, 09 Jun 2021 10:18:14 GMT');
$cookies.clear-expired; # contains 'name1' cookie only

```

Removes expired cookies.

### method clear

```
my $cookies = HTTP::Cookies.new;
$cookies.load;   # contains something
$cookies.clear;  # will be empty after this action

```

Removes all cookies.

### method push-cookie

```
my $c = HTTP::Cookie.new(:name<a>, :value<b>, :httponly);
my $cookies = HTTP::Cookies.new;
$cookies.push-cookie: $c;

```

Pushes cookies (passed as an argument $c of type HTTP::Cookie) to the list of cookies.

### method Str

Returns all cookies in human (and server) readable form.

## HTTP::UserAgent::Common - the most commonly used User-Agents

This module provides a list of the most commonly used User-Agents.

```
use HTTP::UserAgent::Common;
say get-ua('chrome_linux');

```

### routine get-ua

```
say get-ua('chrome_linux');

```

Returns correct UserAgent or unchaged passed argument if UserAgent could not be found.

Available UserAgents:

```
chrome_w7_64 firefox_w7_64 ie_w7_64 chrome_w81_64 firefox_w81_64 mob_safari_osx
safari_osx chrome_osx firefox_linux chrome_linux

```

## HTTP::Header - class encapsulating HTTP message header

This module provides a class with a set of methods making us able to easily handle HTTP message headers.

```
use HTTP::Header;
my $h = HTTP::Header.new;
$h.field(Accept => 'text/plain');
say $h.field('Accept');
$h.remove-field('Accept');

```

### method new

```
my $head = HTTP::Header.new(:h1<v1>, :h2<v2>);

```

A constructor. Takes name => value pairs as arguments.

### method header

```
my $head = HTTP::Header.new(:h1<v1>, :h2<v2>);
say $head.header('h1');

my $head = HTTP::Header.new(:h1<v1>, :h2<v2>);
$head.header(:h3<v3>);

```

Gets/sets header field.

### method init-field

```
my $head = HTTP::Header.new;
$head.header(:h1<v1>);
$head.init-header(:h1<v2>, :h2<v2>); # it doesn't change the value of 'h1'
say ~$head;

```

Initializes a header field: adds a field only if it does not exist yet.

### method push-header

```
my $head = HTTP::Header.new;
$head.push-header( HTTP::Header::Field.new(:name<n1>, :value<v1>) );
say ~$head;

```

Pushes a new field. Does not check if exists.

### method remove-header

```
my $head = HTTP::Header.new;
$head.header(:h1<v1>);
$head.remove-header('h1');

```

Removes a field of name $field.

### method header-field-names

```
my $head = HTTP::Header.new(:h1<v1>, :h2<v2>);
my @names = $head.header-field-names;
say @names; # h1, h2

```

Returns a list of names of all fields.

### method clear

```
my $head = HTTP::Header.new(:h1<v1>, :h2<v2>);
$head.clear;

```

Removes all fields.

### method Str

Returns readable form of the whole header section.

### method parse

```
my $head = HTTP::Header.new.parse("h1: v1\r\nh2: v2\r\n");
say $head.raku;

```

Parses the whole header section.

## HTTP::Header::Field

This module provides a class encapsulating HTTP Message header field.

```
use HTTP::Header::Field;
my $header = HTTP::Header::Field.new(:name<Date>, values => (123, 456));

```

### method new

Constructor. Takes these named arguments:

| key | description |
| --- | --- |
| name | name of a header field |
| values | array of values of a header field |

### method Str

Stringifies an HTTP::Header::Field object. Returns a header field in a human (and server) readable form.

## HTTP::Request - class encapsulating HTTP request message

Module provides functionality to easily manage HTTP requests.

```
use HTTP::Request;
my $request = HTTP::Request.new(GET => 'http://www.example.com/');

```

### method new

A constructor, the first form takes parameters like:

* method => URL, where method can be POST, GET ... etc.
* field => values, header fields

```
my $req = HTTP::Request.new(:GET<example.com>, :h1<v1>);

```

The second form takes the key arguments as simple positional parameters and is designed for use in places where for example the request method may be calculated and the headers pre-populated.

### method set-method

```
my $req = HTTP::Request.new;
$req.set-method: 'POST';

```

Sets a method of the request.

### method uri

```
my $req = HTTP::Request.new;
$req.uri: 'example.com';

```

Sets URL to request.

### method add-cookies

```
method add-cookies(HTTP::Cookies $cookies)

```

This will cause the appropriate cookie headers to be added from the supplied HTTP::Cookies object.

### method add-form-data

```
multi method add-form-data(%data, :$multipart)
multi method add-form-data(:$multipart, *%data);
multi method add-form-data(Array $data, :$multipart)

```

Adds the form data, supplied either as a `Hash`, an `Array` of `Pair`s, or in a named parameter style, to the POST request (it doesn't make sense on most other request types).

The default is to use 'application/x-www-form-urlencoded' and 'multipart/form-data' can be used by providing the ':multipart' named argument. Alternatively a previously applied "content-type" header of either 'application/x-www-form-urlencoded' or 'multipart/form-data' will be respected and in the latter case any applied boundary marker will be retained.

As a special case for multipart data if the value for some key in the data is an `Array` of at least one item then it is taken to be a description of a file to be "uploaded" where the first item is the path to the file to be inserted, the second (optional) an alternative name to be used in the content disposition header and the third an optional `Array` of `Pair`s that will provide additional header lines for the part.

### method Str

Returns stringified object.

### method parse

```
method parse(Str $raw_request --> HTTP::Request:D)

```

Parses raw HTTP request. See `HTTP::Message`

## HTTP::Request::Common - Construct common HTTP::Request objects

```
use HTTP::Request::Common;

my $ua       = HTTP::UserAgent.new;
my $response = $ua.request(GET 'http://google.com/');

```

This module provide functions that return newly created `HTTP::Request` objects. These functions are usually more convenient to use than the standard `HTTP::Request` constructor for the most common requests. The following functions are provided:

### GET $url, Header => Value...

The `GET` function returns an `HTTP::Request` object initialized with the "GET" method and the specified URL.

### HEAD $url, Header => Value,...

Like `GET` but the method in the request is "HEAD".

### DELETE $url, Header => Value,...

Like `GET` but the method in the request is "DELETE".

### `PUT $url, Header =` Value,..., content => $content>

Like `GET` but the method in the request is "PUT".

## HTTP::Response - class encapsulating HTTP response message

```
use HTTP::Response;
my $response = HTTP::Response.new(200);
say $response.is-success; # it is

```

Module provides functionality to easily manage HTTP responses.

Response object is returned by the .get() method of [HTTP::UserAgent](http::UserAgent).

### method new

```
my $response = HTTP::Response.new(200, :h1<v1>);

```

A constructor, takes named arguments:

| key | description |
| --- | --- |
| code | code of the response |
| fields | header fields (field\_name => values) |

### method is-success

```
my $response = HTTP::Response.new(200);
say 'YAY' if $response.is-success;

```

Returns True if response is successful (status == 2xx), False otherwise.

## method set-code

```
my $response = HTTP::Response.new;
$response.set-code: 200;

```

Sets code of the response.

### method Str

Returns stringified object.

### method parse

See `HTTP::Message`.

## HTTP::Message - class encapsulating HTTP message

```
use HTTP::Message;
my $raw_msg = "GET / HTTP/1.1\r\nHost: somehost\r\n\r\n";
my $mess = HTTP::Message.new.parse($raw_msg);
say $mess;

```

This module provides a bunch of methods to easily manage HTTP message.

### method new

```
my $msg = HTTP::Message.new('content', :field<value>);

```

A constructor, takes these named arguments:

| key | description |
| --- | --- |
| content | content of the message (optional) |
| fields | fields of the header section |

### method add-content

```
my $msg = HTTP::Message.new('content', :field<value>);
$msg.add-content: 's';
say $msg.content; # says 'contents'

```

Adds HTTP message content. It does not remove the existing value, it concats to the existing content.

### method decoded-content

```
my $msg = HTTP::Message.new();
say $msg.decoded-content;

```

Returns decoded content of the message (using <Encode> module to decode).

### method field

See `HTTP::Header`.

### method init-field

See `HTTP::Header`.

### method push-field

See `HTTP::Header`.

### method remove-field

See `HTTP::Header`.

### method clear

```
my $msg = HTTP::Message.new('content', :field<value>);
$msg.clear;
say ~$msg; # says nothing

```

Removes the whole message, both header and content section.

### method parse

```
my $msg = HTTP::Message.new.parse("GET / HTTP/1.1\r\nHost: example\r\ncontent\r\n");
say $msg.raku;

```

Parses the whole HTTP message.

It takes the HTTP message (with \r\n as a line separator) and obtains the header and content sections, creates a `HTTP::Header` object.

### method Str

Returns HTTP message in a readable form.

# AUTHOR

* Filip Sergot

Source can be located at: <https://github.com/raku-community-modules/HTTP-UserAgent> . Comments and Pull Requests are welcome.

# COPYRIGHT AND LICENSE

Copyright 2014 - 2022 Filip Sergot

Copyright 2023 - 2025 The Raku Community

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