txt
stringlengths 93
37.3k
|
---|
## dist_github-avuserow-Audio-Taglib-Simple.md
# NAME
Audio::Taglib::Simple - Read, write ID3 and other audio metadata with TagLib
# SYNOPSIS
```
my $taglib = Audio::Taglib::Simple.new("awesome.mp3");
# read a tag
say "artist: ", $taglib.artist;
# edit a tag
$taglib.artist = "Awesome Band";
$taglib.save;
# free memory when you're done
$taglib.free;
```
See also examples/taglib.p6
# DESCRIPTION
This module uses NativeCall to provide bindings to TagLib's C API. The C API is
the "simple" API, which only provides commonly used fields that are abstracted
over all file types.
If you are interested in the non-abstract API, check out the
[Audio::TagLib](https://github.com/avuserow/raku-audio-taglib) module.
TagLib supports many audio and tag formats. Audio formats include MP3, MPC,
FLAC, MP4, ASF, AIFF, WAV, TrueAudio, WavPack, Ogg FLAC, Ogg Vorbis, Speex and
Opus file formats. Tag formats include ID3v1, ID3v2, APE, FLAC, Xiph,
iTunes-style MP4 and WMA. See their website for an exhaustive list.
TagLib is nice and fast. The example script runs on a directory of 501 files
(499 are MP3, 2 are non-audio) in around 4 seconds.
# METHODS
## new(Str|IO $file)
Prepares to read the provided file. Dies if the file does not exist or if
TagLib cannot parse it. TagLib attempts to guess the file type here.
## free
Frees the internal data used by TagLib.
## file returns IO
Readonly accessor to the file variable passed in.
## artist() returns Str
Returns the artist of the song.
## album() returns Str
Returns the name of the album associated with the song.
## title() returns Str
Returns the title of the song.
## comment() returns Str
A generic comment field.
## genre() returns Str
A string describing the genre.
## year() returns Int
Returns the year associated with the song as an integer (e.g. 2004) or 0 if not
present.
## track() returns Int
Returns the track number of this song as an integer (e.g. 12) or 0 if not
present.
## save() returns Bool
Call save after assigning to one or more tag attributes (listed above) to write
out the changes.
## length() returns Duration
Returns the length of the file as a Duration. TagLib provides it as an integer.
Not editable.
## bitrate() returns Int
Returns the bit rate of the file as an Int in kb/s. Example: 128. Not editable.
## samplerate() returns Int
Returns the sample rate of the file as an Int in Hz. Example: 44100. Not
editable.
## channels() returns Int
Returns the number of channels present in the file as an Int. Example: 2. Not
editable.
# EXCEPTIONS
## X::InvalidAudioFile
The constructor may raise exceptions if the file does not exist or does not
appear to be audio that TagLib can parse.
### file
The file that is invalid.
### text
The specific error text.
# CAVEATS
* TagLib will start claiming some files are not valid after a
certain amount of objects are creating them without freeing them.
* TagLib prints some warnings to STDERR directly.
* All fields are read from the metadata, and corrupted files can often have
incorrect values for length. TagLib does not actually parse the music stream
to find this out.
* Tags are read at object initialization time. This means that if some other
process modifies the tags on the music file, you won't see changes unless you
create a new object.
# REQUIREMENTS
* Rakudo Perl 6 2014.11 or above. Tested primarily on MoarVM.
* NativeCall (included in Rakudo 2015.02 and above)
# TODO
See <TODO>.
# SEE ALSO
[TagLib website](http://taglib.github.io)
[tag\_c.h from the TagLib project](https://github.com/taglib/taglib/blob/master/bindings/c/tag_c.h)
|
## dist_zef-raku-community-modules-ClassX-StrictConstructor.md
[](https://github.com/raku-community-modules/ClassX-StrictConstructor/actions) [](https://github.com/raku-community-modules/ClassX-StrictConstructor/actions) [](https://github.com/raku-community-modules/ClassX-StrictConstructor/actions)
# NAME
ClassX::StrictConstructor - Make your object constructors blow up on unknown attributes
# SYNOPSIS
```
use ClassX::StrictConstructor;
class Foo does ClassX::StrictConstructor {
has $.a;
has %.b;
}
Foo.new(a => 1, b => {bb => 2, bbb => 3}); # ok
Foo.new(a => 1, b => 2, c => 3); # dies
```
# DESCRIPTION
This is Perl's [MooseX::StrictConstructor](https://metacpan.org/pod/MooseX::StrictConstructor) module ported to Raku as a role.
The test suite is ported as well, except for the parts that don't make sense in Raku anymore.
I had fun writing this. I hope you enjoy using it too.
# AUTHOR
Tadeusz Sośnierz
# COPYRIGHT AND LICENSE
Copyright 2014 - 2019 Tadeusz Sośnierz
Copyright 2024 Raku Community
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-thundergnat-Text-Center.md
[](https://github.com/thundergnat/Text-Center/actions)
# NAME
Text::Center - Easy centering of text fields
# SYNOPSIS
```
use Text::Center;
say 'Raku'.¢er; # Center in a 79 columns by default, space padded by default
# Raku
say 'Raku'.¢er(20); # Center in 20 columns, space padded
# Raku
say 'Raku'.¢er(30, :fill('=')); # Center in 30 columns, equal sign padded
#============ Raku ============
```
# DESCRIPTION
Easily center text in a configurable field width (default 79). Pad with spaces by default but may substitute some other character if desired. Will leave a single space on either side of the text unless the text is too large to fit into the field width. In that case, just returns the text unaltered.
Exports a single subroutine:
`center( $text, $width = 79, :fill(' ') )`
where
```
$text is the text to be centered.
$width (optional) is the field width to center within, default 79
:fill (optional) is the fill character to use, default ' ' (space)
```
# AUTHOR
thundergnat aka Steve Schulze
# COPYRIGHT AND LICENSE
Copyright 2020 thundergnat
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_cpan-JGOFF-Vroom-Reveal.md
# Vroom::Reveal
Vroom::Reveal translates Vroom-format files to Reveal.js format.
# Installation
* Using zef (a module management tool bundled with Rakudo Star):
```
zef update && zef install ANTLR4
```
## Testing
To run tests:
```
prove -e perl6
```
## Author
Jeffrey Goff, DrForr on #perl6, <https://github.com/drforr/>
## License
Artistic License 2.0
|
## dist_cpan-MELEZHIK-Sparrowdo-Prometheus.md
# SYNOPSIS
Simple Sparrowdo installer for Prometheus.
# USAGE
```
$ zef install Sparrowdo::Prometheus
$ sparrowdo --module_run=Prometheus --host=$remote_host
```
# Platforms supported
Any Linux Box with systemd.
# TODO
* Make prometheus configuration file customizable
* Make distribution version customizable
# Author
Alexey Melezhik
|
## dist_zef-grizzlysmit-Gzz-Text-Utils.md
## Chunk 1 of 2
## Table of Contents
* [NAME](#name)
* [AUTHOR](#author)
* [VERSION](#version)
* [TITLE](#title)
* [SUBTITLE](#subtitle)
* [COPYRIGHT](#copyright)
* [Introduction](#introduction)
* [Motivations](#motivations)
* [Update](#update)
* [Exceptions](#exceptions)
* [BadArg](#badarg)
* [ArgParityMissMatch](#argparitymissmatch)
* [FormatSpecError](#formatspecerror)
* [`UnhighlightBase` & `UnhighlightBaseActions` and `Unhighlight` & `UnhighlightActions`](#unhighlightbase--unhighlightbaseactions-and-unhighlight--unhighlightactions)
* [The Functions Provided](#the-functions-provided)
* [Here are 4 functions provided to **`centre`**, **`left`** and **`right`** justify text even when it is ANSI formatted](#here-are-4-functions-provided-to-centre-left-and-right-justify-text-even-when-it-is-ansi-formatted)
* [centre(…)](#centre)
* [left(…)](#left)
* [right(…)](#right)
* [crop-field(…)](#crop-field)
* [Sprintf](#sprintf)
* [Printf](#printf)
* [MultiT](#multit)
* [menu(…)](#menu)
* [input-menu(…)](#input-menu)
* [dropdown(…)](#dropdown)
* [lead-dots(…)](#lead-dots)
* [trailing-dots(…)](#trailing-dots)
* [dots(…)](#dots)
# NAME
Gzz::Text::Utils
# AUTHOR
Francis Grizzly Smit ([[email protected]](mailto:[email protected]))
# VERSION
v0.1.23
# TITLE
Gzz::Text::Utils
# SUBTITLE
A Raku module to provide text formatting services to Raku programs.
# COPYRIGHT
LGPL V3.0+ [LICENSE](https://github.com/grizzlysmit/Gzz-Text-Utils/blob/main/LICENSE)
# Introduction
A Raku module to provide text formatting services to Raku programs.
Including a sprintf front-end Sprintf that copes better with Ansi highlighted text and implements **`%U`** and does octal as **`0o123`** or **`0O123`** if you choose **`%O`** as I hate ambiguity like **`0123`** is it an int with leading zeros or an octal number. Also there is **`%N`** for a new line and **`%T`** for a tab helpful when you want to use single quotes to stop the **`$`** specs needing back slashes.
And a **`printf`** alike **`Printf`**.
Also it does centring and there is a **`max-width`** field in the **`%`** spec i.e. **`%*.*.*E`**, and more.
[Top of Document](#table-of-contents)
## Motivations
When you embed formatting information into your text such as **bold**, *italics*, etc ... and **colours** standard text formatting will not work e.g. printf, sprintf etc also those functions don't do centring.
Another important thing to note is that even these functions will fail if you include such formatting in the **text** field unless you supply a copy of the text with out the formatting characters in it in the **:ref** field i.e. **`left($formatted-text, $width, :ref($unformatted-text))`** or **`text($formatted-text, $width, :$ref)`** if the reference text is in a variable called **`$ref`** or you can write it as **`left($formatted-text, $width, ref => $unformatted-text)`**
[Top of Document](#able-of-contents)
### Update
Fixed the proto type of **`left`** etc is now
```
sub left(Str:D $text, Int:D $width is copy, Str:D $fill = ' ',
:&number-of-chars:(Int:D, Int:D --> Bool:D) = &left-global-number-of-chars,
Str:D :$ref = strip-ansi($text), Int:D
:$max-width = 0, Str:D :$ellipsis = '' --> Str) is export
```
Where **`sub strip-ansi(Str:D $text --> Str:D) is export`** is my new function for striping out ANSI escape sequences so we don't need to supply **`:$ref`** unless it contains codes that **`sub strip-ansi(Str:D $text --> Str:D) is export`** cannot strip out, if so I would like to know so I can update it to cope with these new codes.
[Top of Document](#table-of-contents)
# Exceptions
## BadArg
```
class BadArg is Exception is export
```
BadArg is a exception type that Sprintf will throw in case of badly specified arguments.
[Top of Document](#table-of-contents)
## ArgParityMissMatch
```
class ArgParityMissMatch is Exception is export
```
ArgParityMissMatch is an exception class that Sprintf throws if the number of arguments does not match what the number the format string says there should be.
**NB: if you use *`num$`* argument specs these will not count as they grab from the args add hoc, *`*`* width and precision spec however do count as they consume argument.**
[Top of Document](#table-of-contents)
## FormatSpecError
```
class FormatSpecError is Exception is export
```
FormatSpecError is an exception class that Format (used by Sprintf) throws if there is an error in the Format specification (i.e. **`%n`** instead of **`%N`** as **`%n`** is already taken, the same with using **`%t`** instead of **`%T`**).
Or anything else wrong with the Format specifier.
**NB: *`%N`* introduces a *`\n`* character and *`%T`* a tab (i.e. *`\t`*).**
[Top of Document](#table-of-contents)
# Format and FormatActions
Format & FormatActions are a grammar and Actions pair that parse out the **%** spec and normal text chunks of a format string.
For use by Sprintf a sprintf alternative that copes with ANSI highlighted text.
[Top of Document](#table-of-contents)
# `UnhighlightBase` & `UnhighlightBaseActions` and `Unhighlight` & `UnhighlightActions`
**`UnhighlightBase`** & **`UnhighlightBaseActions`** are a grammar & role pair that does the work required to to parse apart ansi highlighted text into ANSI highlighted and plain text.
**`Unhighlight`** & **`UnhighlightActions`** are a grammar & class pair which provide a simple TOP for applying an application of **`UnhighlightBase`** & **`UnhighlightBaseActions`** for use by **`sub strip-ansi(Str:D $text --` Str:D) is export**> to strip out the plain text from a ANSI formatted string
[Top of Document](#table-of-contents)
# The Functions Provided
* strip-ansi
```
sub strip-ansi(Str:D $text --> Str:D) is export
```
Strips out all the ANSI escapes, at the moment just those provided by the **`Terminal::ANSI`** or **`Terminal::ANSI::OO`** modules both available as **`Terminal::ANSI`** from zef etc I am not sure how exhaustive that is, but I will implement any more escapes as I become aware of them.
* hwcswidth
```
sub hwcswidth(Str:D $text --> Int:D) is export
```
Same as **`wcswidth`** but it copes with ANSI escape sequences unlike **`wcswidth`**.
* The secret sauce is that it is defined as:
```
sub hwcswidth(Str:D $text --> Int:D) is export {
return wcswidth(strip-ansi($text));
} # sub hwcswidth(Str:D $text --> Int:D) is export #
```
[Top of Document](#table-of-contents)
### Here are 4 functions provided to **`centre`**, **`left`** and **`right`** justify text even when it is ANSI formatted.
### centre
* ⋄
* Centring text in a field.
```
sub centre(Str:D $text,
Int:D $width is copy,
Str:D $fill = ' ',
:&number-of-chars:(Int:D, Int:D --> Bool:D) =
¢re-global-number-of-chars,
Str:D :$ref = strip-ansi($text),
Int:D :$max-width = 0,
Str:D :$ellipsis = '' --> Str) is export {
```
* Centres the text **`$text`** in a field of width **`$width`** padding either side with **`$fill`**
* **Where:**
* **`$fill`** is the fill char by default **`$fill`** is set to a single white space.
* If it requires an odd number of padding then the right hand side will get one more char/codepoint.
* **`&number-of-chars`** takes a function which takes 2 **`Int:D`**'s and returns a **`Bool:D`**.
* By default this is equal to the closure **`centre-global-number-of-chars`** which looks like:
```
our $centre-total-number-of-chars is export = 0;
our $centre-total-number-of-visible-chars
is export = 0;
sub centre-global-number-of-chars(
Int:D $number-of-chars,
Int:D $number-of-visible-chars --> Bool:D) {
$centre-total-number-of-chars =
$number-of-chars;
$centre-total-number-of-visible-chars =
$number-of-visible-chars;
return True;
}
```
* Which is a closure around the variables: **`$centre-total-number-of-chars`** and **`$centre-total-number-of-visible-chars`**, these are global **`our`** variables that **`Gzz::Text::Utils`** exports. But you can just use **`my`** variables from with a scope, just as well. And make the **`sub`** local to the same scope.
[Top of Document](#table-of-contents)
i.e.
```
sub Sprintf(Str:D $format-str,
:&number-of-chars:(Int:D, Int:D --> Bool:D) = &Sprintf-global-number-of-chars,
Str:D :$ellipsis = '', *@args --> Str) is export {
...
...
...
my Int:D $total-number-of-chars = 0;
my Int:D $total-number-of-visible-chars = 0;
sub internal-number-of-chars(Int:D $number-of-chars, Int:D $number-of-visible-chars --> Bool:D) {
$total-number-of-chars += $number-of-chars;
$total-number-of-visible-chars += $number-of-visible-chars;
return True;
} # sub internal-number-of-chars(Int:D $number-of-chars, Int:D $number-of-visible-chars --> Bool:D) #
...
...
...
for @format-str -> %elt {
my Str:D $type = %elt«type»;
if $type eq 'literal' {
my Str:D $lit = %elt«val»;
$total-number-of-chars += $lit.chars;
$total-number-of-visible-chars += strip-ansi($lit).chars;
$result ~= $lit;
} elsif $type eq 'fmt-spec' {
...
...
...
given $spec-char {
when 'c' {
$arg .=Str;
$ref .=Str;
BadArg.new(:msg("arg should be one codepoint: {$arg.codes} found")).throw if $arg.codes != 1;
$max-width = max($max-width, $precision, 0) if $max-width > 0; #`« should not really have a both for this
so munge together.
Traditionally sprintf etc treat precision
as max-width for strings. »
if $padding eq '' {
if $justify eq '' {
$result ~= right($arg, $width, :$ref, :number-of-chars(&internal-number-of-chars), :$max-width);
} elsif $justify eq '-' {
$result ~= left($arg, $width, :$ref, :number-of-chars(&internal-number-of-chars), :$max-width);
} elsif $justify eq '^' {
$result ~= centre($arg, $width, :$ref, :number-of-chars(&internal-number-of-chars), :$max-width);
}
} else {
if $justify eq '' {
$result ~= right($arg, $width, $padding, :$ref, :number-of-chars(&internal-number-of-chars), :$max-width);
} elsif $justify eq '-' {
$result ~= left($arg, $width, $padding, :$ref, :number-of-chars(&internal-number-of-chars), :$max-width);
} elsif $justify eq '^' {
$result ~= centre($arg, $width, $padding, :$ref, :number-of-chars(&internal-number-of-chars), :$max-width);
}
}
}
when 's' {
...
...
...
...
...
...
...
...
...
return $result;
KEEP {
&number-of-chars($total-number-of-chars, $total-number-of-visible-chars);
}
} #`««« sub Sprintf(Str:D $format-str,
:&number-of-chars:(Int:D, Int:D --> Bool:D) = &Sprintf-global-number-of-chars,
Str:D :$ellipsis = '', *@args --> Str) is export »»»
```
* The parameter **`:$ref`** is by default set to the value of **`strip-ansi($text)`**
* This is used to obtain the length of the of the text using ***`wcswidth(Str)`*** from module **"`Terminal::WCWidth`"** which is used to obtain the width the text if printed on the current terminal:
* **NB: `wcswidth` will return -1 if you pass it text with colours etc embedded in them**.
* **"`Terminal::WCWidth`"** is witten by **bluebear94** [github:bluebear94](https://raku.land/github:bluebear94) get it with **zef** or whatever
* **`:$max-width`** sets the maximum width of the field but if set to **`0`** (The default), will effectively be infinite (∞).
* **`:$ellipsis`** is used to elide the text if it's too big I recommend either **`''`** the default or **`'…'`**.
[Top of Document](#table-of-contents)
### left
* ⋄
* Left Justifying text.
```
sub left(Str:D $text, Int:D $width is copy, Str:D $fill = ' ',
:&number-of-chars:(Int:D, Int:D --> Bool:D) = &left-global-number-of-chars,
Str:D :$ref = strip-ansi($text), Int:D :$max-width = 0,
Str:D :$ellipsis = '' --> Str) is export
```
* **`left`** is the same except that except that it puts all the padding on the right of the field.
[Top of Document](#table-of-contents)
### right
* ⋄
* Right justifying text.
```
sub right(Str:D $text, Int:D $width is copy, Str:D $fill = ' ',
:&number-of-chars:(Int:D, Int:D --> Bool:D) = &right-global-number-of-chars,
Str:D :$ref = strip-ansi($text), Int:D :$max-width = 0,
Str:D :$ellipsis = '' --> Str) is export
```
* **`right`** is again the same except it puts all the padding on the left and the text to the right.
* [Top of Document](#table-of-contents)
#### crop-field
* text
* Cropping Text in a field.
```
sub crop-field(Str:D $text,
Int:D $w is rw,
Int:D $width is rw,
Bool:D $cropped is rw,
Int:D $max-width,
Str:D :$ellipsis = '' --> Str:D) is export {
```
* **`crop-field`** used by **`centre`**, **`left`** and **`right`** to crop their input if necessary. Copes with ANSI escape codes.
* **Where**
* **`$text`** is the text to be cropped possibly, wit ANSI escapes embedded.
* **`$w`** is used to hold the width of **`$text`** is read-write so will return that value.
* **`$width`** is the desired width. Will be used to return the updated width.
* **`$cropped`** is used to return the status of whether or not **`$text`** was truncated.
* **`$max-width`** is the maximum width we are allowing.
* **`$ellipsis`** is used to supply a eliding . Empty string by default.
[Top of Document](#table-of-contents)
## Sprintf
* Sprintf like sprintf only it can deal with ANSI highlighted text. And has lots of other options, including the ability to specify a **`$max-width`** using **`width.precision.max-width`**, which can be **`.*`**, **`*<num>$`**, **`.*`**, or **`<num>`**
```
sub Sprintf(Str:D $format-str,
:&number-of-chars:(Int:D, Int:D --> Bool:D) =
&Sprintf-global-number-of-chars,
Str:D :$ellipsis = '',
*@args --> Str) is export
```
* Where:
* **`format-str`** is is a superset of the **`sprintf`** format string, but it has extra features: like the flag **`[ <char> ]`** where can be almost anything except **`[`**, **`]`** **control characters**, **white space other than the normal space**, and **`max-width`** after the precision.
* The format string looks like this:
```
token format { <chunks>+ }
token chunks { [ <chunk> || '%' <format-spec> ] }
token chunk { <-[%]>+ }
token format-spec { [ <fmt-esc> || <fmt-spec> ] }
token fmt-esc { [ '%' #`« a literal % »
|| 'N' #`« a nl i.e. \n char but does not require interpolation so no double quotes required »
|| 'T' #`« a tab i.e. \t char but does not require interpolation so no double quotes required »
|| 'n' #`« not implemented and will not be, throws an exception if matched »
|| 't' #`« not implemented and will not be, throws an exception if matched »
]
}
token fmt-spec { [ <dollar-directive> '$' ]? <flags>? <width>? [ '.' <precision> [ '.' <max-width> ]? ]? <modifier>? <spec-char> }
```
* [Top of Document](#table-of-contents)
* Where
* **`dollar-directive`** is a integer >= 1
* **`flags`** is any zero or more of:
* **`+`** put a plus in front of positive values.
* **`-`** left justify, right is the default
* **`^`** centre justify.
* **`#`** ensure the leading **`0`** for any octal, prefix non-zero hexadecimal with **`0x`** or **`0X`**, prefix non-zero binary with **`0b`** or **`0B`**
* **`v`** vector flag (used only with d directive)
* **`' '`** pad with spaces.
* **`0`** pad with zeros.
* **`[ <char> ]`** pad with character char where char matches:
* **`<-[ <cntrl> \s \[ \] ]> || ' '`** i.e. anything except control characters, white space (apart from the basic white space (i.e. \x20 or the one with ord 32)), and **`[`** and finally **`]`**.
* [Top of Document](#table-of-contents)
* **`width`** is either an integer or a **`*`** or a **`*`** followed by an integer >= 1 and a '$'.
* **`precision`** is a **`.`** followed by either an positive integer or a **`*`** or a **`*`** followed by an integer >= 1 and a '$'.
* **`max-width`** is a **`.`** followed by either an positive integer or a **`*`** or a **`*`** followed by an integer >= 1 and a '$'.
* **`modifier`** These are not implemented but is one of:
* **`hh`** interpret integer as a type **`char`** or **`unsigned char`**.
* **`h`** interpret integer as a type **`short`** or **`unsigned short`**.
* **`j`** interpret integer as a type **`intmax_t`**, only with a C99 compiler (unportable).
* **`l`** interpret integer as a type **`long`** or **`unsigned long`**.
* **`ll`** interpret integer as a type **`long long`**, **`unsigned long long`**, or **`quad`** (typically 64-bit integers).
* **`q`** interpret integer as a type **`long long`**, **`unsigned long long`**, or **`quad`** (typically 64-bit integers).
* **`L`** interpret integer as a type **`long long`**, **`unsigned long long`**, or **`quad`** (typically 64-bit integers).
* **`t`** interpret integer as a type **`ptrdiff_t`**.
* **`z`** interpret integer as a type **`size_t`**.
* [Top of Document](#table-of-contents)
* **`spec-char`** or the conversion character is one of:
* **`c`** a character with the given codepoint.
* **`s`** a string.
* **`d`** a signed integer, in decimal.
* **`u`** an unsigned integer, in decimal.
* **`o`** an unsigned integer, in octal, with a **`0o`** prepended if the **`#`** flag is present.
* **`x`** an unsigned integer, in hexadecimal, with a **`0x`** prepended if the **`#`** flag is present.
* **`e`** a floating-point number, in scientific notation.
* **`f`** a floating-point number, in fixed decimal notation.
* **`g`** a floating-point number, in %e or %f notation.
* **`X`** like **`x`**, but using uppercase letters, with a **`0X`** prepended if the **`#`** flag is present.
* **`E`** like **`e`**, but using an uppercase **`E`**.
* **`G`** like **`g`**, but with an uppercase **`E`** (if applicable).
* **`b`** an unsigned integer, in binary, with a **`0b`** prepended if the **`#`** flag is present.
* **`B`** an unsigned integer, in binary, with a **`0B`** prepended if the **`#`** flag is present.
* **`i`** a synonym for **`%d`**.
* **`D`** a synonym for **`%ld`**.
* **`U`** a synonym for **`%lu`**.
* **`O`** a synonym for **`%lo`**.
* **`F`** a synonym for **`%f`**.
* [Top of Document](#table-of-contents)
* **`:&number-of-chars`** is an optional named argument which takes a function with a signature **`:(Int:D, Int:D --` Bool:D)**> if not specified it will have the value of **`&Sprintf-global-number-of-chars`** which is defined as:
```
our $Sprintf-total-number-of-chars is export = 0;
our $Sprintf-total-number-of-visible-chars is export = 0;
sub Sprintf-global-number-of-chars(Int:D $number-of-chars, Int:D $number-of-visible-chars --> Bool:D) {
$Sprintf-total-number-of-chars = $number-of-chars;
$Sprintf-total-number-of-visible-chars = $number-of-visible-chars;
return True
}
```
* This is exactly the same as the argument by the same name in **`centre`**, **`left`** and **`right`** above.
i.e.
```
sub test( --> True) is export {
...
...
...
my $test-number-of-chars = 0;
my $test-number-of-visible-chars = 0;
sub test-number-of-chars(Int:D $number-of-chars, Int:D $number-of-visible-chars --> Bool:D) {
$test-number-of-chars = $number-of-chars;
$test-number-of-visible-chars = $number-of-visible-chars;
return True
}
put Sprintf('%30.14.14s, %30.14.13s%N%%%N%^*.*s%3$*4$.*3$.*6$d%N%2$^[&]*3$.*4$.*6$s%T%1$[*]^100.*4$.99s',
${ arg => $highlighted, ref => $text }, $text, 30, 14, $highlighted, 13,
:number-of-chars(&test-number-of-chars), :ellipsis('…'));
dd $test-number-of-chars, $test-number-of-visible-chars;
put Sprintf('%30.14.14s, testing %30.14.13s%N%%%N%^*.*s%3$*4$.*3$.*6$d%N%2$^[&]*3$.*4$.*6$s%T%1$[*]^100.*4$.99s',
$[ $highlighted, $text ], $text, 30, 14, $highlighted, 13, 13,
:number-of-chars(&test-number-of-chars), :ellipsis('…'));
dd $test-number-of-chars, $test-number-of-visible-chars;
...
...
...
}
```
* **Note: This is a closure we should always use a closure if we want to get the number of characters printed.**
* [Top of Document](#table-of-contents)
* **`:$ellipsis`** this is an optional argument of type **`Str:D`** which defaults to **`''`**, if set will be used to mark elided text, if the argument is truncated due to exceeding the value of **`max-width`** (note **`max-width`** defaults to **`0`** which means infinity). The recommended value would be something like **`…`**.
* **`*@args`** is an arbitrary long list of values each argument can be either a scalar value to be printed or a Hash or an Array
* If a Hash then it should contain two pairs with keys: **`arg`** and **`ref`**; denoting the actual argument and a reference argument respectively, the ref argument should be the same as **`arg`** but with no ANSI formatting etc to mess up the counting. As this ruins formatting spacing. If not present will be set to **`strip-ansi($arg)`**, only bother with all this if **`strip-ansi($arg)`** isn't good enough.
* If a Array then it should contain two values. The first being **`arg`** and the other being **`ref`**; everything else is the same as above.
* **`arg`** the actual argument.
* **`@args[$i][]`** the actual argument. Where **`$i`** is the current index into the array of args.
* **`@args[$i][1]`** the reference argument, as in the **`:$ref`** arg of the **left**, **right** and **centre** functions which it uses. It only makes sense if your talking strings possibly formatted if not present will be set to **`strip-ansi($arg)`** if $arg is a Str or just $arg otherwise.
* If it's a scalar then it's the argument itself. And **`$ref`** is **`strip-ansi($arg)`** if $arg is a string type i.e. Str or just **C**$arg>> otherwise.
* **`ref`** the reference argument, as in the **`:$ref`** arg of the **left**, **right** and **centre** functions which it uses. It only makes sense if your talking strings possibly formatted if not present will be set to **`strip-ansi($arg)`** if $arg is a Str or just $arg otherwise.
i.e.
```
put Sprintf('%30.14.14s, %30.14.13s%N%%%N%^*.*s%3$*4$.*3$.*6$d%N%2$^[&]*3$.*4$.*6$s%T%1$[*]^100.*4$.99s',
${ arg => $highlighted, ref => $text }, $text, 30, 14, $highlighted, 13,
:number-of-chars(&test-number-of-chars), :ellipsis('…'));
dd $test-number-of-chars, $test-number-of-visible-chars;
put Sprintf('%30.14.14s, testing %30.14.13s%N%%%N%^*.*s%3$*4$.*3$.*6$d%N%2$^[&]*3$.*4$.*6$s%T%1$[*]^100.*4$.99s',
$[ $highlighted, $text ], $text, 30, 14, $highlighted, 13, 13,
:number-of-chars(&test-number-of-chars), :ellipsis('…'));
dd $test-number-of-chars, $test-number-of-visible-chars;
```
[Top of Document](#table-of-contents)
## Printf
* Same as **`Sprintf`** but writes it's output to **`$*OUT`** or an arbitrary filehandle if you choose.
* defined as
```
multi sub Printf(Str:D $format-str,
:&number-of-chars:(Int:D, Int:D --> Bool:D) = &Sprintf-global-number-of-chars,
Str:D :$ellipsis = '', *@args --> True) is export {
Sprintf($format-str, :&number-of-chars, :$ellipsis, |@args).print;
} #`««« sub Printf(Str:D $format-str,
:&number-of-chars:(Int:D, Int:D --> Bool:D) = &Sprintf-global-number-of-chars,
Str:D :$ellipsis = '', *@args --> True) is export »»»
multi sub Printf(IO::Handle:D $fp, Str:D $format-str,
:&number-of-chars:(Int:D, Int:D --> Bool:D) = &Sprintf-global-number-of-chars,
Str:D :$ellipsis = '', *@args --> True) is export {
$fp.print: Sprintf($format-str, :&number-of-chars, :$ellipsis, |@args);
} #`««« sub Printf(my IO::Handle:D $fp, Str:D $format-str,
:&number-of-chars:(Int:D, Int:D --> Bool:D) = &Sprintf-global-number-of-chars,
Str:D :$ellipsis = '', *@args --> True) is export »»»
```
[Top of Document](#table-of-contents)
### MultiT
A lot of types but not Any.
```
subset MultiT is export of Any where * ~~ Str | Int | Rat | Num | Bool | Array;
```
### menu
Display a text based menu.
```
sub menu(@candidates is copy, Str:D $message = "",
:&row:(Int:D $c, Int:D $p, @a,
Bool:D :$colour = False, Bool:D :$syntax = False,
Str:D :$highlight-bg-colour = '',
Str:D :$highlight-fg-colour = '',
Str:D :$bg-colour0 = '',
Str:D :$fg-colour0 = '',
Str:D :$bg-colour1 = '',
Str:D :$fg-colour1 = '' --> Str:D) = &default-row,
:&value:(Int:D $c, @a --> MultiT) = &default-value,
Bool:D :c(:color(:$colour)) is copy = False,
Bool:D :s(:$syntax) = False,
Str:D :$highlight-bg-colour = t.bg-color(0, 0, 127) ~ t.bold,
Str:D :$highlight-fg-colour = t.bright-yellow,
Str:D :$bg-colour0 = t.bg-yellow ~ t.bold,
Str:D :$fg-colour0 = t.bright-blue,
Str:D :$bg-colour1 = t.bg-color(0, 127, 0) ~ t.bold,
Str:D :$fg-colour1 = t.bright-blue,
Str:D :$bg-prompt = t.bg-green ~ t.bold,
Str:D :$fg-prompt = t.bright-blue,
Bool:D :$wrap-around = False --> MultiT) is export
```
* Where:
* **`@candidates`** is an array of hashes to make up the rows of the menu.
* **`$message`** is a message to be displayed at the top of the ascii text form of things (i.e. no colourising).
* **`&row`** is is a callback to deal with the rows of the menu.
* Where
* **`$c`** is the current row count.
* **`$p`** is the current position in the @candidates array.
* **`@a`** is the array @candidates itself.
* **`$highlight-bg-colour`** is the background colour of the current row (i.e. $c == $p).
* **`$highlight-fg-colour`** is the foreground colour of the current row (i.e. $c == $p).
* **`$bg-colour0`** is the background colour of the row (i.e. $c %% 2).
* **`$fg-colour0`** is the foreground colour of the row (i.e. $c %% 2).
* **`$bg-colour1`** is the background colour of the row (i.e. $c % 2 != 0 or not $c %% 2).
* **`$fg-colour1`** is the foreground colour of the row (i.e. $c % 2 != 0).
* **`&value`** is a callback to get the return value for the function.
* **`$c`** is the row selected.
* **`$c`** is the array @candidates.
* **`:c(:color(:$colour))`** defines a boolean flag to |
## dist_zef-grizzlysmit-Gzz-Text-Utils.md
## Chunk 2 of 2
tell whether to use colours or not.
* you can use **`:c`**, **`:color`** or **`:colour`** for this they are all exactly the same.
* **`:s(:$syntax)`** same as **`$colour`** except it could result in some sort of syntax highlighting.
* **`$highlight-bg-colour`** the background colour to use to highlight the current line.
* **`$highlight-fg-colour`** the foreground colour to use to highlight the current line.
* **`$bg-colour0`** the background colour to use if the line count is divisible by 2.
* **`$fg-colour0`** the foreground colour to use if the line count is divisible by 2.
* **`$bg-colour1`** the background colour to use if the line count is not divisible by 2.
* **`$fg-colour1`** the foreground colour to use if the line count is not divisible by 2.
* **`$bg-prompt`** the background colour to use on the prompt line below the selection area.
* **`$fg-prompt`** the foreground colour to use on the prompt line below the selection area.
* **`$wrap-around`** if true then the selection area wraps around, (i.e going past the end wraps around, instead of refusing to go there).
* **`$highlight-bg-colour`** to **`$wrap-around`** are all just used for the dropdown case (i.e. **`$colour`** or **`$syntax`** are True)
* **`$syntax`** is no different from **`$colour`** unless the user defines it using the **`:&row`** parameter.
* calls [dropdown](#dropdown) to do the colour work.
[Top of Document](#table-of-contents)
### input-menu(…)
```
sub input-menu(@candidates is copy, Str:D $message = "",
:&row:(Int:D $c, Int:D $p, @a,
Bool:D :$colour = False, Bool:D :$syntax = False,
Str:D :$highlight-bg-colour = '', Str:D :$highlight-fg-colour = '',
Str:D :$bg-colour0 = '', Str:D :$fg-colour0 = '',
Str:D :$bg-colour1 = '', Str:D :$fg-colour1 = '' --> Str:D) = &default-row-input-menu,
:&value:(Int:D $c, @a --> MultiT) = &default-value,
:&elt-prompt:(Int:D $c, @a,
Bool:D :$colour = False, Bool:D :$syntax = False,
Str:D :$bg-prompt = '', Str:D :$fg-prompt = '' --> Str:D) = &default-prompt,
:&edit:(Int:D $c, @a is copy, Str:D $e --> Bool:D) = &default-edit,
Bool:D :c(:color(:$colour)) is copy = False,
Bool:D :s(:$syntax) = False,
Str:D :$highlight-bg-colour = t.bg-color(0, 0, 127) ~ t.bold,
Str:D :$highlight-fg-colour = t.bright-yellow,
Str:D :$bg-colour0 = t.bg-yellow ~ t.bold,
Str:D :$fg-colour0 = t.bright-blue,
Str:D :$bg-colour1 = t.bg-color(0, 127, 0) ~ t.bold,
Str:D :$fg-colour1 = t.bright-blue,
Str:D :$bg-prompt = t.bg-green ~ t.bold,
Str:D :$fg-prompt = t.bright-blue,
Bool:D :$wrap-around = False --> MultiT) is export
```
* Where:
* **`@candidates`** is an array of hashes to make up the rows of the menu.
* **`$message`** is a message to be displayed at the top of the ascii text form of things (i.e. no colourising).
* **`&row`** is is a callback to deal with the rows of the menu.
* Where
* **`$c`** is the current row count.
* **`$p`** is the current position in the @candidates array.
* **`@a`** is the array @candidates itself.
* **`$highlight-bg-colour`** is the background colour of the current row (i.e. $c == $p).
* **`$highlight-fg-colour`** is the foreground colour of the current row (i.e. $c == $p).
* **`$bg-colour0`** is the background colour of the row (i.e. $c %% 2).
* **`$fg-colour0`** is the foreground colour of the row (i.e. $c %% 2).
* **`$bg-colour1`** is the background colour of the row (i.e. $c % 2 != 0 or not $c %% 2).
* **`$fg-colour1`** is the foreground colour of the row (i.e. $c % 2 != 0).
* **`&value`** is a callback to get the return value for the function.
* **`$c`** is the row selected.
* **`$c`** is the array @candidates.
* **`&elt-prompt:(Int:D $c, @a, Bool:D :$colour = False, Bool:D :$syntax = False, Str:D :$bg-prompt = '', Str:D :$fg-prompt = '' --> Str:D) = &default-prompt`**
The callback called by the function to get the prompts to let the user edit the value of the row.
* **`$c`** is the entry choosen by the user.
* **`@a`** is the candidates array.
* **`:c(:color(:$colour))`** defines a boolean flag to tell whether to use colours or not.
* you can use **`:c`**, **`:color`** or **`:colour`** for this they are all exactly the same.
* **`:s(:$syntax)`** same as **`$colour`** except it could result in some sort of syntax highlighting.
* **`$bg-prompt`** the background colour to use on the prompt line below the selection area.
* **`$fg-prompt`** the foreground colour to use on the prompt line below the selection area.
* **`&edit:(Int:D $c, @a is copy, Str:D $e --> Bool:D) = &default-edit`**
The callback called by the function to set the new value of the row.
* **`$c`** is the entry choosen by the user.
* **`@a`** is the candidates array.
* **`:c(:color(:$colour))`** defines a boolean flag to tell whether to use colours or not.
* you can use **`:c`**, **`:color`** or **`:colour`** for this they are all exactly the same.
* **`:s(:$syntax)`** same as **`$colour`** except it could result in some sort of syntax highlighting.
* **`$highlight-bg-colour`** the background colour to use to highlight the current line.
* **`$highlight-fg-colour`** the foreground colour to use to highlight the current line.
* **`$bg-colour0`** the background colour to use if the line count is divisible by 2.
* **`$fg-colour0`** the foreground colour to use if the line count is divisible by 2.
* **`$bg-colour1`** the background colour to use if the line count is not divisible by 2.
* **`$fg-colour1`** the foreground colour to use if the line count is not divisible by 2.
* **`$bg-prompt`** the background colour to use on the prompt line below the selection area.
* **`$fg-prompt`** the foreground colour to use on the prompt line below the selection area.
* **`$wrap-around`** if true then the selection area wraps around, (i.e going past the end wraps around, instead of refusing to go there).
* **`$highlight-bg-colour`** to **`$wrap-around`** are all just used for the dropdown case (i.e. **`$colour`** or **`$syntax`** are True)
* **`$syntax`** is no different from **`$colour`** unless the user defines it using the **`:&row`** parameter.
* calls [dropdown](#dropdown) to do the colour work.
* **NB: the colours stuff is not yet implemented**
[Top of Document](#table-of-contents)
### dropdown(…)
A text based dropdown/list or menu with ANSI colours.
```
sub dropdown(MultiT:D $id, Int:D $window-height is copy, Str:D $id-name,
&setup-option-str:(Int:D $c, Int:D $p, @a --> Str:D),
&find-pos:(MultiT $r, Int:D $p, @a --> Int:D),
&get-result:(MultiT:D $res, Int:D $p, Int:D $l, @a --> MultiT:D),
@array,
Str:D :$highlight-bg-colour = t.bg-color(0, 0, 127) ~ t.bold,
Str:D :$highlight-fg-colour = t.bright-yellow,
Str:D :$bg-colour0 = t.bg-yellow ~ t.bold,
Str:D :$fg-colour0 = t.bright-blue,
Str:D :$bg-colour1 = t.bg-color(0, 127, 0) ~ t.bold,
Str:D :$fg-colour1 = t.bright-blue,
Str:D :$bg-prompt = t.bg-green ~ t.bold,
Str:D :$fg-prompt = t.bright-blue,
Bool:D :$wrap-around = False --> MultiT) is export
```
* Where
* **`$id`** is the starting value of our position in the array/choices.
* **`$window-height`** is the number of rows of characters to display at a time.
* **`$id-name`** is the name of the parameter we are scrolling.
* **`&setup-option-str`** is a function that returns the current row.
* Where:
* the arg **`$c`** will be the count of the row we are drawing.
* the arg **`$p`** will be the position in the array we are at.
* the arg **`@a`** will be the **`@array`** supplied to **`dropdown(…)`**
* the use of a function for this means you can compute a much more complex field.
* **`&find-pos`** is a function that finds the start position in the **`dropdown`**.
* Where:
* the arg **`$r`** is the value in the array **`@array`** to look for.
* the arg **`$p`** is the best approximation of where it might be if you are using it in a loop or something it could be where it last was.
* the arg **`@a`** the argument **`@array`** that was passed to **`dropdown`**.
* you can name these argument anything you like in you function, and because of the computed nature of this function and the other two you have great flexibility.
* **`&get-result`** is a function to work out the value selected.
* Where:
* the arg **`$res`** is the default value to return.
* the arg **`$p`** is the current position in the array **`@array`** supplied to **`dropdown`**.
* the arg **`$l`** is the length of the array **`@array`**.
* the arg **`@a`** is the array **`@array`** that was supplied to **`dropdown`**.
* **`@array`** the array of rows to display.
* **`$highlight-bg-colour`** the background colour to use to highlight the current line.
* **`$highlight-fg-colour`** the foreground colour to use to highlight the current line.
* **`$bg-colour0`** the background colour to use if the line count is divisible by 2.
* **`$fg-colour0`** the foreground colour to use if the line count is divisible by 2.
* **`$bg-colour1`** the background colour to use if the line count is not divisible by 2.
* **`$fg-colour1`** the foreground colour to use if the line count is not divisible by 2.
* **`$bg-prompt`** the background colour to use on the prompt line below the selection area.
* **`$fg-prompt`** the foreground colour to use on the prompt line below the selection area.
* **`$wrap-around`** if true then the selection area wraps around, (i.e going past the end wraps around, instead of refusing to go there).
* Because we use a function we can compute much more complex results; depending on what we have in **`@array`**. The result can be any of Str, Int, Rat or Num see [MultiT](#multit).
Here is an example of use.
[Top of Document](#table-of-contents)
```
my &setup-option-str = sub (Int:D $cnt, Int:D $p, @array --> Str:D ) {
my Str $name;
my Str $cc;
my Str $flag;
my Str $prefix;
if $cnt < 0 {
$name = "No country selected yet.";
$cc = "";
$flag = "";
$prefix = "you must choose one";
} else {
my %row = @array[$cnt];
$name = %row«_name»;
$cc = %row«cc»;
try {
CATCH {
default {
my $Name = $name;
$Name ~~ s:g/ <wb> 'and' <wb> /\&/;
try {
CATCH {
default { $flag = uniparse 'PENGUIN'}
}
$flag = uniparse $Name;
}
}
}
$flag = uniparse $name;
}
$prefix = %row«prefix»;
}
return "$flag $name: $cc ($prefix)"
};
my &find-pos = sub (MultiT $result, Int:D $pos, @array --> Int:D) {
for @array.kv -> $idx, %r {
if %r{$id-name} == $result {
$pos = $idx;
last; # found so don't waste resources #
}
}
return $pos;
}
my &get-result = sub (MultiT:D $result, Int:D $pos, Int:D $length, @array --> MultiT:D ) {
my $res = $result;
if $pos ~~ 0..^$length {
my %row = |%(@array[$pos]);
$res = %row«id» if %row«id»:exists;
}
return $res
};
my Int:D $cc-id = dropdown($cc_id, 20, 'id',
&setup-option-str, &find-pos, &get-result, @_country);
while !valid-country-cc-id($cc-id, %countries) {
$cc-id = dropdown($cc-id, 20, 'id',
&setup-option-str, &find-pos, &get-result, @_country);
}
```
Or using a much simpler array. **NB: from `menu`**
[Top of Document](#table-of-contents)
```
my &setup-option-str = sub (Int:D $cnt, Int:D $pos, @array --> Str:D ) {
return @array[$cnt];
};
my &get-result = sub (MultiT:D $result, Int:D $pos, Int:D $length, @array --> MultiT:D ) {
my $res = $result;
if $pos ~~ 0..^$length {
$res = @array[$pos];
}
return $res
};
my &find-pos = sub (MultiT $result, Int:D $pos, @array --> Int:D) {
for @array.kv -> $idx, $r {
if $r eq $result {
$pos = $idx;
last; # found so don't waste resources #
}
}
return $pos;
}
my Str:D $result = dropdown(@candidates[@candidates.elems - 1], 40, 'backup',
&setup-option-str, &find-pos, &get-result, @candidates);
```
[Top of Document](#table-of-contents)
### lead-dots(…)
Returns **`$text`** in a field of **`$width`** with a line of dots preceding it. Sort of like **`left`** with **`$fill`** defaulting to **`.`** but with a single space between the text and the padding.
```
sub lead-dots(Str:D $text, Int:D $width is copy, Str:D $fill = '.' --> Str) is export
```
* Where:
* **`$text`** the text to be preceded by the dots.
* **`$width`** the width of the total field.
* **`$fill`** the fill char or string.
[Top of Document](#table-of-contents)
### trailing-dots(…)
Returns **`$text`** in a field of **`$width`** with a line of dots trailing after it. Sort of like **`right`** with **`$fill`** defaulting to **`.`** but with a single space between the text and the padding.
```
sub trailing-dots(Str:D $text, Int:D $width is copy, Str:D $fill = '.' --> Str) is export
```
* Where:
* **`$text`** the text to be trailed by the dots.
* **`$width`** the width of the total field.
* **`$fill`** the fill char or string.
[Top of Document](#table-of-contents)
### dots(…)
Returns **`$text`** in a field of **`$width`** with a line of dots preceding it. Sort of like **`left`** with **`$fill`** defaulting to **`.`**.
```
sub dots(Str:D $text, Int:D $width is copy, Str:D $fill = '.' --> Str) is export
```
* Where:
* **`$text`** the text to be preceded by the dots.
* **`$width`** the width of the total field.
* **`$fill`** the fill char or string.
[Top of Document](#table-of-contents)
|
## dist_zef-tbrowder-DateTime-Posix.md
[](https://github.com/tbrowder/DateTime-Posix/actions) [](https://github.com/tbrowder/DateTime-Posix/actions) [](https://github.com/tbrowder/DateTime-Posix/actions)
# NAME
**DateTime::Posix** - Provides a DateTime object that returns posix values with fractional seconds
Note this module's routines have been incorporated into core Raku version **6.e**.
# SYNOPSIS
```
use DateTimePosixReal;
my $dt = DateTime::Posix.new: '1970-01-01T00:00:00.23Z';
say $dt.Posix; # OUTPUT: «0.23»
say $dt.posix-real; # OUTPUT: «0.23»
```
# DESCRIPTION
**DateTime::Posix** is a child class of Raku's **DateTime** class that returns 'posix' values as fractional instead of integral seconds.
The module has two methods with slightly different names to allow some user flexibility:
```
method Posix($in-timezone? --> Real:D) {...}
```
and
```
method posix-real($in-timezone? --> Real:D) {...}
```
This module will be deprecated when Raku version **6.e** is released since that version will provide the same capability for the **DateTime** base class as its 'posix' method will then return fractional rather than integral seconds.
# AUTHOR
Tom Browder ([[email protected]](mailto:[email protected]))
# COPYRIGHT and LICENSE
Copyright © 2021-2023 Tom Browder
This library is free software; you may redistribute or modify it under the Artistic License 2.0.
|
## dist_zef-tony-o-DB-Xoos-Pg.md
# DB::Xoos::Pg
DB::Xoos::Pg is an ORM designed for convenience and ease of use. It is based upon [DB::Xoos](https://github.com/tony-o/p6-xoo), provides roles and enhancements and allows you to connect to postgres for ultimate magic.
[](https://circleci.com/gh/tony-o/p6-db-xoos-pg)
# Usage
Below is a minimum viable model setup for your app. Xoos does *not* create the table for you, that is up to you.
## autoloading models (only available in Pg at the moment)
### lib/app.pm6
```
use DB::Xoos::Pg;
my DB::Xoos::Pg $d .=new;
$d.connect('pg://xyyz/example', options => { :dynamic-loading });
my $customer-model = $d.model('Customer');
my $new-customer = $customer-model.new-row;
$new-customer.name('xyz co');
$new-customer.rate(150);
$new-customer.update; # runs an insert because this is a new row
my $xyz = $customer-model.search({ name => { 'like' => '%xyz%' } }).first;
$xyz.rate( $xyz.rate * 2 ); #twice the rate!
$xyz.update; # UPDATEs the database
my $xyz-orders = $xyz.orders.count;
```
## same example with model modules
### lib/app.pm6
```
use DB::Xoos::Pg;
my DB::Xoos::Pg $d .=new;
$d.connect('sqlite://xyz.sqlite3');
my $customer-model = $d.model('Customer');
my $new-customer = $customer-model.new-row;
$new-customer.name('xyz co');
$new-customer.rate(150);
$new-customer.update; # runs an insert because this is a new row
my $xyz = $customer-model.search({ name => { 'like' => '%xyz%' } }).first;
$xyz.rate( $xyz.rate * 2 ); #twice the rate!
$xyz.update; # UPDATEs the database
my $xyz-orders = $xyz.orders.count;
```
### lib/Model/Customer.pm6
```
use DB::Xoos::Role::Model;
unit class Model::Customer does DB::Xoos::Role::Model['customer'];
has @.columns = [
id => {
type => 'integer',
nullable => False,
is-primary-key => True,
auto-increment => 1,
},
name => {
type => 'text',
},
rate => {
type => 'integer',
},
];
has @.relations = [
orders => { :has-many, :model<Order>, :relate(id => 'customer_id') },
];
```
# role DB::Xoos::Role::Model
What is a model? A model is essentially a table in your database. Your ::Model::X is pretty barebones, in this module you'll defined `@.columns` and `@.relations` (if there are any relations).
## Example
```
use DB::Xoos::Role::Model;
# the second argument below is optional and also accepts a type.
# if the arg is omitted then it attempts to auto load ::Row::Customer
# if it fails to auto load then it uses an anonymous Row and adds convenience methods to that
unit class X::Model::Customer does DB::Xoos::Role::Model['customer', 'X::Row::Customer'];
has @.columns = [
id => {
type => 'integer',
nullable => False,
is-primary-key => True,
auto-increment => 1,
},
name => {
type => 'text',
},
contact => {
type => 'text',
},
country => {
type => 'text',
},
];
has @.relations = [
orders => { :has-many, :model<Order>, :relate(id => 'customer_id') },
open_orders => { :has-many, :model<Order>, :relate(id => 'customer_id', '+status' => 'open') },
completed_orders => { :has-many, :model<Order>, :relate(id => 'customer_id', '+status' => 'closed') },
];
# down here you can have convenience methods
method delete-all { #never do this in real life
die '.delete-all disabled in prod or if %*ENV{in-prod} not defined'
if !defined %*ENV{in-prod} || so %*ENV{in-prod};
my $s = self.search({ id => { '>' => -1 } });
$s.delete;
!so $s.count;
}
```
In this example we're creating a customer model with columns `id, name, contact, country` and relations with specific filter criteria. You may notice the `+status => 'open'` on the open\_orders relationship, the `+` here indicates it's a filter on the original table.
### Breakdown
`class :: does DB::Xoos::Role::Model['table-name', 'Optional String or Type'];`
Here you can see the role accepts one or two parameters, the first is the DB table name, the latter is a String or Type of the row you'd like to use for this model. If no row is found then Xoos will create a generic row and add helper methods for you using the model's column data.
`@.columns`
A list of columns in the table. It is highly recommended you have *one* `is-primary-key` or `.update` will have unexpected results.
`@.relations`
This accepts a list of key values, the key defining the accessor name, the later a hash describing the relationship. `:has-one` and `:has-many` are both used to dictate whether a Xoos model returns an inflated object (:has-one) or a filterable object (:has-many).
## Methods
### `search(%filter?, %options?)`
Creates a new filterable model and returns that. Every subsequent call to `.search` will *add* to the existing filters and options the best it can.
Example:
```
my $customer = $dbo.model('Customer').search({
name => { like => '%bozo%' },
}, {
order-by => [ created_date => 'DESC', 'customer_name' ],
});
# later on ...
my $geo-filtered-customers = $customer.search({ country => 'usa' });
# $geo-filtered-customers effective filter is:
# {
# name => { like => '%bozo%' },
# country => 'usa',
# }
```
### `.all(%filter?)`
Returns all rows from query (an array of inflated `::Row::XYZ`). Providing `%filter` is the same as doing `.search(%filter).all` and is provided only for convenience.
### `.first(%filter?, :$next = False)`
Returns the first row (again, inflated `::Row::XYZ`) and caches the prepared statement (this is destroyed and ignored if $next is falsey)
### `.next(%filter?)`
Same as calling `.first(%filter, :next)`
### `.count(%filter?)`
Returns the result of a `select count` for the current filter selection. Providing `%filter` results in `.search(%filter).count`
### `.delete(%filter?)`
Deletes all rows matching criteria. Providing `%filter` results in `.search(%filter).delete`
### `.insert(%field-data?)`
Creates a new row with %field-data.
## Convenience methods
DB::Xoos::Role::Model inheritance allows you to have convenience methods, these methods can act on whatever the current set of filters is.
Consider the following:
Convenience model definition:
```
class X::Model::Customer does DB::Xoos::Role::Model['customer'];
# columns and relations
method remove-closed-orders {
self.closed_orders.delete;
}
```
Later in your code:
```
my $customers = $dbo.model('Customer');
my $all-customers = $customers.search({ id => { '>' => -1 } });
my $single-customers = $customers.search({ id => 5 });
$all-customers.remove-closed-orders;
# this removes all orders for customers with an id > -1
$single-customer.remove-closed-orders;
# this removes all orders for customers with id = 5
```
# role DB::Xoos::Role::Row
A role to apply to your `::Row::Customer`. If there is no `::Row::Customer` a generic row is created using the column and relationship data specified in the corresponding `Model` and this file is only really necessary if you want to add convenience methods.
When a `class :: does DB::Xoos::Role::Row`, it receives the info from the model and adds the methods for setting/getting field data.
With the model definition above:
```
my $invoice-model = $dbo.model('invoice');
my $invoice = $invoice-model.new-row({
customer_id => $customer.id,
amount => 400,
}); # this $invoice is NOT in the database until .update
my $old-amount = $invoice.amount; # = 400
$invoice.amount($invoice.amount * 2);
my $new-amount = $invoice.amount; # = 800
$invoice.update;
```
If there is a collision in the naming conventions between your model and the row then you'll need to use `[set|get]-column`
## Methods
### `.duplicate`
Duplicates the row omitting the `is-primary-key` field so the subsequent `.save` results in a new row rather than updating
### `.as-hash`
Returns the current field data for the row as a hash. If there has been unsaved updates to fields then it returns *those* values instead of what is in the database. You can determine whether the row has field-changes with `is-dirty`
### `.set-column(Str $key, $value)`
Updates the field data for the column (not stored in database until `.update` is called). If you want to `.wrap` a field setter for a certain key, wrap this and filter for the key
### `.get-column(Str $key)`
Retrieves the value for `$key` with any field changes having priority over data in database, use `.is-dirty`
### `.get-relation(Str $column, :%spec?)`
It is recommended any Model with a relationship name that conflicts and causes no convenience method to be generated be renamed, but use this if you must. `$customer.orders` is calling essentially `$customer.get-relation('orders')`. Do not provide `%spec` unless you know what you're doing.
### `.update`
Saves the row in the database. If the field with a positive `is-primary-key` is *set* then it runs and `UPDATE ...` statement, otherwise it `INSERT ...`s and updates the Row's `is-primary-key` field. Ensure you set one field with `is-primary-key`
## Field validation
It's just this easy:
```
has @.columns = [
qw<...>,
phone => {
type => 'text',
validate => sub ($new-value) {
# return Falsey value here for validation to fail
# Truthy value will cause validation to succeed
},
},
qw<...>,
];
```
|
## dist_zef-dwarring-Text-FriBidi.md
## Name
Text::FriBidi
## Synopsis
### Single line reordering
```
use Text::FriBidi::Line;
use Test;
plan 1;
enum ( :Shin<ש>, :Resh<ר>, :He<ה> );
my $text = "Sarah ({Shin~Resh~He})";
my Text::FriBidi::Line $line .= new: :$text;
my $visual = $line.Str;
is-deeply $visual, "Sarah ({He~Resh~Shin})";
is $line[7], He;
```
### Multiple lines reordering (experimental)
```
use Text::FriBidi::Lines;
use Test;
plan 1;
constant $LRO = "\c[LEFT-TO-RIGHT OVERRIDE]";
constant $RLO = "\c[RIGHT-TO-LEFT OVERRIDE]";
constant $PDF = "\c[POP DIRECTIONAL FORMATTING]";
@lines = "Left", "{$RLO}Right{$PDF}", "{$LRO}left{$PDF}";
my Text::FriBidi::Lines $para .= new: :@lines;
is-deeply $para.lines, ('Left', 'thgiR', 'left');
```
## Description
The Unicode standard calls for characters to be ordered 'logically', i.e. in the sequence they are intended to be interpreted, as opposed to 'visually', the sequence they appear.
The Unicode® Bidirectional Algorithm (BiDi Algorithm) is then used to reorder for visual display.
This algorithm primarily based on character detection, but also uses special BiDi control characters available for manual control.
FriBidi is a library that implements the Unicode BiDi algorithm to reorder text for visual display. This module provides Raku
bindings to FriBidi.
## Text::FriBidi::Line Methods
### new()
```
use Text::FriBidi::Defs :FriBidiType, :FriBidiFlag;
method new(
Str:D :$text!, # text, in logical order
UInt:D :$direction = FRIBIDI_TYPE_LTR, # default direction
UInt:D :$flags = FRIBIDI_FLAGS_DEFAULT +| FRIBIDI_FLAGS_ARABIC,
)
```
#### `:$text` option
Input text, in logical reading/processing order. Possibly including [Unicode BiDi control characters](https://www.w3.org/International/questions/qa-bidi-unicode-controls.en).
## Text::FriBidi::Lines Methods
### new()
```
use Text::FriBidi::Defs :FriBidiType, :FriBidiFlag;
method new(
Str:D :@lines!, # paragraph lines, in logical order
UInt:D :$direction = FRIBIDI_TYPE_LTR, # default direction
UInt:D :$flags = FRIBIDI_FLAGS_DEFAULT +| FRIBIDI_FLAGS_ARABIC,
)
```
#### `:@lines` option
Input text lines, in logical reading/processing order. Possibly including [Unicode BiDi control characters](https://www.w3.org/International/questions/qa-bidi-unicode-controls.en).
## Common Options
#### `:$flags` option
A set of 'ored` flag, including:
* `FRIBIDI_FLAG_SHAPE_MIRRORING`: Do mirroring.
* `FRIBIDI_FLAG_SHAPE_ARAB_PRES`: Shape Arabic characters to their presentation form glyphs.
* `FRIBIDI_FLAG_SHAPE_ARAB_LIGA`: Form mandatory Arabic ligatures.
* `FRIBIDI_FLAG_REMOVE_SPECIALS`: Remove Bidi marks from output
#### `:$direction` option
Base text direction; one of:
* `FRIBIDI_TYPE_LTR`: Left to right
* `FRIBIDI_TYPE_RTL`: Right to left
* `FRIBIDI_TYPE_WLTR`: Weak left to right
* `FRIBIDI_TYPE_WRTL`: Weak right to left
* `FRIBIDI_TYPE_LTR`: Left to right
* `FRIBIDI_TYPE_RTL`: Right to left
### Str()
The string, after applying any mirroring, shaping and directional ordering and with BiDi control characters removed (by default).
### AT-POS, List, Array
Methods for obtaining individual visual characters.
Note that Raku may perform its own Unicode normalizations on strings. These
methods can be used to get corresponding characters and properties.
```
use Text::FriBidi::Line;
my Text::FriBidi::Line $line .= new(:text("A\r\nB"));
say $line.Str.comb.raku; # "A", "\r\n", "B"
say $line.List.raku; # "A" "\r" "\n" "B"
say $line[3] ~ ' has type ' ~ $line.bidi-types[3];
```
## Installation
### Debian/Ubuntu Linux
```
sudo apt-get install libfribidi-dev
```
### Mac OS X
```
brew update
brew install fribidi
```
## See Also
* [UAX #9: Unicode Bidirectional Algorithm](https://unicode.org/reports/tr9/)
* [fribidi](https://github.com/fribidi/fribidi) GitHub repository
* [Text::Bidi](https://metacpan.org/pod/Text::Bidi) Perl Module
|
## dist_github-PerlGameDev-SDL.md
This module provides access to the Simple DirectMedia Layer ([www.libsdl.org](http://www.libsdl.org)) to Perl6.
It makes use of NativeCall, so a C compiler is not needed in order to install this module.
## Dependencies
* libSDL, libSDL-mixer, libSDL-image
To aid NativeCall locating the libaries you should just do:
```
sudo apt install libsdl1.2-dev libsdl-mixer1.2-dev libsdl-image1.2-dev
```
|
## dist_zef-bbkr-JSON-RPC.md
# JSON-RPC client and server for [Raku](https://www.raku.org) language
[](https://github.com/bbkr/JSON-RPC/actions/workflows/test.yml)
Supports [2.0 specification](http://www.jsonrpc.org/specification).
## CLIENT
```
use JSON::RPC::Client;
# create new client with url to server
my $c = JSON::RPC::Client.new( url => 'http://127.0.0.1:8080' );
# method without params
say $c.ping;
# method with positional params
say $c.hi( 'John Doe' );
# method with named params
say $c.hello( name => 'John Doe' );
```
## SERVER
```
use JSON::RPC::Server;
# define application class
# that will handle remote procedure calls
class My::App {
# method without params
method ping { return 'pong' }
# method with positional params
method hi ( Str $name! ) { return 'Hi ' ~ $name }
# method with named params
method hello ( Str :$name! ) { return 'Hello ' ~ $name }
# multi method with different signatures
multi method offer ( Int $age where { $age < 8 } ) {
return [ 'Toy' ];
}
multi method offer ( Int $age where { 8 <= $age <= 16 } ) {
return [ 'Computer', 'Pet' ];
}
}
# start server with your application as handler
JSON::RPC::Server.new( application => My::App ).run( );
```
Your server is now available at <http://localhost:8080>.
## ADVANCED STUFF
Examples above *make easy things easy*, now it is time to make *hard things possible*.
### Protocol versions
There are 4 specs of JSON-RPC published so far:
* [1.0](http://json-rpc.org/wiki/specification) - Not implemented. Does not support named params, error objects or batch requests and has different way of handling notifications compared to current spec. It is rarely used nowadays and because of that there are no plans to implement it, however contributions are welcome if someone wants to add backward compatibility.
* [1.1](http://web.archive.org/web/20100718181845/http://json-rpc.org/wd/JSON-RPC-1-1-WD-20060807.html) - Rejected. This working draft forces error reporting through HTTP codes making whole communication transport-dependent.
* [1.2](http://jsonrpc.org/historical/jsonrpc12_proposal.html) - Proposal of 2.0 (see below).
* [2.0](http://www.jsonrpc.org/specification) - Fully implemented!
### Can I use URI object to initialize client?
Use `uri` param in constructor.
```
JSON::RPC::Client.new( uri => URI.new( 'http://127.0.0.1:8080' ) );
```
### Can I bind server to port other than 8080?
Use `port` param in `run( )` method.
```
JSON::RPC::Server.new( application => My::App ).run( port => 9999 );
```
### Should I use class name or object instance as server handler?
You can use both. Using class name results in static dispatch while using object instance allows you to initialize attributes in your class.
```
class My::App {
has $!db;
submethod BEGIN { $!db = ... } # connect to database
method ping ( ) { return 'pong' }
}
# BEGIN is not called
JSON::RPC::Server.new( application => My::App ).run( );
# BEGIN is called
JSON::RPC::Server.new( application => My::App.new ).run( );
```
### How can method be excluded from server handler dispatch?
Declare it as private.
```
method !get_database_info ( ) {
return 'username', 'password';
}
```
### Should I declare signatures for server handler methods?
It is recommended that you validate params in signatures instead of method bodies. This way server correctly returns "Invalid params" error (more info later) and method is not called if signature does not match - you can easily separate validation from logic.
```
method add_programmer (
Str :$name!,
Int :$age! where { $age >= 0 },
Int :$experience! where { $experience <= $age }
) {
# params can be trusted here
# all fields are required and
# negative age or experience exceeding age shall not pass
$!db.insert( $name, $age, $experience );
}
```
### What happens when more than one server handler candidate matches?
When request can be dispatched to more than one multi method then first candidate is chosen and called. JSON-RPC protocol design does not include multi methods - it can not mimic [calling sets](https://docs.raku.org/language/operators#methodop_.*) mechanism and does not have "Ambiguous call" error in specification like Raku does. Therefore such request is not considered an error.
### Can I use my own transport layers?
This is useful when you want to use JSON-RPC on some framework which provides its own data exchange methods. It is even possible to use JSON-RPC over protocols different than HTTP.
**Client**
Pass `transport` param to `new( )` instead of `uri`/ `url` param. This should be a closure that accepts JSON request and returns JSON response.
```
sub transport ( Str :$json, Bool :$get_response ) {
return send_request_in_my_own_way_and_obtain_response_if_needed( $request );
}
my $client = JSON::RPC::Client.new( transport => &transport );
```
Your transport will be given extra param `get_response` which informs if response is expected from the server or not (for example in case of Notification or Batch of Notifications).
**Server**
Do not `run( )` server. Instead use `handler( )` method which takes JSON request param and returns JSON response.
```
my $server = JSON::RPC::Server.new( application => My::App );
my $response = handler( json => receive_request_in_my_own_way( ) );
send_response_in_my_own_way( $_ ) with $response;
```
It is possible that request is a Notification or Batch of Notifications and `$response` is not returned from the server.
**Notifications**
When request is a Notification or Batch of Notifications then client is not expecting response and server should not return one. That is not always possible due to specification of used protocol or assumptions in framework used. In this case try to use most un:!canonicalize response possible.
For example code `204 No Content` should be used in HTTP transport.
### How to enable debugging?
**Client** has no debugging yet.
**Server** accepts `debug` param in `run( )` method.
```
JSON::RPC::Server.new( application => My::App ).run( :debug );
```
### How to implement Error handling?
Errors :!canonicalize in 2.0 spec are represented by `X::JSON::RPC` exceptions:
* `X::JSON::RPC::ParseError` - Invalid JSON was received by the server.
* `X::JSON::RPC::InvalidRequest` - The structure sent by client is not a valid Request object.
* `X::JSON::RPC::MethodNotFound` - The method does not exist in server handler application.
* `X::JSON::RPC::InvalidParams` - Invalid method parameters, no handler candidates with matching signature found.
* `X::JSON::RPC::InternalError` - Remote method died.
* `X::JSON::RPC::ProtocolError` - Other deviation from specification.
Every exception has numeric `code` attribute that indicates the error type that occurred, text `message` attribute that provides a short description of the error and optional `data` attribute that contains additional information about the error.
**Client** can catch those exceptions.
```
try {
$c.hello( 'John Doe' );
CATCH {
when X::JSON::RPC::MethodNotFound {
say 'Server is rude';
}
default {
# stringified exception is in human-readable form
say ~$_;
}
}
}
```
**Server** does all the exception handling automatically. For example if you provide application handler without some method client will receive "Method not found" error on call to this method. However if you want to report error from method it can be done in two ways.
* End method using die.
```
method divide ( Int $x, Int $y ) {
die 'Cannot divide by 0' if $y ~~ 0;
return $x / $y;
}
```
Client will receive `message` attribute "Internal error" with explanation "Cannot divide by 0" as `data` attribute.
* Throw `X::JSON::RPC` exception.
```
class My::App {
method treasure {
X::JSON::RPC.new( code => -1, message => 'Access denied', data => 'Thou shall not pass!' ).throw( );
}
}
```
Exception `X::JSON::RPC` is composable so you can easily define your own errors.
```
class My::Error does X::JSON::RPC {
method new {
self.bless( code => -1, message => 'Access denied', data => 'Thou shall not pass!' );
}
}
```
And use them in application handler.
```
method treasure {
My::Error.new.throw( );
}
```
### How to make Notification call?
Method `'rpc.notification'( )` puts client in notification context.
Note that this method contains dot in name and it must be quoted.
```
$client.'rpc.notification'( ).heartbeat( ); # no response from this one
say $client.ping( ) # regular call again
```
You can save client context to avoid typing.
```
my $n = $client.'rpc.notification'( );
for ^1024 {
$n.heartbeat( ); # no responses from those
}
```
### How to make Batch call?
Method `'rpc.batch'( )` puts client in batch context while method `'rpc.flush'( )` sends Requests.
Note that those methods contain dot in names and they must be quoted.
```
$client.'rpc.batch'( ).add( 2, 2 );
$client.'rpc.batch'( ).'rpc.notification'( ).heartbeat( );
$client.'rpc.batch'( ).suicide( );
for $client.'rpc.flush'( ) -> $response {
try {
$response.say;
CATCH {
when X::JSON::RPC {
say 'Oops! ', .message;
}
}
}
}
# Output:
# 4
# Opps! Suicide served.
```
Important things to remember:
* Server may process methods in Batch in any order and with any width of parallelism.
* Client will sort responses to match order in which methods were stacked.
* Notifications do not have corresponding response.
* Batch containing only Notifications will return Nil on flush.
* Attempt to flush empty Batch will result in `X::JSON::RPC::InvalidRequest` exception.
* Individual exceptions are returned as Failures, thrown when called in sink context.
You can save client context to avoid typing.
```
my $b = $client.'rpc.batch'( );
for ^1024 {
$b.is_prime( $_ );
}
my @responses = $b.'rpc.flush'( );
```
### How to call method that has name used by language itself?
Every object instance has some methods inherited from [Mu](https://docs.raku.org/type/Mu) and [Any](https://docs.raku.org/type/Any) classes.
This rule also applies to `JSON::RPC::Client` and in rare cases you may fall into the trap.
Below example calls `Mu::can( )` instead of doing remote procedure call of method named "can".
```
$client.can( 'tuna' );
```
The workaround is to prefix method name with `rpc.`.
Note that whole name must be quoted because it contains dot.
```
$client.'rpc.can'( 'tuna' );
```
You can get full list of those troublemakers by invoking following code.
```
JSON::RPC::Client.^mro>>.^methods>>.say
```
|
## grammar.md
class Grammar
Formal grammar made up of named regexes
```raku
class Grammar is Match {}
```
Every type declared with `grammar`, and not explicitly stating its superclass, becomes a subclass of `Grammar`.
```raku
grammar Identifier {
token TOP { <initial> <rest>* }
token initial { <+myletter +[_]> }
token rest { <+myletter +mynumber +[_]> }
token myletter { <[A..Za..z]> }
token mynumber { <[0..9]> }
}
say Identifier.isa(Grammar); # OUTPUT: «True»
my $match = Identifier.parse('W4anD0eR96');
say ~$match; # OUTPUT: «W4anD0eR96»
```
More [documentation on grammars](/language/grammars) is available.
# [Methods](#class_Grammar "go to top of document")[§](#Methods "direct link")
## [method parse](#class_Grammar "go to top of document")[§](#method_parse "direct link")
```raku
method parse($target, :$rule = 'TOP', Capture() :$args = \(), Mu :$actions = Mu, *%opt)
```
Parses the `$target`, which will be coerced to [`Str`](/type/Str) if it isn't one, using `$rule` as the starting rule. Additional `$args` will be passed to the starting rule if provided.
```raku
grammar RepeatChar {
token start($character) { $character+ }
}
say RepeatChar.parse('aaaaaa', :rule('start'), :args(\('a')));
say RepeatChar.parse('bbbbbb', :rule('start'), :args(\('b')));
# OUTPUT:
# 「aaaaaa」
# 「bbbbbb」
```
If the `actions` named argument is provided, it will be used as an actions object, that is, for each successful regex match, a method of the same name, if it exists, is called on the actions object, passing the match object as the sole positional argument.
```raku
my $actions = class { method TOP($/) { say "7" } };
grammar { token TOP { a { say "42" } b } }.parse('ab', :$actions);
# OUTPUT: «427»
```
Additional named arguments are used as options for matching, so you can for example specify things like `:pos(4)` to start parsing from the fifth (:pos is zero-based) character. All [matching adverbs](/language/regexes#Adverbs) are allowed, but not all of them take effect. There are several types of adverbs that a regex can have, some of which apply at compile time, like `:s` and `:i`. You cannot pass those to `.parse`, because the regexes have already been compiled. But, you can pass those adverbs that affect the runtime behavior, such as `:pos` and `:continue`.
```raku
say RepeatChar.parse('bbbbbb', :rule('start'), :args(\('b')), :pos(4)).Str;
# OUTPUT: «bb»
```
Method `parse` only succeeds if the cursor has arrived at the end of the target string when the match is over. Use [method subparse](/routine/subparse) if you want to be able to stop in the middle.
The top regex in the grammar will be allowed to backtrack.
Returns a [`Match`](/type/Match) on success, and [`Nil`](/type/Nil) on failure.
## [method subparse](#class_Grammar "go to top of document")[§](#method_subparse "direct link")
```raku
method subparse($target, :$rule = 'TOP', Capture() :$args = \(), Mu :$actions = Mu, *%opt)
```
Does exactly the same as [method parse](/routine/parse), except that cursor doesn't have to reach the end of the string to succeed. That is, it doesn't have to match the whole string.
Note that unlike [method parse](/routine/parse), `subparse` *always* returns a [`Match`](/type/Match), which will be a failed match (and thus falsy), if the grammar failed to match.
```raku
grammar RepeatChar {
token start($character) { $character+ }
}
say RepeatChar.subparse('bbbabb', :rule('start'), :args(\('b')));
say RepeatChar.parse( 'bbbabb', :rule('start'), :args(\('b')));
say RepeatChar.subparse('bbbabb', :rule('start'), :args(\('a')));
say RepeatChar.subparse('bbbabb', :rule('start'), :args(\('a')), :pos(3));
# OUTPUT:
# 「bbb」
# Nil
# #<failed match>
# 「a」
```
## [method parsefile](#class_Grammar "go to top of document")[§](#method_parsefile "direct link")
```raku
method parsefile(Str(Cool) $filename, :$enc, *%opts)
```
Reads file `$filename` encoding by `$enc`, and parses it. All named arguments are passed on to [method parse](/routine/parse).
```raku
grammar Identifiers {
token TOP { [<identifier><.ws>]+ }
token identifier { <initial> <rest>* }
token initial { <+myletter +[_]> }
token rest { <+myletter +mynumber +[_]> }
token myletter { <[A..Za..z]> }
token mynumber { <[0..9]> }
}
say Identifiers.parsefile('users.txt', :enc('UTF-8'))
.Str.trim.subst(/\n/, ',', :g);
# users.txt :
# TimToady
# lizmat
# jnthn
# moritz
# zoffixznet
# MasterDuke17
# OUTPUT: «TimToady,lizmat,jnthn,moritz,zoffixznet,MasterDuke17»
```
# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")
Type relations for `Grammar`
raku-type-graph
Grammar
Grammar
Match
Match
Grammar->Match
Mu
Mu
Any
Any
Any->Mu
Capture
Capture
Capture->Any
Cool
Cool
Cool->Any
Match->Capture
Match->Cool
[Expand chart above](/assets/typegraphs/Grammar.svg)
|
## dist_zef-raku-community-modules-Concurrent-Queue.md
[](https://github.com/raku-community-modules/Concurrent-Queue/actions) [](https://github.com/raku-community-modules/Concurrent-Queue/actions) [](https://github.com/raku-community-modules/Concurrent-Queue/actions)
# NAME
Concurrent::Queue - A lock-free concurrent queue data structure
# SYNOPSIS
```
use Concurrent::Queue;
my $queue = Concurrent::Queue.new;
$queue.enqueue('who');
$queue.enqueue('what');
$queue.enqueue('why');
say $queue.dequeue; # who
say ?$queue; # True
say $queue.elems; # 2
say $queue.Seq; # (what why)
say $queue.list; # (what why)
say $queue.dequeue; # what
$queue.enqueue('when');
say $queue.dequeue; # why
say $queue.dequeue; # when
say ?$queue; # False
say $queue.elems; # 0
my $val = $queue.dequeue;
say $val.WHO; # Failure
say $val.exception.WHO; # X::Concurrent::Queue::Empty
```
# DESCRIPTION
Lock-free data structures may be safely used from multiple threads, yet do not use locks in their implementation. They achieve this through the use of atomic operations provided by the hardware. Nothing can make contention between threads cheap - synchronization at the CPU level is still synchronization - but lock-free data structures tend to scale better.
This lock-free queue data structure implements an [algorithm described by Maged M. Michael and Michael L. ScottL](https://www.cs.rochester.edu/u/scott/papers/1996_PODC_queues.pdf). The only (intended) differences are:
* A `Failure` is returned to indicate emptiness, rather than a combination of boolean return value and out parameter, in order that this type feels more natural to Raku language users
* There is an out-of-band element count (which doesn't change the algorithm at all, just increments and decrements the count after an enqueue/dequeue)
* Raku doesn't need ABA-problem mitigation thanks to having GC
The `elems` and `Bool` method should not be used to decide whether to dequeue, unless it is known that no other thread could be performing an enqueue or dequeue at the same time. Their only use in the presence of concurrent use of the queue is for getting an approximate idea of queue size. In the presence of a single thread, the element count will be accurate (so if many workers were to enqueue data, and are known to have completed, then at that point the `elems` will be an accurate reflection of how many values were placed in the queue).
Note that there is no blocking dequeue operation. If looking for a blocking queue, consider using the Raku built-in `Channel` class. (If tempted to write code that sits in a loop testing if `dequeue` gives back a `Failure` - don't. Use `Channel` instead.)
# METHODS
## enqueue(Any $value)
Puts the value into the queue at its tail. Returns `Nil`.
## dequeue()
If the queue is not empty, removes the head value and returns it. Otherwise, returns a `Failure` containing an exception of type `X::Concurrent::Queue::Empty`.
## elems()
Returns the number of elements in the queue. This value can only be relied upon when it is known that no threads are interacting with the queue at the point this method is called. **Never** use the result of `elems` to decide whether to `dequeue`, since another thread may `enqueue` or `dequeue` in the meantime. Instead, check if `dequeue` returns a `Failure`.
## Bool()
Returns `False` if the queue is empty and `True` if the queue is non-empty. The result can only be relied upon when it is known that no other threads are interacting with the queue at the point this method is called. **Never** use the result of `Bool` to decide whether to `dequeue`, since another thread may `enqueue` or `dequeue` in the meantime. Instead, check if `dequeue` returns a `Failure`.
## Seq
Returns a `Seq` that will iterate the queue contents. The iteration will include all values that had not been dequeued at the point the `Seq` method was called. Additionally, it will incorporate any values that are enqueued during the iteration, meaning that if values are being enqueued at a rate at least as fast as the iteration is visiting them then the iteration may not terminate.
If wanting to prevent this, consider limiting the result length to that of the result of `elems` (e.g. `$cq.head($cq.elems)`). If using the queue to collect values in many threads and then iterate them in one thread afterwards, this is not a concern, since nothing will be enqueueing further values at that point. However, consider using `Concurrent::Stack` instead, since a concurrent stack's operations are cheaper than those of a concurrent queue (the same algorithmic order, but a lower constant factor).
## list
Equivalent to `.Seq.list`; see the description of `Seq` for caveats, and remember that a `List` preserves its elements, so the potentially endless iteration could also eat endless memory.
# AUTHOR
Jonathan Worthington
# COPYRIGHT AND LICENSE
Copyright 2018 - 2022 Jonathan Worthington
Copyright 2024 Raku Community
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_cpan-PMQS-IO-Compress.md
```
IO-Compress
Version 2.094
13 July 2020
Copyright (c) 1995-2020 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it
and/or modify it under the same terms as Perl itself.
DESCRIPTION
-----------
This distribution provides a Perl interface to allow reading and writing of
compressed data created with the zlib and bzip2.
IO-Compress supports reading and writing of the following compressed data formats
* bzip2
* RFC 1950
* RFC 1951
* RFC 1952 (i.e. gzip)
* zip
There are a number of companion modules for IO-Compress that extend
the suite of compression formats available.
* IO-Compress-Lzma
Adds support for lzma, xz and lzip.
* IO-Compress-Lzf
Adds support for lzf.
* IO-Compress-Lzop
Adds support for lzop.
Note that the following modules used to be distributed separately, but are now
included with the IO-Compress distribution.
Compress-Zlib
IO-Compress-Zlib
IO-Compress-Bzip2
IO-Compress-Base
PREREQUISITES
-------------
Before you can build IO-Compress you need to have the following
installed on your system:
* Perl 5.006 or better.
* Compress::Raw::Zlib
* Compress::Raw::Bzip2
BUILDING THE MODULE
-------------------
Assuming you have met all the prerequisites, the module can now be built
using this sequence of commands:
perl Makefile.PL
make
make test
INSTALLATION
------------
To install IO-Compress, run the command below:
make install
TROUBLESHOOTING
---------------
SUPPORT
-------
General feedback/questions/bug reports should be sent to
https://github.com/pmqs/IO-Compress/issues (preferred) or
https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress.
FEEDBACK
--------
How to report a problem with IO-Compress.
To help me help you, I need all of the following information:
1. The Versions of everything relevant.
This includes:
a. The *complete* output from running this
perl -V
Do not edit the output in any way.
Note, I want you to run "perl -V" and NOT "perl -v".
If your perl does not understand the "-V" option it is too
old. This module needs Perl version 5.004 or better.
b. The version of IO-Compress you have.
If you have successfully installed IO-Compress, this one-liner
will tell you:
perl -MIO::Compress::Gzip -e 'print qq[ver $IO::Compress::Gzip::VERSION\n]'
If you are running windows use this
perl -MIO::Compress::Gzip -e "print qq[ver $IO::Compress::Gzip::VERSION\n]"
If you haven't installed IO-Compress then search IO::Compress::Gzip.pm
for a line like this:
$VERSION = "2.094" ;
2. If you are having problems building IO-Compress, send me a
complete log of what happened. Start by unpacking the IO-Compress
module into a fresh directory and keep a log of all the steps
[edit config.in, if necessary]
perl Makefile.PL
make
make test TEST_VERBOSE=1
Paul Marquess
```
|
## dist_zef-rbt-Net-DNS.md
# Net::DNS
A simple DNS resolver.
Note: If you are behind a firewall that blocks Google DNS, you will need to set
DNS\_TEST\_HOST in your environment to pass the tests.
## Example Usage
```
my $resolver = Net::DNS.new('8.8.8.8'); # google dns server
my @mx-ips = $resolver.lookup-mx('gmail.com');
my @all = $resolver.lookup-ips('google.com');
my @ipv4 = $resolver.lookup-ips('google.com', :inet);
my @ipv6 = $resolver.lookup-ips('google.com', :inet6);
my @dns-answers = $resolver.lookup('A', 'google.com'); # ("1.2.3.4", "5.6.7.8", ...)
```
## Methods
* `new(Str $host, $socket = IO::Socket::INET)`
Creates a new DNS resolver using the specified DNS server.
The `$socket` parameter lets you inject your own socket class to use for the
query (so you can do a proxy negotiation or somesuch first).
* `lookup-ips(Str $name, :$inet, :$inet6)`
Looks up the specified $name, looking for A and AAAA records (only searches
for A when :inet is specified, and only searches for AAAA when :inet6 is
specified). Will chase down CNAME records to get you the actual IP
addresses. Will return a list of A and AAAA responses.
* `lookup-mx(Str $name, :$inet, :$inet6)`
Does a lookup for MX records, and then internally calls `lookup-ips` to
find the actual addresses for the mailservers. Returns a list of A and AAAA
records, in MX priority order.
* `lookup(Str $type, Str $name)`
Looks up the specified $name, looking for records of $type. Returns a list of
response classes, specified below. A failed lookup returns an empty list.
## Supported DNS Types
The return of a lookup is a list of classes. Which class depends on the request
type.
The object returned will stringify to something useful, and will also provide
attributes to access each piece of information that was returned.
Note that all of these classes also have a `@.owner-name` attribute. Normally this
is the same as the domain name you did the lookup on.
* `A`
Returns a class with attribute `@.octets`, which will have 4 elements.
Stringifies to an ip address ("192.168.0.1")
* `AAAA`
Returns a class with attribute `@.octets`, which will have 16 elements.
Stringifies to an ipv6 address ("2607:f8b0:…")
* `CNAME`
Returns a class with attribute `@.name`, which is a domain name split on '.'.
To get the full domain name, call $object.name.join('.');
Stringifies to a domain name.
* `MX`
Returns a class with attributes `$.priority`, `@.name`.
Stringifies to a domain name.
* `NS`
Returns a class with attribute `@.name`
Stringifies to a domain name.
* `PTR`
Returns a class with attribute `@.name`
Stringifies to a domain name.
* `RRSIG`
Returns a class with attributes `$.type-covered`, `$.algorithm`,
`$.labels`, `$.original-ttl`, `$.signature-expiration`,
`$.signature-inception`, `$.key-tag`, `$.signer-name`, and
`$.signature`.
Stringifies to a a string with similar output to the output produced
by the `dig` command line utility.
Note that this module does not validate the validity of a DNSSEC signature.
* `SRV`
Returns a class with the attributes `$.priority`, `$.weight`, `$.port`, `@.name`.
Stringifies to "the.server:port".
* `SPF`
Returns a class with the attribute `$.text`
Stringifies to the text
* `TXT`
Returns a class with the attribute `$.text`
Stringifies to the text
* `SOA`
Returns a class with the attributes `@.mname`, `@.rname`, `$.serial`, `$.refresh`,
`$.retry`, `$.expire`, `$.minimum`
Stringifies to a format similar to nslookup
* `AXFR`
Zone transfer request.
This is a special case - it returns a list of the above objects instead of it's
own response type.
## Exceptions
DNS Server errors will produce a Failure response on lookup(), lookup-ips(), and lookup-mx() with an X::Net::DNS object.
* server-message
A complete Net::DNS::Message structured response from the server.
* rcode-value
Return code Integer received from the DNS server.
* rcode-name
[Return code name](https://support.umbrella.com/hc/en-us/articles/232254248-Common-DNS-return-codes-for-any-DNS-service-and-Umbrella-)
received from the DNS server. Common values are SERVFAIL and NXDOMAIN.
* message
A short english message which might be shown to users.
|
## dist_cpan-GDONALD-BDD-Behave.md
## Behave
A behavior driven development framework written in [Perl 6](https://perl6.org/).
Currently developed against Rakudo `v6.d`.
#### Install using zef
```
zef install BDD::Behave
```
#### Running Behave:
If a file is not specificed Behave will automatically look for a `specs` directory and will run anything matching `/spec.p6/`.
#### An example:
**specs/001-spec.p6**
```
use BDD::Behave;
describe -> 'this spec' {
it -> 'passes' {
expect(42).to.be(42);
}
}
describe -> 'this final spec' {
it -> 'fails at line 12' {
expect(42).to.be(41);
}
}
```
You can run the spec like this:
```
$ behave specs/001-spec.p6
```
Output:
```
specs/001-spec.p6
⮑ 'this spec'
⮑ 'passes'
⮑ SUCCESS
⮑ 'this final spec'
⮑ 'fails at line 12'
⮑ FAILURE
Failures:
[ ✗ ] specs/001-spec.p6:12
```
#### Status
[](https://travis-ci.org/gdonald/BDD-Behave)
#### Documentation
No docs yet, see the examples in [specs/\*](https://github.com/gdonald/BDD-Behave/tree/master/specs).
#### License
Behave is released under the [Artistic License 2.0](https://opensource.org/licenses/Artistic-2.0)
|
## twigil.md
class X::Syntax::Variable::Twigil
Compilation error due to an unallowed twigil in a declaration
```raku
class X::Syntax::Variable::Twigil does X::Syntax { }
```
Syntax error thrown when a variable with a twigil is used in an incompatible declaration.
For example
```raku
my $!foo;
```
dies with
「text」 without highlighting
```
```
===SORRY!===
Cannot use ! twigil on my variable
```
```
# [Methods](#class_X::Syntax::Variable::Twigil "go to top of document")[§](#Methods "direct link")
## [method twigil](#class_X::Syntax::Variable::Twigil "go to top of document")[§](#method_twigil "direct link")
```raku
method twigil(--> Str:D)
```
Returns the twigil that was illegally used
## [method scope](#class_X::Syntax::Variable::Twigil "go to top of document")[§](#method_scope "direct link")
```raku
method scope(--> Str:D)
```
Returns the scope that did not harmonize with the twigil.
|
## distribution.md
role Distribution
Distribution
```raku
role Distribution { }
```
This role is an interface for objects that provide API access mapping META6 data to the files it represents. Objects that fulfill the `Distribution` role can be read by e.g. [`CompUnit::Repository::Installation`](/type/CompUnit/Repository/Installation). Generally a `Distribution` provides read access to a set of modules and metadata. These may be backed by the filesystem ([`Distribution::Path`](/type/Distribution/Path), [`Distribution::Hash`](/type/Distribution/Hash)) but could also read from an e.g. tar file or socket.
# [Required Methods](#role_Distribution "go to top of document")[§](#Required_Methods "direct link")
## [method meta](#role_Distribution "go to top of document")[§](#method_meta "direct link")
```raku
method meta(--> Hash:D) { ... }
```
Returns a Hash with the representation of the metadata. Please note that an actual `META6.json` file does not need to exist, just a representation in that format.
## [method content](#role_Distribution "go to top of document")[§](#method_content "direct link")
```raku
method content($name-path --> IO::Handle:D) { ... }
```
Returns an [`IO::Handle`](/type/IO/Handle) to the file represented by `$name-path`. `$name-path` is a relative path as it would be found in the metadata such as `lib/Foo.rakumod` or `resources/foo.txt`.
# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")
Type relations for `Distribution`
raku-type-graph
Distribution
Distribution
Distribution::Locally
Distribution::Locally
Distribution::Locally->Distribution
Mu
Mu
Any
Any
Any->Mu
Distribution::Path
Distribution::Path
Distribution::Path->Distribution::Locally
Distribution::Path->Any
Distribution::Hash
Distribution::Hash
Distribution::Hash->Distribution::Locally
Distribution::Hash->Any
[Expand chart above](/assets/typegraphs/Distribution.svg)
|
## dist_zef-witawayar-Slang-Forgiven.md
## Slang::Forgiven
When a for loop meets a given statement
```
use Slang::Forgiven;
# `$num` as well as `$_` are available in the loop body
forgiven [2, -3, 4, -5] -> $num {
# `$_` is aliased to `$num`, so `when` will know
when * > 0 { put "$num is positive" }
when * < 0 { put "$num is negative" }
default { put "neutral" }
}
```
### What
A for loop with a parametrized block lets you iterate over things with names, and a given statement allows for topicalization. The "forgiven" statement does both: you have the usual looping but also have `$_` available.
That is,
```
for @values -> $val {
given $val {
when * > 0 { "$val is positive" }
...
}
}
```
is possible as
```
forgiven @values -> $val {
when * > 0 { "$val is positive" }
...
}
```
i.e., it's as if `$_ := $val` is placed immediately after the opening curly bracket. Arrays, Hashes, their destructuring, optional and/or typed parameters are possible, too; examples for them can be found in the "t/" directory.
### Why
"For fun" should be enough but this also came up in at least 2 places:
* "habere-et-disper" (~"tire") [on IRC](https://irclogs.raku.org/raku-beginner/2022-11-10.html#10:26) mentions the "-Ofun idea of `forgiven`"
* "VZ." asks about an "elegant way to write when inside a for loop" [on StackOverflow](https://stackoverflow.com/questions/75186531)
I thank "habere-et-dispertire" for the idea; this arose from their message(s). They informed me that "deoac" on [exercism](https://exercism.org/tracks/raku) had mentioned it originally; so thanks to them as well! I also thank Damian Conway for their [for-else](https://blogs.perl.org/users/damian_conway/2019/09/itchscratch.html) writing (as well as the numerous presentations online that leave me amazed).
### How
Grammar follows that of the "for" loop. Actions first gather the parameter names of the block of the loop, and then unshift the `$_ := ...` statement (a "bind" QAST::Op) to the AST of the statement list of the block.
#### Installation
Using [pakku](https://github.com/hythm7/Pakku):
```
git clone https://github.com/mustafaaydn/Slang-Forgiven.git && cd "$(basename "$_" .git)"
pakku add . && cd .. && rm -rf Slang-Forgiven
```
|
## dist_github-cbk-WebService-GoogleDyDNS.md
# WebService::DyDNS [Build Status](https://travis-ci.org/cbk/WebService-GoogleDyDNS)
## SYNOPSIS
Simple web service used to update an IP address on domains.google.com if the current one has changed.
Obtains current IP address using the WebService::HazIP module, then compares the results with the IP
address that was set the last time the service was ran. It there was a change, the updateIP() method
is then called to update the IP address using the HTTP::UserAgent module.
## TODO
* Maybe POST request would be better
## Methods
* checkPreviousIP()
* updateIP()
## Returns
* One of the response codes from domains.google.com
* "No change. No action taken."
## Example usage:
```
use v6;
use WebService::GoogleDyDNS;
multi sub MAIN( :$domain, :$login, :$password ) {
my $updater = WebService::GoogleDyDNS.new(domainName => $domain, login => $login , password => $password );
$updater.checkPreviousIP();
if $updater.outdated { say $updater.updateIP(); } else { say "No change. No action taken."; }
}
```
|
## dist_zef-lizmat-HTML-Entity-Fast.md
[](https://github.com/lizmat/HTML-Entities-Fast/actions) [](https://github.com/lizmat/HTML-Entities-Fast/actions) [](https://github.com/lizmat/HTML-Entities-Fast/actions)
# NAME
HTML::Entity::Fast - Encode / Decode HTML entities faster
# SYNOPSIS
```
use HTML::Entity::Fast;
say encode-html-entities '<ent> & ©'; # <ent> & ©
say decode-html-entities '<ent> & ©'; # <ent> & ©
my $w-encode = whitelist-in-encode("<",">");
say encode-html-entities '<ent> & ©', $w-encode; # <ent> & ©
my $w-decode = whitelist-in-decode('&');
say decode-html-entities '<ent> & ©', $w-decode; # <ent> & ©
```
# DESCRIPTION
HTML::Entity::Fast provides subroutines for encoding and decoding HTML entities in a string.
# SUBROUTINES
## encode-html-entities
```
say encode-html-entities '<ent> & ©'; # <ent> & ©
my $w-encode = whitelist-in-encode("<",">");
say encode-html-entities '<ent> & ©', $w-encode; # <ent> & ©
```
Encode any special characters in a given string to their HTML entity counterpart. Optionally takes a second argument indicating the exact mapping to be used (which is usually the result of a call to the `whitelist-in-encode` subroutine).
## decode-html-entities
```
say decode-html-entities '<ent> & ©'; # <ent> & ©
my $w-decode = whitelist-in-decode('&');
say decode-html-entities '<ent> & ©', $w-decode; # <ent> & ©
```
Decode any HTML entities in a given string to their Unicode counterpart. Optionally takes a second argument indicatig the exact mapping to be used (which is usually the result of a call to the `whitelist-in-decode` subroutine).
## whitelist-in-encode
```
my $w-encode = whitelist-in-encode("<",">");
```
The `whitelist-in-encode` subroutine takes any number of arguments, each indicating a character that should **not** be converted by the `encode-html-entities` subroutine. It returns a lookup map that can be specified as the second positional argument to `encode-html-entities`.
## whitelist-in-decode
```
my $w-decode = whitelist-in-decode('&');
```
The `whitelist-in-decode` subroutine takes any number of arguments, each indicating a HTML entity that should **not** be converted by the `decode-html-entities` subroutine. It returns a lookup map that can be specified as the second positional argument to `decode-html-entities`.
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
Source can be located at: <https://github.com/lizmat/HTML-Entity-Fast> . 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_cpan-JNTHN-Cro-APIToken.md
# Cro::APIToken
This is part of the Cro libraries for implementing services and distributed
systems in Raku. See the [Cro website](http://cro.services/) for further
information and documentation.
|
## dist_cpan-VRURG-IP-Addr.md
# NAME
IP::Addr - dealing with IPv4/IPv6 addresses
# SYNOPSIS
```
my $cidr = IP::Addr.new( "192.0.2.2/27" );
say $cidr;
say $cidr.ip;
for $cidr.network.each -> $ip {
say $ip;
}
my $cidr6 = IP::Addr.new( "600d::f00d/123" );
say $cidr6;
say $cidr6.ip;
```
# DESCRIPTION
This module provides functionality for working with IPv4/IPv6 addresses.
## Module Structure
The main interface is provided by `IP::Addr` class. Typical class usage is demonstrated in the synopsis. The class is a frontend which tries to determine version of the IP address provided to its constructor and creates corresponding handler object available on its `handler` attribute. All methods of the handler are available on `IP::Addr` object via `handles` trait.
For example, for an arbitrary `$ip` object of the class `$ip.ip` call is actually same as calling `$ip.handler.ip`. Method `ip` is a universal one for both v4 and v6 addresses and therefore it is not necessary to care about what exact kind of object we're currently dealing with.
Similarly, version-dependant methods are available too but only when corresponding handler is active. For example:
```
say IP::Addr.new( "192.0.2.2/27" ).broadcast;
```
is a valid call; while
```
say IP::Addr.new( "2001:db8::/123" ).broadcast;
```
will fail with "no method" exception because `broadcast` is not available for IPv6 addresses.
## Glossary
### Address forms
Besides of its version each IP address has one more characteristic property: form. It is defined by handler's attribute of the same name: `$!form`. Particular forms are defined by IP-FORM enum defined in `IP::Addr::Common`:
* *ip*
Simple IP address. It has prefix length of 32 bits.
* *cidr*
CIDR form is an IP address with *prefix* defined.
```
192.0.2.3/24
192.0.2.3/255.255.255.0
2001::/64
```
* *range*
A range is defined by its first and last IP addresses. It has a *selected* or *current* IP address which could be changed as a result of increase, decrease, or iteration operations.
```
192.0.2.3-192.0.2.20
2001::1-2001::1f
```
### Ranged forms
CIDR and ranges are *ranged forms* contrary to a single IP form.
### N-tets
As it is known IP addresses are represented by groups of integers called *octets* for IPv4 and *hextets* for IPv6 (there are variations but I chose these two). *N-tets* is used as a general term for both of them.
# METHODS
## Constructor
Class constructor `new` simply re-dispatches its arguments to method `set`.
## `set`
* *`$ip.set( Str $source )` / `$ip.set( Str :$source! )`*
`$source` is a string representation of an IP address in either plain or CIDR notation, or of a range of addresses in a form \*- \*. Formats of valid IP addresses are defined by corresponding standards.
* *`$ip.set( [ :v4 | :v6 ], *%params )`*
Creates a handler object of specified version of handler (v4 or v6) by passing named `%params` to its constructor.
For example, the following statement:
```
$ip.set( :v4, ip => 3221225986, prefix-len => 24 )
```
Is equivalent to:
```
$ip.set( "192.0.2.2/24" )
```
**Note:** all calls to `set` method result in creation of a new handler object. I.e.:
```
my $old-handler = $ip.handler;
$ip.set( ... );
say $old-handler === $ip.handler; # False
```
## `Str`
Returns a valid string representation of the IP object.
## `gist`
Same as `Str` method.
## `each`
Returns an iterable object which would iterate over IPs contained in the current object starting with selected address (i.e. the one returned by `ip` method). For ranged forms to iterate over the whole range (from the `first-ip` to the `last-ip`) use of method `first` is recommended:
```
.say for IP::Addr.new( "192.0.2.3/29" ).each; # 192.0.2.3/29\n192.0.2.4/29 ...
.say for IP::Addr.new( "192.0.2.3/29" ).first.each; # 192.0.2.0/29\n192.0.2.1/29 ...
```
## `Supply`
Similar to `each` method but returns a `Supply` object. Same rule about starting with selected IP and use of `first` method apply.
# HANDLER METHODS
This sections documents methods common for both IPv4 and IPv6 handlers.
## Notes
For all methods accepting another IP address as a parameter and where descriptions has a statement *"same version only"* `X::IPAddr::TypeCheck` exception would be thrown if object with a handler of different version is passed.
Address method parameters could either be `IP::Addr` instances or string representations.
## `set`
Configures the handler object.
**Note** In the following subsection `$handler` notation is used instead of `$ip.handler`.
* *`$handler.set( Str:D $source )` / `$handler.set( Str:D :$source! )`*
Handler attributes are set by parsing a string representation of IP address.
* *`$handler.set( Int:D :$ip!, Int:D :$!prefix-len )`*
Configures handler object as *CIDR* form.
* *`$handler.set( Int:D :$first!, Int:D :$!last, Int :$ip? )`*
Configures handler object as *range* form. Optional named parameter `:ip` defines selected IP within range (i.e. the one returned by `ip` method). If omitted then range initial selected IP is its first address.
* *`$handler.set( Int:D $ip! )`*
Configures a single IP form.
* *`$handler.set( Int:D @n-tets )`*
Configures a single IP form from integer octets for IPv4 or hextets for IPv6. Number of elements in @n-tets array is defined by the method of the same name.
## `addr-len`
Returns number of bits for correponding IP version (*32* for IPv4 and *128* for IPv6).
## `n-tets`
Returns number of n-tets for the current handler (*4* for IPv4 and *8* for IPv6).
## `version`
Returns integer version of the IP object (*4* or *6*).
## `ip-classes`
Returns list of hashes of reserved IP ranges. Each hash has two keys:
* *net*
`IP::Addr` object representing the reserved range.
* *info*
Another hash containing information about the scope of the reserved range in very brief text description:
* *scope*
Scopes are defined by `SCOPE` enum in `IP::Addr::Common`. Currently the following scopes are known:
* `undetermined`
* `mpublic`
* `software`
* `private`
* `host`
* `subnet`
* `documentation`
* `internet`
* `routing`
* `link`
Of those `routing` and `link` are specific to IPv6. `public` isn't officially recognized but used to represent anything not been reserved. `undetermined` is also a special value to be returned if a requested range of IP addresses overlaps with a reserved range but isn't fully contained in it.
* *description*
Textual information about the reserved block.
## `ip`
Returns a new `IP::Addr` object representing just an IP address of the current `IP::Addr` object.
```
my $ip = IP::Addr.new( "192.0.2.3/24" );
say $ip; # 192.0.2.3/24
say $ip.ip; # 192.0.2.3
say $ip.ip.WHO; # IP::Addr
```
## `prefix`
Returns CIDR representation of any form of IP address. For example:
```
say IP::Addr.new( "192.0.2.3" ).prefix; # 192.0.2.3/32
```
For IPv4 handler additional named parameter `:mask` can be used to use network mask instead of prefix length:
```
say IP::Addr.new( "192.0.2.3/24" ).prefix( :mask ); # 192.0.2.3/255.255.255.0
```
## `first-ip`
`IP::Addr` object for the first IP address in the range. For single IP will be the same as `ip` method.
## `last-ip`
`IP::Addr` object for the last IP address in the range. For single IP will be the same as `ip` method.
## `network`
`IP::Addr` object of the network current IP object belongs to. Makes real sense for CIDR form only though can be used with any other form too.
## `mask`
Returns string representation of the current IP object mask. Doesn't make much sense for IPv6 addresses because there is officially no such thing for them.
## `wildcard`
Returns string representation of current IP object wildcard. Doesn't make much sense for IPv6 addresses because there is officially no such thing for them.
## `size`
Returns number of IP addresses contained in the current `IP::Addr` object. For example:
```
say IP::Addr.new( "192.0.0.0/13" ).size; # 524288
say IP::Addr.new( "192.0.2.3-192.0.2.23" ); # 21
```
## `int-ip`
Returns integer value of the IP address.
## `int-first-ip`
Returns integer value of the first IP address in the current IP object.
## `int-last-ip`
Returns integer value of the last IP address in the current IP object.
## `int-mask`
Returns integer value of current IP object mask. Though not defined as such for IPv6 addresses but could be useful in some address arithmetics.
## `int-wildcard`
Returns integer value of current IP object wildcard. Though not defined as such for IPv6 addresses but could be useful in some address arithmetics.
## `inc` / `succ`
Increments IP address by *1*. For ranged IP forms result of this operation won't be greater than the last IP of the range:
```
my $ip = IP::Addr.new( "192.0.2.255/24" );
say $ip.inc; # 192.0.2.255/24
```
Rerturns current `IP::Addr` object.
## `dec` / `pred`
Decrements IP address by *1*. For ranged IP forms result of this operation won't be less than the first IP of the range:
```
my $ip = IP::Addr.new( "192.0.2.0/24" );
say $ip.dec; # 192.0.2.0/24
```
Returns current `IP::Addr` object.
## `add( Int:D $count )`
Shifts IP of the current object by `$count` positions higher. `$count` could be negative. For ranged IP form the result of the operation won't leave the range boundaries:
```
my $ip = IP::Addr.new( "192.0.2.255/24" );
say $ip.add( 10 ); # 192.0.2.255/24
say $ip.add( -300 ); # 192.0.2.0/24
```
Returns current `IP::Addr` object.
## `eq( $addr )`
Same version only.
Returns *True* if current object is equal to `$addr`.
## `lt( $addr )`
Same version only.
Returns true if the current object is less than `$addr`.
## `gt( $addr )`
Same version only.
Returns true if the current object is greater than `$addr`
## `cmp( $addr )`
Same version only.
Returns one of three `Order` values: `Less`, `Same`, or `More`. For ranges comparison is performed by the selected IP.
## `contains( $addr )`
Same version only.
Returns *True* if current object contains `$addr`. Wether the `$addr` object is the same (e.g. `eq` method would return *True*) then it is also considered as contained.
## `overlaps( $addr )`
Same version only.
Returns *True* if the current object and `$addr` have at least one common IP address. Useful for starting iteration:
## `first`
Returns a new `IP::Addr` object whose IP address is the first IP of the current object. Useful for starting iteration.
```
my $ip = IP::Addr.new( "192.0.2.12/24" );
for $ip.first.each { say $_ } # 192.0.2.0\n192.0.2.1\n...
```
See `each` method.
## `next`
Returns a new `IP::Addr` object successive to the current object or *Nil* if current is the last IP of the range.
## `prev`
Returns a new `IP::Addr` object preceding the current object or *Nil* if current is the first IP of the range.
## `next-network`
Returns a new `IP::Addr` object containing network successive to the network of the current object. Valid for CIDR form only. Flips over begining/end of IP range:
```
$ip = IP::Addr.new( "255.255.255.13/24" );
say $ip.next-network; # 0.0.0.0/24
```
## `prev-network`
Returns a new `IP::Addr` object containing network preceding the network of the current object. Valid for CIDR form only. Flips over the begining of IP range:
```
$ip = IP::Addr.new( "0.0.0.2/24" );
say $ip.prev-network; # 255.255.255.0/24
```
## `next-range`
Returns a new `IP::Addr` object containing range of the same length successive to the current object. Valid for range form only.
## `prev-range`
Returns a new `IP::Addr` object containing range of the same length preceding the current object. Valid for range form only.
## `to-int( @n-tets )`
Converts an array of n-tets to integer value corresponding to the current handler's IP version.
## `to-n-tets( Int:D $addr )`
Splits integer represnation of IP address into n-tets corresponding to the current handler's IP version.
## `info`
Returns a hash with information about the current IP object. The hash contains two keys: `scope` and `description`. See `ip-classes` method for more information.
## `Str`
Stringifies current IP object with regard to its form.
# OPERATORS
For all supported operators where both operands are addresses at least one of them has to be a `IP::Addr` object. The other one could be a string representation of an address.
## `prefix/postfix ++` and `prefix/postfix --`
Standard Raku operatios working by calling `succ`/`pred` methods on `IP::Addr` object.
## `infix + ( $addr, $int )`
Adds an integer value to the address. The resulting address will never get out of network/range boundaries for objects of corresponding forms. A new `IP::Addr` object is returned.
```
$ip2 = $ip1 + 3;
```
## `infix - ( $addr, $int )`
Deducts an integer value from the address. The resulting address will never get out of network/range boundaries for objects of corresponding forms. A new `IP::Addr` object is returned.
```
$ip2 = $ip1 - 3;
```
## `infix cmp ( $addr1, $addr2 )`
Compares two IP addresses.
```
given $ip1 cmp $ip2 {
when Less { say "smaller" }
when Same { say "same" }
when More { say "bigger" }
}
```
## `infix eqv / infix == ( $addr1, $addr2 )`
Checks if two addresses are equal. See handler's `eq` method.
## `infix < ( $addr1, $addr2 )`
*True* if `$addr1` is less than `$addr2`. See handler's `lt` method.
## `infix <= / infix ≤ ( $addr1, $addr2 )`
*True* if `$addr1` is less than or equal to `$addr2`.
## `infix > ( $addr1, $addr2 )`
*True* if `$addr1` is greater than `$addr2`. See handler's `gt` method.
## `infix >= / infix ≥ ( $addr1, $addr2 )`
*True* `$addr1` greater than or equal to `$addr2`.
## `infix (cont) / infix ⊇ ( $addr1, $addr2 )`
*True* if `$addr1` object contains `$addr2`. See handler's `contains` method.
## `infix ⊆ ( $addr1, $addr2 )`
*True* if `$addr1` is contained by `$addr2`.
# CAVEATS
The author doesn't use IPv6 in his setups. All the functionality provided here is developed using information from corresponding Wikipedia pages. Therefore, "here be dragons"©. Please, report back any issue encountered!
# AUTHOR
Vadim Belman [[email protected]](mailto:[email protected])
|
## dist_github-grondilu-TrigPi.md
# TrigPi
[](https://travis-ci.org/grondilu/trigpi)
This modules implements `cosPi`, `sinPi` and `cisPi` as mentioned in [IEEE
754](https://www.csee.umbc.edu/~tsimo1/CMSC455/IEEE-754-2008.pdf).
`cosPi($x)`, `sinPi($x)` and `cisPi($x)`
are designed to be more accurate values of
`cos($x*pi)`, `sin($x*pi)` and `cis($x*pi)` respectively,
especially for large values of `$x`.
|
## dist_zef-lizmat-IRC-Client.md
[](https://github.com/lizmat/IRC-Client/actions) [](https://github.com/lizmat/IRC-Client/actions)
# NAME
IRC::Client - Extendable Internet Relay Chat client
# SYNOPSIS
```
use IRC::Client;
use Pastebin;
.run with IRC::Client.new:
:host<irc.libera.chat>
:channels<#rakubot #zofbot>
:debug
:plugins(
class { method irc-to-me ($ where /hello/) { 'Hello to you too!'} }
)
:filters(
-> $text where .chars > 200 {
'The output is too large to show here. See: '
~ Pastebin.new.paste: $text;
}
);
```
# DESCRIPTION
The module provides the means to create clients to communicate with IRC (Internet Relay Chat) servers. Has support for non-blocking responses and output post-processing.
# DOCUMENTATION MAP
* [Blog Post](https://github.com/Raku/CCR/blob/main/Remaster/Zoffix%20Znet/IRC-Client-Raku-Multi-Server-IRC-or-Awesome-Async-Interfaces-with-Raku.md) \* [Basics Tutorial](https://github.com/lizmat/IRC-Client/blob/main/docs/01-basics.md) \* [Event Reference](https://github.com/lizmat/IRC-Client/blob/main/docs/02-event-reference.md) \* [Method Reference](https://github.com/lizmat/IRC-Client/blob/main/docs/03-method-reference.md) \* [Big-Picture Behaviour](https://github.com/lizmat/IRC-Client/blob/main/docs/04-big-picture-behaviour.md) \* [Examples](https://github.com/lizmat/IRC-Client/blob/main/examples/)
# AUTHORS
* Zoffix Znet
* Elizabeth Mattijsen
Source can be located at: <https://github.com/lizmat/IRC-Client> . 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!
# CONTRIBUTORS
* Daniel Green
* Patrick Spek
# COPYRIGHT AND LICENSE
Copyright 2015-2021 Zoffix Znet
Copyright 2021-2025 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
The `META6.json` file of this distribution may be distributed and modified without restrictions or attribution.
|
## brackets.md
Brackets
Valid opening/closing paired delimiters
The following table shows all of the valid graphemes usable as opening and closing paired delimiters in such constructs as *Pod6 declarator blocks*. Note they are shown between pipe symbols so the extra bounding space for any wide characters can be seen.
The data source for the table is the *$brackets* string defined in the *HLL::Grammar* module in the *github.com/Raku/nqp* repository.
The data are arranged in the order found in the source string. Each opening bracket is shown in its printed form followed by its paired closing bracket. Each pair is then followed by its codepoints. There are two sets of bracket pairs shown per table row.
Bracket pairs
| LChar | RChar | LHex | RHex | LChar | RChar | LHex | RHex |
| --- | --- | --- | --- | --- | --- | --- | --- |
| |(| | |)| | 0x0028 | 0x0029 | |<| | |>| | 0x003C | 0x003E |
| |[| | |]| | 0x005B | 0x005D | |{| | |}| | 0x007B | 0x007D |
| |«| | |»| | 0x00AB | 0x00BB | |༺| | |༻| | 0x0F3A | 0x0F3B |
| |༼| | |༽| | 0x0F3C | 0x0F3D | |᚛| | |᚜| | 0x169B | 0x169C |
| |‘| | |’| | 0x2018 | 0x2019 | |‚| | |’| | 0x201A | 0x2019 |
| |‛| | |’| | 0x201B | 0x2019 | |“| | |”| | 0x201C | 0x201D |
| |„| | |”| | 0x201E | 0x201D | |‟| | |”| | 0x201F | 0x201D |
| |‹| | |›| | 0x2039 | 0x203A | |⁅| | |⁆| | 0x2045 | 0x2046 |
| |⁽| | |⁾| | 0x207D | 0x207E | |₍| | |₎| | 0x208D | 0x208E |
| |∈| | |∋| | 0x2208 | 0x220B | |∉| | |∌| | 0x2209 | 0x220C |
| |∊| | |∍| | 0x220A | 0x220D | |∕| | |⧵| | 0x2215 | 0x29F5 |
| |∼| | |∽| | 0x223C | 0x223D | |≃| | |⋍| | 0x2243 | 0x22CD |
| |≒| | |≓| | 0x2252 | 0x2253 | |≔| | |≕| | 0x2254 | 0x2255 |
| |≤| | |≥| | 0x2264 | 0x2265 | |≦| | |≧| | 0x2266 | 0x2267 |
| |≨| | |≩| | 0x2268 | 0x2269 | |≪| | |≫| | 0x226A | 0x226B |
| |≮| | |≯| | 0x226E | 0x226F | |≰| | |≱| | 0x2270 | 0x2271 |
| |≲| | |≳| | 0x2272 | 0x2273 | |≴| | |≵| | 0x2274 | 0x2275 |
| |≶| | |≷| | 0x2276 | 0x2277 | |≸| | |≹| | 0x2278 | 0x2279 |
| |≺| | |≻| | 0x227A | 0x227B | |≼| | |≽| | 0x227C | 0x227D |
| |≾| | |≿| | 0x227E | 0x227F | |⊀| | |⊁| | 0x2280 | 0x2281 |
| |⊂| | |⊃| | 0x2282 | 0x2283 | |⊄| | |⊅| | 0x2284 | 0x2285 |
| |⊆| | |⊇| | 0x2286 | 0x2287 | |⊈| | |⊉| | 0x2288 | 0x2289 |
| |⊊| | |⊋| | 0x228A | 0x228B | |⊏| | |⊐| | 0x228F | 0x2290 |
| |⊑| | |⊒| | 0x2291 | 0x2292 | |⊘| | |⦸| | 0x2298 | 0x29B8 |
| |⊢| | |⊣| | 0x22A2 | 0x22A3 | |⊦| | |⫞| | 0x22A6 | 0x2ADE |
| |⊨| | |⫤| | 0x22A8 | 0x2AE4 | |⊩| | |⫣| | 0x22A9 | 0x2AE3 |
| |⊫| | |⫥| | 0x22AB | 0x2AE5 | |⊰| | |⊱| | 0x22B0 | 0x22B1 |
| |⊲| | |⊳| | 0x22B2 | 0x22B3 | |⊴| | |⊵| | 0x22B4 | 0x22B5 |
| |⊶| | |⊷| | 0x22B6 | 0x22B7 | |⋉| | |⋊| | 0x22C9 | 0x22CA |
| |⋋| | |⋌| | 0x22CB | 0x22CC | |⋐| | |⋑| | 0x22D0 | 0x22D1 |
| |⋖| | |⋗| | 0x22D6 | 0x22D7 | |⋘| | |⋙| | 0x22D8 | 0x22D9 |
| |⋚| | |⋛| | 0x22DA | 0x22DB | |⋜| | |⋝| | 0x22DC | 0x22DD |
| |⋞| | |⋟| | 0x22DE | 0x22DF | |⋠| | |⋡| | 0x22E0 | 0x22E1 |
| |⋢| | |⋣| | 0x22E2 | 0x22E3 | |⋤| | |⋥| | 0x22E4 | 0x22E5 |
| |⋦| | |⋧| | 0x22E6 | 0x22E7 | |⋨| | |⋩| | 0x22E8 | 0x22E9 |
| |⋪| | |⋫| | 0x22EA | 0x22EB | |⋬| | |⋭| | 0x22EC | 0x22ED |
| |⋰| | |⋱| | 0x22F0 | 0x22F1 | |⋲| | |⋺| | 0x22F2 | 0x22FA |
| |⋳| | |⋻| | 0x22F3 | 0x22FB | |⋴| | |⋼| | 0x22F4 | 0x22FC |
| |⋶| | |⋽| | 0x22F6 | 0x22FD | |⋷| | |⋾| | 0x22F7 | 0x22FE |
| |⌈| | |⌉| | 0x2308 | 0x2309 | |⌊| | |⌋| | 0x230A | 0x230B |
| |〈| | |〉| | 0x2329 | 0x232A | |⎴| | |⎵| | 0x23B4 | 0x23B5 |
| |❨| | |❩| | 0x2768 | 0x2769 | |❪| | |❫| | 0x276A | 0x276B |
| |❬| | |❭| | 0x276C | 0x276D | |❮| | |❯| | 0x276E | 0x276F |
| |❰| | |❱| | 0x2770 | 0x2771 | |❲| | |❳| | 0x2772 | 0x2773 |
| |❴| | |❵| | 0x2774 | 0x2775 | |⟃| | |⟄| | 0x27C3 | 0x27C4 |
| |⟅| | |⟆| | 0x27C5 | 0x27C6 | |⟕| | |⟖| | 0x27D5 | 0x27D6 |
| |⟝| | |⟞| | 0x27DD | 0x27DE | |⟢| | |⟣| | 0x27E2 | 0x27E3 |
| |⟤| | |⟥| | 0x27E4 | 0x27E5 | |⟦| | |⟧| | 0x27E6 | 0x27E7 |
| |⟨| | |⟩| | 0x27E8 | 0x27E9 | |⟪| | |⟫| | 0x27EA | 0x27EB |
| |⦃| | |⦄| | 0x2983 | 0x2984 | |⦅| | |⦆| | 0x2985 | 0x2986 |
| |⦇| | |⦈| | 0x2987 | 0x2988 | |⦉| | |⦊| | 0x2989 | 0x298A |
| |⦋| | |⦌| | 0x298B | 0x298C | |⦍| | |⦐| | 0x298D | 0x2990 |
| |⦏| | |⦎| | 0x298F | 0x298E | |⦑| | |⦒| | 0x2991 | 0x2992 |
| |⦓| | |⦔| | 0x2993 | 0x2994 | |⦕| | |⦖| | 0x2995 | 0x2996 |
| |⦗| | |⦘| | 0x2997 | 0x2998 | |⧀| | |⧁| | 0x29C0 | 0x29C1 |
| |⧄| | |⧅| | 0x29C4 | 0x29C5 | |⧏| | |⧐| | 0x29CF | 0x29D0 |
| |⧑| | |⧒| | 0x29D1 | 0x29D2 | |⧔| | |⧕| | 0x29D4 | 0x29D5 |
| |⧘| | |⧙| | 0x29D8 | 0x29D9 | |⧚| | |⧛| | 0x29DA | 0x29DB |
| |⧸| | |⧹| | 0x29F8 | 0x29F9 | |⧼| | |⧽| | 0x29FC | 0x29FD |
| |⨫| | |⨬| | 0x2A2B | 0x2A2C | |⨭| | |⨮| | 0x2A2D | 0x2A2E |
| |⨴| | |⨵| | 0x2A34 | 0x2A35 | |⨼| | |⨽| | 0x2A3C | 0x2A3D |
| |⩤| | |⩥| | 0x2A64 | 0x2A65 | |⩹| | |⩺| | 0x2A79 | 0x2A7A |
| |⩽| | |⩾| | 0x2A7D | 0x2A7E | |⩿| | |⪀| | 0x2A7F | 0x2A80 |
| |⪁| | |⪂| | 0x2A81 | 0x2A82 | |⪃| | |⪄| | 0x2A83 | 0x2A84 |
| |⪋| | |⪌| | 0x2A8B | 0x2A8C | |⪑| | |⪒| | 0x2A91 | 0x2A92 |
| |⪓| | |⪔| | 0x2A93 | 0x2A94 | |⪕| | |⪖| | 0x2A95 | 0x2A96 |
| |⪗| | |⪘| | 0x2A97 | 0x2A98 | |⪙| | |⪚| | 0x2A99 | 0x2A9A |
| |⪛| | |⪜| | 0x2A9B | 0x2A9C | |⪡| | |⪢| | 0x2AA1 | 0x2AA2 |
| |⪦| | |⪧| | 0x2AA6 | 0x2AA7 | |⪨| | |⪩| | 0x2AA8 | 0x2AA9 |
| |⪪| | |⪫| | 0x2AAA | 0x2AAB | |⪬| | |⪭| | 0x2AAC | 0x2AAD |
| |⪯| | |⪰| | 0x2AAF | 0x2AB0 | |⪳| | |⪴| | 0x2AB3 | 0x2AB4 |
| |⪻| | |⪼| | 0x2ABB | 0x2ABC | |⪽| | |⪾| | 0x2ABD | 0x2ABE |
| |⪿| | |⫀| | 0x2ABF | 0x2AC0 | |⫁| | |⫂| | 0x2AC1 | 0x2AC2 |
| |⫃| | |⫄| | 0x2AC3 | 0x2AC4 | |⫅| | |⫆| | 0x2AC5 | 0x2AC6 |
| |⫍| | |⫎| | 0x2ACD | 0x2ACE | |⫏| | |⫐| | 0x2ACF | 0x2AD0 |
| |⫑| | |⫒| | 0x2AD1 | 0x2AD2 | |⫓| | |⫔| | 0x2AD3 | 0x2AD4 |
| |⫕| | |⫖| | 0x2AD5 | 0x2AD6 | |⫬| | |⫭| | 0x2AEC | 0x2AED |
| |⫷| | |⫸| | 0x2AF7 | 0x2AF8 | |⫹| | |⫺| | 0x2AF9 | 0x2AFA |
| |⸂| | |⸃| | 0x2E02 | 0x2E03 | |⸄| | |⸅| | 0x2E04 | 0x2E05 |
| |⸉| | |⸊| | 0x2E09 | 0x2E0A | |⸌| | |⸍| | 0x2E0C | 0x2E0D |
| |⸜| | |⸝| | 0x2E1C | 0x2E1D | |⸠| | |⸡| | 0x2E20 | 0x2E21 |
| |⸨| | |⸩| | 0x2E28 | 0x2E29 | |〈| | |〉| | 0x3008 | 0x3009 |
| |《| | |》| | 0x300A | 0x300B | |「| | |」| | 0x300C | 0x300D |
| |『| | |』| | 0x300E | 0x300F | |【| | |】| | 0x3010 | 0x3011 |
| |〔| | |〕| | 0x3014 | 0x3015 | |〖| | |〗| | 0x3016 | 0x3017 |
| |〘| | |〙| | 0x3018 | 0x3019 | |〚| | |〛| | 0x301A | 0x301B |
| |〝| | |〞| | 0x301D | 0x301E | |︗| | |︘| | 0xFE17 | 0xFE18 |
| |︵| | |︶| | 0xFE35 | 0xFE36 | |︷| | |︸| | 0xFE37 | 0xFE38 |
| |︹| | |︺| | 0xFE39 | 0xFE3A | |︻| | |︼| | 0xFE3B | 0xFE3C |
| |︽| | |︾| | 0xFE3D | 0xFE3E | |︿| | |﹀| | 0xFE3F | 0xFE40 |
| |﹁| | |﹂| | 0xFE41 | 0xFE42 | |﹃| | |﹄| | 0xFE43 | 0xFE44 |
| |﹇| | |﹈| | 0xFE47 | 0xFE48 | |﹙| | |﹚| | 0xFE59 | 0xFE5A |
| |﹛| | |﹜| | 0xFE5B | 0xFE5C | |﹝| | |﹞| | 0xFE5D | 0xFE5E |
| |(| | |)| | 0xFF08 | 0xFF09 | |<| | |>| | 0xFF1C | 0xFF1E |
| |[| | |]| | 0xFF3B | 0xFF3D | |{| | |}| | 0xFF5B | 0xFF5D |
| |⦅| | |⦆| | 0xFF5F | 0xFF60 | |「| | |」| | 0xFF62 | 0xFF63 |
| |⟮| | |⟯| | 0x27EE | 0x27EF | |⸤| | |⸥| | 0x2E24 | 0x2E25 |
| |⟬| | |⟭| | 0x27EC | 0x27ED | |⸢| | |⸣| | 0x2E22 | 0x2E23 |
| |⸦| | |⸧| | 0x2E26 | 0x2E27 | | | | |
|
## dist_zef-jjmerelo-Syslog-Parse.md

# NAME
Syslog::Parse - Creates a supply out of syslog entries
# SYNOPSIS
```
use Syslog::Parse;
my $parser = Syslog::Parse.new;
$parser.parsed.tap: -> $v {
say $v;
}
sleep( @*ARGS[0] // 120 );
```
Or
```
use Syslog::Parse;
my $parser = Syslog::Parse.new;
Promise.at(now+1).then: {
shell "logger logging $_" for ^10;
};
react {
whenever $parser.parsed -> %v {
say %v;
done(); # Just interested in the last one
}
}
```
Also, you can run
```
watch-syslog.p6
```
which is going ot be installed along with the distribution.
# DESCRIPTION
Syslog::Parse is a parser that extracts information from every line in
`/var/log/syslog`. Creates two objects of the kind `Supply`: one (simply
called `.supply`) that returns the raw lines, another, `.parsed`, which
returns a structure with the following keys:
```
day # Day in the month
month # TLA of month
hour # String with hour
hostname # Hostname that produced it
actor # Who produced the message log
pid # Sometimes, it goes with a PID
message # Another data structure, with key message (the whole message) and
# user if one has been identified
```
## PLATFORMS
It works on platforms that use `/var/log/syslog` as a syslog file,
with the same format. All Debian seem to be that way.
If you don't have that platform, you can still use the grammars on
files with that format.
# AUTHOR
JJ Merelo [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2020 JJ Merelo
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-guifa-User-Language.md
# User::Language
> **⚠︎ Name change ⚠**
> This module changed name from `Intl::UserLanguage` to `User::Language`.
> It will continue to provide under both names until the end of 2024.
This is a incredibly simple module for Raku designed to do one thing and one thing
only: obtain the current user’s preferred language(s). There is no universal way
to do this, so this module aims to be the one-stop shop to get that information.
To use, simply ask for the preferred language (if you just want one) or
preferred languages (more common).
```
use Intl::UserLanguage;
user-language; # ↪︎ [ast-US] (on my system)
user-languages; # ↪︎ [ast-US], [es-US], [en-US], [pt-PT] (on my system)
# (sidenote: no idea why Apple adds -US onto ast…)
# (sidenote: Microsoft makes it ast-Latn… weird.)
```
In truth, the preferred language is just a wrapper for calling `.head` on the
list. I'd recommend using the plural version anytime there may need to be a
negotiation to find a best (HTTP request headers, localization frameworks).
In any case, both functions allow you to supply a default code which may be a
string in BCP-47 format or a `LanguageTag`. This is useful in case for some reason
the user’s language(s) cannot be determined, for example, if the user is
running an operating system that has not had its settings cataloged in this
module. If you do not provide a default, and no language can be found, the
*default* default language is **en** (English).
As a final option, particularly if you want to test your code with other
languages, you can override the user’s system languages:
```
use Intl::UserLanguage :override; # imports override functions
user-languages; # ↪︎ [ast-US], [es-US], [en-US], [pt-PT] (on my system)
override-user-languages('jp','zh');
user-languages; # ↪︎ [jp], [zh]
```
The override can be cleared at any time with `clear-user-language-override`.
Note that the override is *global*, and there is no current way to lexically
scope it;
# Support
Support is current available for the following OSes:
* **macOS**
Full list of languages (as defined in *System Preferences → Language & Region → Preferred Languages*). Paralinguistic preferences (e.g. calendar type) are not set on a per-language basis, so they carry to all languages.
* **Linux**: If `$LANGUAGE` is set, then an ordered list is provided. Otherwise, it falls back to the more universal `$LANG`, which only provides a single language.
* **Windows**: If the registry value `Languages` is set in `HKCU\Control Panel\International\User Profile`, uses the ordered list found there. Otherwise, it falls back to the registry value `LocaleName` found in at `HKCU\Control Panel\International`.
Support is not available for \*nix machines right now, but only because I am not
sure what the `$*DISTRO` value is for those systems. I imagine detection will be
similar if not identical to Linux. Please contact me with your `$*DISTRO` value
and how to detect your system language(s) and I'll gladly add it.
# Lightweight mode (under development)
If your program only needs the language code to pass it through to something that only employs strings (e.g. to directly create an HTTP request), it may
be useful to `use` the module in a `:light` mode.
Instead of receiving a `LanguageTag` object, you will get a `Str` that can be passed into other modules.
# Version History
* 0.5.2
* Fix dependency issue in META6 file
* 0.5.1
* Removed debug code
* 0.5.0
* Renamed module to `User::Language` to be in line with modules like `User::Timezone`
* Fixed a bug in the fallbacks as specified by use statements
* 0.4.0
* Moved individual OS versions into separate submodules. This will be more maintainable long term
* Adjusted OS detection for macOS (Rakudo no longer reports it as `macosx` but rather `macos`)
* Completely rewritten Mac code to support some extended attributes.
* Sets up a model for using NativeCall when possible, and falling back to a slower method if not (Windows will eventually adopt a similar approach)
* 0.3
* Cache language(s) on first call to `user-language[s]`
This should provide a substantial speed up for modules like `Intl::*` that call this frequently as a fall back.
# Licenses and Legal Stuff
This module is Copyright 2020-2022 by Matthew Stephen Stuckwisch and
licensed under the Artistic License 2.0 which is included
with the source. Camelia (the butterfly) is a trademark belonging to
Larry Walls and used in accordance with his terms.
|
## dist_zef-sdondley-Win32-Registry.md
[](https://github.com/sdondley/Win32-Registry-Subkeys/actions)
# NAME
Win32::Registry - Query the Windows registry using the Windows API
# SYNOPSIS
```
use Win32::Registry::Subkeys;
my $hive = 'HKEY_LOCAL_MACHINE';
my $key = 'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths';
my @array = get-subkeys( $hive, $key );
```
# DESCRIPTION
Win32::Registry uses the NativeCall module to execute WinAPI functions to extract information from the registry.
# Native Call Functions
The following Windows API native call functions are currently supported:
## RegCloseKey(int32) is native("Kernel32.dll") returns int32 is export {\*};
## RegGetValueW(int32, CArray[WCHAR], CArray[WCHAR], int32, int32, CArray[uint16], int32 is rw) is native("Kernel32.dll") returns int32 is export {\*};
## RegOpenKeyExW(int32, WCHARS, int32, int32, int32 is rw) is native("Kernel32.dll") returns int32 is export {\*};
## RegQueryInfoKeyW(int32, int32, int32, int32, int32 is rw, int32 is rw, int32, int32, int32, int32, int32, int32) returns int32 is native('kernel32') is export {\*};
# ROUTINES
## get-hkey-handle(Str:D $hive)
Returns the handle for a hive name. Hive names can be shortened to leave off the `HKEY_` bit at the beginning. Capitlization is ignored.
```
my $handle = get-hkey-handler('hkey_local_machine);
my $handle = get-hkey-handler('local_machine); # same as above
```
## get-hkey(Str:D $h)
Returns the name of a hive, if found. Dies otherwise.
```
my $handle = get-hkey('local_machine');
say $handle; # OUTPUT: hkey_local_machine
```
## key-exists(Str:D $key)
Test to see if a key exists in the registry. Accepts a string representing a path to a registry key. Returns a boolean value.
```
my $exists = key-exists('hkey_local_machine\SOFTWARE\Microsoft\Windows \CurrentVersion \App Paths');
```
## close-key(Int:D $key-handle)
Closes an open key. Accepts a handle to an already open key. Returns boolean value based on success of operation. False will be returned if the key was already closed.
```
$key-exists = key-exists('hkey_local_machine\SOFTWARE\Microsoft\Windows \CurrentVersion \App Paths');
```
## wstr(Str $str)
Converts a string into a wide characgter string, suitable for passing to a Windows API native call function. Returns the original string in a native `CArray[WCHAR]` object that is terminated with a null character.
## multi sub open-key(Str:D $key)
## multi sub open-key(Int:D $hkey-handle, Str:D $key)
Opens a registry key. Returns the key's handle. Dies if key does not exist.
```
my $handle = open-key('local_machine', 'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths' );
my $handle = open-key('hkey_local_machine\SOFTWARE\Microsoft\Windows \CurrentVersion\App Paths' );
```
# SUBMODULES
* [Win32::Registry::Subkeys](https://github.com/sdondley/Win32-Registry/blob/main/lib/Win32/Registry/Subkeys.rakumod)
See the documentation for the individual submodules for further details.
# AUTHOR
Steve Dondley [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2022 Steve Dondley
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-lizmat-Memoize.md
[](https://github.com/lizmat/Memoize/actions)
# NAME
Raku port of Perl's Memoize module 1.03
# SYNOPSIS
```
use Memoize;
memoize(&slow_function);
slow_function(arguments); # Is faster than it was before
```
This is normally all you need to know. However, many options are available:
```
memoize(&function, options...);
```
Options include:
```
:NORMALIZER(&function) # default: join with \x[1C] (aka chr(28)
:CACHE<MEMORY> # in memory, single threaded, default
:CACHE<MULTI> # in memory, multi-threaded, slower
:CACHE(%cache_hash) # any Associative object
```
# DESCRIPTION
This module tries to mimic the behaviour of Perl's `Memoize` module as closely as possible in the Raku Programming Language.
`Memoizing` a function makes it faster by trading space for time. It does this by caching the return values of the function in a table. If you call the function again with the same arguments, `memoize` jumps in and gives you the value out of the table, instead of letting the function compute the value all over again.
Here is an extreme example. Consider the Fibonacci sequence, defined by the following function:
```
# Compute Fibonacci numbers
sub fib($n) {
return $n if $n < 2;
fib($n-1) + fib($n-2);
}
```
This function is very slow. Why? To compute fib(14), it first wants to compute fib(13) and fib(12), and add the results. But to compute fib(13), it first has to compute fib(12) and fib(11), and then it comes back and computes fib(12) all over again even though the answer is the same. And both of the times that it wants to compute fib(12), it has to compute fib(11) from scratch, and then it has to do it again each time it wants to compute fib(13). This function does so much recomputing of old results that it takes a really long time to run---fib(14) makes 1,200 extra recursive calls to itself, to compute and recompute things that it already computed.
This function is a good candidate for memoization. If you memoize the 'fib' function above, it will compute fib(14) exactly once, the first time it needs to, and then save the result in a table. Then if you ask for fib(14) again, it gives you the result out of the table. While computing fib(14), instead of computing fib(12) twice, it does it once; the second time it needs the value it gets it from the table. It doesn't compute fib(11) four times; it computes it once, getting it from the table the next three times. Instead of making 1,200 recursive calls to 'fib', it makes 15. This makes the function about 150 times faster.
You could do the memoization yourself, by rewriting the function, like this:
```
# Compute Fibonacci numbers, memoized version
{
my @fib;
sub fib($n) {
return $_ with @fib[$n];
return @fib[$n] = $n if $n < 2;
@fib[$n] = fib($n-1) + fib($n-2);
}
}
```
Or you could use this module, like this:
```
use Memoize;
memoize('fib');
# Rest of the fib function just like the original version.
```
This makes it easy to turn memoizing on and off.
Here's an even simpler example: I wrote a simple ray tracer; the program would look in a certain direction, figure out what it was looking at, and then convert the `color` value (typically a string like `red`) of that object to a red, green, and blue pixel value, like this:
```
for ^300 -> $direction {
# Figure out which object is in direction $direction
$color = $object{color};
($r, $g, $b) = ColorToRGB($color);
...
}
```
Since there are relatively few objects in a picture, there are only a few colors, which get looked up over and over again. Memoizing `ColorToRGB` sped up the program by several percent.
# PORTING CAVEATS
Because pads / stashes are immutable at runtime and the way code can be wrapped in Raku, it is **not** possible to install a memoized version of a function **and** not wrap the original code. Therefore it seemed more sensible to remove the INSTALL feature altogether, at least at this point in time.
The CACHE<MULTI> is a special version of CACHE<MEMORY> that installs a thread-safe in memory storage, which is slower because of the required locking.
Since Raku does not have the concept of `scalar` versus `list` context, only one type of cache is used internally, as opposed to two different ones as in Perl. Many functions / modules of the CPAN Butterfly Plan accept a `Scalar` as the first positional parameter to indicate the scalar context version of the called function is requested. Since this is a parameter like any other, it will be used to distinguish scalar vs list meaning by the default normalizer.
Therefore there are no separate `:SCALAR_CACHE` and `:LIST_CACHE` named parameters necessary anymore: instead a single `:CACHE` parameter is recognized, that only accepts either `'MEMORY'`, `'MULTI'` or an object that does the `Associative` role as a parameter (as there is no need for the `'FAULT'` and `'MERGE'` values anymore).
Since Raku has proper typing, it can recognize that an object that does the `Associative` role is being passed as the parameter with `:CACHE`, so there is no need to specify the word 'HASH' anymore.
The default in-memory backend for memoized values is **not** thread-safe. If you want multiple threads to work with the same memoized function, you will need to specify a CACHE parameter with a backend that **is** threadsafe.
# DETAILS
This module exports exactly one function, `memoize`. The rest of the functions in this package are None of Your Business.
You should say
```
memoize(function)
```
where `function` is the name of the function or the `Routine` object that you want to memoize. `memoize` returns a reference to the new, memoized version of the function, or `Nil` on a non-fatal error. At present, there are no non-fatal errors, but there might be some in the future.
If `function` was the name of a function, then `memoize` hides the old version and installs the new memoized version under the old name, so that `&function(...)` actually invokes the memoized version.
# OPTIONS
There are some optional options you can pass to `memoize` to change the way it behaves a little. To supply options, invoke `memoize` like this:
```
memoize(function,
NORMALIZER => function,
CACHE => option,
);
```
Each of these options is optional; you can include some, all, or none of them.
## NORMALIZER
Suppose your function looks like this:
```
# Typical call: f('aha!', A => 11, B => 12);
sub f($a, *%hash {
%hash{B} ||= 2; # B defaults to 2
%hash{C} ||= 7; # C defaults to 7
# Do something with $a, %hash
}
```
Now, the following calls to your function are all completely equivalent:
```
f(OUCH);
f(OUCH, B => 2);
f(OUCH, C => 7);
f(OUCH, B => 2, C => 7);
f(OUCH, C => 7, B => 2);
(etc.)
```
However, unless you tell `Memoize` that these calls are equivalent, it will not know that, and it will compute the values for these invocations of your function separately, and store them separately.
To prevent this, supply a `NORMALIZER` function that turns the program arguments into a string in a way that equivalent arguments turn into the same string. A `NORMALIZER` function for `f` above might look like this:
```
sub normalize_f($a,*%hash {
%hash{B} ||= 2;
$hash{C} ||= 7;
join(',', $a, %hash.sort>>.kv);
}
```
Each of the argument lists above comes out of the `normalize_f` function looking exactly the same, like this:
```
OUCH,B,2,C,7
```
You would tell `Memoize` to use this normalizer this way:
```
memoize('f', NORMALIZER => 'normalize_f');
```
`memoize` knows that if the normalized version of the arguments is the same for two argument lists, then it can safely look up the value that it computed for one argument list and return it as the result of calling the function with the other argument list, even if the argument lists look different.
The default normalizer just concatenates the stringified arguments with character 28 in between. (In ASCII, this is called FS or control-.) This always works correctly for functions with only one string argument, and also when the arguments never contain character 28. However, it can confuse certain argument lists:
```
normalizer("a\034", "b")
normalizer("a", "\034b")
normalizer("a\034\034b")
```
for example.
Since hash keys are strings, the default normalizer will not distinguish between type objects / Nil and the empty string.
```
sub normalize($a, @b) { join ' ', $a, @b }
```
For the example above, this produces the key "13 1 2 3 4 5 6 7".
Another use for normalizers is when the function depends on data other than those in its arguments. Suppose you have a function which returns a value which depends on the current hour of the day:
```
sub on_duty($problem_type) {
my $hour = DateTime.now.hour;
my $fh = open("$DIR/$problem_type") or die...;
$fh.lines.skip(DateTime.now.hour).head;
}
```
At 10:23, this function generates the 10th line of a data file; at 3:45 PM it generates the 15th line instead. By default, `Memoize` will only see the $problem\_type argument. To fix this, include the current hour in the normalizer:
```
sub normalize(*@_) { join ' ', DateTime.now.hour, @_ }
```
## CACHE
Normally, `Memoize` caches your function's return values into an ordinary Perl hash variable. However, you might like to have the values cached on the disk, so that they persist from one run of your program to the next, or you might like to associate some other interesting semantics with the cached values.
The argument to `CACHE` must either the string `MEMORY`, the string `MULTI` or an object that performs the `Associative` role.
```
MEMORY
MULTI
%hash
```
### MEMORY
`MEMORY` means that return values from the function will be cached in an ordinary Raku hash. The hash will not persist after the program exits. This is the default.
### MULTI
`MULTI` means that return values from the function will be cached in a Raku hash that has been hardened to function correctly in a multi-threaded program (which is slower due to necessary locking). The hash will not persist after the program exits.
### %hash
Allows you to specify that a particular hash that you supply will be used as the cache. Any object that does the `Associative` role is acceptable.
Such an `Associative` object can have any semantics at all. It is typically tied to an on-disk database, so that cached values are stored in the database and retrieved from it again when needed, and the disk file typically persists after your program has exited.
A typical example is:
```
my %cache is MyStore[$filename];
memoize 'function', CACHE => %cache;
```
Or if you want to use the "name of named parameter is the same as the variable" feature of Raku:
```
my %CACHE is MyStore[$filename];
memoize 'function', :%CACHE;
```
This has the effect of storing the cache in a `MyStore` database whose name is in `$filename`. The cache will persist after the program has exited. Next time the program runs, it will find the cache already populated from the previous run of the program. Or you can forcibly populate the cache by constructing a batch program that runs in the background and populates the cache file. Then when you come to run your real program the memoized function will be fast because all its results have been precomputed.
Another reason to use `HASH` is to provide your own hash variable. You can then inspect or modify the contents of the hash to gain finer control over the cache management.
# OTHER FACILITIES
## unmemoize
There's an `unmemoize` function that you can import if you want to. Why would you want to? Here's an example: Suppose you have your cache tied to a DBM file, and you want to make sure that the cache is written out to disk if someone interrupts the program. If the program exits normally, this will happen anyway, but if someone types control-C or something then the program will terminate immediately without synchronizing the database. So what you can do instead is
```
signal(SIGINT).tap: { unmemoize &function; exit }
```
`unmemoize` accepts the `Callable` object, or the name of a previously memoized function, and undoes whatever it did to provide the memoized version in the first place, including making the name refer to the unmemoized version if appropriate. It returns a reference to the unmemoized version of the function.
If you ask it to unmemoize a function that was never memoized, it will throw an exception.
## flush\_cache
`flush_cache(function)` will flush out the caches, discarding *all* the cached data. The argument may be a function name or a reference to a function. For finer control over when data is discarded or expired, see the documentation for `Memoize::Expire`, included in this package.
Note that if the cache is a tied hash, `flush_cache` will attempt to invoke the `CLEAR` method on the hash. If there is no `CLEAR` method, this will cause a run-time error.
An alternative approach to cache flushing is to use the `HASH` option (see above) to request that `Memoize` use a particular hash variable as its cache. Then you can examine or modify the hash at any time in any way you desire. You may flush the cache by using `%hash = ()`.
# CAVEATS
Memoization is not a cure-all:
## depending on program state
Do not memoize a function whose behavior depends on program state other than its own arguments, such as global variables, the time of day, or file input. These functions will not produce correct results when memoized. For a particularly easy example:
```
sub f {
time;
}
```
This function takes no arguments, and as far as `Memoize` is concerned, it always returns the same result. `Memoize` is wrong, of course, and the memoized version of this function will call `time` once to get the current time, and it will return that same time every time you call it after that.
## side effects
Do not memoize a function with side effects.
```
sub f($a,$b) {
my $s = $a + $b;
say "$a + $b = $s.";
}
```
This function accepts two arguments, adds them, and prints their sum. Its return value is the number of characters it printed, but you probably didn't care about that. But `Memoize` doesn't understand that. If you memoize this function, you will get the result you expect the first time you ask it to print the sum of 2 and 3, but subsequent calls will return 1 (the return value of `print`) without actually printing anything.
## modified by caller
Do not memoize a function that returns a data structure that is modified by its caller.
Consider these functions: `getusers` returns a list of users somehow, and then `main` throws away the first user on the list and prints the rest:
```
sub main {
my @userlist = getusers();
shift @userlist;
for @userlist -> $u {
print "User $u\n";
}
}
sub getusers {
my @users;
# Do something to get a list of users;
@users
}
```
If you memoize `getusers` here, it will work right exactly once. The reference to the users list will be stored in the memo table. `main` will discard the first element from the referenced list. The next time you invoke `main`, `Memoize` will not call `getusers`; it will just return the same reference to the same list it got last time. But this time the list has already had its head removed; `main` will erroneously remove another element from it. The list will get shorter and shorter every time you call `main`.
Similarly, this:
```
$u1 = getusers();
$u2 = getusers();
pop @$u1;
```
will modify $u2 as well as $u1, because both variables are references to the same array. Had `getusers` not been memoized, $u1 and $u2 would have referred to different arrays.
## simple function
Do not memoize a very simple function.
Recently someone mentioned to me that the Memoize module made his program run slower instead of faster. It turned out that he was memoizing the following function:
```
sub square($value) {
$value * $value;
}
```
I pointed out that `Memoize` uses a hash, and that looking up a number in the hash is necessarily going to take a lot longer than a single multiplication. There really is no way to speed up the `square` function.
Memoization is not magical.
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
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!
Source can be located at: <https://github.com/lizmat/Memoize> . Comments and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2018, 2019, 2020, 2021, 2023 Elizabeth Mattijsen
Re-imagined from Perl as part of the CPAN Butterfly Plan.
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## withoutmonkeytyping.md
class X::Syntax::Augment::WithoutMonkeyTyping
Compilation error due to augmenting a type without the `MONKEY-TYPING` pragma
```raku
class X::Syntax::Augment::WithoutMonkeyTyping does X::Syntax { }
```
Compile time error thrown when `augment` is used without `use MONKEY-TYPING`.
Since `augment` is considered a rather unsafe and impolite action, you have to pre-declare your intent with the `use MONKEY-TYPING;` pragma.
If you don't do that, like here
```raku
augment class Int { };
```
you get the error
「text」 without highlighting
```
```
===SORRY!===
augment not allowed without 'use MONKEY-TYPING'
```
```
|
## dist_cpan-MELEZHIK-Sparrowdo-RemoteFile.md
# SYNOPSIS
Fetch remote file using http.
# INSTALL
```
$ zef install Sparrowdo::RemoteFile
```
# USAGE
```
$ cat sparrowfile
module-run 'RemoteFile', %(
url => 'https://github.com/melezhik/remote-file/archive/master.zip',
location => '/tmp/foo/bar/master.zip'
);
```
# Parameters
## url
Remote file url. No default value. Obligatory.
## location
A local file path where to store a downloaded file. No default value. Obligatory.
## user
Sets user name for resources with access restricted by http basic authentication. Optional,
no default value.
## password
Sets password for resources with access restricted by http basic authentication. Optional,
no default value.
## headers
You may set Http headers for request:
```
headers => (
"Name: Alexey",
"LastName: Melezhik"
)
```
# Author
[Alexey Melezhik]([email protected])
|
## dist_zef-raku-community-modules-vCard-Parser.md
[](https://github.com/raku-community-modules/vCard-Parser/actions) [](https://github.com/raku-community-modules/vCard-Parser/actions) [](https://github.com/raku-community-modules/vCard-Parser/actions)
# NAME
vCard::Parser - a basic parser of vCard
# SYNOPSIS
```
use vCard::Parser;
my $vcard = 'BEGIN:VCARD
VERSION:4.0
N:Gump;Forrest;;Mr.;
x-qq:21588891
END:VCARD';
say from-vCard($vcard);
use JSON::Tiny;
say to-json(from-vCard($vcard)); #Output is jCard
```
# DESCRIPTION
vCard::Parser is a basic parser of vCard files of version 4.0. It also serves as it's convertor to jCard, which is a JSON format for vCard data.
# AUTHOR
Petr Kolář
# COPYRIGHT AND LICENSE
Copyright 2019 Petr Kolář
Copyright 2024 Raku Community
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-lizmat-Hash-Agnostic.md
[](https://github.com/lizmat/Hash-Agnostic/actions) [](https://github.com/lizmat/Hash-Agnostic/actions) [](https://github.com/lizmat/Hash-Agnostic/actions)
# NAME
Hash::Agnostic - be a hash without knowing how
# SYNOPSIS
```
use Hash::Agnostic;
class MyHash does Hash::Agnostic {
method AT-KEY($key) { ... }
method keys() { ... }
}
my %a is MyHash = a => 42, b => 666;
```
# DESCRIPTION
This module makes an `Hash::Agnostic` role available for those classes that wish to implement the `Associative` role as a `Hash`. It provides all of the `Hash` functionality while only needing to implement 2 methods:
## Required Methods
### method AT-KEY
```
method AT-KEY($key) { ... } # simple case
method AT-KEY($key) { Proxy.new( FETCH => { ... }, STORE => { ... } }
```
Return the value at the given key in the hash. Must return a `Proxy` that will assign to that key if you wish to allow for auto-vivification of elements in your hash.
### method keys
```
method keys() { ... }
```
Return the keys that currently exist in the hash, in any order that is most convenient.
## Optional Methods (provided by role)
You may implement these methods out of performance reasons yourself, but you don't have to as an implementation is provided by this role. They follow the same semantics as the methods on the [Hash object](https://docs.perl6.org/type/Hash).
In alphabetical order: `append`, `ASSIGN-KEY`, `elems`, `end`, `gist`, `grab`, `Hash`, `iterator`, `kv`, `list`, `List`, `new`, `pairs`, `perl`, `push`, `Slip`, `STORE`, `Str`, `values`
## Optional Internal Methods (provided by role)
These methods may be implemented by the consumer for performance reasons or to provide a given capability.
### method BIND-KEY
```
method BIND-KEY($key, $value) { ... }
```
Bind the given value to the given key in the hash, and return the value. Throws an error if not implemented.
### method DELETE-KEY
```
method DELETE-KEY($key) { ... }
```
Remove the the given key from the hash and return its value if it existed (otherwise return `Nil`). Throws an error if not implemented.
### method EXISTS-KEY
```
method EXISTS-KEY($key) { ... }
```
Return `Bool` indicating whether the key exists in the hash. Will call `AT-KEY` and return `True` if the returned value is defined.
### method CLEAR
```
method CLEAR(--> Nil) { ... }
```
Reset the array to have no elements at all. By default implemented by repeatedly calling `DELETE-KEY`, which will by all means, be very slow. So it is a good idea to implement this method yourself.
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
Source can be located at: <https://github.com/lizmat/Hash-Agnostic> . 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, 2023, 2024 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_github-ppentchev-Getopt-Std.md
# NAME
Getopt::Std - Process single-character options with option clustering
# SYNOPSIS
```
use Getopt::Std;
# Classical usage, slightly extended:
# - for options that take an argument, return only the last one
# - for options that don't, return a string containing the option
# name as many times as the option was specified
my Str:D %opts = getopts('ho:V', @*ARGS);
CATCH { when X::Getopt::Std { .message.note; usage } };
version() if %opts<V>;
usage(True) if %opts<h>;
exit(0) if %opts{<V h>}:k;
my $outfile = %opts<o> // 'a.out';
# "All options" usage:
# - for options that take an argument, return an array of all
# the arguments supplied if specified more than once
# - for options that don't, return the option name as many times
# as it was specified
my %opts = getopts-all('o:v', @*ARGS);
$verbose_level = %opts<v>.elems;
for %opts<o> -> $fname {
process_outfile $fname;
}
# Permute usage (with both getopts() and getopts-all()):
# - don't stop at the first non-option argument, look for more
# arguments starting with a dash
# - stop at an -- argument
my Str:D %opts;
%opts = getopts('ho:V', @*ARGS, :permute);
```
# DESCRIPTION
This module exports the `getopts()` and `getopts-all()`> functions for parsing command-line arguments similarly to the POSIX getopt(3) standard C library routine.
The options are single letters (no long options) preceded by a single dash character. Options that do not accept arguments may be clustered (e.g. `-hV` for `-h` and `-V`); the last one may be an option that accepts an argument (e.g. `-vo outfile.txt`). Options that accept arguments may have their argument "glued" to the option or in the next element of the arguments array, i.e. `-ooutfile` is equivalent to `-o outfile`. There is no equals character between an option and its argument; if one is supplied, it will be considered the first character of the argument.
If an unrecognized option character is supplied in the arguments array, `getopts()` will throw an exception. Otherwise it will return a hash with the options found in the arguments array. The key in the returned hash is the option name (e.g. `h` or `o`); the value is the option argument for options that accept one or the option name (as many times as it has been specified) for options that do not.
# FUNCTIONS
* sub getopts
```
sub getopts(Str:D $optstr, @args, Bool :$nonopts,
Bool :$permute, Bool :$unknown) returns Hash[Str:D]
```
Look for the command-line options specified in `$optstr` in the `@args` array. Return the options found in a hash, leave only the non-option arguments in the `@args` array.
Note that if an option is specified more than once on the command line, `getopts()` will only record the last argument in the returned hash; see also the `getopts-all()` function below.
The `:permute` flag specifies whether option parsing should stop at the first non-option argument, or go on and process any other arguments starting with a dash. A double dash (--) stops the processing in this case, too.
The `:unknown` flag controls the handling of unknown options - ones not specified in the `$optstr`, but present in the `@args`. If it is false (the default), `getopts()` will throw an exception; otherwise, the unknown option character will be present in the returned hash as an argument to a `:` option and `getopts()` will still succeed. This is similar to the behavior of some `getopt(3)` implementations if `$optstr` starts with a `:` character.
The `:nonopts` flag makes `getopts()` treat each non-option argument as an argument to an option with a character code 1. This is similar to the behavior of some `getopt(3)` implementations if `$optstr` starts with a `-` character. The `:permute` flag is redundant if `:nonopts` is specified since the processing will not stop until the arguments array has been exhausted.
Throws an `X::Getopt::Std` exception if an invalid option string has been specified or an unknown option has been found in the arguments array.
Current API available since version 1.0.0.
* sub getopts-all
```
sub getopts-all(Str:D $optstr, @args, Bool :$nonopts,
Bool :$permute, Bool :$unknown) returns Hash[Array[Str:D]]
```
Same as the `getopts()` function, but all the returned values are arrays containing all the specified arguments if any options have been specified more than once.
For example, the command line -vI foo -I bar -v, matched against an option string of I:v, would produce `{ :I<bar> :v<vv> }` with `getopts()` and `{ :I(['foo', 'bar']) :v(['v', 'v']) }` with `getopts-all()`.
Current API available since version 1.0.0.
# AUTHOR
Peter Pentchev <[[email protected]](mailto:[email protected])>
# COPYRIGHT
Copyright (C) 2016, 2017, 2020 Peter Pentchev
# LICENSE
The Getopt::Std module is distributed under the terms of the Artistic License 2.0. For more details, see the full text of the license in the file LICENSE in the source distribution.
|
## dist_cpan-JNTHN-IO-Socket-Async-SSL.md
# IO::Socket::Async::SSL [Build Status](https://travis-ci.org/jnthn/p6-io-socket-async-ssl)
This module provides a secure sockets implementation with an API very much
like that of the Raku built-in `IO::Socket::Async` class. For the client
case, provided the standard certificate and host verification are sufficient,
it is drop-in replacement. The server case only needs two extra arguments to
`listen`, specifying the server key and certificate.
As with `IO::Socket::Async`, it is safe to have concurrent connections and to
share them across threads.
## Synopsis
Client:
```
use IO::Socket::Async::SSL;
my $conn = await IO::Socket::Async::SSL.connect('www.raku.org', 443);
$conn.print: "GET / HTTP/1.0\r\nHost: www.raku.org\r\n\r\n";
react {
whenever $conn {
.print
}
}
$conn.close;
```
Server (assumes certificate and key files `server-crt.pem` and `server-key.pem`):
```
use IO::Socket::Async::SSL;
react {
my %ssl-config =
certificate-file => 'server-crt.pem',
private-key-file => 'server-key.pem';
whenever IO::Socket::Async::SSL.listen('localhost', 4433, |%ssl-config) -> $conn {
my $req = '';
whenever $conn {
$req ~= $_;
if $req.contains("\r\n\r\n") {
say $req.lines[0];
await $conn.print(
"HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n" ~
"<strong>Hello from a Raku HTTP server</strong>\n");
$conn.close;
}
}
}
}
```
## Client
The `connect` method on `IO::Socket::Async::SSL` is used to establish a SSL
connection to a server. It requies two positional arguments, which specify the
`host` and `port` to connect to. It returns a `Promise`, which will be kept
with an `IO::Socket::Async::SSL` instance when the connection is established
and the SSL handshake completed.
```
my $conn = await IO::Socket::Async::SSL.connect($host, $port);
```
By default, the SSL certificate will be verified, using the default set of
accepted Certificate Authorities. The `Promise` return by `conenct` will be
broken if verification fails.
Sometimes it is convenient to create a CA and use it to sign certificates for
internal use, for example to secure communications between a set of services
on an internal network. In this case, the `ca-file` named argument can be
passed to specify the certificate authority certificate file:
```
my $ca-file = '/config/ca-crt.pem';
my $conn = await IO::Socket::Async::SSL.connect('user-service', 443, :$ca-file);
```
Alternatively, a `ca-path` argument can be specified, indicating a directory
where one or more certificates may be found.
It is possible to disable certificate verification by passing the `insecure`
named argument a true value. As the name suggests, **this is not a secure
configuration**, since there is no way for the client to be sure that it is
communicating with the intended server. Therefore, it is vulnerable to
man-in-the-middle attacks.
For control over the ciphers that may be used, pass the `ciphers` argument to
`connect`. It should be a string in [OpenSSL cipher list format](https://www.openssl.org/docs/man1.0.2/apps/ciphers.html).
If wishing to view encrypted traffic with a tool such as Wireshark for debugging
purposes, pass a filename to `ssl-key-log-file`. Session keys will be written to
this log file, and Wireshark can then be configured to introspect the encrypted
traffic (Preferences -> Protocols -> TLS -> (Pre-)-Master-Secret log filename). Note
that this key exposure compromises the security of the session!
## Server
The `listen` method returns a `Supply` that, when tapped, will start an SSL
server. The server can be shut down by closing the tap. Whenever a connection
is made to the server, the `Supply` will emit an `IO::Socket::Async::SSL`
instance. The `listen` method requires two positional arguments, specifying
the `host` and `port` to listen on. Two named arguments are also required,
providing the `certificate-file` and `private-key-file`.
```
my %ssl-config =
certificate-file => 'server-crt.pem',
private-key-file => 'server-key.pem';
my $connections = IO::Socket::Async::SSL.listen('localhost', 4433, |%ssl-config);
react {
my $listener = do whenever $connections -> $conn {
say "Got a connection!";
$conn.close;
}
whenever signal(SIGINT) {
say "Shutting down...";
$listener.close;
exit;
}
}
```
For control over the ciphers that may be used, pass the `ciphers` argument to
`connect`. It should be a string in [OpenSSL cipher list format](https://www.openssl.org/docs/man1.0.2/apps/ciphers.html). The following boolean options are also accepted:
* `prefer-server-ciphers` - indicates that the order of the ciphers list as
configured on the server should be preferred over that of the one presented
by the client
* `no-compression` - disables compression
* `no-session-resumption-on-renegotiation`
## Common client and server functionality
Both the `connect` and `listen` methods take the following optional named
arguments:
* `enc`, which specifies the encoding to use when the socket is used in
character mode. Defaults to `utf-8`.
* `scheduler`, which specifies the scheduler to use for processing events from
the underlying `IO::Socket::Async` instance. The default is `$*SCHEDULER`.
There is rarely a need to change this.
The `Supply`, `print`, `write`, and `close` methods have the same semantics as
in [IO::Socket::Async](https://docs.raku.org/type/IO$COLON$COLONSocket$COLON$COLONAsync).
## Upgrading connections
Some protocols use [opportunistic TLS](https://en.wikipedia.org/wiki/Opportunistic_TLS),
where the decision to use transport layer security is first negotiated using
a non-encrypted protocol - provided negotiation is successful - a TLS handshake
is then performed. This functionality is provided by the `upgrade-server` and
`upgrade-client` methods. Note that the socket to upgrade must be an instance
of `IO::Socket::Async`. Further, it is important to **stop reading from the
socket before initiating the upgrade**, which will typically entail working with
the `Tap` directly, something not normally needed in `react`/`whenever` blocks.
Here is an example of using `upgrade-server`.
```
react whenever IO::Socket::Async.listen('localhost', TEST_PORT) -> $plain-conn {
my $plain-tap = do whenever $plain-conn.Supply -> $start {
if $start eq "Psst, let's talk securely!\n" {
# Must stop reading...
$plain-tap.close;
# ...so the module can take over the socket.
my $enc-conn-handshake = IO::Socket::Async::SSL.upgrade-server(
$plain-conn,
private-key-file => 't/certs-and-keys/server.key',
certificate-file => 't/certs-and-keys/server-bundle.crt'
);
whenever $enc-conn-handshake -> $enc-conn {
uc-service($enc-conn);
}
$plain-conn.print("OK, let's talk securely!\n");
}
else {
$plain-conn.print("OK, let's talk insecurely\n");
uc-service($plain-conn);
}
}
sub uc-service($conn) {
whenever $conn -> $crypt-text {
whenever $conn.print($crypt-text.uc) {
$conn.close;
}
}
}
}
```
Here's an example using `upgrade-client`; again, take note of the careful handling
of the `Tap`.
```
my $plain-conn = await IO::Socket::Async.connect('localhost', TEST_PORT);
await $plain-conn.print("Psst, let's talk securely!\n");
react {
my $plain-tap = do whenever $plain-conn -> $msg {
$plain-tap.close;
my $enc-conn-handshake = IO::Socket::Async::SSL.upgrade-client(
$plain-conn,
host => 'localhost',
ca-file => 't/certs-and-keys/ca.crt');
whenever $enc-conn-handshake -> $enc-conn {
await $enc-conn.print("hello!\n");
whenever $enc-conn.head -> $got {
print $got; # HELLO!
done;
}
}
}
}
```
## Bugs, feature requests, and contributions
Please use [GitHub Issues](https://github.com/jnthn/p6-io-socket-async-ssl/issues)
to file bug reports and feature requests. If you wish to contribute to this
module, please open a GitHub Pull Request, or email a Git patch (produced using
`format-patch`) to [[email protected]](mailto:[email protected]). Please also use
this email address to report security vulnerabilities.
|
## changed.md
changed
Combined from primary sources listed below.
# [In IO::Special](#___top "go to top of document")[§](#(IO::Special)_method_changed "direct link")
See primary documentation
[in context](/type/IO/Special#method_changed)
for **method changed**.
```raku
method changed(IO::Special:D: --> Instant)
```
The last changed time for the filehandle. It always returns an [`Instant`](/type/Instant) type object.
# [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_changed "direct link")
See primary documentation
[in context](/type/IO/Path#method_changed)
for **method changed**.
Returns an [`Instant`](/type/Instant) object indicating the metadata of the file or directory was last changed (e.g. permissions, or files created/deleted in directory). Compare with [modified](/routine/modified).
```raku
say "path/to/file".IO.changed; # Instant:1424089165
say "path/to/file".IO.changed.DateTime; # 2015-02-16T12:18:50Z
```
|
## dist_cpan-CTILMES-Math-Primesieve.md
# Math::Primesieve
Raku bindings for [primesieve](http://primesieve.org/).
primesieve generates primes using a highly optimized [sieve of
Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) implementation. It counts the primes below 10¹⁰ in
just 0.45 seconds on an Intel Core i7-6700 CPU (4 x 3.4GHz).
primesieve can generate primes and [prime k-tuplets](http://en.wikipedia.org/wiki/Prime_k-tuple)
up to 2⁶⁴.
# USAGE
```
use Math::Primesieve;
my $p = Math::Primesieve.new;
say "Using libprimesieve version $p.version()";
say $p.primes(100); # Primes under 100
say $p.primes(100, 200); # Primes between 100 and 200
say $p.n-primes(20); # First 20 primes
say $p.n-primes(10, 1000); # 10 primes over 1000
say $p.nth-prime(10); # nth-prime
say $p[10]; # Can also just subscript for nth-prime
say $p.nth-prime(100, 1000); # 100th prime over 1000
say $p.count(10**9); # Count primes under 10^9
$p.print(10); # Print primes under 10
say $p.count(10**8, 10**9); # Count primes between 10^8 and 10^9
$p.print(10, 20); # Print primes between 10 and 20
```
Pass options :twins, :triplets, :quadruplets, :quintuplets,
:sextuplets to `count` or `print` for prime k-tuplets.
# Iterator
```
my $iterator = Math::Primesieve::iterator.new;
say $iterator.next for ^10; # Print first 10 primes;
$iterator.skipto(1000); # skip to a specific start (can also
# specify stop_hint)
say $iterator.next for ^10; # Print 10 primes over 1000
say $iterator.prev for ^10; # Previous primes
my $it = Math::Primesieve::iterator.new(1000); # Can start at a num
```
# INSTALLATION
First install the
[primesieve](https://github.com/kimwalisch/primesieve) library.
For Ubuntu linux, just run:
```
sudo apt install libprimesieve-dev
```
Then install this module in the normal way with zef.
```
zef install Math::Primesieve
```
|
## dist_zef-jjmerelo-Unicode-Security.md
# NAME [Test-install distro](https://github.com/JJ/raku-unicode-security/actions/workflows/test.yaml)
Unicode::Security - Check scripts for confusables and mixed script strings
# SYNOPSIS
```
use v6.d;
use Unicode::Security;
say "Nope" if mixed-script( "abcdef" );
say "Yea" if mixed-script( "aαbβ" );
say "Looks fake, Rick" if confusable('paypal',
"p\x[0430]yp\x[0430]l");
say "No problem" unless confusable('Paypal', 'paypal');
say "Not confusing" unless whole-script-confusable("Latin", "DFRVz");
say "Confusing" if whole-script-confusable("Cyrillic", "scope");
```
# DESCRIPTION
`Unicode::Security` is a (partial) transcription of its namesake Perl
module. It incorporates confusion tables from the Unicode consortium
to detect which graphemes can cause confusion between two alphabets,
or which strings could be confused between two or more alphabets; also
detect when some strings have mixed scripts, which can be used to slip
by literal-string detectors.
The list of confusables is generated from the list published by the
unicode consortium using the scripts in `resources/script`. You should
have received a copy along with this. The scripts generate two JSON
files, which must be moved by hand to the `resources/data`
directory. You don't need to do this unless you're certain that the
supplied copy is *really* out of sync with the real ones.
# METHODS
## sub confusable( $string-a, $string-b )
Returns true if one string could be confusable for the other.
## sub whole-script-confusable( $script, $string )
Returns True if the string would be confusable for another written in the indicated script
## sub mixed-script( $str )
Returns `True` if the string includes several scripts, `False` otherwise
## sub mixed-script-confusable( $str )
Returns `True` if the scripts present in a string could make it
confusable for any of them.
## Upgrading
This modules uses a couple of scripts to generate the tables used in it. It will be updated from time to time, but you can also update it by running the scripts included. It will need `LWP::Simple` and `IO::Socket::SSL` installed, besides those in `META6.json`
# AUTHOR
JJ Merelo [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2019,2022 JJ Merelo
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-jonathanstowe-Crypt-SodiumPasswordHash.md
# Crypt::SodiumPasswordHash
Password hashing using the libsodium recommended algorithm

## Synopsis
```
use Crypt::SodiumPasswordHash;
my $password = 'somepa55word';
my $hash = sodium-hash($password);
if sodium-verify($hash, $password ) {
# password ok
}
```
## Description
This module provides a binding to the password hashing functions provided by [libsodium](https://libsodium.gitbook.io/doc/).
The algorithm used is the one recomended by the installed version of libsodium. as of version 23 this is a variant of Argon2, but older versions may provide a different one as may future versions. Additionally the `sodium-verify` should be able to verify a password hash created by other libraries that support the Argon2 family such as Crypt::Argon2.
The hash returned by `sodium-hash` is in the format used in `/etc/shadow` and can be verified by other libraries that understand the algorithm. By default the *interactive* limits for memory and CPU usage are used, which is a reasonable compromise for the time taken for both hashing and verification. If the `:sensitive` switch is supplied to `sodium-hash` then both hashing and verification take significantly longer (and use more memory,) so this may not suitable for some applications.
## Installation
You will need to have C installed for this to work, it is commonly packaged for various Linux distributions, so you should be able
to use the usual package management tools.
Assuming that you have a working installation of Rakudo then you should be able to install this with *zef* :
```
zef install Crypt::SodiumPasswordHash
# Or from a local clone
zef install .
```
The tests take a little longer than might be expected because it tests the *sensitive* profile which is designed to take longer.
## Support
If you any suggestions/patches feel free to send them via:
<https://github.com/jonathanstowe/Crypt-SodiumPasswordHash/issues>
I've tested this with libsodium versions from 13 to 23, but if you find it doesn't work please let me know which version you have installed.
## Licence & Copyright
This is free software please see the <LICENCE> file in the distribution
for details.
© Jonathan Stowe 2019 - 2021
|
## dist_cpan-JJATRIA-HTTP-Tiny.md
## NAME
HTTP::Tiny - A small, simple, correct HTTP/1.1 client
## SYNOPSIS
```
use HTTP::Tiny;
my $response = HTTP::Tiny.new.get: 'http://httpbin.org/get';
die "Failed!\n" unless $response<success>;
say "$response<status> $response<reason>";
# OUTPUT:
# 200 OK
for $response<headers>.kv -> $key, $v {
for $v.List -> $value {
say "$key: $value";
}
}
# OUTPUT:
# content-type: application/json
# date: Fri, 09 Oct 2020 21:49:38 GMT
# connection: close
# content-length: 230
# server: gunicorn/19.9.0
# access-control-allow-origin: *
# access-control-allow-credentials: true
print $response<content>.decode if $response<content>;
# OUTPUT:
# {
# "args": {},
# "headers": {
# "Host": "httpbin.org",
# "User-Agent": "HTTP-Tiny",
# "X-Amzn-Trace-Id": "..."
# },
# "origin": "...",
# "url": "http://httpbin.org/get"
# }
```
## DESCRIPTION
This is a very simple but correct HTTP/1.1 client, designed for doing simple
requests without the overhead of a large framework like HTTP::UserAgent.
It is a Raku port of the Perl library of the same name. It supports
redirection, streaming requests and responses, multipart and URL-encoded
form uploads, and correctly handles multipart responses to ranged requests.
Cookie support is not yet implemented.
## METHODS
Calling the `new` method to construct an object is optional when using the
methods described in this section. When not doing so, `new` will be called
automatically before executing the request, and the created object will be
discarded after the request is complete.
### new
```
method new (
:%default-headers,
Set() :%no-proxy,
Str :$http-proxy,
Str :$https-proxy,
Str :$agent = 'HTTP-Tiny/VERSION Raku',
Int :$max-redirect = 5,
Bool :$keep-alive,
Bool :$throw-exceptions,
) returns HTTP::Tiny
```
Creates a new HTTP::Tiny object. The following attributes are parameters:
#### default-headers
A Hash of default headers to apply to requests. Headers specified during the
call take precedence over the ones specified here.
#### agent
A Str to use as the value of the `User-Agent` header. Defaults to
'HTTP-Tiny/$VERSION Raku'.
#### max-redirect
Maximum number of redirects allowed. Defaults to 5. Set to 0 to prevent
redirection.
#### keep-alive
Whether to re-use the last connection, if it is for the same scheme, host,
and port. Defaults to True.
#### throw-exceptions
When set to True, non-success HTTP responses will throw a `X::HTTP::Tiny`
exception. The original error response Hash will be available as the result of
the `.response` method of the exception.
#### proxy
URL of a generic proxy server for both HTTP and HTTPS connections.
Defaults to the value in the `all_proxy` or `ALL_PROXY` environment
variables (in that order). Set to the empty string to ignore variables set in
the environment.
#### no-proxy
Set of domain suffixes that should not be proxied. Any value that implements
the `Set` method is allowed. A Str is also allowed, in which case it must be
a comma-separated list of suffixes that will be split, trimmed, and coerced to
a Set.
Defaults to the value in the `no_proxy`, which will be treated like the Str
case described above.
#### http-proxy
URL of a proxy server for HTTP connections.
Defaults to the value in the `http_proxy` or `HTTP_PROXY` environment
variables, or to the value of the `proxy` parameter described above (in that
order). Set to the empty string to ignore variables set in the environment.
#### https-proxy
URL of a proxy server for HTTPS connections.
Defaults to the value in the `https_proxy` or `HTTPS_PROXY` environment
variables, or to the value of the `proxy` parameter described above (in that
order). Set to the empty string to ignore variables set in the environment.
### delete
Shorthand method for calling `request` with 'DELETE' as the method. See the
documentation for `request` for full details on the supported parameters and
the return value.
### get
Shorthand method for calling `request` with 'GET' as the method. See the
documentation for `request` for full details on the supported parameters and
the return value.
### head
Shorthand method for calling `request` with 'HEAD' as the method. See the
documentation for `request` for full details on the supported parameters and
the return value.
### options
Shorthand method for calling `request` with 'OPTIONS' as the method. See the
documentation for `request` for full details on the supported parameters and
the return value.
### patch
Shorthand method for calling `request` with 'PATCH' as the method. See the
documentation for `request` for full details on the supported parameters and
the return value.
### post
Shorthand method for calling `request` with 'POST' as the method. See the
documentation for `request` for full details on the supported parameters and
the return value.
### put
Shorthand method for calling `request` with 'PUT' as the method. See the
documentation for `request` for full details on the supported parameters and
the return value.
### trace
Shorthand method for calling `request` with 'TRACE' as the method. See the
documentation for `request` for full details on the supported parameters and
the return value.
### request
```
method request (
Str $method,
Str $url,
:%headers,
:$content,
:&data-callback,
:&trailer-callback,
) returns Hash
```
Executes an HTTP request of the given method type on the given URL. The URL
must have unsafe characters escaped and international domains encoded. Valid
HTTP methods are 'GET', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT',
and 'TRACE', with their names being case sensitive as per the HTTP/1.1
specification.
If the URL includes a "user:password" stanza, they will be used for
Basic-style authorisation headers. For example:
```
$ua.request: 'GET', 'http://Aladdin:open [email protected]/';
```
If the "user:password" stanza contains reserved characters, they must
be percent-escaped:
```
$ua.request: 'GET', 'http://john%40example.com:[email protected]/';
```
The `Authorization` header generated from these data will not be included
in a redirected request. If you want to avoid this behaviour you can set the
value manually, in which case it will not be modified or ignored.
The remaining named parameters are detailed below.
#### %headers
A map of headers to include with the request. If the value is a List of
strings, the header will be output multiple times, once with each value in the
array. The headers specified in this parameter overwrite any default ones.
The `Host` header is internally generated from the request URL [in accordance
with RFC 7230](https://tools.ietf.org/html/rfc7230#section-5.4). It is a fatal error to specify this header. Other
headers may be ignored or overwritten if necessary for transport compliance,
but this will in general be avoided.
#### $content
A value to use for the body of the request, which can be a Blob, a Str or
Numeric, a Hash, or a Callable, with each of these modifying the default
assumptions about the request.
If `$content` is a Blob, the `Content-Type` header will default to
`application/octet-stream` and the contents of the Blob will be used as-is as
the body. The `Content-Length` header will also default to the number of
bytes in the Blob.
If `$content` is a Str or Numeric, it will be stringified by calling `Str`
on it and internally encoded as UTF-8 and converted to a Blob. The
`Content-Type` will in this case default to `text/plain;charset=UTF-8`,
but handling will otherwise be as detailed above.
If `$content` is a Hash, the default content type will depend on the values.
If any of the values is an IO::Path object it will be `multipart/form-data`,
otherwise it will be `application/x-www-form-urlencoded`.
If `$content` is a Callable, it will be called iteratively to produce the
body of the request. When called, it must return a Blob with the next part
of the body until the body has been fully generated, in which case it must
return an empty Blob, or a Blob type object.
Note that these behaviours are the *default* behaviours, and represent the
assumptions that will be made about the request based on the input.
When using a Callable, the `Content-Type` will default to
`application/octet-stream` and if no `Content-Length` header has been set,
the `Transfer-Encoding` will default to `chunked`, with each new part of the
body being sent in a separate chunk.
When using a Hash, its contents will be encoded depending on the value of the
`Content-Type` header. Using IO::Path objects as values is only supported
with multipart form encoding. If a value is a IO::Path, IO::Handle, or
anything that supports the `slurp` method, this will be called with the
`:bin` argument to provide the value of that key, and the content type will
be set to `application/octet-stream`. If using an IO::Path object, the
filename will be set to the result of calling `basename`.
If no value is set, no `Content-Type` or `Content-Length` headers will be
generated.
#### &data-callback
The data callback takes a block of code that will be executed once with each
chunk of the response body. The callback will be introspected to determine
how many arguments it can receive, and will be called with up to three
arguments each time:
* A Blob with the current encoded response chunk
* A Hash with the current state of the response Hash
* A Hash with the part headers (only for multipart responses)
This should allow customising the behaviour of the callback depending on the
response status or headers before receiving the full response body.
The callback must support at least the Blob argument. The other two are
optional. Not supporting any of these is an error.
#### &trailer-callback
When using a chunked transfer encoding, this callback will be called once after
the request body has been sent. It should return a Hash which will be used to
add trailing headers to the request.
#### The response Hash
The `request` method returns a Hash with the response. The Hash will have the
following keys:
success
: A Bool that will be true if the response status code starts with a 2.
url
: The URL that provided the response as a Str. This will be the URL provided by
the caller unless there were redirections, in which case it will be the last
URL queried in the redirection chain.
status
: The HTTP status code of the response as an Int.
reason
: The response phrase as provided by the server.
content
: The body of the response as a Buf[uint8]. This key will be missing if the
response had no content or if a data callback was provided to consume the
body. HTTP::Tiny will never automatically decode a response body.
headers
: A Hash of header fields. All header fields will be normalised to be lower
case. If a header is repeated, the value will be a List with the received
values as Str objects. Otherwise, the value will be a Str. Header values will
be decoded using ISO-8859-1 as per [RFC 7230 § 3.2.4](https://tools.ietf.org/html/rfc7230#section-3.2.4).
protocol
: The protocol of the response, such as 'HTTP/1.1' or 'HTTP/1.0'.
redirects
: If this key exists, it will hold a List of response Hash objects from the
encountered redirects in the order they occurred. This key will no exist if
no redirection took place.
If an exception is encountered during execution, the `status` field will be
set to '599' and the `content` field will hold the text of the exception.
### mirror
```
method mirror (
Str $url,
IO() $file,
:$content,
:%headers,
:&trailer-callback,
) returns Hash
```
Executes a `GET` request for the URL and saves the response body to the
specified file. The URL must have unsafe characters escaped and
international domain names encoded. If the file already exists, the request
will include an `If-Modified-Since` header with the modification timestamp
of the file if none has already been provided in the `:%headers` parameter.
The parent directories of the file will not be automatically created.
The value of `$file` can be anything that implements an `.IO` method.
The `success` field of the response will be true if the status code is 2XX
or if the status code is 304 (unmodified).
If the file was modified and the server response includes a properly formatted
`Last-Modified` header, the file modification time will be updated
accordingly. Note that currently this makes use of the `touch` system
command,and will therefore not work if this command is not available.
### can-ssl
```
with HTTP::Tiny.can-ssl {
# SSL support is available
}
else {
note 'SSL support not available: ' ~ .exception.message;
}
```
Indicates if SSL support is available by checking for the correct version
of IO::Socket::SSL (greater than or equal to 0.0.2). It will either return
True if SSL support is available, or a Failure indicating why it isn't.
## PROXY SUPPORT
HTTP::Tiny can proxy both HTTP and HTTPS requests. Only Basic proxy
authorization is supported and it must be provided as part of the proxy URL,
as in `http://user:[email protected]/`.
HTTP::Tiny supports the following proxy environment variables:
* `http_proxy` or `HTTP_PROXY`
* `https_proxy` or `HTTPS_PROXY`
* `all_proxy` or `ALL_PROXY`
An HTTPS connection may be made via an HTTP proxy that supports the
`CONNECT` method (cf. RFC 2817). If your proxy itself uses HTTPS, you can
not tunnel HTTPS over it.
Be warned that proxying an HTTPS connection opens you to the risk of a
man-in-the-middle attack by the proxy server.
The `no_proxy` environment variable is supported in the format of a
comma-separated list of domain extensions proxy should not be used for.
Proxy arguments passed to `new` will override their corresponding
environment variables.
## LIMITATIONS
HTTP::Tiny aims to be *conditionally compliant* with the
[HTTP/1.1 specifications](http://www.w3.org/Protocols/):
* ["Message Syntax and Routing" [RFC7230]](https://tools.ietf.org/html/rfc7230)
* ["Semantics and Content" [RFC7231]](https://tools.ietf.org/html/rfc7231)
* ["Conditional Requests" [RFC7232]](https://tools.ietf.org/html/rfc7232)
* ["Range Requests" [RFC7233]](https://tools.ietf.org/html/rfc7233)
* ["Caching" [RFC7234]](https://tools.ietf.org/html/rfc7234)
* ["Authentication" [RFC7235]](https://tools.ietf.org/html/rfc7235)
It aims to meet all "MUST" requirements of the specification, but only some
of the "SHOULD" requirements.
Some particular limitations of note include:
* HTTP::Tiny focuses on correct transport. Users are responsible for
ensuring that user-defined headers and content are compliant with the
HTTP/1.1 specification.
* Users must ensure that URLs are properly escaped for unsafe characters
and that international domain names are properly encoded to ASCII.
* Redirection is very strict against the specification. Redirection is
only automatic for response codes 301, 302, 307 and 308 if the request
method is `GET` or `HEAD`. Response code 303 is always converted into a
`GET` redirection, as mandated by the specification. There is no
automatic support for status 305 ("Use proxy") redirections.
* There is no provision for delaying a request body using an `Expect`
header. Unexpected `1XX` responses are silently ignored as per the
specification.
* Only 'chunked' `Transfer-Encoding` is supported.
* There is no support for a Request-URI of `*` for the `OPTIONS` request.
* Headers mentioned in the RFCs and some other, well-known headers are
generated with their canonical case. The order of headers is not
preserved: control headers are sent first, while the remainder are sent
in an unspecified order.
* No mitigations for [httpoxy](https://httpoxy.org) have been implemented.
If you are using this library under CGI, you are on your own.
## SEE ALSO
### [HTTP::UserAgent](https://modules.raku.org/dist/HTTP::UserAgent:github:github:sergot)
The de-facto blocking HTTP client for Raku, used by most applications. If a
feature you want is not supported by HTTP::Tiny, try using this distribution.
It is included in the Rakudo Star distribution, so chances are you already
have it.
That said, at the time of writing HTTP::UserAgent does not handle 1XX
responses, nor does it support chunked requests.
### [Cro::HTTP](https://modules.raku.org/dist/Cro::HTTP:cpan:JNTHN)
Part of the Cro family of libraries, it is written with asynchronous code as
its primary goal. Supports HTTP/2.0.
### [HTTP::Tinyish](https://modules.raku.org/dist/HTTP::Tinyish:cpan:SKAJI)
Another port from Perl, HTTP::Tinyish offers a similar interface to this
library while relying on an externally available `curl` binary.
### [LibCurl](https://modules.raku.org/dist/LibCurl:cpan:CTILMES)
Raku bindings for libcurl. The bindings are fairly low-level, so they allow
for finer control than HTTP::Tinyish, but at the cost of a more complicated
interface.
### [LWP::Simple](https://modules.raku.org/dist/LWP::Simple:github:Cosimo%20Streppone)
An older an more barebones blocking HTTP client for Raku, preceding the
development of HTTP::UserAgent.
### [Net::HTTP](https://modules.raku.org/dist/Net::HTTP:github:ugexe)
A library providing the building blocks to write your own HTTP client.
Supports connection caching and should be thread safe.
Code is fairly low-level, so use in real-world scenarios might require
some effort until more progress is done in the implementation of classes
like Net::HTTP::Client.
## AUTHOR
José Joaquín Atria [[email protected]](mailto:[email protected])
## ACKNOWLEDGEMENTS
The code in this distribution is heavily inspired by that of
[the Perl library of the same name](https://metacpan.org/pod/HTTP::Tiny),
written by Christian Hansen and David Golden.
Some parts of the code have been adapted from existing solutions in the
HTTP::UserAgent codebase, which served as a reference on the use of Raku
toolbox.
## COPYRIGHT AND LICENSE
Copyright 2020 José Joaquín Atria
This library is free software; you can redistribute it and/or modify it
under the Artistic License 2.0.
|
## dist_zef-massa-Net-NetRC.md
[](https://github.com/massa/Net-NetRC/actions)
# NAME
Net::NetRC - parse `.netrc` files
# SYNOPSIS
```
use Net::NetRC;
my $x = netrc;
say $x<google.com><login>;
my $y = netrc 'machine azul.example.com login massa password j4k3';
say $y<azul.com><password>;
my $z = netrc '/home/myname/.netrc.alternate';
```
# DESCRIPTION
Net::NetRC is a basic parser for the `.netrc` file format.
I made it as a simple way of obtaining logins and passwords for many other projects.
# AUTHOR
Humberto Massa [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright © 2022 - 2024 Humberto Massa
This library is free software; you can redistribute it and/or modify it under either the Artistic License 2.0 or the LGPL v3.0, at your convenience.
|
## dist_zef-raku-land-URI-Query-FromHash.md
# NAME
URI::Query::FromHash - Construct a query string from a hash
# SYNOPSIS
```
use URI::Query::FromHash;
say hash2query {
foo => 'bar',
baz => < qux quux >,
utf8 => '🦋',
}
# OUTPUT:
# baz=qux&baz=quux&foo=bar&utf8=%F0%9F%A6%8B
```
# DESCRIPTION
URI::Query::FromHash aims to be a fast and lightweight query string
constructor, that does the smallest amount of escaping as possible.
Inspired by [the Perl module of the same name](https://metacpan.org/pod/URI::Query::FromHash) and Ruby on Rails'
[to\_query](http://api.rubyonrails.org/classes/Hash.html#method-i-to_query) hash method.
# SUBROUTINES
## hash2query
```
sub hash2query ( Hash() $hash --> Str )
```
Accepts anything that can be coerced to a Hash of query parameters and
returns a Str suitable to be used as the query parameters of a URI.
Pairs in the input Hash will be processed alphabetically by key.
Values in the coerced Hash should be either objects that can be coerced
to Str; objects that do the Blob role; Bool objects; or List objects whose
elements are any of the ones specified before.
Every value (or element in a List) will appear in the generated query string
once, preceded by the corresponding URL-encoded key and an equal sign (C<=>).
If it is a Blob, it will be URL-encoded per byte, with any byte that does not
map to an ASCII period (`.`), underscore (`_`), hyphen (`-`), tilde (`~`),
or alphanumeric character being percent-encoded (that is, represented by a
percent sign (`%`) followed by the hexadecimal representation of the byte in
uppercase).
Bool objects will be rendered as `1` if true or `0` if false.
Otherwise, it will be coerced to Str, encoded as UTF-8 and URL-encoded like
above.
When this function encounters input it cannot handle, it returns the empty
string, meaning it should always be safe to use.
This function is exported by default, but it can be used as a package
subroutine if desired.
# COPYRIGHT AND LICENSE
Copyright © 2022 by Raku Land authors
This library is free software; you can redistribute it and/or modify it under
the Artistic License 2.0.
|
## uni.md
class Uni
A string of Unicode codepoints
```raku
class Uni does Positional[uint32] does Stringy { }
```
Unlike [`Str`](/type/Str), which is made of Grapheme clusters, Uni is string strictly made of Unicode codepoints. That is, base characters and combining characters are separate elements of a `Uni` instance.
`Uni` presents itself with a list-like interface of integer Codepoints.
Typical usage of `Uni` is through one of its subclasses, [`NFC`](/type/NFC), [`NFD`](/type/NFD), [`NFKD`](/type/NFKD) and [`NFKC`](/type/NFKC), which represent strings in one of the [Unicode Normalization Forms](https://www.unicode.org/reports/tr15/) of the same name.
# [Methods](#class_Uni "go to top of document")[§](#Methods "direct link")
## [method new](#class_Uni "go to top of document")[§](#method_new "direct link")
```raku
method new(*@codes --> Uni:D)
```
Creates a new `Uni` instance from the given codepoint numbers.
## [method list](#class_Uni "go to top of document")[§](#method_list "direct link")
```raku
method list(Uni:D:)
```
Returns a [`Seq`](/type/Seq) of integer codepoints.
## [method NFC](#class_Uni "go to top of document")[§](#method_NFC "direct link")
```raku
method NFC(Uni:D: --> NFC:D)
```
Returns an [`NFC`](/type/NFC) (Normal Form Composed)-converted version of the invocant.
## [method NFD](#class_Uni "go to top of document")[§](#method_NFD "direct link")
```raku
method NFD(Uni:D: --> NFD:D)
```
Returns an [`NFD`](/type/NFD) (Normal Form Decomposed)-converted version of the invocant.
## [method NFKC](#class_Uni "go to top of document")[§](#method_NFKC "direct link")
```raku
method NFKC(Uni:D: --> NFKC:D)
```
Returns an [`NFKC`](/type/NFKC) (Normal Form Compatibility Composed)-converted version of the invocant.
## [method NFKD](#class_Uni "go to top of document")[§](#method_NFKD "direct link")
```raku
method NFKD(Uni:D: --> NFKD:D)
```
Returns an [`NFKD`](/type/NFKD) (Normal Form Compatibility Decomposed)-converted version of the invocant.
## [method codes](#class_Uni "go to top of document")[§](#method_codes "direct link")
```raku
method codes(Uni:D: --> Int:D)
```
Returns the number of codepoints in the invocant.
## [method elems](#class_Uni "go to top of document")[§](#method_elems "direct link")
```raku
method elems(Uni:D: --> Int:D)
```
Returns the number of codepoints in the invocant.
# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")
Type relations for `Uni`
raku-type-graph
Uni
Uni
Any
Any
Uni->Any
Positional
Positional
Uni->Positional
Stringy
Stringy
Uni->Stringy
Mu
Mu
Any->Mu
NFKC
NFKC
NFKC->Uni
NFD
NFD
NFD->Uni
NFC
NFC
NFC->Uni
NFKD
NFKD
NFKD->Uni
[Expand chart above](/assets/typegraphs/Uni.svg)
|
## dist_cpan-HANENKAMP-DateTime-DST.md
# NAME
DateTime::DST - make localtime[8] available as is-dst()
# SYNOPSIS
```
use DateTime::DST;
my $non-dst = DateTime.new(:2016year, :1month, :15day, :0hour, :0minute, :0second);
my $dst = DateTime.new(:2016year, :6month, :15day, :0hour, :0minute, :0second);
say is-dst($non-dst); # False
say is-dst($non-dst.Instant); # False
say is-dst($non-dst.posix); # False
say is-dst($dst); # True
say is-dst($dst.Instant); # True
say is-dst($dst.posix); # True
```
# DESCRIPTION
This is nothing too fancy, just exports a function named `is-dst` which can be used to test for Daylight Savings Time from a DateTime object, an Int (expecting seconds since the start of the POSIX time\_t epoch), or an Instant.
# FUNCTIONS
## is-dst
```
multi is-dst(Instant $time) returns Bool
multi is-dst(DateTime $time) returns Bool
multi is-dst(Int $time) returns Bool
```
Returns `True` if the C-standard library `localtime` function returns a true value for the DST flag or `False` otherwise. This is basically the same as `localtime($time)[8]` in Perl 5.
# AUTHOR
Sterling Hanenkamp `<[email protected]>`
# COPYRIGHT AND LICENSE
Copyright 2016 Andrew Sterling Hanenkamp.
This software is made available under the same terms as Perl 6 itself.
|
## dist_zef-jaguart-Grok.md
[](https://github.com/jaguart/Grok/actions)

# NAME
grok, wisp - introspection helpers.
# SYNOPSIS
From the command line:
```
raku -MGrok -e 'grok( my $a = 42, :deeply :core)'
raku -MGrok -e 'say wisp( Endian )'
```
Within Raku code:
```
use Grok :wisp;
# print the Endian enumerations...
say wisp( Endian );
# Endian - Enum is: Int Cool Any Mu enums: NativeEndian LittleEndian BigEndian
# print Allomorth attributes, methods and recurse into parents, roles including ::CORE types
grok( Allomorph, :deeply, :core )
# lots of output ...
```
# DESCRIPTION
Grok contains introspection helpers that display information about Raku things.
For example: You want to know how many times a sub is wrapped - grok a golf to see what methods are available.
```
>raku -MGrok -e 'sub s { say "s" }; &s.wrap({ say "w"; next }); grok( &s );'
#s - () Sub+{Routine::Wrapped}
# Sub - Class is: Routine Block Code Any Mu does: Callable
# Routine - Class is: Block Code Any Mu does: Callable
# Block - Class is: Code Any Mu does: Callable
# Code - Class is: Any Mu does: Callable
# Any - Class is: Mu
# Mu - Class
# Routine::Wrapped - Role
# Callable - Role
# $!dispatcher - Mu private read-only in Routine
# $!do - Code private read-only in Code
# $!flags - int private read-only in Routine
# $!inline_info - Mu private read-only in Routine
# $!package - Mu private read-only in Routine
# $!phasers - Mu private read-only in Block
# $!signature - Signature private read-only in Code
# $!why - Mu private read-only in Block
# $!wrapper-type - Routine private read-only in Sub+{Routine::Wrapped}
# $!wrappers - Mu private read-only in Sub+{Routine::Wrapped}
# @!compstuff - List private read-only in Code
# @!dispatch_order - List private read-only in Routine
# @!dispatchees - List private read-only in Routine
# ADD-WRAPPER - (Sub+{Routine::Wrapped}: &wrapper, *%_ --> Nil) Method in Routine::Wrapped
# REMOVE-WRAPPER - (Sub+{Routine::Wrapped}: &wrapper, *%_ --> Bool) Method in Routine::Wrapped
# WRAPPER-TYPE - (Sub+{Routine::Wrapped}: *%_) Method in Routine::Wrapped
# WRAPPERS - (Sub+{Routine::Wrapped}: *%_) Method in Routine::Wrapped
# is-wrapped - (Sub+{Routine::Wrapped}: *%_ --> Bool) Method in Routine::Wrapped
```
... and you conclude it's worth checking out `.WRAPPERS.elems`.
### sub grok
```
sub grok(
Mu $thing is raw,
:$deeply = Bool::False,
:$core = Bool::False,
:$local = Bool::False,
:$detail = Bool::False,
:$where = Nil
) returns Mu
```
Introspect a thing. `grok( Allomorph, :deeply, :core );`
* **:deeply** - recurse into parents, roles etc.
* **:core** - include core classes.
* **:local** - skip composed / imported methods.
* **:detail** - include extra detail.
* **:where** - True - show in-package, False - hide in-package, Default - show imported package names.
### sub wisp
```
sub wisp(
Mu $thing is raw
) returns Wisp
```
An introspection helper - e.g. `say wisp( Endian )`
Provides:
* **.gist**
* **.detail**
# AUTHOR
Jeff Armstrong [[email protected]](mailto:[email protected])
Source can be found at: <https://github.com/jaguart/Grok>
This is my first Raku module - comments and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2022 Jeff Armstrong
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_github-azawawi-Graphics-PLplot.md
# Graphics::PLplot
[](https://travis-ci.org/azawawi/perl6-graphics-plplot) [](https://ci.appveyor.com/project/azawawi/perl6-graphics-plplot/branch/master)
This module provides Perl 6 low and high-level native bindings for
[PLplot](http://plplot.sourceforge.net/).
Note: Currently work in progress and the API is being implemented one brick at
a time. Help and feedback is appreciated.
PLplot is a library of subroutines that are often used to make scientific plots
in various compiled languages. PLplot can also be used interactively by
interpreted languages such as Octave, Python, Perl and Tcl. The current version
was written primarily by Maurice J. LeBrun and Geoffrey Furnish and is licensed
under LGPL.
## Example
```
use v6;
use Graphics::PLplot;
if Graphics::PLplot.new(
device => "png",
file-name => "output.png"
) -> $plot {
# Begin plotting
$plot.begin;
# Create a labeled box to hold the plot.
my $y-max = 100;
$plot.environment(
x-range => [0.0, 1.0],
y-range => [0.0, $y-max],
just => 0,
axis => 0,
);
$plot.label(
x-axis => "x",
y-axis => "y=100 x#u2#d",
title => "Simple PLplot demo of a 2D line plot",
);
# Prepare data to be plotted.
constant NSIZE = 101;
my @points = gather {
for 0..^NSIZE -> $i {
my $x = Num($i) / (NSIZE - 1);
my $y = Num($y-max * $x * $x);
take ($x, $y);
}
};
# Plot the data that was prepared above.
$plot.line(@points);
LEAVE {
$plot.end;
}
}
```
For more examples, please see the <examples> folder.
## Installation
* On Debian-based linux distributions, please use the following command:
```
$ sudo apt install libplplot-dev
```
* On Mac OS X, please use the following command:
```
$ brew update
$ brew install plplot
```
* Using zef (a module management tool bundled with Rakudo Star):
```
$ zef install Graphics::PLplot
```
## Testing
* To run tests:
```
$ prove -ve "perl6 -Ilib"
```
* To run all tests including author tests (Please make sure
[Test::Meta](https://github.com/jonathanstowe/Test-META) is installed):
```
$ zef install Test::META
$ AUTHOR_TESTING=1 prove -e "perl6 -Ilib"
```
## Author
Ahmad M. Zawawi, azawawi on #perl6, <https://github.com/azawawi/>
## License
MIT
|
## dist_cpan-MARTIMM-Gnome-Glib.md

# Gnome Glib - C-based object and type system

Note that all modules are now in `:api<1>`. This is done to prevent clashes with future distributions having the same class names only differing in this api string. So, add this string to your import statements and dependency modules of these classes in META6.json. Furthermore add this api string also when installing with zef.
Example;
```
use Gnome::Gtk3::Main:api<1>;
use Gnome::Gtk3::Window:api<1>;
use Gnome::Gtk3::Grid:api<1>;
use Gnome::Gtk3::Button:api<1>;
my Gnome::Gtk3::Main $m .= new;
… etcetera …
```
## Documentation
* [🔗 License document](http://www.perlfoundation.org/artistic_license_2_0)
* [🔗 Release notes](https://github.com/MARTIMM/gnome-glib/blob/master/CHANGES.md)
* [🔗 Issues](https://github.com/MARTIMM/gnome-gtk3/issues)
# Installation
Do not install this package on its own. Instead install `Gnome::Gtk3<1>`.
`zef install 'Gnome::Gtk3:api<1>'`
# Author
Name: **Marcel Timmerman**
Github account name: **MARTIMM**
# Issues
There are always some problems! If you find one, please help by filing an issue at [my Gnome::Gtk3 github project](https://github.com/MARTIMM/gnome-gtk3/issues).
# Attribution
* The developers of Raku of course and the writers of the documentation which helped me out every time again and again.
* The builders of all the Gnome libraries and its documentation.
* Other helpful modules for their insight and use.
|
## dist_github-GildedHonour-TelegramBot.md
# Telegram Bot [Build Status](https://travis-ci.org/GildedHonour/TelegramBot)
A genuine Perl 6 client for the [Telegram's Bot API](https://core.telegram.org/bots).
## Does anyone want to become the maintainer?
Shoot me a text
## Example
```
use Telegram;
my $token = "xxx:yyy"; # replace with your token
my $bot = Telegram::Bot.new($token);
my $res = $bot.get-me();
say $res;
```
## Installation
```
$ zef install TelegramBot
```
## Tests
```
PERL6LIB=lib prove -e perl6 t
```
## Author
[Alex Maslakov](http://gildedhonour.com)
## Contributors
Martin Barth (ufobat)
David Warring (dwarring)
## License
Apache 2.0
|
## dist_github-Skarsnik-NativeCall-TypeDiag.md
# Name NativeCall::TypeDiag
# Synopsis
```
use v6;
use Gumbo::Binding;
use NativeCall::TypeDiag;
my @headers = <gumbo.h>;
my @libs = <-lgumbo>;
my %typ;
# Construct the type from the exported stuff
for Gumbo::Binding::EXPORT::DEFAULT::.keys -> $export {
if ::($export).REPR eq 'CStruct' {
#convert foo_bar_s to FooBar
my $cname = $export.subst(/_s$/, '');
my @t = $cname.split('_').map: {.tc};
%typ{@t.join('')} = ::($export);
}
}
diag-cstructs(:cheaders(@headers), :types(%typ), :clibs(@libs));
```
# Description
A module that provide functions to look at your native types. Comparing with the their C equivalent.
## diag-struct ($ctypename, $nctype, :@cheaders, :@clibs = ())
Analyse the size of the fields of a CStruct and compare them to their C counterpart. It also show potential mistakes
return true if there is no error.
@cheaders is what you need to include to compile a C file using the lib. @clibs is extra options to the compiler.
## diag-cstructs(:@cheaders, :@clibs = (), :%types)
Analyse a given list of structures
%types pairs must look like this :
`"C name of the struct" => ::("name of NC type")`
return true if there is no error.
## diag-functions(:@functions)
REMOVED. It's now part of NativeCall
## @nctd-extracompileroptions
An array that is passed as option to the compiler `cc`
## Example
From one example in the examples folder.
```
use v6;
use NativeCall;
use NativeCall::TypeDiag;
class wrong_rgba_color_s is repr('CStruct'){
has int32 $.red;
has int32 $.blue;
has int32 $.green;
}
class rgba_color_s is repr('CStruct'){
has int32 $.red;
has int32 $.blue;
has int32 $.green;
has int32 $.alpha;
}
#struct s_toyunda_sub {
# usigned int start;
# usigned int stop;
# char* text;
# rgba_color_t color1;
# rgba_color_t color2;
# rgba_color_t tmpcolor;
# float positionx;
# float positiony;
# float position2x;
# float position2y;
# float fadingpositionx;
# float fadingpositiony;
# int size;
# int size2;
# int fadingsize;
# char* image;
#};
class toyunda_subtitle_s is repr('CStruct') {
has int32 $.start;
has int32 $.stop;
has Str $.text;
HAS rgba_color_s $.color1;
HAS rgba_color_s $.color2;
has rgba_color_s $.tmpcolor;
has num32 $.positionx;
has num32 $.positiony;
has num32 $.position2x;
has num32 $.position2y;
has num32 $.fadingpositionx;
has num32 $.fadingpositiony;
has int32 $.size;
has int32 $.size2;
has int32 $.fadingsize;
has str $.image;
}
my @h = <toyundatype.h>;
my @l;
@nctd-extracompileroptions = "-I", "./";
diag-struct("rgba_color_t", wrong_rgba_color_s, :cheaders(@h));
say "----";
diag-struct("toyunda_sub_t", toyunda_subtitle_s, :cheaders(@h));
say "\n Some function \n";
sub foo1(Str $a, Int $b) is native('whatever') { * };
sub foo2(Num $a, Int $b) is native('whatever') { * };
sub foo3(Str $a, int32 $b) is native('whatever') returns Int { * };
diag-functions(:functions([&foo1, &foo2, &foo3]));
```
Its output
```
Compiling a test file, this assume field names are the same
-Perl6 name : wrong_rgba_color_s, C Name : rgba_color_t
__has int32 $red : c-size=4 | nc-size=4 -- :
__has int32 $blue : c-size=4 | nc-size=4 -- :
__has int32 $green : c-size=4 | nc-size=4 -- :
-Size given by sizeof and nativesizeof : C:16/NC:12
-Calculated total sizes : C:12/NC:12
Your representation is smaller than the cstruct, but total size of fields match. Did you forget a field?
----
Compiling a test file, this assume field names are the same
-Perl6 name : toyunda_subtitle_s, C Name : toyunda_sub_t
__has int32 $start : c-size=4 | nc-size=4 -- :
__has int32 $stop : c-size=4 | nc-size=4 -- :
__has Str $text : c-size=4 | nc-size=4 -- :
__HAS rgba_color_s $color1 : c-size=16 | nc-size=16 -- :
__HAS rgba_color_s $color2 : c-size=16 | nc-size=16 -- :
__has rgba_color_s $tmpcolor : c-size=16 | nc-size=4 -- DONT MATCH: C size match nativesizeof(rgba_color_s). put HAS instead of has
__has num32 $positionx : c-size=4 | nc-size=4 -- :
__has num32 $positiony : c-size=4 | nc-size=4 -- :
__has num32 $position2x : c-size=4 | nc-size=4 -- :
__has num32 $position2y : c-size=4 | nc-size=4 -- :
__has num32 $fadingpositionx : c-size=4 | nc-size=4 -- :
__has num32 $fadingpositiony : c-size=4 | nc-size=4 -- :
__has int32 $size : c-size=4 | nc-size=4 -- :
__has int32 $size2 : c-size=4 | nc-size=4 -- :
__has int32 $fadingsize : c-size=4 | nc-size=4 -- :
__has str $image : c-size=4 | nc-size=4 -- : You should replace your 'str' type with 'Str'
-Size given by sizeof and nativesizeof : C:100/NC:88
-Calculated total sizes : C:100/NC:88
Some function
foo1 - Not a valid parameter type for parameter [2] $b : Int
-->For Numerical type, use the appropriate int32/int64/num64...
foo2 - Not a valid parameter type for parameter [1] $a : Num
-->For Numerical type, use the appropriate int32/int64/num64...
foo2 - Not a valid parameter type for parameter [2] $b : Int
-->For Numerical type, use the appropriate int32/int64/num64...
Int foo3 - You should not return a non NC type (like Int inplace of int32), truncating errors can appear with different architectures
```
|
## dist_zef-antononcube-WWW-YouTube.md
# WWW::YouTube
Raku package for getting metadata and transcripts of YouTube videos.
The Raku implementation closely follows the Wolfram Language function `YouTubeTranscript`, [AAf1].
---
## Installation
From [Zef ecosystem](https://raku.land):
```
zef install WWW::YouTube
```
From GitHub:
```
zef install https://github.com/antononcube/Raku-WWW-YouTube.git
```
---
## Usage
`youtube-metadata($id)`
* Get the metadata of the YouTube video with identifier `$id`.
`youtube-playlist($id)`
* Get the video identifiers of the YouTube playlist with identifier `$id`.
`youtube-transcript($id)`
* Get the transcript of the YouTube video with identifier `$id`.
---
## Details
* All three subs, `youtube-metadata`, `youtube-playlist`, and `youtube-transript`,
work with strings that are identifiers or (full) URLs.
* `youtube-metdata` extracts the metadata associated with a YouTube video identifier.
* Returns a record (hashmap) with keys `<channel-title description publish-date title view-count>`.
* `youtube-playlist` extracts the video identifiers of a given YouTube playlist identifier.
* *Currently, gives only the first 100 videos.*
* `youtube-transcript` extracts the captions of the video, if they exist.
* The transcript can be returned as plain text, array of hashmaps, JSON string.
* The YouTube Data API has usage quotas.
* Not all YouTube videos have automatic or manual captions. If no captions are available, the function returns a message indicating this.
* `youtube-transcript` processes "captionTracks" of the YouTube Data API, which is a field of YouTube's video metadata.
* The field "captionTracks" is an array of objects, where each object represents a single caption track (e.g., for a specific language or type).
* From "captionTracks" the "baseURL" string is extracted, which is the URL to fetch the caption content.
---
## Examples
### Metadata
Get the metadata associated with a YouTube video identifier:
```
use WWW::YouTube;
use Data::Translators;
youtube-metadata('S_3e7liz4KM')
==> to-html(align => 'left')
```
| | |
| --- | --- |
| description | Computationally neat examples with Raku packages featuring graphs and graph plots. (3rd set.)\n\nHere is the presentation Jupyter notebook: https://github.com/antononcube/RakuForPrediction-blog/blob/main/Presentations/Notebooks/Graph-neat-examples-set-3.ipynb\n\n------------------\n\nPlease, consider buying me a coffee: https://buymeacoffee.com/antonov70 |
| publish-date | 2024-11-28T11:24:44-08:00 |
| title | Graph neat examples in Raku (Set 3) |
| view-count | 139 views |
| channel-title | N/A |
### Transcripts
```
my $transcript = youtube-transcript('ewU83vHwN8Y');
say $transcript.chars;
say $transcript.substr(^300);
```
```
# 36700
# Hi everyone, welcome to a wolf from
# language design review for version 14.3.
# We are talking about LLM
# graph. So,
# okay. So this is for the purpose of of
# knitting together LLM calls like LLM
# function type calls.
# Exactly.
# To support more complex workflows
# um and and to have asynchronous calls to
# LLMs.
```
Summarize using a Large Language Model (LLM):
```
use LLM::Functions;
use LLM::Prompts;
llm-synthesize(llm-prompt('Summarize')($transcript), e => 'Gemini')
```
```
# This language design review introduces LLM graphs, which orchestrate calls to LLMs for complex workflows, including asynchronous execution. LLM graphs use nodes containing prompts or code (node functions) that can depend on each other, with inputs and outputs managed through associations. The design includes features like listable templates and conditional execution, and it aims to provide a powerful, yet simple, way to build agentic workflows.
```
Get the transcript as a dataset:
```
my @t = youtube-transcript('S_3e7liz4KM', format => 'dataset');
@t.head(10) ==> to-html(field-names => <time duration content>, align => 'left')
```
| time | duration | content |
| --- | --- | --- |
| 0.52 | 4.64 | this presentation is titled graph neat |
| 2.8 | 5.2 | examples in Raku set |
| 5.16 | 4.84 | three my name is Anton Antonov today's |
| 8 | 5 | November 28th |
| 10 | 6 | 2024 I have prepared two sets of |
| 13 | 6.68 | examples nested graphs and file system |
| 16 | 5.72 | graphs the neat examples in general are |
| 19.68 | 3.96 | defined as concise or straightforward |
| 21.72 | 3.76 | code that produce compelling visual |
| 23.64 | 4.399 | textual outputs I'm going to be |
### Playlists
```
youtube-playlist('PLke9UbqjOSOiMnn8kNg6pb3TFWDsqjNTN')
```
```
# [fwQrQyWC7R0 S_3e7liz4KM E7qhutQcWCY kQo3wpiUu6w JHO2Wk1b-Og 5qXgqqRZHow 0uJl9q7jIf8]
```
---
## CLI
The package provides Command Line Interface (CLI) scripts. Here are their usage messages:
```
youtube-metadata --help
```
```
# Usage:
# youtube-metadata <id> [--format=<Str>] -- Get YouTube video metadata.
#
# <id> Video identifier
# --format=<Str> Format of the result, one of 'json', 'raku', 'asis'. [default: 'json']
```
```
youtube-playlist --help
```
```
# Usage:
# youtube-playlist <id> -- Get video identifiers of a YouTube playlist.
#
# <id> Video playlist identifier
```
```
youtube-transcript --help
```
```
# Usage:
# youtube-transcript <id> [--format=<Str>] -- Get YouTube transcripts.
#
# <id> Video identifier
# --format=<Str> Format of the result, one of 'text', 'dataset', or 'json'. [default: 'text']
```
---
## TODO
* TODO Implementation
* DONE Get transcript for a video identifier
* DONE Video metadata retrieval
* TODO Video identifiers for a playlist
* DONE For playlists with ≤ 100 videos
* TODO Large playlists
* TODO Different transcript output formats
* DONE Text
* DONE Dataset (array of hashmap records)
* DONE JSON
* TODO WebVTT
* TODO SRT
* Implement versions of the subs using a YouTube API key
* TODO Documentation
* DONE Basic usage
* TODO Transcripts retrieval for a playlist
---
## References
[AAf1] Anton Antonov,
[YouTubeTranscript](https://resources.wolframcloud.com/FunctionRepository/resources/YouTubeTranscript/),
(2025),
[Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository/).
|
## dist_zef-finanalyst-L10N-CY.md
# NAME
L10N::CY - Welsh localization of Raku
# SYNOPSIS
```
use L10N::CY;
dywedyd "Hello World";
```
# DESCRIPTION
L10N::CY contains the logic to provide a Welsh localization of the Raku Programming Language.
It's based on the Klingon localization by Elizabeth Mattisjen.
# AUTHOR
Richard Hainsworth [[email protected]](mailto:[email protected])
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
Source can be located at: <https://github.com/finanalyst/rakuast-L10N-CY>. Comments and Pull Requests are welcome.
Klingon source can be located at: <https://github.com/lizmat/L10N-TLH> .
# COPYRIGHT AND LICENSE
Copyright 2023 Richard Hainsworth
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## receiveonclosed.md
class X::Channel::ReceiveOnClosed
Error due to calling receive on a closed channel
```raku
class X::Channel::ReceiveOnClosed {}
```
This exception is thrown when a calling `receive` on a [`Channel`](/type/Channel) that has been closed:
```raku
my $s = Channel.new;
$s.close;
$s.receive; # Cannot receive a message on a closed channel
CATCH { default { put .^name, ': ', .Str } };
# OUTPUT: «X::Channel::ReceiveOnClosed: Cannot receive a message on a closed channel»
```
# [Methods](#class_X::Channel::ReceiveOnClosed "go to top of document")[§](#Methods "direct link")
## [method channel](#class_X::Channel::ReceiveOnClosed "go to top of document")[§](#method_channel "direct link")
```raku
method Channel(X::Channel::ReceiveOnClosed:D: --> Channel:D)
```
Returns the Channel object on which the `receive` method was called.
|
## nosuchtype.md
class X::Augment::NoSuchType
Compilation error due to augmenting a non-existing type
```raku
class X::Augment::NoSuchType does X::Comp { }
```
Thrown when trying to augment a type which doesn't exist.
For example
```raku
use MONKEY-TYPING;
augment class NoSuch { }
```
dies with
「text」 without highlighting
```
```
You tried to augment class NoSuch, but it does not exist
```
```
# [Methods](#class_X::Augment::NoSuchType "go to top of document")[§](#Methods "direct link")
## [method package-kind](#class_X::Augment::NoSuchType "go to top of document")[§](#method_package-kind "direct link")
```raku
method package-kind(--> Str:D)
```
Returns the kind of package (class, grammar) that is being tried to augment
## [method package](#class_X::Augment::NoSuchType "go to top of document")[§](#method_package "direct link")
Returns the name that was tried to augment, but which doesn't exist.
|
## dist_zef-jonathanstowe-RPi-Device-PiGlow.md
# RPi::Device::PiGlow
Interface for the [PiGlow](https://shop.pimoroni.com/products/piglow) device on the Raspberry Pi
## Synopsis
```
use RPi::Device::PiGlow;
my $pg = RPi::Device::PiGlow.new();
my $values = [0x01,0x02,0x04,0x08,0x10,0x18,0x20,0x30,0x40,0x50,0x60,0x70,0x80,0x90,0xA0,0xC0,0xE0,0xFF];
$pg.enable-output;
$pg.enable-all-leds;
$pg.write-all-leds($values);
sleep 10;
$pg.reset;
```
See the <examples> directory for more ways of using this.
## Description
The [PiGlow from Pimoroni](http://shop.pimoroni.com/products/piglow)
is a small board that plugs in to the Raspberry PI's GPIO header with
18 LEDs on that can be addressed individually via i²c. This module
uses [RPi::Device::SMBus](https://github.com/jonathanstowe/RPi-Device-SMBus)
to abstract the interface to the device so
that it can be controlled from a Raku programme. It is assumed that
you have installed the OS packages required to make i2c work and have
configured and tested the i²c appropriately. The only difference that
seems to affect the PiGlow device is that it only seems to be reported
by i2cdetect if you use the "quick write" probe flag:
sudo i2cdetect -y -q 1
(assuming you have a Rev B. or version 2 Pi - if not you should supply
0 instead of 1.) I have no way of knowing the compatibility of the
"quick write" with any other devices you may have plugged in to the Pi,
so I wouldn't recommend doing this with any other devices unless you know
that they won't be adversely affected by "quick write". The PiGlow has
a fixed address anyway so the information isn't that useful.
A useful quick guide to setting up for the Raspberry Pi 2 can be found
at <https://blog.robseder.com/2015/04/12/getting-a-piglow-to-work-with-a-raspberry-pi-2/> though
most of that will work for other versions.
With a more recent Raspbian install you may just be able to switch on
the `raspi-config` program, via `5. Interfacing Options`
## Installation
Assuming you have a working Rakudo installation you should be able to install this with *zef* :
```
# From the source directory
zef install .
# Remote installation
zef install RPi::Device::PiGlow
```
The tests will fail if run on other than a Raspberry Pi with i²c configured.
## Support
Suggestions/patches are welcomed via [github](https://github.com/jonathanstowe/RPi-Device-PiGlow/issues).
Because there are limited ways to test this automatically without
physically observing the device, there may be untested bugs.
I've tested this on three different versions of Raspberry Pi, if you find problems please report the Pi version
as well as the OS, Raku version etc.
## Licence
This is free software.
Please see the <LICENCE> file in the distribution
© Jonathan Stowe 2016 - 2021
|
## dist_github-soundart-Crypt-TweetNacl.md
[](https://travis-ci.org/soundart/perl6-tweetnacl)
# NAME
TweetNacl - pulic key crypto lib
# SYNOPSIS
```
# ----------------------------------------------------------------------
# public key encryption
# ----------------------------------------------------------------------
use Crypt::TweetNacl::PublicKey;
# create keys
my $alice = KeyPair.new;
my $bob = KeyPair.new;
# create Buf to encrypt
my $msg = 'Hello World'.encode('UTF-8');
# encrypt
my $cb = CryptoBox.new(pk => $alice.public , sk => $bob.secret);
my $data = $cb.encrypt($msg);
# decrypt
my $cbo = CryptoBoxOpen.new(pk => $bob.public , sk => $alice.secret);
my $rmsg = $cbo.decrypt($data);
say $rmsg.decode('UTF-8')
# ----------------------------------------------------------------------
# public key signatures
# ----------------------------------------------------------------------
use Crypt::TweetNacl::Sign;
# create key
my $keypair = KeyPair.new;
my $msg = 'Hello World'.encode('UTF-8');
# sign
my $cs = CryptoSign.new(buf => $msg, sk => $keypair.secret);
say $cs.signature
# verify, throws if message was corrupted
my $cso = CryptoSignOpen.new(buf => $cs.signature, pk => $keypair.public);
say $cso.message.decode('UTF-8') # 'Hello World'
# ----------------------------------------------------------------------
# secret key encryption
# ----------------------------------------------------------------------
use Crypt::TweetNacl::SecretKey;
# create key
my $alice = Key.new;
# create Buf to encrypt
my $msg = 'Hello World'.encode('UTF-8');
# encrypt
my $csb = CryptoSecretBox.new(sk => $alice.secret);
my $data = $csb.encrypt($msg);
# decrypt
my $csbo = CryptoSecretBoxOpen.new(sk => $alice.secret);
my $rmsg = $csbo.decrypt($data);
say $rmsg.decode('UTF-8') # 'Hello World'
```
# INSTALL
```
# on debian like systems:
apt install rakudo moarvm-dev
git clone https://github.com/soundart/perl6-tweetnacl
cd perl6-tweetnacl
zef install .
```
# DESCRIPTION
For details see
* <https://nacl.cr.yp.to/box.html>
* <http://tweetnacl.cr.yp.to/tweetnacl-20131229.pdf>
This is my first perl6 attempt. Feedback very much appreciated.
open questions:
* class Ciphertext: attributes $!data and $!nonce have to be
transported(e.g. send via network) from encryption to
decryption host. Should there be a serialize() method?
# COPYRIGHT AND LICENSE
see LICENSE
|
## dist_zef-guifa-Intl-Format-List.md
# IntlFormatList
A module for formatting lists in a localized manner
To format lists using this module, use the provided sub C:
```
format-list @list
```
There are three named options available:
* **`:language`** (may be abbreviated to **`:lang`**)
The language to use for formatting.
Should be a valid BCP-47 language code.
Defaults to whatever value `Intl::UserLanguage`'s `user-language` returns (which defaults to 'en' if undetectable).
* **`:type`**
There are three types possible: *and*, *or*, *unit*.
The *and* type indicates a list of collective values (e.g. 'apples, oranges, and peaches').
The *or* type indicates a list of alternate values (e.g. 'apples, oranges, or peaches').
The *unit* type indicates a list of values, without specifying any relation between them (e.g. 'apples, oranges, peaches').
Defaults to *and*.
* **`:length`**
There are three lengths possible: *standard*, *short*, *narrow*.
Many languages do not distinguish *standard* and *short*, perhaps only omitting spaces if they do.
In contrast, *narrow* is designed for minimal contexts, but may be ambiguous between the forms and should have additional context provided if used.
Defaults to *standard*.
## Examples
If your language is set to English…
```
my @list = <apples oranges bananas>;
say format-list @list; # 'apples, oranges, and bananas'
say format-list @list, :type<or>; # 'apples, oranges, or bananas'
say format-list @list, :type<unit>; # 'apples, oranges, bananas'
```
But if your language is set to Spanish…
```
my $a = 'manzanas';
my $o = 'naranjas';
my $b = 'plátanos';
say format-list $a, $o, $b; # 'manzanas, naranjas y plátanos'
say format-list $a, $o, $b, :type<or>; # 'manzanas, naranjas o plátanos'
say format-list $a, $o, $b, :type<unit; # 'manzanas, naranjas y plátanos'
```
As you can tell, the `format-list` sub follows the single-argument rule, allowing either a list proper *or* an inline list of items.
All items passed in are stringified.
### For developers
If you want to integrate the list formatter via `RakuAST`, you can obtain a `Callable` (currently a `RakuAST::PointyBlock`) by the following:
```
use Intl::Format::List :rakuast;
my $formatter-ast = format-list-rakuast('en', 'and', 'standard')
```
Presently, all three parameters (language, type, length) must be specified.
## Version history
* **v0.6.0**
* Added an improved caching mechanism
* RakuAST support (autodetects based on compiler version)
* **v0.5.0**
* First release as its own module
* Much cleaner / more maintainable codebase
* **v0.1** – **v0.4.3**
* Initial release as a part of the `Intl::CLDR` module
* No changes made after initial release
## License and Copyright
© 2020–2022 Matthew Stephen Stuckwisch. Licensed under Artistic License 2.0
|
## dist_zef-ssotka-JSON-CSV.md
**JSON-CSV**
This repository is for a collection of scripts that convert between JSON and CSV.
Written in Raku as a small project to help me learn the language.
* bin/json2csv
* bin/csv2json
* bin/jsonStream2csv
The scripts depend on Text::CSV, JSON::Fast, and JSON::Stream. NOTE: Please feel free to contact me or suggest changes via the github project.
**COPYRIGHT and LICENSE**
© 2022 Scott Sotka. Licensed under the Artistic License 2.0.
|
## dist_zef-l10n-L10N-HU.md
# NAME
L10N::HU - Hungarian localization of Raku
# SYNOPSIS
```
use L10N::HU;
mond "Hello World";
```
# DESCRIPTION
L10N::HU contains the logic to provide a Hungarian localization of the Raku Programming Language.
# AUTHORS
Polgár Márton (Martin Burger)
# COPYRIGHT AND LICENSE
Copyright 2023 Raku Localization Team
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_cpan-FRITH-Archive-Libarchive-Raw.md
## Archive::Libarchive::Raw
Archive::Libarchive::Raw - Raw interface to libarchive using NativeCall.
## Build Status
[](https://github.com/frithnanth/perl6-Archive-Libarchive-Raw/actions)
## Example
```
use v6;
use Archive::Libarchive::Raw;
use Archive::Libarchive::Constants;
sub MAIN(:$file! where { .IO.f // die "file '$file' not found" })
{
my archive $a = archive_read_new();
archive_read_support_filter_all($a);
archive_read_support_format_all($a);
archive_read_open_filename($a, $file, 10240) == ARCHIVE_OK or die 'Unable to open archive';
my archive_entry $entry .= new;
while archive_read_next_header($a, $entry) == ARCHIVE_OK {
my $name = archive_entry_pathname($entry);
say $name;
archive_read_data_skip($a);
}
archive_read_free($a) == ARCHIVE_OK or die 'Unable to free internal data structure';
}
```
For more examples see the `example` directory.
## Description
Archive::Libarchive::Raw is a set of simple bindings to libarchive using NativeCall.
As the Libarchive site (<http://www.libarchive.org/>) states, its implementation is able to:
* Read a variety of formats, including tar, pax, cpio, zip, xar, lha, ar, cab, mtree, rar, and ISO images.
* Write tar, pax, cpio, zip, xar, ar, ISO, mtree, and shar archives.
* Handle automatically archives compressed with gzip, bzip2, lzip, xz, lzma, or compress.
For more details on libarchive see <https://github.com/libarchive/libarchive/wiki/ManualPages> .
## Prerequisites
This module requires the libarchive library to be installed. Please follow the
instructions below based on your platform:
### Debian Linux
```
sudo apt-get install libarchive13
```
## Installation
```
$ zef install Archive::Libarchive::Raw
```
## Testing
To run the tests:
```
$ prove -e "raku -Ilib"
```
## Note
This module relies on a C library which might not be present in one's installation, so it's not a substitute
for a pure Raku module.
This is a raw interface to the functions provided by the C library; any program that uses this module might
need to use NativeCall. If you wish to use a higher level interface, please take a look at Archive::Libarchive.
## Author
Fernando Santagata
## Contributions
Many thanks to Jonathan Worthington for the Windows installer code.
Many thanks to Curt Tilmes for implementing a bunch of calls to libarchive, and providing tests.
## Copyright and license
The Artistic License 2.0
|
## dist_cpan-TITSUKI-Algorithm-XGBoost.md
[](https://github.com/titsuki/raku-Algorithm-XGBoost/actions)
# NAME
Algorithm::XGBoost - A Raku bindings for XGBoost ( <https://github.com/dmlc/xgboost> ).
# SYNOPSIS
```
use Algorithm::XGBoost;
use Algorithm::XGBoost::Booster;
use Algorithm::XGBoost::DMatrix;
use Algorithm::XGBoost::Model;
# agaricus.txt.test is here: https://github.com/dmlc/xgboost/tree/master/demo/data
my $dmat = Algorithm::XGBoost::DMatrix.from-file("agaricus.txt.train");
say $dmat.num-row; # 6513
say $dmat.num-col; # 127
my $model = Algorithm::XGBoost.train($dmat, 10);
$model.num-feature.say; # 127
my @test[2;2] = [[0e0,0e0],[0e0,1e0]];
my $test = Algorithm::XGBoost::DMatrix.from-matrix(@test);
say $model.predict($test); # (0.9858561754226685 0.9858561754226685)
```
# DESCRIPTION
Algorithm::XGBoost is a Raku bindings for XGBoost ( <https://github.com/dmlc/xgboost> ).
## METHODS
### train
Defined as:
```
method train(Algorithm::XGBoost::DMatrix $dmat, Int $num-iteration, %param --> Algorithm::XGBoost::Model)
```
Trains a XGBoost model.
* `$dmat` The instance of Algorithm::XGBoost::DMatrix.
* `$num-iteration` The number of iterations for training.
* `%param` The parameter for training.
### version
Defined as:
```
method version(--> Version)
```
Returns the libxgboost version.
### global-config
Defined as:
```
multi method global-config(Str $json-str)
multi method global-config(--> Str)
```
Sets/Gets the global parameters: verbosity and use\_rmm.
* `verbosity` The verbosity of printing messages. Valid values of 0 (silent), 1 (warning), 2 (info), and 3 (debug).
* `use_rmm` Whether to use RAPIDS Memory Manager (RMM) to allocate GPU memory. This option is only applicable when XGBoost is built (compiled) with the RMM plugin enabled. Valid values are true and false.
# AUTHOR
Itsuki Toyota [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2021 Itsuki Toyota
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_cpan-HANENKAMP-Hash-MultiValue.md
# NAME
Hash::MultiValue - Store multiple values per key, but act like a regular hash too
# SYNOPSIS
```
my %mv := Hash::MultiValue.from-pairs: (a => 1, b => 2, c => 3, a => 4);
say %mv<a>; # 4
say %mv<b>; # 2
say %mv('a').join(', '); # 1, 4
say %mv('b').join(', '); # 2
%mv<a> = 5;
%mv<d> = 6;
%mv('e') = 7, 8, 9;
say %mv.all-pairs».fmt("%s: %s").join("\n");
# a: 5
# b: 2
# c: 3
# d: 6
# e: 7
# e: 8
# e: 9
```
# DESCRIPTION
This class is useful in cases where a program needs to have a hash that may or may not have multiple values per key, but frequently assumes only one value per key. This is commonly the case when dealing with URI query strings. This class also generally preserves the order the keys are encountered, which can also be a useful characteristic when working with query strings.
If some code is handed this object where a common <Associative> object (like a <Hash>) is expected, it will work as expected. Each value will only have a single value available. However, when one of these objects is used as function or using the various `.all-*` alternative methods, the full multi-valued contents of the keys can be fetched, modified, and iterated.
This class makes no guarantees to preserve the order of keys. However, the order of the multiple values stored within a key is guaranteed to be preserved. If you require key order to be preserved, you may want to look into <ArrayHash> instead.
# Methods
## method new
```
multi method new(Hash::MultiValue:U:) returns Hash::MultiValue:D
multi method new(Hash::MultiValue:U: :@pairs!) returns Hash::MultiValue:D
multi method new(Hash::MultiValue:U: :@kv!) returns Hash::MultiValue:D
multi method new(Hash::MultiValue:U: :%mixed-hash!, :$iterate = Iterable, :&iterator) returns Hash::MultiValue:D
```
This method constructs a multi-value hash. If called with no arguments, an empty hash will be constructed.
```
my %empty := Hash::MultiValue.new;
```
If called with the named `pairs` argument, then the given pairs will be used to instantiate the list. This is similar to calling `from-pairs` with the given list..
```
my %from-pairs := Hash::MultiValue.new(
pairs => (a => 1, b => 2, a => 3),
);
```
If called with the named `kv` argument, then the given list must have an even number of elements. The even-indexed items will be treated as keys, and the following odd-indexed items will be treated as the value for the preceding key. This is similar to calling `from-kv`.
```
my %from-kv = Hash::MultiValue.new(
kv => ('a', 1, 'b', 2, 'a', 3),
);
```
If called with the named `mixed-hash` argument, then the given hash will be treated as a mixed value hash. A mixed value hash is complicated, so using it to initialize this data structure is not ideal.
In order to initialize from such a structure, every value in the given hash must be evaluted by type. If the type of the value matches the one found in `$iterator` (<Iterable> by default), then the key will be inserted multiple times, one for each item iterated. The iteration will be handled by just looping over the values using a `map` operation. You can provide your own `&iterator` as well, which will be called for each value matching `$iterator`. The first argument will be key to return and the second will be the value that needs to be iterated. The `&terator` should return a `Seq` of `Pair`s.
```
my %from-mixed := Hash::MultiValue.new(
mixed-hash => {
a => [ 1, 3 ],
b => 2,
},
);
```
## method from-pairs
```
method from-pairs(Hash::MultiValue:U: *@pairs) returns Hash::MultiValue:D
```
This takes a list of pairs and constructs a Hash::MultiValue object from it. Multiple pairs with the same key may be included in this list and all values will be associated with that key.
It should be noted that you may need to be a little careful with how you pass your pairs into this method. Perl 6 treats anything that looks like a named argument as a named argument. Here's a quick example of what works and what doesn't:
```
# THIS
my %h := Hash::MultiValue.from-pairs: (a => 1, b => 2, a => 3);
# OR THIS
my %h := Hash::MultiValue.from-pairs((a => 1, b => 2, a => 3));
# OR THIS
my %h := Hash::MultiValue.from-pairs('a' => 1, 'b' => 2, 'a' => 3);
# OR THIS
my @a := (a => 1, b => 2, a => 3);
my %h := Hash::MultiValue.from-pairs(@a);
# BUT NOT
my %h := Hash::MultiValue.from-pairs(a => 1, b => 2, a => 3);
# ALSO NOT
my %h := Hash::MultiValue.from-pairs(|@a);
```
To protect from accidentally passing these as named arguments, the method will fail if any named arguments are detected.
### method from-pairs
```
method from-pairs(
*@pairs,
*%badness
) returns Hash::MultiValue:D
```
Construct a Hash::MultiValue object from a list of pairs
## method from-kv
```
method from-kv(Hash::MultiValue:U: +@kv) returns Hash::MultiValue:D
```
This takes a list of keys and values in a single list and turns them into pairs. The given list of items must have an even number of elements or the method will fail.
The even-indexed items will be treated as keys, and the following odd-indexed items will be treated as the value for the preceding key. This is similar to calling `from-kv`.
## method from-mixed-hash
```
multi method from-mixed-hash(Hash::MultiValue:U: %hash, :$iterate = Iterable, :&iterate) returns Hash::MultiValue:D
multi method from-mixed-hash(Hash::MultiValue:U: *%hash) returns Hash::MultiValue:D
```
This takes a hash and constructs a new Hash::MultiValue from it as a mixed-value hash. A mixed value hash is complicated, so using it to initialize this data structure is not ideal.
In order to initialize from such a structure, every value in the given hash must be evaluted by type. If the type of the value matches the one found in `$iterator` (<Iterable> by default), then the key will be inserted multiple times, one for each item iterated. The iteration will be handled by just looping over the values using a `map` operation. You can provide your own `&iterator` as well, which will be called for each value matching `$iterator`. The first argument will be key to return and the second will be the value that needs to be iterated. The `&terator` should return a `Seq` of `Pair`s.
```
my %from-mixed := Hash::MultiValue.from-mixed-hash(
a => [ 1, 3 ],
b => 2,
);
# The above is basically identical to:
# Hash::MultiValue.from-pairs: (a => 1, a => 3, b => 2);
```
**Caution:** If you use the slurpy version of this method, you have no additional named options. Passing `iterate` or `iterator` will just result in those being put into the data structure.
### multi method from-mixed-hash
```
multi method from-mixed-hash(
%mixed-hash,
:$iterate = Iterable,
:&iterator = { ... }
) returns Hash::MultiValue:D
```
Construct a Hash::MultiValue object from a mixed value hash
### multi method from-mixed-hash
```
multi method from-mixed-hash(
*%mixed-hash
) returns Hash::MultiValue:D
```
Construct a Hash::MultiValue object from a mixed value hash
## method postcircumfix:<{ }>
```
method postcircumfix:<{ }> (Hash::MultiValue:D: %key) is rw
```
Whenever reading or writing keys using the `{ }` operator, the hash will behave as a regular built-in <Hash>. Any write will overwrite all values that have been set on the multi-value hash with a single value.
```
my %mv := Hash::MultiValue.from-pairs(a => 1, b => 2, a => 3);
%mv<a> = 4;
say %mv('a').join(', '); # 4
```
Any read will only read a single value, even if multiple values are stored for that key.
```
my %mv := Hash::MultiValue.from-pairs(a => 1, b => 2, a => 3);
say %mv<a>; # 3
```
Of those values the last value will always be used. This is in keeping with the usual semantics of what happens when you add two pairs with the same key twice in Perl 6.
You may also use the `:delete` and `:exists` adverbs with these objects.
```
my %mv := Hash::MultiValue.from-pairs(a => 1, b => 2, a => 3);
say %mv<a> :delete; # 3 (both 1 and 3 are gone)
say %mv<b> :exists; # True
```
Binding is also supported. For example,
```
my $a = 4;
%mv<a> := $a;
$a = 5;
say %mv<a>; # 4
```
## method postcircumfix:<( )>
```
method postcircumfix:<( )> (Hash::MultiValue:D: $key) is rw
```
The `( )` operator may be used in a fashion very similar to `{ }`, but in that it always works with multiple values. You may use it to read multiple values from the object:
```
my %mv := Hash::MultiValue.from-pairs(a => 1, b => 2, a => 3);
say %mv('a').join(', '); # 1, 3
```
You may also use it to write multiple values, which will replace all values currently set for that key:
```
my %mv := Hash::MultiValue.from-pairs(a => 1, b => 2, a => 3);
%mv('a') = 4, 5;
%mv('b') = 6, 7;
%mv('c') = 8;
say %mv('a').join(', '); # 4, 5
say %mv('b').join(', '); # 6, 7
say %mv('c').join(', '); # 8
```
At this time, this operator does not support slices (i.e., using a <Range> or <List> of keys to get values for more than one key at once). This might be supported in the future.
## method kv
Returns a list alternating between key and value. Each key will only be listed once with a singular value. See [/method all-kv](/method all-kv) for a multi-value version.
## method pairs
Returns a list of <Pair> objects. Each key is returned just once pointing to the last (or only) value in the multi-value hash. See [/method all-pairs](/method all-pairs) for the multi-value version.
## method antipairs
This is identical to [/method pairs](/method pairs), but with the value and keys swapped.
## method invert
This is a synonym for [/method antipairs](/method antipairs).
## method keys
Returns a list of keys. Each key is returned exactly once. See [/method all-keys](/method all-keys) for the multi-value version.
## method values
Returns a list of values. Only the last value of a multi-value key is returned. See [/method all-values](/method all-values) for the multi-value version.
## method all-kv
Returns a list alternating between key and value. Multi-value key will be listed more than once.
## method all-pairs
Returns a list of <Pair> objects. Multi-value keys will be returned multiple times, once for each value associated with the key.
## method all-antipairs
This is identical to [/method all-pairs](/method all-pairs), but with key and value reversed.
## method all-invert
This is a synonym for [/method all-antipairs](/method all-antipairs).
## method keys
This returns a list of keys. Multi-valued keys will be returned more than once. If you want the unique key list, you want to see [/method keys](/method keys).
## method values
This returns a list of all values, including the multiple values on a single key.
## method push
```
method push(*@values)
```
This adds new pairs to the list. Any pairs given with a key matching an existing key will cause the single value version of that key to be replaced with the new value. This never overwrites existing values.
## method perl
Returns code as a string that can be evaluated with `EVAL` to recreate the object.
## method gist
Like [/method perl](/method perl), but only includes up to the first 100 keys.
|
## dist_zef-raku-community-modules-Email-Notmuch.md
[](https://github.com/raku-community-modules/Email-Notmuch/actions) [](https://github.com/raku-community-modules/Email-Notmuch/actions) [](https://github.com/raku-community-modules/Email-Notmuch/actions)
# NAME
Email::Notmuch - Raku binding for NotmuchMail email database
# SYNOPSIS
```
use Email::Notmuch;
my $database = Database.new('/home/goneri/Maildir');
my $query = Query.new($database, 'tag:todo');
my $messages = $query.search_messages();
for $messages.all() -> $message {
say $message.get_header('from');
$message.add_tag('seen');
say $message.get_tags().all();
}
```
# DESCRIPTION
Notmuchmail ( <https://notmuchmail.org/> ) is a mail indexation tool. This Raku module provides binding for a limited subset of its API.
The library has been tested with Notmuch 0.25 and greater, it does not work anymore with the older versions.
# AUTHOR
Gonéri Le Bouder
# COPYRIGHT AND LICENSE
Copyright 2015 - 2018 Gonéri Le Bouder
Copyright 2024 Raku Community
The project uses the GPLv3 or greater.
|
## dist_cpan-MELEZHIK-Sparrowdo-Rvm.md
# Sparrowdo::Rvm
[](https://travis-ci.org/melezhik/perl6-sparrowdo-rvm)
## SYNOPSIS
[Sparrowdo](https://github.com/melezhik/sparrowdo) module to install RVM and Ruby.
# Usage
cli:
```
s6 --module-run Rvm
```
Sparrow6 DSL:
```
# install default RVM and default Ruby version
module-run 'Rvm';
# install specific Ruby version
module_run 'Rvm', %( version => '2.2.0' );
```
## Tested on
* CentOS
* Ubuntu
## LICENSE
All files (unless noted otherwise) can be used, modified and redistributed
under the terms of the Artistic License Version 2. Examples (in the
documentation, in tests or distributed as separate files) can be considered
public domain.
ⓒ2017 'Alexey Melezhik'
|
## dist_zef-bduggan-Geo-Basic.md
[](https://github.com/bduggan/raku-geo-basic/actions/workflows/linux.yml)
[](https://github.com/bduggan/raku-geo-basic/actions/workflows/macos.yml)
# NAME
Geo::Basic - Basic geospatial functions
# SYNOPSIS
```
use Geo::Basic;
my $hash = geohash-encode lat => 51.435, lon => -0.215, precision => 5;
# "gcpue5"
my $decoded = geohash-decode $hash;
# %( lat-max => 51.416016, lat-min => 51.459961,
# lon-max => -0.219727, lon-min => -0.175781 )
my $neighbors = geohash-neighbors $hash;
# [gcpuek gcpueh gcpudu gcpue7 gcpudg gcpue6 gcpue4 gcpudf]
my $distance-km = haversine-km :lat1(51.435), :lon1(-0.215), :lat2(51.435), :lon2(-0.214);
# 0.06931914818231608
my $distance-mi = haversine-miles :lat1(51.435), :lon1(-0.215), :lat2(51.435), :lon2(-0.214);
# 0.04307292175092216
my $quadkey = latlon-to-quadkey 51.435, -0.215, 8;
my $bounds = quadkey-bounds $quadkey;
```
# DESCRIPTION
These are a few simple utilities for doing geospatial calculations. The following functions are provided:
```
* `geohash-encode` -- encode a latitude and longitude into a geohash
* `geohash-decode` -- decode a geohash into a latitude and longitude
* `geohash-neighbors` -- find the neighbors of a geohash
* `quadkey-encode` -- convert a latitude and longitude to a quadkey
* `quadkey-decode` -- convert a quadkey to lat/lon bounds
* `haversine-km` -- calculate the distance between two points on the earth in kilometers
* `haversine-miles` -- calculate the distance between two points on the earth in miles
```
# FUNCTIONS
### sub geohash-encode
```
sub geohash-encode(
Rat(Real) :$lat,
Rat(Real) :$lon,
Int :$precision = 9
) returns Mu
```
Encode a latitude and longitude into a geohash
### sub geohash-decode
```
sub geohash-decode(
Str $geo
) returns Hash
```
Decode a geohash into a latitude and longitude
### sub radians
```
sub radians(
Real $deg
) returns Mu
```
Convert degrees to radians
### sub km-to-miles
```
sub km-to-miles(
Real $km
) returns Mu
```
Convert kilometers to miles
### sub haversine-miles
```
sub haversine-miles(
Real :$lat1,
Real :$lon1,
Real :$lat2,
Real :$lon2
) returns Mu
```
Calculate the great circle distance in miles, using the havarsine formula
### sub haversine-km
```
sub haversine-km(
Real :$lat1,
Real :$lon1,
Real :$lat2,
Real :$lon2
) returns Mu
```
Calculate the great circle distance in kilometers using the havarsine formula
### sub quadkey-decode
```
sub quadkey-decode(
Str $quadkey
) returns Mu
```
Convert a quadkey to lat/lon bounds
### sub quadkey-encode
```
sub quadkey-encode(
Numeric :$lat,
Numeric :$lon,
Int :$zoom
) returns Mu
```
Convert lat/lon to quadkey
# AUTHOR
Brian Duggan
Original geohash code by Thundergnat on Rosetta Code
|
## cleanup.md
cleanup
Combined from primary sources listed below.
# [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_cleanup "direct link")
See primary documentation
[in context](/type/IO/Path#method_cleanup)
for **method cleanup**.
```raku
method cleanup(IO::Path:D: --> IO::Path:D)
```
Returns a new path that is a canonical representation of the invocant path, cleaning up any extraneous path parts:
```raku
"foo/./././..////bar".IO.cleanup.say; # OUTPUT: «"foo/../bar".IO»
IO::Path::Win32.new("foo/./././..////bar")
.cleanup.say; "foo\..\bar".IO; # OUTPUT: «"foo\..\bar".IO»
```
Note that no filesystem access is made. See also [`resolve`](/routine/resolve).
|
## join.md
join
Combined from primary sources listed below.
# [In Thread](#___top "go to top of document")[§](#(Thread)_method_join "direct link")
See primary documentation
[in context](/type/Thread#method_join)
for **method join**.
```raku
method join(Thread:D:)
```
Waits for the thread to finish.
# [In IO::Spec::Cygwin](#___top "go to top of document")[§](#(IO::Spec::Cygwin)_method_join "direct link")
See primary documentation
[in context](/type/IO/Spec/Cygwin#method_join)
for **method join**.
```raku
method join(|c)
```
Same as [`IO::Spec::Win32.join`](/type/IO/Spec/Win32#method_join), except replaces backslashes with slashes in the final result.
# [In Any](#___top "go to top of document")[§](#(Any)_method_join "direct link")
See primary documentation
[in context](/type/Any#method_join)
for **method join**.
```raku
method join($separator = '') is nodal
```
Converts the object to a list by calling [`self.list`](/type/Any#method_list), and calls [`.join`](/type/List#routine_join) on the list. Can take a separator, which is an empty string by default.
```raku
(1..3).join.say; # OUTPUT: «123»
<a b c>.join("❧").put; # OUTPUT: «a❧b❧c»
```
# [In List](#___top "go to top of document")[§](#(List)_routine_join "direct link")
See primary documentation
[in context](/type/List#routine_join)
for **routine join**.
```raku
sub join($separator, *@list)
method join(List:D: $separator = "")
```
Treats the elements of the list as strings by calling [`.Str`](/type/Mu#method_Str) on each of them, interleaves them with `$separator` and concatenates everything into a single string.
Example:
```raku
say join ', ', <a b c>; # OUTPUT: «a, b, c»
```
The method form also allows you to omit the separator:
```raku
say <a b c>.join; # OUTPUT: «abc»
```
Note that the method form does not flatten sublists:
```raku
say (1, <a b c>).join('|'); # OUTPUT: «1|a b c»
```
The subroutine form behaves slurpily, flattening all arguments after the first into a single list:
```raku
say join '|', 1, <a b c>; # OUTPUT: «1|a|b|c»
```
In this case, the list `<a b c>` is *slurped* and flattened, unlike what happens when `join` is invoked as a method.
If one of the elements of the list happens to be a [`Junction`](/type/Junction), then `join` will also return a [`Junction`](/type/Junction) with concatenation done as much as possible:
```raku
say ("a"|"b","c","d").join; # OUTPUT: «any(acd,bcd)»
```
# [In IO::Spec::Unix](#___top "go to top of document")[§](#(IO::Spec::Unix)_method_join "direct link")
See primary documentation
[in context](/type/IO/Spec/Unix#method_join)
for **method join**.
```raku
method join ($, Str:D $dir, Str:D $file --> Str:D)
```
Similar to [`catpath`](/routine/catpath), takes two path fragments and concatenates them, adding or removing a path separator, if necessary, except it will return just `$file` if both `$dir` and `$file` are string `'/'` or if `$dir` is the string `'.'`. The first argument is ignored (it exists to maintain consistent interface with other [`IO::Spec`](/type/IO/Spec) types for systems that have volumes).
```raku
IO::Spec::Unix.join($, 'foo', 'bar').say; # OUTPUT: «foo/bar»
IO::Spec::Unix.join($, '/', '/').say; # OUTPUT: «/»
IO::Spec::Unix.join($, '.', 'foo').say; # OUTPUT: «foo»
say $*SPEC.join(True,".","/foo"); # OUTPUT: «/foo»
```
# [In IO::Spec::Win32](#___top "go to top of document")[§](#(IO::Spec::Win32)_method_join "direct link")
See primary documentation
[in context](/type/IO/Spec/Win32#method_join)
for **method join**.
```raku
method join (Str:D $volume, Str:D $dir, Str:D $file --> Str:D)
```
Similar to [`catpath`](/routine/catpath), takes two path fragments and concatenates them, adding or removing a path separator, if necessary, except it will return just `$file` if both `$dir` and `$file` are string `'/'` or if `$dir` is the string `'.'`. The first argument is ignored (it exists to maintain consistent interface with other [`IO::Spec`](/type/IO/Spec) types for systems that have volumes).
```raku
IO::Spec::Win32.join('C:', '/some/dir', 'foo.txt').say;
# OUTPUT: «C:/some/dir\and/more»
IO::Spec::Win32.join('C:', '.', 'foo.txt').say;
# OUTPUT: «C:foo.txt»
IO::Spec::Win32.join('C:', 「\」, '/').say;
# OUTPUT: «C:\»
IO::Spec::Win32.join('//server/share', 「\」, '/').say;
# OUTPUT: «//server/share»
IO::Spec::Win32.join('E:', '', 'foo.txt').say;
# OUTPUT: «E:foo.txt»
```
|
## dist_cpan-TADZIK-Acme-Meow.md
```
This is a Perl 6 port of Perl 5's Acme::Meow [1]
It's not a verbatim port. Some things have changed,
and there is more to come. Stay tuned for more fun :)
[1] http://metacpan.org/pod/Acme::Meow
```
|
## dist_github-tokuhirom-Cookie-Baker.md
[](https://travis-ci.org/tokuhirom/p6-Cookie-Baker)
# NAME
Cookie::Baker - Cookie string generator / parser
# SYNOPSIS
```
use Cookie::Baker;
$headers.push_header('Set-Cookie' => bake-cookie($key, $val));
my $cookies_hashref = crush-cookie($headers.header('Cookie'));
```
# DESCRIPTION
Cookie::Baker provides simple cookie string generator and parser.
# FUNCTIONS
* bake-cookie
my $cookie = bake-cookie('foo','val');
my $cookie = bake-cookie(
'foo', 'val',
path => "test",
domain => '.example.com',
expires => '+24h'
);
Generates a cookie string for an HTTP response header. The first argument is the cookie's name and the second argument is a plain string or hash reference that can contain keys such as `value`, `domain`, `expires`, `path`, `httponly`, `secure`, `max-age`.
* value
Cookie's value
* domain
Cookie's domain.
* expires
Cookie's expires date time. Several formats are supported
```
expires => time + 24 * 60 * 60 # epoch time
expires => 'Wed, 03-Nov-2010 20:54:16 GMT'
expires => '+30s' # 30 seconds from now
expires => '+10m' # ten minutes from now
expires => '+1h' # one hour from now
expires => '-1d' # yesterday (i.e. "ASAP!")
expires => '+3M' # in three months
expires => '+10y' # in ten years time
expires => 'now' #immediately
```
* path
Cookie's path.
* httponly
If true, sets HttpOnly flag. false by default.
* secure
If true, sets secure flag. false by default.
* crush-cookie
Parses cookie string and returns a hashref.
```
my %cookies_hashref = crush-cookie($headers.header('Cookie'));
my $cookie_value = %cookies_hashref<cookie_name>;
```
# AUTHOR
Tokuhiro Matsuno [[email protected]](mailto:[email protected]).
And original perl5 code is written by:
Masahiro Nagano [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Perl6 port is:
```
Copyright 2015 Tokuhiro Matsuno <[email protected]>
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
```
Original Perl5 code is:
```
Copyright (C) Masahiro Nagano.
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
```
|
## dist_github-FCO-Punnable.md
[](https://travis-ci.org/FCO/Punnable)
## Usage
```
$ perl6 -Ilib -MPunnable -e 'role R {method r {...}}; make-punnable(R); my $or = R.new; say $or; $or.r'
R.new
Stub code executed
in block <unit> at -e line 1
Actually thrown at:
in block <unit> at -e line 1
```
|
## dist_zef-thundergnat-SDL2-ttf.md
[](https://github.com/thundergnat/SDL2-ttf/actions)
# NAME
SDL2-ttf - FreeType interface to render text in SDL2
# SYNOPSIS
```
use SDL2::Raw;
use SDL2-ttf;
# initialize
TTF_Init();
# set a render color
my $color = TTF_Color(255, 28, 174); # Pink
# select a font file
my $font-file = '/path/to/font/my_Font.ttf';
# open it at a certain point size (May be scaled later by SDL2)
my $font = TTF_OpenFont($font-file, 64);
# render text using the selected font and color as a SDL2 texture
my $raku = SDL_CreateTextureFromSurface(
SDL_CreateRenderer(), TTF_Render_Blended($font, ' Raku ', $color)
);
# Clean up afterwords
TTF_CloseFont($font);
TTF_Quit();
```
The `$raku` variable now contains a rendered texture that may be used in SDL2.
# DESCRIPTION
Provides a convenient interface to FreeType to assist in loading and using TrueType fonts as rendering textures in SDL2.
Needs to have the libsdl2-dev and libsdl2-ttf-dev development libraries installed.
On Debian derived distributions:
```
sudo apt-get install libsdl2-dev libsdl2-ttf-dev
```
Similar for others.
Documentation for the SDL2\_ttf library, which works very similar to, but not exactly the same as these bindings: <https://www.libsdl.org/projects/SDL_ttf/docs/index.html>
Several routines are called slightly differently, and many are not exposed at due to the different requirements and capabilities of the Raku runtime and the C library.
Try out the `ttftest.p6` script in the examples folder to get a feel for how it can be used.
### Enumerations
There are a few enumerations provided.
###
**TTF\_STYLE** - The various font styles that may be available and/or specified:
TTF\_STYLE
| Name | value |
| --- | --- |
| STYLE\_NORMAL | 0 |
| STYLE\_BOLD | 1 |
| STYLE\_ITALIC | 2 |
| STYLE\_UNDERLINE | 4 |
| STYLE\_STRIKETHROUGH | 8 |
###
**TTF\_HINTING** - The various font hints that may be available and/or specified:
TTF\_HINTING
| Name | value |
| --- | --- |
| HINT\_NORMAL | 0 |
| HINT\_LIGHT | 1 |
| HINT\_MONO | 2 |
| HINT\_NONE | 3 |
## Subroutines:
#### General
* [TTF\_Init](#TTF_Init)
* [TTF\_WasInit](#TTF_WasInit)
* [TTF\_Quit](#TTF_Quit)
* [TTF\_GetError](#TTF_GetError)
* [TTF\_OpenFont](#TTF_OpenFont)
* [TTF\_OpenFontIndex](#TTF_OpenFontIndex)
* [TTF\_CloseFont](#TTF_CloseFont)
#### Attributes
* [TTF\_GetFontStyle](#TTF_GetFontStyle)
* [TTF\_GetFontStyles](#TTF_GetFontStyles)
* [TTF\_SetFontStyle](#TTF_SetFontStyle)
* [TTF\_GetFontOutline](#TTF_GetFontOutline)
* [TTF\_SetFontOutline](#TTF_SetFontOutline)
* [TTF\_GetFontHinting](#TTF_GetFontHinting)
* [TTF\_SetFontHinting](#TTF_SetFontHinting)
* [TTF\_GetFontKerning](#TTF_GetFontKerning)
* [TTF\_SetFontKerning](#TTF_SetFontKerning)
* [TTF\_FontHeight](#TTF_FontHeight)
* [TTF\_FontAscent](#TTF_FontAscent)
* [TTF\_FontDescent](#TTF_FontDescent)
* [TTF\_FontLineSkip](#TTF_FontLineSkip)
* [TTF\_FontFaces](#TTF_FontFaces)
* [TTF\_FontFaceIsFixedWidth](#TTF_FontFaceIsFixedWidth)
* [TTF\_FontFaceFamilyName](#TTF_FontFaceFamilyName)
* [TTF\_FontFaceStyleName](#TTF_FontFaceStyleName)
* [TTF\_GlyphIsProvided](#TTF_GlyphIsProvided)
* [TTF\_GlyphMetrics](#TTF_GlyphMetrics)
* [TTF\_GetTextSize](#TTF_GetTextSize)
#### Rendering
* [TTF\_Color](#TTF_Color)
* [TTF\_Render\_Solid](#TTF_Render_Solid)
* [TTF\_Render\_Shaded](#TTF_Render_Shaded)
* [TTF\_Render\_Blended](#TTF_Render_Blended)
* [TTF\_Render\_Blended\_Wrapped](#TTF_Render_Blended_Wrapped)
### Rendering modes
* Solid - Quick and Dirty
* Create an 8-bit palettized surface and render the given text at fast quality with the given font and color. The pixel value of 0 is the colorkey, giving a transparent background when blitted. Pixel and colormap value 1 is set to the text foreground color. This results in no box around the text, but the text is not as smooth.
* Shaded - Slow and Nice, but with a Solid Box
* Create an 8-bit palettized surface and render the given text at high quality with the given font and colors. The 0 pixel value is background, while other pixels have varying degrees of the foreground color from the background color. This results in a box of the background color around the text in the foreground color. The text is antialiased. This will render slower than Solid, but in about the same time as Blended mode.
* Blended - Slow Slow Slow, but Ultra Nice over another image
* Create a 32-bit ARGB surface and render the given text at high quality, using alpha blending to dither the font with the given color. This results in a surface with alpha transparency, so you don’t have a solid colored box around the text. The text is antialiased. This will render slower than Solid, but in about the same time as Shaded mode. Use this when you want high quality, and the text isn’t changing too fast.
---
### `TTF_Init()`
* Initialize the truetype font API.
* Must be called before using other functions in this library, except TTF\_WasInit or TTF\_Color.
* SDL does not have to be initialized before this call.
* Takes: Nothing.
* Returns: 0 on success, -1 on any error
### `TTF_WasInit`
* Query the initilization status of the truetype font API.
* Takes: Nothing.
* Returns: 1 if already initialized, 0 if not initialized.
### `TTF_Quit`
* Shutdown and cleanup the truetype font API.
* Takes: Nothing.
* Returns: Nothing.
### `TTF_GetError`
* Returns the last error set as a string.
* Takes: Nothing
* Returns: String.
### `TTF_OpenFont($file, $ptsize)`
* Load file for use as a font, at ptsize size.
* Takes:
* $file - File name to load font from.
* $ptsize - Point size (based on 72DPI) to load font as. Basically pixel height.
* Returns: Pointer to the font as a TTF\_Font. NULL is returned on error.
### `TTF_OpenFontIndex($file, $ptsize, $index)`
* Load file for use as a font, at ptsize size, selecting $index face.
* Takes:
* $file - File name to load font from.
* $ptsize - Point size (based on 72DPI) to load font as. Basically pixel height.
* $index - Choose a font face from a file containing multiple font faces. The first face is always index 0.
* Returns: Pointer to the font as a TTF\_Font. NULL is returned on error.
### `TTF_CloseFont($font)`
* Free the memory used by font, and free font itself as well.
* Takes: $font - Pointer to loaded font.
* Returns: Nothing.
### `TTF_GetFontStyle($font)`
* Get the rendering style of the loaded font.
* Takes: $font - Pointer to loaded font.
* Returns: The bitwise or of the set styles codes. See [the TTF\_STYLE ENUM](#TTF_STYLE)
### `TTF_GetFontStyles($font)`
* Get the rendering style of the loaded font, enumerated list.
* Takes: $font - Pointer to loaded font.
* Returns: An enumerated list of the set styles. See [the TTF\_STYLE ENUM](#TTF_STYLE)
### `TTF_SetFontStyle($font, $style)`
* Set the rendering style of the loaded font.
* Takes:
* $font - Pointer to loaded font.
* $style - The bitwise or of the desired styles codes. See [the TTF\_STYLE ENUM](#TTF_STYLE)
* Returns: Nothing
### `TTF_GetFontOutline($font)`
* Get the current outline size of the loaded font.
* Takes: $font - Pointer to loaded font.
* Returns: The size of the outline currently set on the font, in pixels.
### `TTF_SetFontOutline($font, $outline)`
* Set the current outline size of the loaded font.
* Takes:
* $font - Pointer to loaded font.
* $outline - The size of outline desired, in pixels.
* Returns: Nothing.
### `TTF_GetFontHinting($font)`
* Get the current hinting setting of the loaded font.
* Takes: $font - Pointer to loaded font.
* Returns: The hinting type matching one of the enumerated values. See [the TTF\_HINTING ENUM](#TTF_HINTING)
### `TTF_SetFontHinting($font, $hint)`
* Set the current hinting setting of the loaded font.
* Takes:
* $font - Pointer to loaded font.
* $hint - One of the enumerated Hint values. See [the TTF\_HINTING ENUM](#TTF_HINTING)
* Returns: Nothing.
### `TTF_GetFontKerning($font)`
* Get the current kerning setting of the loaded font.
* Takes: $font - Pointer to loaded font.
* Returns: Returns: 0(zero) if kerning is disabled; a non-zero value when enabled.
### `TTF_SetFontKerning($font, $allowed)`
* Set the current hinting setting of the loaded font.
* Takes:
* $font - Pointer to loaded font.
* $allowed - 0 to disable kerning; non-zero to enable kerning. The default is 1, enabled.
* Returns: Nothing.
### `TTF_FontHeight($font)`
* Get the maximum pixel height of all glyphs of the loaded font. Minimum size for adjacent rows of text to not overlap.
* Takes: $font - Pointer to loaded font.
* Returns: The maximum pixel height of all glyphs in the font.
### `TTF_FontAscent($font)`
* Get the maximum pixel ascent of all glyphs of the loaded font. - The maximum distance from the baseline to the top.
* Takes: $font - Pointer to loaded font.
* Returns: The maximum pixel ascent of all glyphs in the font.
### `TTF_FontDescent($font)`
* Get the maximum pixel descent of all glyphs of the loaded font. - The maximum distance from the baseline to the bottom.
* Takes: $font - Pointer to loaded font.
* Returns: The maximum pixel descent of all glyphs in the font.
### `TTF_FontLineSkip($font)`
* Get the recommended pixel height of a rendered line of text of the loaded font. - Usually larger than the TTF\_FontHeight of the font.
* Takes: $font - Pointer to loaded font.
* Returns: The maximum pixel height of all glyphs in the font.
### `TTF_FontFaces($font)`
* Get the number of faces ("sub-fonts") available in the loaded font.
* Takes: $font - Pointer to loaded font.
* Returns: The number of faces in the font.
### `TTF_FontFaceIsFixedWidth($font)`
* Test if the current font face of the loaded font is a fixed width font.
* Takes: $font - Pointer to loaded font.
* Returns: >0 if $font is a fixed width font. 0 if not a fixed width font.
### `TTF_FontFaceFamilyName($font)`
* Get the current font face family name from the loaded font.
* Takes: $font - Pointer to loaded font.
* Returns: The current family name of the face of the font, or NULL if not available.
### `TTF_FontFaceStyleName($font)`
* Get the current font face style name from the loaded font.
* Takes: $font - Pointer to loaded font.
* Returns: The current style name of the face of the font, or NULL if not available.
### `TTF_GlyphIsProvided($font, $character or $ordinal)`
* Get the status of the availability of the glyph for $character from the loaded font.
* Takes:
* $font - Pointer to loaded font.
* Either: $character - String containing the $character to check for.
* Or: $ordinal - Integer $ordinal of character.
* Returns: The index of the glyph location in the font for $character, or 0 for an undefined character code. (Note: returns the font file index, NOT the character ordinal.)
### `TTF_GlyphMetrics($font, $character)`
* Get the metrics of the char given in $character from the loaded font.
* Takes:
* $font - Pointer to loaded font.
* $character - String containing the character to get metrics for.
* Returns: A hash containing the following information:
* :font(TTF\_FontFaceFamilyName($font)) - The Family Face name
* :style(TTF\_FontFaceStyleName($font)) - The style
* :char($character) - The character checked
* :$min-x - The minimum X offset into the character.
* :$max-x - The maximum X offset into the character.
* :$min-y - The minimum Y offset into the character.
* :$max-y - The maximum Y offset into the character.
* :$advance - The distance from the end of the previous glyph to the start of the next.
Glyph Metrics explained: (image copyright libsdl.org)

### `TTF_GetTextSize($font, $text)`
* Get the width and height in pixels of the given text in the currently loaded font.
* Takes:
* $font - Pointer to loaded font.
* $text - Text string to get the dimensions.
* Returns: A list of Pairs
* :width(width)
* :height(height)
### `TTF_Color($red, $green, $blue, $alpha = 255)`
* Generate a packed ARGB TTF\_color suitable to pass to the rendering routines.
* Takes:
* $red - 0-255 integer value for red.
* $green - 0-255 integer value for green.
* $blue - 0-255 integer value for blue.
* $alpha - 0-255 integer value for alpha. Optional, default 255
* Returns: The packed TTF\_Color.
### `TTF_Render_Solid($font, $text, $fg)`
* Render the passed $text using $font with $fg color onto a new surface, using Solid mode.
* Takes:
* $font - Pointer to loaded font.
* $text - Text string to render.
* $fg - TTF\_Color to use as the foreground color.
* Returns: A pointer to a new SDL Surface.
### `TTF_Render_Shaded($font, $text, $fg, $bg)`
* Render the passed $text using $font with $fg color onto a new $bg colored surface, using Shaded mode.
* Takes:
* $font - Pointer to loaded font.
* $text - Text string to render.
* $fg - TTF\_Color to use as the foreground color.
* $bg - TTF\_Color to use as the background color.
* Returns: A pointer to a new SDL Surface.
### `TTF_Render_Blended($font, $text, $fg)`
* Render the passed $text using $font with $fg color onto a new surface, using Blended mode.
* Takes:
* $font - Pointer to loaded font.
* $text - Text string to render.
* $fg - TTF\_Color to use as the foreground color.
* Returns: A pointer to a new SDL Surface.
### `TTF_Render_Blended_Wrapped($font, $text, $fg, $length)`
* A convenience routine to render wrapped text, in Blended mode.
* Takes:
* $font - Pointer to loaded font.
* $text - Text string to render.
* $fg - TTF\_Color to use as the foreground color.
* $length - Length in pixels to use as a wrap threshold.
* Returns: A pointer to a new SDL Surface.
# AUTHOR
SDL2\_ttf library: Sam Lantinga
Raku bindings: Steve Schulze (thundergnat)
# COPYRIGHT AND LICENSE
Copyright 2020 Steve Schulze (thundergnat)
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_github-sirrobert-Semantic-Versioning.md
# Semantic Versioning
## Overview
Allows an object to take on versioning attributes in accordance with [the
Semantic Versioning specification (2.0.0)](http://semver.org/). The module
provides a class and a role.
## Role: does Semantic::Versioning
The `Semantic::Versioning` role enables any object to be versioned. Four
properties are added: `.version`, `.major-version`, `.minor-version`, and
`.patch-version`.
### Example use
```
class Document does Semantic::Versioning { }
my $doc = Document.new;
$doc.version = '1.6.23';
say $doc.major-version; # 1
say $doc.minor-version; # 6
say $doc.patch-version; # 23
$doc.minor-version = 7;
say $doc.version; # '1.7.23';
```
## Class: has Semantic::Version
The class version allows for multiple versioning attributes in an object.
### Example use
```
class Document {
has Semantic::Version $.described-in;
has Semantic::Version $.planned-for;
has Semantic::Version $.implemented-in;
}
my $doc = Document.new;
$doc.described-in.version = '1.6.23';
say $doc.described-in.major-version; # 1
say $doc.described-in.minor-version; # 6
say $doc.described-in.patch-version; # 23
$doc.planned-for.version = '2.0.0';
$doc.implemented-in.version = '2.0.0';
# Woops, made a mistake-- got implemented in the next minor version;
$doc.implemented-in.minor-version++;
say $doc.implemented-in; # '2.1.0';
```
|
## dist_cpan-JNTHN-Cro-Core.md
# Cro::Core Build Status
This is part of the Cro libraries for implementing services and distributed
systems in Raku. See the [Cro website](http://cro.services/) for further
information and documentation.
|
## dist_cpan-TYIL-Log-Simple.md
## class Log::Simple
A simple implementation of Log.
### has Positional @!outputs
An array of hashes. Each has must have a handle key, with an IO::Handle to print messages to. A level key with an integer to signify a Log::Level is also required.
### has Supplier $!messages
A supplier to emit messages to.
### has Bool $.hostname
When enabled, include hostname in the log message. This can be useful when running the application redundantly in a cluster with centralized logging.
### multi method emergency
```
multi method emergency(
Str:D $message
) returns Mu
```
Send an emergency message.
## class Str:D $message
The message to print.
### multi method emergency
```
multi method emergency(
Str:D $format,
*@args
) returns Mu
```
Send a formatted emergency message.
## class Str:D $format
A printf-style format string.
## class \*@args
Arguments to substitute into the format string placeholders.
### multi method alert
```
multi method alert(
Str:D $message
) returns Mu
```
Send an alert message.
## class Str:D $message
The message to print.
### multi method alert
```
multi method alert(
Str:D $format,
*@args
) returns Mu
```
Send a formatted alert message.
## class Str:D $format
A printf-style format string.
## class \*@args
Arguments to substitute into the format string placeholders.
### multi method critical
```
multi method critical(
Str:D $message
) returns Mu
```
Send a critical message.
## class Str:D $message
The message to print.
### multi method critical
```
multi method critical(
Str:D $format,
*@args
) returns Mu
```
Send a formatted critical message.
## class Str:D $format
A printf-style format string.
## class \*@args
Arguments to substitute into the format string placeholders.
### multi method error
```
multi method error(
Str:D $message
) returns Mu
```
Send an error message.
## class Str:D $message
The message to print.
### multi method error
```
multi method error(
Str:D $format,
*@args
) returns Mu
```
Send a formatted error message.
## class Str:D $format
A printf-style format string.
## class \*@args
Arguments to substitute into the format string placeholders.
### multi method warning
```
multi method warning(
Str:D $message
) returns Mu
```
Send a warning message.
## class Str:D $message
The message to print.
### multi method warning
```
multi method warning(
Str:D $format,
*@args
) returns Mu
```
Send a formatted warning message.
## class Str:D $format
A printf-style format string.
## class \*@args
Arguments to substitute into the format string placeholders.
### multi method notice
```
multi method notice(
Str:D $message
) returns Mu
```
Send a notice message. This is the "normal" level to publish log entries on.
## class Str:D $message
The message to print.
### multi method notice
```
multi method notice(
Str:D $format,
*@args
) returns Mu
```
Send a formatted notice message. This is the "normal" level to publish log entries on.
## class Str:D $format
A printf-style format string.
## class \*@args
Arguments to substitute into the format string placeholders.
### multi method info
```
multi method info(
Str:D $message
) returns Mu
```
Send an informational message.
## class Str:D $message
The message to print.
### multi method info
```
multi method info(
Str:D $format,
*@args
) returns Mu
```
Send a formatted informational message.
## class Str:D $format
The printf-style format string.
## class \*@args
Arguments to substitute into the format string placeholders.
### multi method debug
```
multi method debug(
Str:D $message
) returns Mu
```
Send a debug message.
## class Str:D $message
The message to print.
### multi method debug
```
multi method debug(
Str:D $format,
*@args
) returns Mu
```
Send a formatted debug message.
## class Str:D $format
A printf-style format string.
## class \*@args
Arguments to substitute into the format string placeholders.
### multi method add-output
```
multi method add-output(
IO::Handle:D $handle,
$level where { ... },
Callable :$filter
) returns Mu
```
Add an output to the logger.
## class IO::Handle:D $handle
The IO::Handle to write log messages to.
## class $level where { ... }
The log level for this particular stream.
## class Callable :$filter
A filter function to apply to any messages sent to the output.
### method callee
```
method callee(
Int:D $depth = 3
) returns Str
```
Convenience method to get the callee name. This is the package name if one exists, or the source file name.
## class Int:D $depth = 3
The depth of which to get the callframe.
### method message
```
method message(
Str:D $level,
Str:D $message
) returns Str
```
Convenience method for formatting the message as desired.
## class Str:D $level
A human readable identifier for the level.
## class Str:D $message
The original message to be logged.
# NAME
Log::Simple
# VERSION
0.1.1
# AUTHOR
Patrick Spek [[email protected]](mailto:[email protected])
# LICENSE
Copyright © 2020
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
## dist_zef-tbrowder-PDF-Combiner.md
[](https://github.com/tbrowder/PDF-Combiner/actions) [](https://github.com/tbrowder/PDF-Combiner/actions) [](https://github.com/tbrowder/PDF-Combiner/actions)
# NAME
**PDF::Combiner** - Provides routines and a program to combine and title PDF documents
# SYNOPSIS
```
use PDF::Combiner;
combine-pdfs config=our-israel-tour.txt
```
# Installation requirements
**PDF::Combiner** requires the system binary program, `ps2pdf`, in order to compress PDF files. To install it on a Debian system, execute:
```
sudo apt-get install ps2pdf
```
To compress any PDF execute:
```
ps2pdf -dPDFSETTINGS=/ebook large.pdf smaller.pdf # 150 dpi
ps2pdf -dPDFSETTINGS=/printer large.pdf smaller.pdf # 300 dpi
```
A 78 Mb combined PDF compressed to the following sizes:
* with '-dPDFSETTINGS=/ebook': 2.9 Mb
* with '-dPDFSETTINGS=/printer': 15 Mb
I could not see any differences in one printed page, but your results may vary. Choose output file compresion on the command line. You may also set it in your project configuration file.
# DESCRIPTION
**PDF::Combiner** is a simple but useful tool to combine PDF documents into a single PDF document.
In the example above, **our-israel-tour.txt** is a simple formatted text file containing several types of lines. See the example project `config` files in directory `/example-project` for usable examples of the input file.
Note the PDF files are expected to be in the same directory as the project file. If that is a problem for your use case, please file an issue.
# `config` file
The configuration (or project) file is a typical text file with data in single-line format for most options or in blocks of text. Its suffix is not specified, but the example files have extensions of `.txt` (the author's preference). Options are entered in a format taken from Rakudoc: `=option-name value....` or `=begin option-name`...`=end option-name`..
Blank lines are ignored (except in text blocks) and comments on a line begin at the first `#` character and continue to the end of the line.
Note comments in a text block resulting in a blank line will result in that blank line being retained in the block.
## Options
* `=begin title`...`=end title`
The lines between the begin/end options are used to populate a cover with the first line being the title and the following lines shown below it after some blank lines.
Note no cover is produced without this text block, nor is any cover produced if **all** lines are blank.
* `=numbers` value?
The 'value' is optional. Without it, the result is `True` if the option alone is present. If the option is **not** present, the result is `False`. If the 'value' is present, it is evaluated for truthiness.
A true value currently produces page numbers on each page (except any cover which is number one but not shown); format: 'Page N of M'.
* `=two-sided` value?
The 'value' is optional. Without it, the result is `True` if the option alone is present. If the option is **not** present, the result is `False`. If the 'value' is present, it is evaluated for truthiness.
* `=back` value?
The 'value' is optional. Without it, the result is `True` if the option alone is present. If the option is **not** present, the result is `False`. If the 'value' is present, it is evaluated for truthiness.
* `=outfile` value!
The option and 'value' are required.
'value' is the file name of the new document which should have no spaces and have a suffix of `.pdf`.
* `=paper` value!
The option is **not** required. But if it is used, then 'value' is required.
'value' defines the paper size. Current choices are 'Letter' or 'A4'. If the option is not used, the default size is 'Letter'.
* `=zip` value!
The option is **not** required. But if it is used, then 'value' is required.
'value' defines the compression level for the output file. It **must** be either '150' or '300' (dots per inch). It is very useful for PDFs generated from scans. The '150' DPI approximates the density of an ebook while '300' DPI approximates the output from a printer.
# Possible additional options
* `=begin introduction`...`=end introduction`
# CREDITS
Thanks to prolific Raku module distribution author David Warring for his wonderful PDF project (<https://github.com/pdf-raku>) and especially for his example of how to combine PDF files into one.
# AUTHOR
Tom Browder [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
© 2022-2023 Tom Browder
This library is free software; you may redistribute it or modify it under the Artistic License 2.0.
|
## markup.md
class RakuAST::Doc::Markup
Contains the information about RakuDoc markup
```raku
class RakuAST::Doc::Markup { }
```
The `RakuAST::Doc::Markup` class contains the information about markup codes in a [`RakuAST::Doc::Paragraph`](/type/RakuAST/Doc/Paragraph) or another `RakuAST::Doc::Markup` object.
Support for [`RakuAST`](/type/RakuAST) functionality is available in language version `6.e+` and was added in Rakudo compiler release 2023.02. In earlier language versions it is only available when specifying:
```raku
use experimental :rakuast;
```
## [Object introspection](#class_RakuAST::Doc::Markup "go to top of document")[§](#Object_introspection "direct link")
`RakuAST::Doc::Markup` objects are typically created when parsing Raku Programming Language code that has `RakuDoc` markers in it. So most developers will only need to know how to introspect the objects created.
### [method letter](#class_RakuAST::Doc::Markup "go to top of document")[§](#method_letter "direct link")
```raku
say "letter = $markup.letter()"; # B
```
Returns the letter of the markup. This is usually an uppercase letter (any Unicode codepoint with the "Lu" property), such as `B`, but can also be a letter like `Δ`.
### [method opener](#class_RakuAST::Doc::Markup "go to top of document")[§](#method_opener "direct link")
```raku
say "opener = $markup.opener()"; # <
```
Returns the string that indicates the opener of the markup. This is typically "<", "<<" or "«". It is mostly intended to be used for stringification of the `RakuAST::Doc::Markup` object.
### [method closer](#class_RakuAST::Doc::Markup "go to top of document")[§](#method_closer "direct link")
```raku
say "closer = $markup.closer()"; # >
```
Returns the string that indicates the closer of the markup. This is typically ">", ">>" or "»". It is mostly intended to be used for stringification of the `RakuAST::Doc::Markup` object.
### [method atoms](#class_RakuAST::Doc::Markup "go to top of document")[§](#method_atoms "direct link")
```raku
.say for $markup.atoms; # and
```
Returns a [`List`](/type/List) of the atoms. Note that each element can either be a string or another `RakuAST::Doc::Markup` object.
### [method meta](#class_RakuAST::Doc::Markup "go to top of document")[§](#method_meta "direct link")
```raku
.say for $markup.meta;
```
Returns a [`List`](/type/List) of the metaobjects. Note that each element can either be a string or another `RakuAST::Doc::Markup` object. The `RakuDoc` standard assigns meaning to the meta-information of markup for certain letters, such as a URL (in case of `L`).
### [method Str](#class_RakuAST::Doc::Markup "go to top of document")[§](#method_Str "direct link")
```raku
put $markup; # B<and>
```
Returns the string for the markup object, with any embedded markup also stringified.
### [method raku](#class_RakuAST::Doc::Markup "go to top of document")[§](#method_raku "direct link")
```raku
# method .gist falls back to .raku
say $markup; # RakuAST::Doc::Markup.new(...
```
Returns the string that is needed for the creation of the markup using [`RakuAST`](/type/RakuAST) calls.
# [Object creation](#class_RakuAST::Doc::Markup "go to top of document")[§](#Object_creation "direct link")
One seldom creates `RakuAST::Doc::Markup` objects directly. This documentation is intended for those few people who'd like to devise their own way of programmatically building a `RakuAST::Doc::Markup` object.
## [method new](#class_RakuAST::Doc::Markup "go to top of document")[§](#method_new "direct link")
```raku
method new(
Str:D :$letter!, # markup identifier, e.g. "B"
Str:D :$opener = "<", # opener marker
Str:D :$closer = ">", # closer marker
:@atoms, # any atoms of this markup
:@meta, # any meta of this markup
)
```
The `new` method can be called to create a new `RakuAST::Doc::Markup` object. It only takes named arguments, with the `:letter` argument being mandatory.
Rakudoc highlighting
```
B<and>
```
```raku
my $markup = RakuAST::Doc::Markup.new(
:letter<B>,
:atoms("and")
);
```
Note that all arguments except `:letter` are optional. So it is possible to create "empty" markup as well.
### [:letter](#class_RakuAST::Doc::Markup "go to top of document")[§](#:letter "direct link")
The "type" of markup object. Generally expected to be an uppercase letter, but this is not enforced. The `RakuDoc` standard assigns meaning to most ASCII uppercase letters, so one would probably do well adhering to this standard when using ASCII uppercase letters.
### [:opener](#class_RakuAST::Doc::Markup "go to top of document")[§](#:opener "direct link")
The markup opening sequence marker. Defaults to `"<"`. Mostly used for stringification.
### [:closer](#class_RakuAST::Doc::Markup "go to top of document")[§](#:closer "direct link")
The markup closing sequence marker. Defaults to `">"`. Mostly used for stringification.
### [:atoms](#class_RakuAST::Doc::Markup "go to top of document")[§](#:atoms "direct link")
The actual content of the markup, specified as a [`Positional`](/type/Positional). Each element can either be a string or another `RakuAST::Doc::Markup` object.
### [:meta](#class_RakuAST::Doc::Markup "go to top of document")[§](#:meta "direct link")
The meta-information of the markup, specified as a [`Positional`](/type/Positional). Each element can either be a string or another `RakuAST::Doc::Markup` object. Note that the `RakuDoc` standard associates certain meaning to the meta-information for certain letters, such as the meta-information being a URL in the case of `L` being the letter.
# [Object modification](#class_RakuAST::Doc::Markup "go to top of document")[§](#Object_modification "direct link")
## [method set-atoms](#class_RakuAST::Doc::Markup "go to top of document")[§](#method_set-atoms "direct link")
```raku
$markup.set-atoms; # reset
$markup.set-atoms( ("and",) );
```
Set the atoms to the given [`Positional`](/type/Positional). Values are expected to be either a string, or a `RakuAST::Doc::Markup` object. If no values are specified, then the object will have no atoms.
## [method add-atom](#class_RakuAST::Doc::Markup "go to top of document")[§](#method_add-atom "direct link")
```raku
$markup.add-atom( ("foo",) );
```
Add an atom to the atoms of the object. Values are expected to be either a string, or a `RakuAST::Doc::Markup` object.
## [method set-meta](#class_RakuAST::Doc::Markup "go to top of document")[§](#method_set-meta "direct link")
```raku
$markup.set-meta; # reset
$markup.set-meta( ("https://raku.org",) );
```
Set the meta-information to the given [`Positional`](/type/Positional). Values are expected to be either a string, or a `RakuAST::Doc::Markup` object. If no values are specified, then the object will have no meta-information.
## [method add-meta](#class_RakuAST::Doc::Markup "go to top of document")[§](#method_add-meta "direct link")
```raku
$markup.add-meta( ("bar",) );
```
Add an item to the meta-information of the object. Values are expected to be either a string, or a `RakuAST::Doc::Markup` object.
|
## dist_zef-elcaro-Deepgrep.md
# NAME
Deepgrep - Grep elements inside nested iterables.
# SYNOPSIS
```
use Deepgrep;
my @xs = (
[< a b c d >],
[< e f* g h >],
[< i j* k l >],
[< m n o p >],
);
say deepgrep(@xs, *.ends-with('*')).raku;
# ("f*", "j*").Seq
say deepgrep(@xs, *.ends-with('*'), :k).raku;
# ((1, 1), (2, 1)).Seq
say deepgrep(@xs, *.ends-with('*'), :kv).raku;
# ((1, 1), "f*", (2, 1), "j*").Seq
say deepgrep(@xs, *.ends-with('*'), :p).raku;
# ((1, 1) => "f*", (2, 1) => "j*").Seq
```
# NOTES
Similar to [`deepmap`](https://docs.raku.org/routine/deepmap), this function will descend into Iterables. It returns a flattened list of values that match the given predicate.
You might think that like `deepmap`, the nesting structure should be maintained, but that functionality can already be achieved with `deepmap`
```
say @xs.deepmap(-> $x { $x if $x.ends-with('*') }).raku;
# [[], ["f*"], ["j*"], []]
```
However `deepmap` cannot return keys (indices), or pairs, etc. Getting the indicies is useful if you want to modify deeply nested mutable elements in-place
```
for deepgrep(@xs, *.ends-with('*'), :k) -> ($x, $y) {
@xs[$x;$y] .= chop
}
```
This extends down to deeper nested structures as expected
```
my @zs = [
[
['a', 'b'], ['c', 'd'],
['e', 'F'], ['g', 'h'],
],
[
['i', 'J'], ['k', 'l'],
['m', 'n'], ['o', 'p'],
]
];
for @zs.&deepgrep(/<:Lu>/, :k) -> ($x, $y, $z) {
@zs[$x;$y;$z] .= lc
}
```
# CAVEATS & LIMITATIONS
If you are running under v6.e, Raku has support for Semilist syntax on Iterables, which allows this
```
use v6.e.PREVIEW;
for @zs.&deepgrep(/<:Lu>/, :k) -> @idx {
@zs[||@idx] .= lc
}
```
Without Semilist support, you will have to manually unpack your indices and index into the array, which means the shape should be uniform (eg. a M×N matrix).
# LICENSE
```
The Artistic License 2.0
```
See LICENSE file in the repository for the full license text.
|
## dist_zef-demanuel-App-JSONDiff.md
# Name
App::JSONDiff - Shows the differences in json files
# Goal
To be able to quick see what's different between similar json files.
I had several k8s environments and i wanted to compare the configmaps.
A diff falls short since it compares line by line and in a json file the order of the name/value pairs doesn't matter much.
# Usage
with file1.json as:
```
{
"name": "John Smith",
"age": 30,
"email": "[email protected]",
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"phoneNumbers": [
{
"type": "home",
"number": "555-1234"
},
{
"type": "work",
"number": "555-5678"
}
],
"isActive": true,
"preferences": {
"newsletter": true,
"notifications": false
}
}
```
with file2.json as:
```
{
"name": "Jane Smith",
"age": 28,
"email": "[email protected]",
"address": {
"street": "456 Elm St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"phoneNumbers": [
{
"type": "home",
"number": "555-4321"
},
{
"type": "work",
"number": "555-8765"
}
],
"isActive": true,
"preferences": {
"newsletter": false,
"notifications": true
}
}
```
Invoke it:
$ jsondiff file1.json file2.json
```
Difference at age:
30
28
Difference at name:
John Smith
Jane Smith
Difference at address.street:
123 Main St
456 Elm St
Difference at preferences.newsletter:
True
False
Difference at preferences.notifications:
False
True
Difference at email:
[email protected]
[email protected]
Difference at phoneNumbers[0].number:
555-1234
555-4321
Difference at phoneNumbers[1].number:
555-5678
555-8765
```
# License
This project is licensed under EUPL v1.2
# Bugs
Plentiful! Report them in <https://codeberg.org/demanuel/App-JSONDiff/issues> or via email at [[email protected]](mailto:[email protected])
|
## dist_zef-p6steve-Math-Polygons.md
# raku-Math-Polygons
Some polygon objects that draw via SVG - an alpha with the potential to do inheritance of Parallelograms, Rhomboids, etc.
[](https://travis-ci.org/p6steve/perl6-Math-Polygons)
# Instructions
There are three ways to consume this module:
1. Jupyter Notebook local
* Clone this repo locally on your machine
* Do the Quick Start here Brian Duggan perl6 jupyter-notebook at <https://github.com/bduggan/p6-jupyter-kernel>
* From the root directory run *jupyter-notebook*
1. Jupyter Notebook hosted on Binder
* Click this badge => [](https://mybinder.org/v2/gh/p6steve/perl6-Math-Polygons/master)
* Go to /eg and click Polygons.ipynb, then Run
* If you are the first to build e.g. a new version this can take 24 mins or so and the Binder browser UI may lose hope - please just be patient (do not reload as this restarts the build)
* If not, go to <mybinder.org> and paste this url <https://github.com/p6steve/perl6-Math-Polygons>, then the ./Dockerfile will be used to (re)build and run on Jupyter at Binder
1. Perl6 Module
* *zef install Math::Polygons*
# Synopsis
```
use SVG::Drawing;
use Math::Polygons;
my $rectangle = Rectangle.new(
origin => Point.new(20, 20),
width => 120,
height => 80
);
my $square = Square.new(
origin => Point.new(170, 20),
side => 100
);
my \A = Point.new( 20, 260);
my \B = Point.new( 30, 200);
my \C = Point.new(120, 145);
my \D = Point.new(125, 250);
my $quadrilateral = Quadrilateral.new(
A, B, C, D,
);
my $triangle = Triangle.new(
fill => "green",
stroke => "black",
apex => Point.new(220, 160),
side => 100
);
my $drawing = SVG::Drawing.new(
elements => [
$rectangle,
$square,
$quadrilateral,
$triangle,
],
);
$drawing.serialize.say;
```
# Inspired by
* Brian Duggan's perl6 jupyter-notebook at <https://github.com/bduggan/p6-jupyter-kernel>
* Jonathan Stowe's perl6 advent calendar [Christmas Tree](https://perl6advent.wordpress.com/2018/12/18/day-18-an-svg-christmas-tree/)
|
## kv.md
kv
Combined from primary sources listed below.
# [In List](#___top "go to top of document")[§](#(List)_routine_kv "direct link")
See primary documentation
[in context](/type/List#routine_kv)
for **routine kv**.
```raku
sub kv($list --> Seq:D)
method kv(List:D: --> Seq:D)
```
Returns an interleaved sequence of indexes and values. For example
```raku
say <a b c>.kv; # OUTPUT: «(0 a 1 b 2 c)»
```
# [In role Baggy](#___top "go to top of document")[§](#(role_Baggy)_method_kv "direct link")
See primary documentation
[in context](/type/Baggy#method_kv)
for **method kv**.
```raku
method kv(Baggy:D: --> Seq:D)
```
Returns a [`Seq`](/type/Seq) of keys and values interleaved.
```raku
my $breakfast = bag <eggs spam spam spam>;
say $breakfast.kv; # OUTPUT: «(spam 3 eggs 1)»
my $n = ("a" => 5, "b" => 2, "a" => 1).BagHash;
say $n.kv; # OUTPUT: «(a 6 b 2)»
```
# [In Capture](#___top "go to top of document")[§](#(Capture)_method_kv "direct link")
See primary documentation
[in context](/type/Capture#method_kv)
for **method kv**.
```raku
multi method kv(Capture:D: --> Seq:D)
```
Returns a [`Seq`](/type/Seq) of alternating [keys](#method_keys) and [values](#method_values). The positional keys and values, if any, comes first followed by the named keys and values.
```raku
my $capture = \(2, 3, apples => (red => 2));
say $capture.kv; # OUTPUT: «(0 2 1 3 apples red => 2)»
```
# [In role Enumeration](#___top "go to top of document")[§](#(role_Enumeration)_method_kv "direct link")
See primary documentation
[in context](/type/Enumeration#method_kv)
for **method kv**.
```raku
multi method kv(::?CLASS:D:)
```
Returns a list with key and value of the enum-pair.
```raku
say g.kv; # OUTPUT: «(g 1)»
```
# [In Map](#___top "go to top of document")[§](#(Map)_method_kv "direct link")
See primary documentation
[in context](/type/Map#method_kv)
for **method kv**.
```raku
method kv(Map:D: --> Seq:D)
```
Returns a [`Seq`](/type/Seq) of keys and values interleaved.
```raku
Map.new('a', 1, 'b', 2).kv # (a 1 b 2)
```
# [In Pair](#___top "go to top of document")[§](#(Pair)_method_kv "direct link")
See primary documentation
[in context](/type/Pair#method_kv)
for **method kv**.
```raku
multi method kv(Pair:D: --> List:D)
```
Returns a two-element [`List`](/type/List) with the *key* and *value* parts of `Pair`, in that order. This method is a special case of the same-named method on [`Hash`](/type/Hash), which returns all its entries as a list of keys and values.
```raku
my $p = (Raku => "d");
say $p.kv[0]; # OUTPUT: «Raku»
say $p.kv[1]; # OUTPUT: «d»
```
# [In Any](#___top "go to top of document")[§](#(Any)_routine_kv "direct link")
See primary documentation
[in context](/type/Any#routine_kv)
for **routine kv**.
```raku
multi method kv(Any:U:)
multi method kv(Any:D:)
multi kv($x)
```
Returns an empty [`List`](/type/List) if the invocant is a type object:
```raku
Sub.kv.say ;# OUTPUT: «()»
```
It calls `list` on the invocant for value objects and returns the result of [List.kv](/type/List#routine_kv) on it as a list where keys and values will be ordered and contiguous
```raku
<1 2 3>.kv.say; # OUTPUT: «(0 1 1 2 2 3)»
```
In the case of [`Positional`](/type/Positional)s, the indices will be considered *keys*.
# [In role Setty](#___top "go to top of document")[§](#(role_Setty)_method_kv "direct link")
See primary documentation
[in context](/type/Setty#method_kv)
for **method kv**.
```raku
multi method kv(Setty:D: --> Seq:D)
```
Returns a [`Seq`](/type/Seq) of the set's elements and `True` values interleaved.
```raku
my $s = Set.new(1, 2, 3);
say $s.kv; # OUTPUT: «(3 True 1 True 2 True)»
```
|
## dist_cpan-AZAWAWI-App-Perl6LangServer.md
# App::Perl6LangServer
[](https://travis-ci.org/azawawi/app-perl6langserver) [](https://ci.appveyor.com/project/azawawi/app-perl6langserver/branch/master)
This is usually invoked from a language client (e.g.
[ide-perl6](https://github.com/azawawi/ide-perl6)). This language server
only supports at the moment `stdin` / `stdout` mode. `stderr` is used to report debug information at the moment.
This
**Note: This is currently experimental and API may change. Please DO NOT use in
a production environment.**
## Features:
| Feature | Implements | Type | Status | Description |
| --- | --- | --- | --- | --- |
| Diagnostics | [PublishDiagnostics](https://microsoft.github.io/language-server-protocol/specification#textDocument_publishDiagnostics) | Notification | ✔️ | Parse syntax check errors output from `perl6 -c`. |
| Document outline | [Document Symbols](https://microsoft.github.io/language-server-protocol/specification#textDocument_documentSymbol) | Request | 🚧 | Experimental regex-based parser. |
| Hover | [Hover](https://microsoft.github.io/language-server-protocol/specification#textDocument_hover) | Request | 🚧 | Experimental p6doc support / find declaration. |
## Installation
* Install this module using [zef](https://github.com/ugexe/zef):
```
$ zef install App::Perl6LangServer
```
## Testing
* To run tests:
```
$ prove -ve "perl6 -Ilib"
```
* To run all tests including author tests (Please make sure
[Test::Meta](https://github.com/jonathanstowe/Test-META) is installed):
```
$ zef install Test::META
$ AUTHOR_TESTING=1 prove -e "perl6 -Ilib"
```
## Author
Ahmad M. Zawawi, [azawawi](https://github.com/azawawi/) on #perl6.
## License
MIT License
|
## canonpath.md
canonpath
Combined from primary sources listed below.
# [In IO::Spec::Cygwin](#___top "go to top of document")[§](#(IO::Spec::Cygwin)_method_canonpath "direct link")
See primary documentation
[in context](/type/IO/Spec/Cygwin#method_canonpath)
for **method canonpath**.
```raku
method canonpath(Str() $path, :$parent --> Str:D)
```
Returns a string that is a canonical representation of `$path`. If `:$parent` is set to true, will also clean up references to parent directories. **NOTE:** the routine does not access the filesystem.
```raku
IO::Spec::Cygwin.canonpath(「C:\foo\\..\bar\..\ber」).say;
# OUTPUT: «C:/foo/../bar/../ber»
IO::Spec::Cygwin.canonpath("foo///./../bar/../ber").say;
# OUTPUT: «foo/../bar/../ber»
IO::Spec::Cygwin.canonpath("foo///./../bar/../ber", :parent).say;
# OUTPUT: «ber»
```
# [In IO::Spec::Unix](#___top "go to top of document")[§](#(IO::Spec::Unix)_method_canonpath "direct link")
See primary documentation
[in context](/type/IO/Spec/Unix#method_canonpath)
for **method canonpath**.
```raku
method canonpath(Str() $path, :$parent --> Str:D)
```
Returns a string that is a canonical representation of `$path`. If `:$parent` is set to true, will also clean up references to parent directories. **NOTE:** the routine does not access the filesystem, so no symlinks are followed.
```raku
IO::Spec::Unix.canonpath("foo//../bar/../ber").say;
# OUTPUT: «foo/../bar/../ber»
IO::Spec::Unix.canonpath("foo///./../bar/../ber").say;
# OUTPUT: «foo/../bar/../ber»
IO::Spec::Unix.canonpath("foo///./../bar/../ber", :parent).say;
# OUTPUT: «ber»
```
# [In IO::Spec::Win32](#___top "go to top of document")[§](#(IO::Spec::Win32)_method_canonpath "direct link")
See primary documentation
[in context](/type/IO/Spec/Win32#method_canonpath)
for **method canonpath**.
```raku
method canonpath(Str() $path, :$parent --> Str:D)
```
Returns a string that is a canonical representation of `$path`. If `:$parent` is set to true, will also clean up references to parent directories. **NOTE:** the routine does not access the filesystem.
```raku
IO::Spec::Win32.canonpath("C:/foo//../bar/../ber").say;
# OUTPUT: «C:\foo\..\bar\..\ber»
IO::Spec::Win32.canonpath("C:/foo///./../bar/../ber").say;
# OUTPUT: «C:\foo\..\bar\..\ber»
IO::Spec::Win32.canonpath("C:/foo///./../bar/../ber", :parent).say;
# OUTPUT: «C:\ber»
```
# [In IO::Spec::QNX](#___top "go to top of document")[§](#(IO::Spec::QNX)_method_canonpath "direct link")
See primary documentation
[in context](/type/IO/Spec/QNX#method_canonpath)
for **method canonpath**.
```raku
method canonpath(Str() $path, :$parent --> Str:D)
```
Returns a string that is a canonical representation of `$path`. If `:$parent` is set to true, will also clean up references to parent directories. **NOTE:** the routine does not access the filesystem, so no symlinks are followed.
```raku
IO::Spec::QNX.canonpath("foo//../bar/../ber").say;
# OUTPUT: «foo/../bar/../ber»
IO::Spec::QNX.canonpath("foo///./../bar/../ber").say;
# OUTPUT: «foo/../bar/../ber»
IO::Spec::QNX.canonpath("foo///./../bar/../ber", :parent).say;
# OUTPUT: «ber»
```
|
## dist_zef-melezhik-Tomtit-Profile-Python.md
# Tomtit::Profile::Python
Tomtit scripts for Python development
# Install
```
zef install Tomtit::Profile::Python
```
# Usage
```
tom --list --profile Tomtit-Profile-Python
tom --profile Tomtit-Profile-Python
# run new helpers
tom python-pip-install-from-req
```
# Helpers doc
See ["python-helpers"](http://sparrowhub.io/search?q=%22python-helpers%22) Sparrow plugin.
# Author
Alexey Melezhik
|
## dist_zef-raku-community-modules-Datetime-Math.md
[](https://github.com/raku-community-modules/Datetime-Math/actions)
# NAME
Datetime::Math - Add common math operations to DateTime objects
# SYNOPSIS
```
use Datetime::Math;
# Given $dt1 and $dt2 are both DateTime objects.
my $days = from-seconds($dt2 - $dt1, 'd');
say "The events where $days days apart";
my $target = $dt1 + to-seconds(1, 'M');
say "One month after $dt1 would be $target";
my $hours = duration-from-to(3, 'y', 'h');
say "3 years contains $hours hours.";
```
# DESCRIPTION
Provides `to-seconds()`, `from-seconds()`, `duration-from-to()` and the ability to perform certain math operations on DateTime objects.
The math functions allowed are:
* Seconds = DateTime + DateTime
* Seconds = DateTime - DateTime
* DateTime = DateTime + Seconds
* DateTime = DateTime - Seconds
# SUBROUTINES
## to-seconds
Takes a value and a unit indicator and converts the value to seconds.
The value must be a number, the unit string must be one of:
```
's' Seconds, this is redundant it returns the string without the 's'.
'm' Minutes, so 1m will return 60.
'h' Hour, so 1h will return 3600.
'd' Day, so 1d will return 86400.
'w' Week, so 1w will return 604800.
'M' Month, so 1M will return 2592000. This is based on 30 days.
'y' Year, so 1y will return 31449600. Uses a round 365 days.
```
The Month estimation is not very accurate as it assumes 30 days regardless of month, if you need more accuracy, use a day count instead.
The Year estimation is based on a round 365 days, and does not take into account leap years or anything else. Again, if you need more accuracy, use a smaller unit.
## from-seconds
Takes a value in seconds and converts it into the specified unit.
The value and unit must be specified using the same rules as `to-seconds()`.
## duration-from-to
Takes a value, the unit string the value is currently in, and the unit string you want to covert the value to. The value and units must be specified using the same rules as `to-seconds()`.
# AUTHOR
Timothy Totten
# CONTRIBUTIONS BY
Clifton Wood
# COPYRIGHT AND LICENSE
Copyright 2013 - 2017 Timothy Totten
Copyright 2018 - 2022 Raku Community
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-jjmerelo-Services-PortMapping.md
# Services::PortMapping [Test-install distro](https://github.com/JJ/raku-service-portmapping/actions/workflows/test.yaml)
Map ports to services (and back) for internet services. Using [this CSV file](https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv)
included in the distribution, creates and exports 4 hashes that map ports to
services and back, for UDP and TCP.
* `%TCPServices` maps ports to TCP services
* `%TCPPorts` maps service names to ports;
And idem with UDP instead of TCP.
# Example
We have `[protocol]Services`, a hash that maps port numbers to the services
it hosts, and `[protocol]Ports`, which maps the conventional service name to
the port it uses. `protocol == any <TCP UDP SCTP DCCP>`
> No, I had never heard about these last two before
```
say %TCPServices<80>; # should return www-http
say %UDPPorts<domain>; # should return 53
```
You can also use `.keys` to print the existing ports or services.
## License
(c) JJ Merelo, `[email protected]`, 2020-2022
Released under the GPL-3.0 license.
|
## dist_cpan-CTILMES-BitEnum.md
# NAME
BitEnum -- Wrapper for Bitfields stored in an integer
# SYNOPSIS
```
use BitEnum;
my enum MyBits (
A => 0x01,
B => 0x02,
C => 0x04,
D => 0x08,
);
my $x = BitEnum[MyBits].new(6); # Pass in an integer
# or
my $x = BitEnum[MyBits].new(B,C); # flags to set
# or
my $x = BitEnum[MyBits].new; # nothing defaults to 0
put $x; # Stringify to list of keys
# B C # could also get "C B"
put +$x; # Numify to value
# 6
say $x; # gistify to value and list
6 = B C # or '6 = C B'
$x.set(A,B); # Set bits
$x.clear(B); # Clear bits
say $x.isset(A,B); # Check if all listed bits are set
# False
$x.toggle(C); # Flip bits
.key.say for @$x; # listify
```
# DESCRIPTION
Especially when interfacing with Nativecall libraries, various flags are often packed into an integer. Helpful library developers thoughfully provide various SET(), CLEAR(), ISSET(), etc. macros to perform the bit manipulations for C programmers. This module makes it easy to wrap an Enumeration of bit field values with a parameterized role that make it easy to perform the bit manipulations and human display for such values from Perl 6.
Printing as a string or gist make it easy to see which bits are set, and numifying and Int-ifying make it easy to pass in to routines that just want the value.
## COMBO keys
Sometimes libraries have convenience values that have multiple bits set. Those will work fine too. You can handle them in one of two ways.
Just put them into the enumeration like normal:
```
my enum MyBits (
A => 0x01,
B => 0x02,
C => 0x04,
D => 0x08,
AB => 0x03,
BC => 0x06,
);
my $x = BitEnum[MyBits].new(6);
say $x;
# 6 = B C BC
$x.set(AB, C);
say $x;
# 7 = AB BC A B C
```
or
Put them in their own, separate enumeration. They won't show up in the stringification, but you can still use them to set/clear/etc. combinations of bits.
```
my enum MyBits (
A => 0x01,
B => 0x02,
C => 0x04,
D => 0x08,
);
my enum Combos (
AB => 0x03,
BC => 0x06,
);
my $x = BitEnum[MyBits].new(6);
say $x;
# 6 = B C
$x.set(AB, C);
say $x;
# 7 = A B C
```
## Trimming prefixes
Sometimes the enumerated symbols have a common prefix that is nice to remove for printing. Pass an optional named parameter *:prefix* with a String and the number of characters in that string will be removed from each key when stringifying. Optionally lowercase them as well by passing in *:lc*. You can also set/clear/toggle bits by substring without the prefix.
```
my enum MyBits (
LONG_PREFIX_A => 0x01,
LONG_PREFIX_B => 0x02,
LONG_PREFIX_C => 0x04,
LONG_PREFIX_D => 0x08,
);
my $x = BitEnum[MyBits, prefix => 'LONG_PREFIX_', :lc].new(6);
put $x; # 'b c' or 'c b'
$x.set(<a b>);
$x.clear(<c>);
put $x; # 'a b' or 'b a'
```
# COPYRIGHT and LICENSE
Copyright 2019 Curt Tilmes
This module is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## native-descriptor.md
native-descriptor
Combined from primary sources listed below.
# [In IO::Socket::Async](#___top "go to top of document")[§](#(IO::Socket::Async)_method_native-descriptor "direct link")
See primary documentation
[in context](/type/IO/Socket/Async#method_native-descriptor)
for **method native-descriptor**.
```raku
method native-descriptor(--> Int)
```
Returns the file descriptor of this socket.
# [In IO::Socket::Async::ListenSocket](#___top "go to top of document")[§](#(IO::Socket::Async::ListenSocket)_method_native-descriptor "direct link")
See primary documentation
[in context](/type/IO/Socket/Async/ListenSocket#method_native-descriptor)
for **method native-descriptor**.
```raku
method native-descriptor(--> Int)
```
Returns the corresponding file descriptor (`SOCKET` on Windows) for the listening socket.
# [In IO::Handle](#___top "go to top of document")[§](#(IO::Handle)_method_native-descriptor "direct link")
See primary documentation
[in context](/type/IO/Handle#method_native-descriptor)
for **method native-descriptor**.
```raku
method native-descriptor(IO::Handle:D:)
```
This returns a value that the operating system would understand as a "file descriptor" and is suitable for passing to a native function that requires a file descriptor as an argument such as `fcntl` or `ioctl`.
# [In role IO::Socket](#___top "go to top of document")[§](#(role_IO::Socket)_method_native-descriptor "direct link")
See primary documentation
[in context](/type/IO/Socket#method_native-descriptor)
for **method native-descriptor**.
```raku
method native-descriptor()
```
This returns a value that the operating system would understand as a "socket descriptor" and is suitable for passing to a native function that requires a socket descriptor as an argument such as `setsockopt`.
# [In IO::CatHandle](#___top "go to top of document")[§](#(IO::CatHandle)_method_native-descriptor "direct link")
See primary documentation
[in context](/type/IO/CatHandle#method_native-descriptor)
for **method native-descriptor**.
```raku
method native-descriptor(IO::CatHandle:D: --> Int:D)
```
Returns the [native-descriptor](/type/IO/Handle#method_native-descriptor) of the currently active source handle or [`Nil`](/type/Nil) if the [source handle queue has been exhausted](/type/IO/CatHandle#method_next-handle).
Since the `CatHandle` closes a source handle, once it's done with it, it's possible for successive source handles to have the same native descriptor, if they were passed to [.new](/type/IO/CatHandle#method_new) as [`Cool`](/type/Cool) or [`IO::Path`](/type/IO/Path) objects.
```raku
(my $f1 = 'foo'.IO).spurt: 'foo';
(my $f2 = 'bar'.IO).spurt: 'bar';
with IO::CatHandle.new: $f1, $f2, $*IN {
repeat { .native-descriptor.say } while .next-handle;
# OUTPUT: «13139»
}
```
|
## dist_zef-antononcube-EBNF-Grammar.md
# EBNF::Grammar Raku package
## Introduction
Raku package for Extended Backus-Naur Form (EBNF) parsing and interpretation.
The grammar follows the description of the Wikipedia entry
["Extended Backus–Naur form"](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form), [Wk1],
which refers to the *proposed* ISO/IEC 14977 standard, by R. S. Scowen, page 7, table 1. [RS1, ISO1].
### Motivation
The main motivation for this package is to have:
1. Multiple EBNF styles parsed (quickly)
2. Grammar generation for multiple languages
The motivation comes from the the "need" to parse (and interpret) EBNF grammars
generated with Large Language Models (LLMs), like ChatGPT and PaLM. For more details see
["Incremental grammar enhancement"](https://github.com/antononcube/Raku-EBNF-Grammar/blob/main/doc/Incremental-grammar-enhancement.md).
I considered extending ["Grammar::BNF"](https://raku.land/github:tadzik/Grammar::BNF),
but ultimately decided that "Grammar::BNF" needs too much refactoring for my purposes,
and, well, it is for BNF not EBNF.
---
## Installation
From [Zef ecosystem](https://raku.land):
```
zef install EBNF::Grammar;
```
From GitHub:
```
zef install https://github.com/antononcube/Raku-EBNF-Grammar.git
```
---
## Usage examples
Here is an EBNF grammar for integers and its interpretation into a Raku grammar:
```
use EBNF::Grammar;
my $ebnf = q:to/END/;
<digit> = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ;
<integer> = <digit> , { <digit> } ;
<TOP> = <integer> ;
END
ebnf-interpret($ebnf);
```
```
# grammar EBNF_1702441429_8786073 {
# regex digit { '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' }
# regex integer { <digit> <digit>* }
# regex TOP { <integer> }
# }
```
Here the obtained Raku grammar is evaluated and used to do a few parsings:
```
my $gr = ebnf-interpret($ebnf):eval;
.say for <212 89 9090>.map({ $gr.parse($_) });
```
```
# 「212」
# integer => 「212」
# digit => 「2」
# digit => 「1」
# digit => 「2」
# 「89」
# integer => 「89」
# digit => 「8」
# digit => 「9」
# 「9090」
# integer => 「9090」
# digit => 「9」
# digit => 「0」
# digit => 「9」
# digit => 「0」
```
---
### Random sentence generation
Random sentences of grammars given in EBNF can be generated with additional help of the package
["Grammar::TokenProcessing"](https://github.com/antononcube/Raku-Grammar-TokenProcessing), [AAp2].
Here is an EBNF grammar:
```
my $ebnfCode = q:to/END/;
<statement> = <who> , <verb> , <lang> ;
<who> = 'I' | 'We' ;
<verb> = [ 'really' ] , ( 'love' | 'hate' | { '♥️' } | '🤮' );
<lang> = 'Julia' | 'Perl' | 'Python' | 'R' | 'WL' ;
END
```
```
# <statement> = <who> , <verb> , <lang> ;
# <who> = 'I' | 'We' ;
# <verb> = [ 'really' ] , ( 'love' | 'hate' | { '♥️' } | '🤮' );
# <lang> = 'Julia' | 'Perl' | 'Python' | 'R' | 'WL' ;
```
Here is the corresponding Raku grammar:
```
ebnf-interpret($ebnfCode, name=>'LoveHateProgLang');
```
```
grammar LoveHateProgLang {
regex statement { <who> <verb> <lang> }
regex who { 'I' | 'We' }
regex verb { 'really'? ['love' | 'hate' | '♥️'* | '🤮'] }
regex lang { 'Julia' | 'Perl' | 'Python' | 'R' | 'WL' }
}
```
Here we generate random sentences:
```
use Grammar::TokenProcessing;
my $gr = ebnf-interpret($ebnfCode, name=>'LoveHateProgLang'):eval;
.say for random-sentence-generation($gr, '<statement>') xx 12;
```
```
# We really love Perl
# We hate Perl
# I really hate R
# We hate Python
# I really 🤮 Python
# I really ♥️ R
# We really love Perl
# I hate WL
# I hate Python
# I really ♥️ WL
# I love Julia
# I love Julia
```
---
## CLI
The package provides a Command Line Interface (CLI) script for parsing EBNF. Here is its usage message:
```
ebnf-parse --help
```
```
# Usage:
# /Users/antonov/.rakubrew/versions/moar-2023.11/share/perl6/site/bin/ebnf-parse <ebnf> [-t|--target=<Str>] [--name|--parser-name=<Str>] [-s|--style=<Str>] -- Generates a parser code for a given EBNF grammar.
#
# <ebnf> EBNF text.
# -t|--target=<Str> Target. [default: 'Raku::Grammar']
# --name|--parser-name=<Str> Parser name. [default: 'Whatever']
# -s|--style=<Str> EBNF style, one of 'Standard', 'Inverted', 'Relaxed', or 'Whatever'. [default: 'Standard']
```
---
## Implementation notes
1. The first version of "EBNF::Grammar::Standardish" was *generated* with "FunctionalParsers", [AAp1], using the EBNF grammar (given in EBNF) in [Wk1].
2. Refactored `<term>` (originally `<pTERM>`) into separate parenthesized, optional, and repeated specs.
* This corresponds to the design in "FunctionalParsers".
3. Tokens and regexes were renamed. (More concise, easier to read names.)
4. Implemented the "relaxed" version of the standard EBNF.
---
## Comparison with other packages
The following table overviews the similarities and differences of this package
with the packages "FunctionalParsers" and "Grammar::TokenProcessing":
| Feature | FunctionalParsers | EBNF::Grammar | Grammar::TokenProcessing |
| --- | --- | --- | --- |
| **Parsing EBNF:** | | | ✔ |
| Standard | ✔ | ✔ | |
| Modified versions | ✔ | ✔ | |
| Whatever | ✔ | | |
| Automatic top rule determination | ✔ | | |
| **Parsing Raku grammar:** | | | ✔ |
| Pick left and pick right | ✔ | | |
| Skip element | | | ✔ |
| Automatic top rule determination | ✔ | | ✔ |
| Comprehensive quantifiers | | | ✔ |
| **Interpretation:** | ✔ | ✔ | |
| Raku grammar | ✔ | ✔ | |
| EBNF grammar (standard) | ✔ | | ✔ |
| WL grammar | ✔ | | |
| Java functional parsers | ✔ | | |
| Raku functional parsers | ✔ | | |
| Scala functional parsers | ✔ | | |
| WL functional parsers | ✔ | ✔ | |
| **Random sentence generation** | ✔ | | ✔ |
| **CLI** | ✔ | ✔ | ✔ |
Here are some additional- and clarification points:
* Since one of the motivations for "FunctionalParsers" and "EBNF::Grammar" is parsing and interpretation of EBNF
grammars derived with Large Language Models (LLMs) multiple EBNF variants have to be parsed.
* And a `Whatever` parsing method would be of great convenience.
* It is envisioned that "EBNF::Grammar" is completed with functionalities from "Grammar::TokenProcessing".
* (Like random sentence generation.)
* Both "FunctionalParsers" and "EBNF::Grammar" generate Functional Parsers (FPs) for other programming languages
because many languages have packages implementing FPs.
* The interpretations to FPs of other programming languages (Java, Swift) with "EBNF::Grammar" will be also implemented.
* In many cases the parsing with "EBNF::Grammar" is much faster than "FunctionalParsers".
* The conjecture that that would be case was one of the motivations for implementing of "EBNF::Grammar".
* Cross-interfacing:
* The package "Grammar::TokenProcessing" can translate Raku grammars into EBNFs.
* Both "FunctionalParsers" and "EBNF::Grammar" can translate EBNFs into Raku grammars.
* "EBNF::Grammar" can generate parser classes that are utilizing the FPs of "FunctionalParsers".
The following diagram summarizes the relationships (and implied workflows) in the comparison table
and clarification points above:
```
graph TD
EBNF>EBNF]
RakuGrammar>"Raku grammar"]
FPClass>"Functional parsers class<br/>(grammar)"]
FPs[[FunctionalParsers::EBNF]]
FPsEBNFMmdGraph[[FunctionalParsers::EBNF::Actions::MermaidJS::Graph]]
FPsEBNFWLGraph[[FunctionalParsers::EBNF::Actions::WL::Graph]]
EBNFGram[[EBNF::Grammar]]
GT[[Grammar::TokenProcessing]]
RS>Random sentences]
RakuAST>Raku AST]
MmdGraph>Mermaid JS<br>graph]
WLGraph>Mathematica/WL<br>graph]
EBNF --> FPs
EBNF --> EBNFGram
EBNFGram --> |ebnf-interpret|FPClass
EBNFGram --> |ebnf-grammar-graph|RakuAST
FPs --> |fp-ebnf-parse|FPClass
GT --> |random-sentence-generation|RS
FPClass --> |fp-random-sentence|RS
FPs --> |fp-ebnf-parse|RakuAST
RakuAST --> |fp-grammar-graph|FPsEBNFMmdGraph
FPsEBNFMmdGraph --> MmdGraph
RakuAST --> |fp-grammar-graph|FPsEBNFWLGraph
FPsEBNFWLGraph --> WLGraph
EBNFGram --> |ebnf-interpret|RakuGrammar
FPs --> |fp-ebnf-interpret|RakuGrammar
RakuGrammar --> GT
```
---
## TODO
* TODO Parsing of EBNF
* DONE Parse apply function, `<@`
* TODO Sequence-pick-left, `<&`
* TODO Sequence-pick-right, `&>`
* TODO "Named" tokens
* `'_?StringQ'` or `'_String'`
* `'_WordString'`, `'_LetterString'`, and `'_IdentifierString'`
* `'_?NumberQ'` and `'_?NumericQ'`
* `'_Integer'`
* `'Range[*from*, *to*]'`
* TODO Interpreters of EBNF
* TODO Java
* TODO ["funcj.parser"](https://github.com/typemeta/funcj/tree/master/parser)
* TODO Mermaid JS
* DONE Simple
* TODO Proper
* Most likely, via "FunctionalParsers"
* TODO Scala
* TODO built-in
* TODO [parsley](https://github.com/j-mie6/parsley)
* MAYBE Python
* TODO Raku
* DONE Grammar
* DONE FunctionalParsers
* TODO MermaidJS
* Other EBNF styles
* TODO WL
* DONE FunctionalParsers, [AAp1, AAp2]
* TODO GrammarRules
* DONE Implement grammar-graph translator
* Introduced dependency on ["FunctionalParsers"](https://github.com/antononcube/Raku-FunctionalParsers)
* DONE CLI
---
## References
### Articles
[Wk1] Wikipedia entry, ["Extended Backus–Naur form"](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).
[RS1] Roger S. Scowen: Extended BNF — A generic base standard. Software Engineering Standards Symposium 1993.
[ISO1] [ISO/IEC 14977:1996](https://www.iso.org/standard/26153.html).
### Packages, repositories
[AAp1] Anton Antonov,
[FunctionParsers Raku package](https://github.com/antononcube/Raku-FunctionalParsers),
(2023),
[GitHub/antononcube](https://github.com/antononcube).
[AAp2] Anton Antonov,
[Grammar::TokenProcessing Raku package](https://github.com/antononcube/Raku-Grammar-TokenProcessing),
(2022-2023),
[GitHub/antononcube](https://github.com/antononcube).
|
## dist_cpan-FRITH-File-Metadata-Libextractor.md
[](https://travis-ci.org/frithnanth/perl6-File-Metadata-Libextractor)
# NAME
File::Metadata::Libextractor - Use libextractor to read file metadata
# SYNOPSIS
```
use File::Metadata::Libextractor;
#| This program extracts all the information about a file
sub MAIN($file! where { .IO.f // die "file '$file' not found" })
{
my File::Metadata::Libextractor $e .= new;
my @info = $e.extract($file);
for @info -> %record {
for %record.kv -> $k, $v {
say "$k: $v"
}
say '-' x 50;
}
}
```
# DESCRIPTION
File::Metadata::Libextractor provides an OO interface to libextractor in order to query files' metadata.
As the Libextractor site (<https://www.gnu.org/software/libextractor>) states, it is able to read information in the following file types:
* HTML
* MAN
* PS
* DVI
* OLE2 (DOC, XLS, PPT)
* OpenOffice (sxw)
* StarOffice (sdw)
* FLAC
* MP3 (ID3v1 and ID3v2)
* OGG
* WAV
* S3M (Scream Tracker 3)
* XM (eXtended Module)
* IT (Impulse Tracker)
* NSF(E) (NES music)
* SID (C64 music)
* EXIV2
* JPEG
* GIF
* PNG
* TIFF
* DEB
* RPM
* TAR(.GZ)
* LZH
* LHA
* RAR
* ZIP
* CAB
* 7-ZIP
* AR
* MTREE
* PAX
* CPIO
* ISO9660
* SHAR
* RAW
* XAR FLV
* REAL
* RIFF (AVI)
* MPEG
* QT
* ASF
Also, various additional MIME types are detected.
## new(Bool :$in-process?)
Creates a **File::Metadata::Libextractor** object.
libextractor interfaces to several libraries in order to extract the metadata. To work safely it starts sub-processes to perform the actual extraction work.
This might cause problems in a concurrent envirnment with locks. A possible solution is to run the extraction process inside the program's own process. It's less secure, but it may avoid locking problems.
The optional argument **$in-process** allows the execution of the extraction job in the parent's process.
## extract($file where .IO.f // fail "file '$file' not found" --> List)
Reads all the possible information from an existing file, or fails if the file doesn't exist. The output **List** is actually a List of Hashes. Each hash has the following keys:
* mime-type The file's mime-type
* plugin-name The name of the plugin the library used to find out the information
* plugin-type The plugin subtype used for the operation
* plugin-format The format of the plugin's output
* data-type The value returned by the plugin subtype
The possible values for **plugin-format** are:
* EXTRACTOR\_METAFORMAT\_UNKNOWN
* EXTRACTOR\_METAFORMAT\_UTF8
* EXTRACTOR\_METAFORMAT\_BINARY
* EXTRACTOR\_METAFORMAT\_C\_STRING
The possible values for the **plugin-type** field are listed in File::Metadata::Libextractor::Constants, in the EXTRACTOR\_MetaType enum (231 values as for v3.1.6).
# Prerequisites
This module requires the libextractor library to be installed. It has been successfully tested on the following Linux distributions:
* Debian 9
* Debian sid
* Ubuntu 16.04
* Ubuntu 18.04
It doesn't work with the version of the library that comes with Ubuntu 14.04.
```
sudo apt-get install libextractor3
```
This module looks for a library called libextractor.so.3 .
# Installation
To install it using zef (a module management tool):
```
$ zef install File::Metadata::Libextractor
```
# Testing
To run the tests:
```
$ prove -e "perl6 -Ilib"
```
# AUTHOR
Fernando Santagata [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2018 Fernando Santagata
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_github-croservices-Cro-SSL.md
# This module is deprecated
Please see [Cro::TLS](https://github.com/croservices/cro-tls) instead.
|
## sink-all.md
sink-all
Combined from primary sources listed below.
# [In role Iterator](#___top "go to top of document")[§](#(role_Iterator)_method_sink-all "direct link")
See primary documentation
[in context](/type/Iterator#method_sink-all)
for **method sink-all**.
```raku
method sink-all(Iterator:D: --> IterationEnd)
```
Should exhaust the iterator purely for the side-effects of producing the values, without actually saving them in any way. Should always return `IterationEnd`. If there are no side-effects associated with producing a value, then it can be implemented by a consuming class to be a virtual no-op.
```raku
say (1 .. 1000).iterator.sink-all; # OUTPUT: «IterationEnd»
```
The Iterator role implements this method as a loop that calls `pull-one` until it is exhausted.
|
## dist_zef-sdondley-Menu-Simple.md
[](https://github.com/sdondley/MenuSimple/actions)
# NAME
Menu::Simple - Create, display, and execute a simple option menu on the command line
# SYNOPSIS
Simple usage:
```
use Menu::Simple;
# menu sorted alphabetically
my $m = Menu.new(); # construct a menu
$m.add-option: 'Opt A'; # add options to it
$m.add-option: 'Opt B';
my $option = $m.execute; # execute the menu
say $option.option-number; # get user's choice
# a menu sorted with option sort numbers
my $m = Menu.new(:strip-sort-num); # hides sort numbers
$m.add-option: '01 - Opt Z'; # displayed first
$m.add-option: '02 - Opt A'; # displayed second
# Menu options are output as:
1 - Opt Z # not "1 - 01 - Opt Z"
2 - Opt A # not "2 - 02 - Opt A"
```
More advanced usage:
```
use Menu::Simple;
# The code to run after an option is selected
sub some-action {
say "running some-action";
}
# Construct a submenu and add two options to it
my $submenu = Menu.new().add-options: <'First option', 'Second option'>;
# Create a main menu
my $menu = Menu.new();
# Add an option to the main menu with an action that runs an action
$menu.add-option(
action => &some-action,
option-value => 'some value',
display-string => "Do an action"
);
# Add an option that will show the submenu
$menu.add-option(
submenu => $submenu,
option-value => 'some other value',
display-string => 'Show submenu'
);
# Add an option that calls the action and shows the submenu
$menu.add-option(
action => &some-action,
submenu => $submenu,
display-string => 'Do an action and show submenu' );
# Execute the menu
$menu.execute;
```
Generate a menu from a hash:
```
use Menu::HashtoMenu;
my %hash = 'Option A' => 'Value A',
'Option B' => 'Value B',
'Option C' =>
{submenu1 =>
{ subsubmenu => 1},
'Option D' => 'hello' };
my $menu = HashToMenu.new(%hash2);
$menu.execute
```
Subroutines for adding actions and processing values of selected options can also be added to the menu with `HashToMenu`. See the Menu::HashToMenu class for more details.
# INSTALLATION
Assuming Raku and zef is already installed, install the module with:
`zef install Menu::Simple`
# DESCRIPTION
The `Menu::Simple` module outputs a list of numbered menu options to a terminal. Users are prompted to enter the option on the command line.
After a user selects an option, a submenu can be shown or an action can be executed, or both a submenu and an action can be executed. If neither a submenu or action is executed, an option's object is returned back can control is given back to to code calling the menu.
Menus are always sorted alphabetically. Add a sort number to the beginning of an option's display string to sort in a more arbitrary fashion. The sort numbers can be hidden from the menu by using the `:strip-sort-num` argument when constructing the menu.
**TIP:** When using sort numbers, leave large gaps between the numbers so you can easily add new menus between existing menu items. Pad the option sort numbers with leading zeroes if you expect to have more than a handful of options.
## Current Features
* Unlimited number of options can go on a menu
* Options can execute a submenu which can be nested to an unlimited depth
* Options can also execute an action which can run arbitrary code
* Can traverse back to parent menu from submenu
* Menus are displayed on the command line
* User selections are validated
* Customizable prompt and option delimiter
* Menus options are sorted alphabetically
* Menus can be shown in a different order by adding leading numbers to options
* A leading number for controlling option sorting can be optionally stripped
# CLASSES AND METHODS
## Menu Class
### Higher level instance methods
The following higher level methods are the most useful methods for generating and executing menus.
#### new()
```
my $menu = Menu.new();
```
Creates a new menu object. Returns the menu object created.
#### add-options(\*@options where { $options.all ~~ Str })
```
my $menu = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
```
Accepts a series of strings to add to a menu group.
Returns the menu the option was added to.
*Use this method to quickly add several menu options to a menu at once.*
#### multi method add-option(Str $display-string, $option-value? where \* !~~ Menu|Callable)
#### multi method add-option(Str $display-string, &action, $option-value?)
#### multi method add-option(Str $display-string, Menu $submenu, $option-value?)
#### multi method add-option(Str $display-string, Menu $submenu, &action, $option-value?)
#### multi method add-option(Str:D :$display-string, Menu :$submenu, :&action, :$option-value)
```
my $menu = Menu.new();
my $submenu = Menu.new.add-option('Option 1');
$menu.add-option('Run submenu and action', $submenu, { say 'hi' } );
```
Adds a single option to the menu. It can accept a submenu to display and/or a subroutine to execute after the option is selected by the user. Options are displayed in the menu alphabetically by default. A value can optionally be associated with a option.
Returns the menu the option was added to.
*Use this method to add an option to a menu that executes a submenu and/or calls a subroutine when selected.*
#### execute()
```
my $menu = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
$menu.execute;
```
Outputs a menu, prompts the user for a selection, validates the selection, and then returns the selected option or executes the appropriate action and/or displays a submenu based on the user's selection.
This method wraps many of the lower-level methods for processing the user's input.
*After a menu is built, use This method to display a menu and collect, validate, and execute responses to a user's selection from the menu.*
#### add-submenu(Menu:D $menu)
```
my $main-menu = Menu.new().add-options: <'Option A', 'Option B'>;
$main-menu.add-option: Option.new(display-string => 'Some string');
my $submenu = Menu.new().add-options: <'Option A', 'Option B', 'Option C'>
$main-menu.add-submenu($submenu);
```
Adds a submenu to the most recently added option. The submenu will be executed if the option is selected by the user.
*Use this method to add a submenu to the last option in an existing menu.*
#### add-submenu(Menu:D $menu, Int:D $option-number)
```
my $main-menu = Menu.new.add-options: <'Option A', 'Option B'>;
my $submmenu = Menu.new.add-options: <'Option 1', 'Option 2', 'Option 3'>;
$main-menu.add-submenu($submenu, 1); # adds a submenu to o 'Option A'
```
Adds a submenu to an existing option as indicated by the `$option-number` within the number group. The submenu will be executed when the option is selected by the user.
*Use this method to add a submenu that's executed when an option is selected.*
#### add-action(&action)
```
sub some-action() { say 'doing some actionn' };
my $menu = Menu.new();
$menu.add-option(display-string = 'Option 1';
$menu.add-action(&some-action); # added to Option 1
```
Adds an action to the last option added to the menu. The action will get executed if the option is selected.
*Use this method to add an action that's executed when an option is selected.*
#### add-action(&action, Int:D $option-number)
```
my $menu = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
$menu.add-action({ say 'running action'}, 1); # adds the action to o 'Option 1'
```
Adds an action to an existing option as indicated by the `$option-number` argument. The action is executed when the option is selected by the user.
*Use this method to execute an action when the option is selected.*
### Lower level instance methods
The Menu class methods below are typically not called directly and are provided in case you wish to override them or have more control over how menus are executed.
#### display()
```
my $menu = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
$menu.display;
```
Outputs a menu's option group and the prompt to the command line.
*This is a lower level method and is not usually not run directly.*
#### display-group()
```
my $menu = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
$menu.display-group;
```
Outputs a menu's option group to the command line.
*This is a lower level method and is not usually not run directly.*
#### get-option($option-number where Str:D|Int:D)
```
my $menu = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
my $option = $menu.get-option(3);
```
Returns an option object that has already been added to a menu. Accepts an integer value representing the number value of ordinal position of the option in the menu.
*This is a lower level method and is not usually not run directly.*
#### option-count()
```
my $menu = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
my $count = $menu.option-count();
```
Returns the number of options that have been added to a menu.
*This is a lower level method and is not usually not run directly.*
#### display-prompt()
```
my $menu = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
$menu.prompt;
```
Displays a menu's prompt on the command line.
*This is a lower level method and is not usually not run directly.*
#### get-selection()
```
my $menu = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
$menu.get-selection;
```
Gets selection input from the user.
*This is a lower level method and is not usually not run directly.*
#### validate-selection( --> Bool )
```
my $menu = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
$menu.selection = 3;
my $is-valid = $menu.validate-selection;
```
Determines if the user has selected a valid option. Returns a True or False value.
*This is a lower level method and is not usually not run directly.*
#### process-selection()
```
my $menu = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
$menu.selection = 2;
$menu.process-selection;
```
#### menuID()
```
my $menu1 = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
my $menu2 = Menu.new().add-options: <'Option A', 'Option B', 'Option C'>;
$menu1.menuID; # returns the Int value '1'
$menu2.menuID; # returns the Int value '2'
```
Returns the internal menu id of the menu.
*This is a lower level method and is not usually not run directly.*
### Class methods
#### get-menu(Int:D $id)
```
my $menu = Menu.new().add-options: <'Option 1', 'Option 2', 'Option 3'>;
my $submenu = Menu.new().add-options: <'Option A', 'Option B', 'Option C'>;
Menu.get-menu(1); # returns $menu
Menu.get-menu(2); # returns $submenu
```
Returns the menu that corresponds to the `$id` passed to `get-menu`
*This is a lower level method and is not usually not run directly.*
#### get-counters()
Dumps the hash containing the options counters for all menus
*This is a lower level method and is not usually not run directly.*
### Attributes
#### has Bool $.strip-sort-num;
Hides the sort number which can be used for sorting options. The menu will Look for digits at the beginning of the option's display string followed by a dash character. Whitespace surrounding the dash is optional.
#### %.options
A hash of the options in an options groups.
#### $.menuID = ++$ID;
A unique ID number for the menu
#### $.option-format is rw = "%d - %s";
The format string for displaying options where `%d` is the option number and `%s` is the display string.
#### $.selection is rw;
The string the user has input
#### $.validated-selection is rw = Nil;
The validated string of the user's input
#### $.option-separator is rw = "\n";
The string that separates menu options
#### $.prompt = "\nMake selection: ";
The prompt shown to the user
#### $.error-msg = "\nSorry, invalid entry. Try again. ";
The error show when a user make an invalid selection
## Option Class
### Methods
#### Option.new(Str:D :display-string, :action, :submenu)
```
my $menu = Option.new(
display-string => Str,
action => Callable?,
submenu => Menu?
);
```
Creates a new option.
The `display-string` is the string shown to the user.
The `action` is the subroutine run when the option is selected.
The `submenu` is the menu displayed when the option is selected.
### Attributes
#### $.option-number;
The number of the option
#### $.option-value;
An optional value associated with an option
#### $.display-string is required;
The string shown when an option is printed
#### $.submenu is rw;
The submenu executed when an option is selected
#### Int $.parent-menuID is rw;
The menuID of the option belongs to
#### Int $.child-menuID is rw;
The menuID of the submenu the option executes. Return 0 if none.
#### &.action is rw;
The action executed when an option is selected
|
## dist_zef-jforget-Date-Calendar-CopticEthiopic.md
# NAME
Date::Calendar::CopticEthiopic - conversions from / to the Coptic calendar and from / to the Ethiopic calendar
# SYNOPSIS
Converting a Gregorian date to both Coptic and Ethiopic
```
use Date::Calendar::Coptic;
use Date::Calendar::Ethiopic;
my Date $Perlcon-Riga-grg;
my Date::Calendar::Coptic $Perlcon-Riga-cop;
my Date::Calendar::Ethiopic $Perlcon-Riga-eth;
$Perlcon-Riga-grg .= new(2019, 8, 7);
$Perlcon-Riga-cop .= new-from-date($Perlcon-Riga-grg);
$Perlcon-Riga-eth .= new-from-date($Perlcon-Riga-grg);
say $Perlcon-Riga-cop.strftime("%A %e %B %Y");
#--> Peftoou 1 Mesori 1735
say $Perlcon-Riga-eth.strftime("%A %e %B %Y");
#--> Rob 1 Nahas 2011
```
Converting a Coptic date and an Ethiopic date to Gregorian
```
use Date::Calendar::Coptic;
use Date::Calendar::Ethiopic;
my Date::Calendar::Coptic $TPC-Pittsburgh-cop;
my Date::Calendar::Ethiopic $TPC-Pittsburgh-eth;
my Date $TPC-Pittsburgh-grg1;
my Date $TPC-Pittsburgh-grg2;
$TPC-Pittsburgh-cop .= new(year => 1735, month => 10, day => 9);
$TPC-Pittsburgh-grg1 = $TPC-Pittsburgh-cop.to-date;
#--> 9 Paoni 1735 = 16 June 2019
$TPC-Pittsburgh-eth .= new(year => 2011, month => 10, day => 14);
$TPC-Pittsburgh-grg2 = $TPC-Pittsburgh-eth.to-date;
#--> 14 Sane 2011 = 21 June 2019
```
# INSTALLATION
```
zef install Date::Calendar::CopticEthiopic
```
or
```
git clone https://github.com/jforget/raku-Date-Calendar-CopticEthiopic.git
cd Date-Calendar-CopticEthiopic
zef install .
```
# DESCRIPTION
Date::Calendar::CopticEthiopic is a module distribution providing two
classes, Date::Calendar::Coptic and Date::Calendar::Ethiopic. The
corresponding calendars both derive from the ancient Egyptian
calendar. In each, a year consists of 12 months with 30 days each,
plus 5 or 6 additional days (epagomene) at the end of the year. Leap
years occurs every fourth year, with no adjustment for century years.
The calendars also define weeks which last for 7 days, beginning on
sunday and ending on saturday.
# AUTHOR
Jean Forget
# COPYRIGHT AND LICENSE
Copyright (c) 2019, 2020, 2024, 2025 Jean Forget
This library is free software; you can redistribute it and/or modify
it under the Artistic License 2.0.
|
## dist_cpan-CLARKEMA-Pod-To-Man.md
# Pod::To::Man
Render Perl 6 Pod as Roff for `man(1)`, so your scripts can have proper
manpages.
## Install
zef install Pod::To::Man
## Sysopsis
From the command line:
```
perl6 --doc=Man your_script > your_script.1
```
## Limitations
This is a very early work in progress, and the Roff is not ideal. Certain
features such as nested lists haven't received much attention yet. On the
other hand, it's already useful enough to produce much nicer documentation
for some of my scripts than the plain text formatter.
Issues / patches / pull requests / Roff formatting suggestions are
all extremely welcome.
|
## dist_zef-cro-Cro-WebSocket.md
# Cro::WebSocket Build Status
This is part of the Cro libraries for implementing services and distributed
systems in Raku. See the [Cro website](http://cro.services/) for further
information and documentation.
|
## dist_zef-lizmat-P5math.md
[](https://github.com/lizmat/P5math/actions)
# NAME
Raku port of Perl's math built-ins
# SYNOPSIS
```
use P5math; # exports abs cos crypt exp int log rand sin sqrt
```
# DESCRIPTION
This module tries to mimic the behaviour of Perl's `abs`, `cos`, `crypt`, `exp`, `int`, `log`, `rand`, `sin` and `sqrt` builtins as closely as possible in the Raku Programming Language..
# ORIGINAL PERL 5 DOCUMENTATION
```
abs VALUE
abs Returns the absolute value of its argument. If VALUE is omitted,
uses $_.
cos EXPR
cos Returns the cosine of EXPR (expressed in radians). If EXPR is
omitted, takes the cosine of $_.
For the inverse cosine operation, you may use the
"Math::Trig::acos()" function, or use this relation:
sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
crypt PLAINTEXT,SALT
Creates a digest string exactly like the crypt(3) function in the
C library (assuming that you actually have a version there that
has not been extirpated as a potential munition).
crypt() is a one-way hash function. The PLAINTEXT and SALT are
turned into a short string, called a digest, which is returned.
The same PLAINTEXT and SALT will always return the same string,
but there is no (known) way to get the original PLAINTEXT from the
hash. Small changes in the PLAINTEXT or SALT will result in large
changes in the digest.
There is no decrypt function. This function isn't all that useful
for cryptography (for that, look for Crypt modules on your nearby
CPAN mirror) and the name "crypt" is a bit of a misnomer. Instead
it is primarily used to check if two pieces of text are the same
without having to transmit or store the text itself. An example is
checking if a correct password is given. The digest of the
password is stored, not the password itself. The user types in a
password that is crypt()'d with the same salt as the stored
digest. If the two digests match, the password is correct.
When verifying an existing digest string you should use the digest
as the salt (like "crypt($plain, $digest) eq $digest"). The SALT
used to create the digest is visible as part of the digest. This
ensures crypt() will hash the new string with the same salt as the
digest. This allows your code to work with the standard crypt and
with more exotic implementations. In other words, assume nothing
about the returned string itself nor about how many bytes of SALT
may matter.
Traditionally the result is a string of 13 bytes: two first bytes
of the salt, followed by 11 bytes from the set "[./0-9A-Za-z]",
and only the first eight bytes of PLAINTEXT mattered. But
alternative hashing schemes (like MD5), higher level security
schemes (like C2), and implementations on non-Unix platforms may
produce different strings.
When choosing a new salt create a random two character string
whose characters come from the set "[./0-9A-Za-z]" (like "join '',
('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]"). This set
of characters is just a recommendation; the characters allowed in
the salt depend solely on your system's crypt library, and Perl
can't restrict what salts "crypt()" accepts.
Here's an example that makes sure that whoever runs this program
knows their password:
$pwd = (getpwuid($<))[1];
system "stty -echo";
print "Password: ";
chomp($word = <STDIN>);
print "\n";
system "stty echo";
if (crypt($word, $pwd) ne $pwd) {
die "Sorry...\n";
} else {
print "ok\n";
}
Of course, typing in your own password to whoever asks you for it
is unwise.
The crypt function is unsuitable for hashing large quantities of
data, not least of all because you can't get the information back.
Look at the Digest module for more robust algorithms.
If using crypt() on a Unicode string (which potentially has
characters with codepoints above 255), Perl tries to make sense of
the situation by trying to downgrade (a copy of) the string back
to an eight-bit byte string before calling crypt() (on that copy).
If that works, good. If not, crypt() dies with "Wide character in
crypt".
Portability issues: "crypt" in perlport.
exp EXPR
exp Returns me (the natural logarithm base) to the power of EXPR. If
EXPR is omitted, gives "exp($_)".
int EXPR
int Returns the integer portion of EXPR. If EXPR is omitted, uses $_.
You should not use this function for rounding: one because it
truncates towards 0, and two because machine representations of
floating-point numbers can sometimes produce counterintuitive
results. For example, "int(-6.725/0.025)" produces -268 rather
than the correct -269; that's because it's really more like
-268.99999999999994315658 instead. Usually, the "sprintf",
"printf", or the "POSIX::floor" and "POSIX::ceil" functions will
serve you better than will int().
log EXPR
log Returns the natural logarithm (base e) of EXPR. If EXPR is
omitted, returns the log of $_. To get the log of another base,
use basic algebra: The base-N log of a number is equal to the
natural log of that number divided by the natural log of N. For
example:
sub log10 {
my $n = shift;
return log($n)/log(10);
}
See also "exp" for the inverse operation.
rand EXPR
rand Returns a random fractional number greater than or equal to 0 and
less than the value of EXPR. (EXPR should be positive.) If EXPR is
omitted, the value 1 is used. Currently EXPR with the value 0 is
also special-cased as 1 (this was undocumented before Perl 5.8.0
and is subject to change in future versions of Perl).
Automatically calls "srand" unless "srand" has already been
called. See also "srand".
Apply "int()" to the value returned by "rand()" if you want random
integers instead of random fractional numbers. For example,
int(rand(10))
returns a random integer between 0 and 9, inclusive.
(Note: If your rand function consistently returns numbers that are
too large or too small, then your version of Perl was probably
compiled with the wrong number of RANDBITS.)
"rand()" is not cryptographically secure. You should not rely on
it in security-sensitive situations. As of this writing, a number
of third-party CPAN modules offer random number generators
intended by their authors to be cryptographically secure,
including: Data::Entropy, Crypt::Random, Math::Random::Secure, and
Math::TrulyRandom.
sin EXPR
sin Returns the sine of EXPR (expressed in radians). If EXPR is
omitted, returns sine of $_.
For the inverse sine operation, you may use the "Math::Trig::asin"
function, or use this relation:
sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) }
sqrt EXPR
sqrt Return the positive square root of EXPR. If EXPR is omitted, uses
$_. Works only for non-negative operands unless you've loaded the
"Math::Complex" module.
use Math::Complex;
print sqrt(-4); # prints 2i
```
# PORTING CAVEATS
## Can not use int()
As of this writing (2020.10), it is **not** possible to actually use `int` in your code because of code generation issue caused by the fact that `int` is a built-in native type in Raku.
## crypt() not supported on all platforms
The `crypt` function will return `Nil` if it is not supported by the OS.
## $\_ no longer accessible from caller's scope
In future language versions of Raku, it will become impossible to access the `$_` variable of the caller's scope, because it will not have been marked as a dynamic variable. So please consider changing:
```
cos;
```
to either:
```
cos($_);
```
or, using the subroutine as a method syntax, with the prefix `.` shortcut to use that scope's `$_` as the invocant:
```
.&cos;
```
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
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!
Source can be located at: <https://github.com/lizmat/P5math> . Comments and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2018, 2019, 2020, 2021, 2023 Elizabeth Mattijsen
Re-imagined from Perl as part of the CPAN Butterfly Plan.
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_github-retupmoca-Net-SOCKS.md
# P6-Net-SOCKS
A small SOCKS5 client. Currently only supports connection requests.
## Example Usage
```
use Net::SOCKS;
my $socket = Net::SOCKS.connect(:host('myhost'), :port(123), :proxy-server('proxy'));
```
## Methods
* `connect(:$host!, :$port!, :$proxy-server, :$proxy-port = 1080, :$socket = IO::Socket::INET)`
Opens a connection to the `$host` via the `$proxy-server`. Returns a ready-to-use
socket on success, and a Failure otherwise.
The `$socket` parameter allows you to pass an already-connected handle (in
which case `$proxy-server` and `$proxy-port` are ignored), or to define an
alternate socket class to make the connection with.
|
## x.md
x
Combined from primary sources listed below.
# [In Operators](#___top "go to top of document")[§](#(Operators)_infix_x "direct link")
See primary documentation
[in context](/language/operators#infix_x)
for **infix x**.
```raku
sub infix:<x>($a, $b --> Str:D)
```
String repetition operator.
Repeats the string `$a` `$b` times, if necessary coercing `$a` to [`Str`](/type/Str) and `$b` to [`Int`](/type/Int). Returns an empty string if `$b <= 0`. An exception `X::Numeric::CannotConvert` will be thrown if `$b` is `-Inf` or `NaN`.
```raku
say 'ab' x 3; # OUTPUT: «ababab»
say 42 x 3; # OUTPUT: «424242»
my $a = 'a'.IO;
my $b = 3.5;
say $a x $b; # OUTPUT: «aaa»
```
# [In IO::Special](#___top "go to top of document")[§](#(IO::Special)_method_x "direct link")
See primary documentation
[in context](/type/IO/Special#method_x)
for **method x**.
```raku
method x(IO::Special:D: --> False)
```
The 'execute access' file test operator, always returns `False`.
# [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_x "direct link")
See primary documentation
[in context](/type/IO/Path#method_x)
for **method x**.
```raku
method x(IO::Path:D: --> Bool:D)
```
Returns `True` if the invocant is a path that exists and is executable. The method will [`fail`](/routine/fail) with [`X::IO::DoesNotExist`](/type/X/IO/DoesNotExist) if the path points to a non-existent filesystem entity.
**NOTE:** If the file is a script (an executable text file and not a native executable), and the file has *only* executable permissions and *no* read permissions, this method will return `True` but trying to execute will fail. That is a limitation of the operating system.
|
## dist_zef-jonathanstowe-Audio-Hydrogen.md
# Audio::Hydrogen
Work with Hydrogen songs and drumkits

## Synopsis
```
use Audio::Hydrogen;
for Audio::Hydrogen.new.drumkits -> $dk {
say $dk.name;
}
```
There are also some vaguely useful examples in the <examples> directory.
## Description
This provides the facilities for creating and manipulating drumkit and
song data of the [Hydrogen](http://www.hydrogen-music.org/) drum software.
I originally wrote this with no other purpose than as a test for
[XML::Class](https://github.com/jonathanstowe/XML-Class) so it may well
be missing some features that you would like to see, but please see the
examples for things that you can do with it.
## Installation
Assuming you have a working Rakudo installation you should be able to install this with *zef* :
```
# From the source directory
zef install .
# Remote installation
zef install Audio::Hydrogen
```
Other install mechanisms may be become available in the future.
## Support
I'm sure this is almost certainly missing some useful features,
and am quite open to any ideas that could make it more useful.
I'd also be delighted to hear about anything interesting you
do with it.
Suggestions/patches are welcomed via [github](https://github.com/jonathanstowe/Audio-Hydrogen/issues)
## Licence
This is free software.
Please see the <LICENCE> file in the distribution
© Jonathan Stowe 2016 - 2021
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.