txt
stringlengths 93
37.3k
|
---|
## dist_zef-bduggan-LLM-DWIM.md
[](https://github.com/bduggan/raku-llm-dwim/actions/workflows/linux.yml)
[](https://github.com/bduggan/raku-llm-dwim/actions/workflows/macos.yml)
# NAME
LLM::DWIM -- Do What I Mean, with help from large language models.
# SYNOPSIS
```
use LLM::DWIM;
say dwim "How many miles is it from the earth to the moon?";
# Approximately 238,900 miles (384,400 kilometers)
say dwim "@NothingElse How many miles is it from the earth to the moon? #NumericOnly";
# 238900
sub distance-between($from,$to) {
dwim "@NothingElse #NumericOnly What is the distance in miles between $from and $to?";
}
say distance-between("earth","sun");
# 92955887.6 miles
my $agent = dwim-chat("Answer every question with an exclamation point!");
say $agent.eval: "My name is bob and I have five dogs.";
# That's great!
say $agent.eval: "How many paws is that?";
# Twenty!
```
Meanwhile, in ~/.config/llm-dwim.toml:
```
evaluator = "gemini"
gemini.temperature = 0.5
```
# DESCRIPTION
This is a simple wrapper around [LLM::Functions](https://raku.land/zef:antononcube/LLM::Functions), and [LLM::Prompts](https://raku.land/zef:antononcube/LLM::Prompts) It provides a single subroutine, `dwim`, that sends a string to an LLM evaluator, making use of a configuration file to say a little more about what you mean.
# FUNCTIONS
## dwim
```
sub dwim(Str $str) returns Str
```
This function takes a string, expands it using LLM::Prompts, and uses LLM::Functions to evaluate the string.
## dwim-chat
```
sub dwim-chat(Str $prompt) returns Str
```
Create a chat agent that will have a conversation.
For diagnostics, use [Log::Async](https://raku.land/cpan:BDUGGAN/Log::Async) and add a tap, like so:
```
use LLM::DWIM;
use Log::Async;
logger.send-to($*ERR);
say dwim "How many miles is it from earth is the moon? #NumericOnly";
```
# CONFIGURATION
This module looks for `llm-dwim.toml` in either `XDG_HOME` or `HOME/.config`. This can be overridden by setting `DWIM_LLM_CONF` to another filename.
The configuration file should be in TOML format and should contain at least one key, `evaluator`, which should be the name of the LLM evaluator to use. Evaluators can be configured using TOML syntax, with the evaluator name as the key.
Sample configurations:
Use Gemini (which has a free tier) :
```
evaluator = "gemini"
```
Use OpenAI, and modify some parameters:
```
evaluator = "OpenAI"
OpenAI.temperature = 0.9
OpenAI.max-tokens = 100
```
See [LLM::Functions](https://raku.land/zef:antononcube/LLM::Functions) for all of the configuration options.
# COMMAND LINE USAGE
This package has two scripts:
First, `llm-dwim` can be used to evaluate a string from the command line.
Sample usage:
```
llm-dwim -h # get usage
llm-dwim "How many miles is it from the earth to the moon?"
llm-dwim -v how far is it from the earth to the moon\?
echo "what is the airspeed velocity of an unladen swallow?" | llm-dwim -
```
Second, `llm-dwim-chat` will have a chat with you.
Sample session:
```
llm-dwim-chat you are a french tutor --name=Professor
you > Hello
Professor > Bonjour ! Comment allez-vous ?
you > Bien merci
Professor > Et vous ? (And you?)
you >
```
# SEE ALSO
[LLM::Functions](https://raku.land/zef:antononcube/LLM::Functions), [LLM::Prompts](https://raku.land/zef:antononcube/LLM::Prompts)
This was inspired by the also excellent [DWIM::Block](https://metacpan.org/pod/DWIM::Block) module.
# AUTHOR
Brian Duggan
|
## submethod.md
class Submethod
Member function that is not inherited by subclasses
```raku
class Submethod is Routine {}
```
A Submethod is a method that is not inherited by child classes. They are typically used for per-class initialization and tear-down tasks which are called explicitly per class in an inheritance tree, usually for enforcing a particular order. For example object construction with the `BUILD` submethod happens from the least-derived to most-derived, so that the most-derived (child) classes can depend on the parent already being initialized.
Submethods are of type `Submethod`, and are declared with the `submethod` declarator:
```raku
class Area {
has $.size;
submethod BUILD(:$x, :$y, :$z) {
$!size = $x * $y * $z;
}
}
```
Since submethods are not inherited, an interesting use case is precisely methods that are going to be called from the *standard* submethods such as `BUILD` or `TWEAK`.
```raku
class Hero {
has @.inventory;
has Str $.name;
submethod BUILD( :$!name, :@!inventory ) {
@!inventory = self.clean-inventory( @!inventory );
}
submethod clean-inventory( @inventory ) {
@!inventory.unique.sort
}
}
my Hero $þor .= new( name => "Þor",
inventory => ( "Mjölnir", "Megingjörð", "Mjölnir" ) );
say $þor.inventory;
# OUTPUT: «[Megingjörð Mjölnir]»
```
Invoking these methods make sense only in the specific context of the submethod it is invoked from.
# [Methods](#class_Submethod "go to top of document")[§](#Methods "direct link")
## [method gist](#class_Submethod "go to top of document")[§](#method_gist "direct link")
```raku
multi method gist(Submethod:D:)
```
Returns the name of the submethod.
# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")
Type relations for `Submethod`
raku-type-graph
Submethod
Submethod
Routine
Routine
Submethod->Routine
Mu
Mu
Any
Any
Any->Mu
Callable
Callable
Code
Code
Code->Any
Code->Callable
Block
Block
Block->Code
Routine->Block
[Expand chart above](/assets/typegraphs/Submethod.svg)
|
## dist_zef-raku-community-modules-IO-Path-ChildSecure.md
[](https://github.com/raku-community-modules/IO-Path-ChildSecure/actions)
# NAME
IO::Path::ChildSecure - Secure version of IO::Path.child
# SYNOPSIS
```
use IO::Path::ChildSecure;
# good; you get IO::Path
"foo".IO.&child-secure: 'meow';
# still good if 'foo/meow/foo/bar/../' exists; Failure if it doesn't
"foo".IO.&child-secure: 'meow/foo/bar/../meow';
# bad; path isn't a child; you get Failure
"foo".IO.&child-secure: '../';
```
# DESCRIPTION
In the Raku Programming Language, [IO::Path.child](https://docs.raku.org/type/IO::Path#method_child) isn't secure, in a sense that it does no checks for whether the resultant path is actually a child of the original path.
This module provides a subroutine that can be used as an alternative that **will** check whether the resultant path is a child of the original path.
# EXPORTED SUBROUTINES
## child-secure
```
"foo".IO.&child-secure: 'meow'; # good; you get IO::Path
"foo".IO.&child-secure: 'meow/foo/bar/../meow'; # still good
"foo".IO.&child-secure: '../'; # bad; path isn't a child; you get Failure
child-secure "foo".IO, '../'; # can also use as a proper sub
```
Appends the given path chunk to the invocant and ensures the resultant path is, in fact, a child of the invocant, by accessing the filesystem and fully-resolving the path. The last chunk of the resultant path does not have to exist for the resolution to succeed.
Will [fail](https://docs.raku.org/routine/fail) with `X::IO::Resolve` if failed to fully resolve the resultant path or with `X::IO::NotAChild` if the resultant path is not a child of the invocant.
# SPECIAL NOTES
If you don't need to ensure secureness, use the much-faster core [`IO::Path.add` method](https://docs.raku.org/type/IO::Path#method_add)
# AUTHOR
Zoffix Znet
# COPYRIGHT AND LICENSE
Copyright 2017-2018 Zoffix Znet
Copyright 2019-2022 Raku Community
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-lizmat-Sequence-Generator.md
[](https://github.com/lizmat/Sequence-Generator/actions) [](https://github.com/lizmat/Sequence-Generator/actions) [](https://github.com/lizmat/Sequence-Generator/actions)
# NAME
Sequence::Generator - generate sequences of values from endpoints
# SYNOPSIS
```
use Sequence::Generator;
say 1,2,4 ... 64; # (1 2 4 8 16 32 64)
```
# DESCRIPTION
Raku provides a `...` operator (and its friends `...^`, `^...` and `^...^`) to generate values from a given set of endpoints. It is one of the oldest parts of the Raku Programming Language.
During its development, it obtained some quirks and behaviours that are now considered too magical, or considered to be a bug (which is sometimes actually frozen into spectests). On top of that, the development of the `...` operator preceded the occurrence of the `Iterator` role, so it actually does not use any of its benefits.
This module started out as an attempt to make the `...` operator (and friends) much faster by re-implementing it using `Iterator`s, rather than `gather` / `take`. However, it became clear that fixing behaviour considered too magical or buggy, could break existing Raku code. It was therefore decided to turn this work into this module, with the option of incorporating it into a later language version of Raku.
This module is between 4x and 20x faster than the Raku 6.d implementation.
# RULES
This describes the rules that are being applied to the begin and end points of these generated sequences.
## Meaning of carets
The carets `^` on the infix `...` operator are interpreted in a very strict way. On the left-hand side (`^...`) it means that the **initial** value will **not** be produced. On the right-hand side it means that the final value will **not** be produced.
## Two Real numbers
If the end point is larger than the begin point, then the functionality is the same as the `..` infix operator: add **1** for each step until the value is larger than the end point value.
```
say 1 ... 10; # (1 2 3 4 5 6 7 8 9 10)
say 1.5 ... 10; # (1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5)
```
If the end point is smaller than the begin point, then **-1** is added for each step until the value is smaller than the end point value.
```
say 10 ... 1; # (10 9 8 7 6 5 4 3 2 1)
say 10.5 ... 1; # (10.5 9.5 8.5 7.5 6.5 5.5 4.5 3.5 2.5 1.5)
```
If you need other increments or decrements, you must either use elucidation or provide a `Callable` that will do the production of values.
## Sequence elucidation
If the left hand side just consists of two or more `Real` numbers, then the last three (or two if there are only two) values will be used to try to determine the type of sequence in a process called "elucidation".
If the difference between the values is constant (or if there are only two values), then the sequence is called to be "arithmetic": the difference will then be assumed to the the step to be applied for each subsequent value produced.
```
say 1, 3 ... 10; # (1 3 5 7 9)
say 10, 8, 6 ... 1; # (10 8 6 4 2)
```
If the division between the values is constant, then the sequence is called to the "geometric": that value will then be used to multiply to produce the next value.
```
say 1 2 4 8 16 32 64; # (1 2 4 8 16 32 64)
say 64, 32, 16 ... 1; # (64 32 16 8 4 2 1)
```
If elucidation fails, a `Failure` will be returned with as much information possible to indicate the reason of the failure.
## Non-numeric endpoints
If the sequence has a non-numeric end point, then the sequence will continue to produce values until the generated value smartmatches with the end point.
```
say 5, { $_ ?? $_ - 1 !! "liftoff" } ... Str;
# (5 4 3 2 1 0 liftoff)
```
## Two strings
A sequence can only be generated for two strings if they have the same number of characters and all of the characters are either in the range of `a .. z`, `A .. Z` or `0 .. 9`. Furthermore, the range of each character of the begin point needs to be in the same range as the associated end point.
Each character will be incremented / decremented according to its counterpart to generate strings, with the rightmost character being incremented / decremented first.
```
say "ac" ... "ba"; # (ac ab aa bc bb ba)
```
Any other combination of strings will return a `Failure`. If you want some other string based sequence semantics, you should probably be using the magic increment / decrementfunctionality on strings, as offered by the `.succ` and `.pred` methods, and use a `Callable` to produce the values.
```
say ("zy", *.succ ... *).head(8); # (zy zz aaa aab aac aad aae aaf)
say ("¹²", *.pred ... *).head(20); # (¹² ¹¹ ¹⁰ ⁰⁹ ⁰⁸ ⁰⁷ ⁰⁶ ⁰⁵ ⁰⁴ ⁰³ ⁰² ⁰¹ ⁰⁰)
```
# BREAKING CHANGES
## Semantics of multiple endpoints
The original implementation of the `...` operator allowed a chain of endpoints to be specified:
```
say 1 ... 5 ... 1; # (1 2 3 4 5 4 3 2 1)
```
This is no longer supported because of the unclear semantics of an endpoint also serving as a starting point as soon as it is anything more than a numeric value. If you would like to have such a sequence, you will have to use parentheses to indicate meaning:
```
say 1 ... (5 ... 1); # (1 2 3 4 5 4 3 2 1)
```
## Strict meaning of ^
The original implementation of the `...^` operator treated omission of endpoints differently for numeric values:
```
say 1 ...^ 5.5; # (1 2 3 4 5)
```
This is generalized to **always** omit the last **generated** value, regardless of whether it actually compared exactly with the endpoint or not.
## Using .pred ends sequence if Failure
The original implementation of the `...` operator would die if `.pred` was being used to generate the next value, and that would return a Failure. This has been changed to ending the sequence.
## No longer silently ignores values on LHS after Callable
The original implementation of the `...` operator would ignore any values **after** a Callable on the LHS, e.g.:
```
1,2,3, * + 1, 7,8,9 ... 100;
```
This now returns a `Failure`.
## No longer silently ignores values with RHS list starting with \*
The original implementation of the `...` operator would ignore any values **after** a Whatever as the first element of a list on the RHS, e.g.:
```
1,2,3 ... *,42,666;
```
This now returns a `Failure`.
## LHS elucidation should always have identical types
This implementation requires all values for sequence elucidation (either 2 elements on the left, or the last three of three or more values) to be either all Real, or of the same type. If they are not, the elucidation will fail. This behaviour makes quite a few edge cases fail that the original implementation of the `...` operator would try to make sense of.
## Elucidation of LHS with identical values now fail
The original implementation of the `...` operator would produce unexplicable results if the 2 or the last 3 values of the LHS list would contain the same values. This will now return `Failure`.
## Multiplication factor must be positive
In elucidation, any multiplication factor found must be positive. Negative multiplication factors are too magic with regards to determine when the sequence must be ended. Please use a WhateverCode (e.g. `* * -1`) to indicate a negative multiplication factor.
# CLASS INTERFACE
The `Sequence::Generator` class can not be instantiated: it merely serves as an entry point to the sequence generating logic. It exposes **one** method:
## iterator
The `iterator` method takes two positional arguments: the seed for the sequence (aka the left-hand side of the `...` infix operator) and the end point (aka the right-hand side of the `...` infix operator). It returns an `Iterator` object.
```
my $iterator = Sequence::Generator.iterator((1,2,4), 64);
say Seq.new($iterator); # (1 2 4 8 16 32 64)
```
If you like to exclude the first or last generated value, you can pass the `:no-first` and/or the `:no-last` named arguments.
```
my $iterator = Sequence::Generator.iterator((1,2,4), 64, :no-first, :no-last);
say Seq.new($iterator); # (2 4 8 16 32)
```
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
Source can be located at: <https://github.com/lizmat/Sequence-Generator> . Comments and Pull Requests are welcome.
If you like this module, or what I'm doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!
# COPYRIGHT AND LICENSE
Copyright 2020, 2024 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-martimm-Gnome-N.md

# Gnome::N - Native Object and Raku - Gnome Interfacing

# Description
This package holds the native object descriptions and types as well as the interface description to connect to the Gnome libraries. This set of modules will never act on their own. They will be used by other packages such as `Gnome::Gtk4` and the like.
## Documentation
* [🔗 Website, entry point for all documents and blogs](https://martimm.github.io/)
* [🔗 License document](https://www.perlfoundation.org/artistic_license_2_0)
* [🔗 Release notes of all the packages in `:api<2>`](https://github.com/MARTIMM/gnome-source-skim-tool/blob/main/CHANGES.md)
* [🔗 Issues of all the packages in `:api<2>`](https://github.com/MARTIMM/gnome-source-skim-tool/issues)
# Installation
Do not install this package on its own. Instead install `Gnome::Gtk4` newest api.
`zef install Gnome::Gtk4:api<2>`
# 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 github project](https://github.com/MARTIMM/gnome-source-skim-tool/issues).
# Attribution
* The inventors of Raku, formerly known as Perl 6, 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 the documentation.
* Other helpful modules for their insight and use.
|
## atomic-inc-fetch.md
atomic-inc-fetch
Combined from primary sources listed below.
# [In atomicint](#___top "go to top of document")[§](#(atomicint)_sub_atomic-inc-fetch "direct link")
See primary documentation
[in context](/type/atomicint#sub_atomic-inc-fetch)
for **sub atomic-inc-fetch**.
```raku
multi atomic-inc-fetch(atomicint $ is rw)
```
Performs an atomic increment on a native integer. This will be performed using hardware-provided atomic operations. Since the operation is atomic, it is safe to use without acquiring a lock. Returns the value resulting from the increment. Overflow will wrap around silently.
|
## dist_zef-raku-community-modules-Geo-Coder-OpenCage.md
[](https://github.com/raku-community-modules/Geo-Coder-OpenCage/actions) [](https://github.com/raku-community-modules/Geo-Coder-OpenCage/actions)
# NAME
Geo::Coder::OpenCage - Geocode addresses with the OpenCage Geocoder API
# DESCRIPTION
This module provides an interface to the OpenCage geocoding service.
For full details on the API visit <https://opencagedata.com>.
# SYNOPSIS
```
my $geocoder = Geo::Coder::OpenCage.new: api_key => $my_api_key;
my $result = $geocoder.geocode("Donostia");
```
## class Geo::Coder::OpenCage
That's the object you'll use to interface with the OpenCage API. It has a required attribute C, which you can obtain from <http://geocoder.opencagedata.com>.
### method geocode
```
method geocode(
Str $place-name,
*%params
) returns Geo::Coder::OpenCage::Response
```
This method calls to the OpenCage API to obtain geocoding results for C<$place-name>. It returns an object with convenient access methods for all the data that the API returns. You can pass additional hints and requirements to the API through the slurpy C<%params> argument. The validity of these parameters will B be verified/enforced to ensure compatibility with potential API changes. Some of the supported arguments include: C – An IETF format language code (such as es for Spanish or pt-BR for Brazilian Portuguese); if this is omitted a code of en (English) will be assumed. C – Provides the geocoder with a hint to the country that the query resides in. This value will help the geocoder but will not restrict the possible results to the supplied country. The country code is a 3 character code as defined by the ISO 3166-1 Alpha 3 standard. As a full example: my $result = $geocoder.geocode( location => "Псковская улица, Санкт-Петербург, Россия", language => "ru", country => "rus", );
### method reverse-geocode
```
method reverse-geocode(
Numeric $lat,
Numeric $lng,
*%params
) returns Geo::Coder::OpenCage::Response
```
This method, as the name suggests, call the API to obtain information about places existing under the specified coordinates (C<$lat> for lattitude, C<$lng> for longtitude). Additional C<%params> can be passed according to the same rules as in the C<geocode()> method.
# AUTHOR
Tadeusz Sośnierz
# COPYRIGHT AND LICENSE
Copyright 2016 - 2017 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-lizmat-Slang-Lambda.md
[](https://github.com/lizmat/Slang-Lambda/actions) [](https://github.com/lizmat/Slang-Lambda/actions) [](https://github.com/lizmat/Slang-Lambda/actions)
# NAME
Slang::Lambda - allow λ as a pointy block starter
# SYNOPSIS
```
use Slang::Lambda;
say (1,2,3).map: λ $x { $x+1 } # (2 3 4)
```
# DESCRIPTION
Slang::Lambda modifies the Raku grammar to make it possible to use simple the `λ` (lambda) symbol as the starter symbol of a pointy block (which is usually `->`).
# INSPIRATION
A question on [/r/rakulang](https://www.reddit.com/r/rakulang/comments/1idts0a/how_can_i_use_%CE%BB_lambda_for_if_at_all/).
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
Source can be located at: <https://github.com/lizmat/Slang-Lambda> . 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 2025 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_cpan-TYIL-Config-Parser-toml.md
# Config::Parser::toml
A TOML parser for [Config](https://github.com/scriptkitties/p6-Config).
[](https://travis-ci.org/scriptkitties/p6-Config-Parser-toml)
## Installation
```
zef install Config::Parser::toml
```
## Known issues
The dependency `Config::TOML` fails to test on Rakudo 2017.03. As such,
you will need to use Rakudo 2017.04 or higher in order to use this module.
## License
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
|
## get.md
get
Combined from primary sources listed below.
# [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_sub_get "direct link")
See primary documentation
[in context](/type/independent-routines#sub_get)
for **sub get**.
```raku
multi get (IO::Handle:D $fh = $*ARGFILES) { $fh.get }
```
This routine is a wrapper for the [method of the same name in `IO::Handle`](/type/IO/Handle#routine_get). If no `Handle` is specified, defaults to [`$*ARGFILES`](/language/variables#$*ARGFILES).
# [In IO::Socket::INET](#___top "go to top of document")[§](#(IO::Socket::INET)_method_get "direct link")
See primary documentation
[in context](/type/IO/Socket/INET#method_get)
for **method get**.
```raku
method get()
```
Reads a line from the socket and returns it as of type [`Str`](/type/Str). Return [`Nil`](/type/Nil) on end-of-file (EOF).
# [In IO::Handle](#___top "go to top of document")[§](#(IO::Handle)_routine_get "direct link")
See primary documentation
[in context](/type/IO/Handle#routine_get)
for **routine get**.
```raku
method get(IO::Handle:D: --> Str:D)
multi get (IO::Handle $fh = $*ARGFILES --> Str:D)
```
Reads a single line of input from the handle, removing the trailing newline characters (as set by [`.nl-in`](/routine/nl-in)) if the handle's `.chomp` attribute is set to `True`. Returns [`Nil`](/type/Nil), if no more input is available. The subroutine form defaults to [`$*ARGFILES`](/language/variables#index-entry-%24%2AARGFILES) if no handle is given.
Attempting to call this method when the handle is [in binary mode](/type/IO/Handle#method_encoding) will result in [`X::IO::BinaryMode`](/type/X/IO/BinaryMode) exception being thrown.
```raku
$*IN.get.say; # Read one line from the standard input
my $fh = open 'filename';
$fh.get.say; # Read one line from a file
$fh.close;
say get; # Read one line from $*ARGFILES
```
# [In role IO::Socket](#___top "go to top of document")[§](#(role_IO::Socket)_routine_get "direct link")
See primary documentation
[in context](/type/IO/Socket#routine_get)
for **routine get**.
```raku
method get(IO::Socket:D: --> Str:D)
```
Reads a single line of input from the socket, removing the trailing newline characters (as set by [`.nl-in`](/routine/nl-in)). Returns [`Nil`](/type/Nil), if no more input is available.
Fails if the socket is not connected.
# [In IO::CatHandle](#___top "go to top of document")[§](#(IO::CatHandle)_method_get "direct link")
See primary documentation
[in context](/type/IO/CatHandle#method_get)
for **method get**.
```raku
method get(IO::CatHandle:D: --> Bool:D)
```
Returns a single line of input from the handle, with the new line string defined by the value(s) of [`$.nl-in` attribute](/type/IO/CatHandle#method_nl-in), which will be removed from the line if [`$.chomp` attribute](/type/IO/CatHandle#method_chomp) is set to `True`. Returns [`Nil`](/type/Nil) when there is no more input. It is an error to call this method when the handle is [in binary mode](/type/IO/CatHandle#method_encoding), resulting in [`X::IO::BinaryMode`](/type/X/IO/BinaryMode) exception being thrown.
```raku
(my $f1 = 'foo'.IO).spurt: "a\nb\nc";
(my $f2 = 'bar'.IO).spurt: "d\ne";
my $cat = IO::CatHandle.new: $f1, $f2;
.say while $_ = $cat.get; # OUTPUT: «abcde»
```
|
## special.md
class IO::Special
Path to special I/O device
```raku
class IO::Special does IO { }
```
Used as a [`$.path`](/type/IO/Handle#method_path) attribute in filehandles for special standard input `$*IN` and output `$*OUT` and `$*ERR`. Provides a bridged interface of [`IO::Handle`](/type/IO/Handle), mostly file tests and stringification.
# [Methods](#class_IO::Special "go to top of document")[§](#Methods "direct link")
## [method new](#class_IO::Special "go to top of document")[§](#method_new "direct link")
```raku
method new(:$!what!)
```
Takes a single required attribute [what](/routine/what). It is unlikely that you will ever need to construct one of these objects yourself.
## [method what](#class_IO::Special "go to top of document")[§](#method_what "direct link")
```raku
say $*IN.path.what; # OUTPUT: «<STDIN>»
say $*OUT.path.what; # OUTPUT: «<STDOUT>»
say $*ERR.path.what; # OUTPUT: «<STDERR>»
```
Returns one of the strings `'<STDIN>'`, `'<STDOUT>'`, or `'<STDERR>'`, specifying the type of the special IO device.
## [method WHICH](#class_IO::Special "go to top of document")[§](#method_WHICH "direct link")
```raku
method WHICH(IO::Special:D: --> Str)
```
This returns a string that identifies the object. The string is composed by the type of the instance (`IO::Special`) and the `what` attribute:
```raku
$*IN.path.what; # OUTPUT: «<STDIN>»
$*IN.path.WHICH; # OUTPUT: «IO::Special<STDIN>»
```
## [method Str](#class_IO::Special "go to top of document")[§](#method_Str "direct link")
```raku
method Str(IO::Special:D:)
```
This returns `'<STDIN>'`, `'<STDOUT>'`, or `'<STDERR>'` as appropriate.
## [method IO](#class_IO::Special "go to top of document")[§](#method_IO "direct link")
```raku
method IO(IO::Special:D: --> IO::Special)
```
Returns the invocant.
```raku
say $*IN.path.IO.what; # OUTPUT: «<STDIN>»
say $*IN.path.what; # OUTPUT: «<STDIN>»
```
## [method e](#class_IO::Special "go to top of document")[§](#method_e "direct link")
```raku
method e(IO::Special:D: --> True)
```
The 'exists' file test operator, always returns `True`.
## [method d](#class_IO::Special "go to top of document")[§](#method_d "direct link")
```raku
method d(IO::Special:D: --> False)
```
The 'directory' file test operator, always returns `False`.
## [method f](#class_IO::Special "go to top of document")[§](#method_f "direct link")
```raku
method f(IO::Special:D: --> False)
```
The 'file' file test operator, always returns `False`.
## [method s](#class_IO::Special "go to top of document")[§](#method_s "direct link")
```raku
method s(IO::Special:D: --> 0)
```
The 'size' file test operator, always returns `0`.
## [method l](#class_IO::Special "go to top of document")[§](#method_l "direct link")
```raku
method l(IO::Special:D: --> False)
```
The 'symbolic links' file test operator, always returns `False`.
## [method r](#class_IO::Special "go to top of document")[§](#method_r "direct link")
```raku
method r(IO::Special:D: --> Bool)
```
The 'read access' file test operator, returns `True` if and only if this instance represents the standard input handle(`<STDIN>`).
## [method w](#class_IO::Special "go to top of document")[§](#method_w "direct link")
```raku
method w(IO::Special:D: --> Bool)
```
The 'write access' file test operator, returns `True` only if this instance represents either the standard output (`<STOUT>`) or the standard error (`<STDERR>`) handle.
## [method x](#class_IO::Special "go to top of document")[§](#method_x "direct link")
```raku
method x(IO::Special:D: --> False)
```
The 'execute access' file test operator, always returns `False`.
## [method modified](#class_IO::Special "go to top of document")[§](#method_modified "direct link")
```raku
method modified(IO::Special:D: --> Instant)
```
The last modified time for the filehandle. It always returns an [`Instant`](/type/Instant) type object.
## [method accessed](#class_IO::Special "go to top of document")[§](#method_accessed "direct link")
```raku
method accessed(IO::Special:D: --> Instant)
```
The last accessed time for the filehandle. It always returns an [`Instant`](/type/Instant) type object.
## [method changed](#class_IO::Special "go to top of document")[§](#method_changed "direct link")
```raku
method changed(IO::Special:D: --> Instant)
```
The last changed time for the filehandle. It always returns an [`Instant`](/type/Instant) type object.
## [method mode](#class_IO::Special "go to top of document")[§](#method_mode "direct link")
```raku
method mode(IO::Special:D: --> Nil)
```
The mode for the filehandle, it always returns [`Nil`](/type/Nil)
|
## dist_github-grondilu-SSL.md
## Status
**THIS REPO IS NOT MAINTAINED ANYMORE.**
It is only left public for informative purpose.
The license still applies, though.
## Description
Perl6 interface to OpenSSL. So far only digests (SSL::Digest).
Digests supported include md2, md4, md5, sha0, sha1, sha2 variants (as sha224,
sha256, sha384, sha512), whirlpool, and ripemd160 (as rmd160). These are all
exported by default.
* Whirlpool support was added to openssl in 1.0.0, released in 2010. If your
openssl lacks this support, two tests will fail.
* Note that many of these digests are considered completely insecure (md2, md4,
md5, sha0).
|
## dist_github-oposs-JSONHound.md
# jsonHound [Build Status](https://travis-ci.org/oposs/jsonhound)
*a system for parsing JSON data structures and identifying anomalies*
While the name and the structure of this tool is very generic, it was built for a highly specific purpose:
Modern Cisco Switches allow export of their configuration in JSON format. The purpose of the jsonHound is
to identify misconfiguration of the switches. It does that by identifying *interesting* data structures,
like interfaces, and then choosing a set of checks to verify that they are properly configured. The
checks are chosen by looking at features of the interface or the configuration as a whole. For example,
if an interface is part of VLAN 643 we *know* that this is part of your IP Telefony VLAN and will thus
require a particular set of configuration options to be active.
The configuration of the jsonHound works in 3 stages:
* Stage 1 identifies the "interesting structures"
* Stage 2 applies a set of checks to these structures
jsonHound is implemented in in Raku programming language, and Raku is also used to write the jsonHound rule files.
## The jsonHound rule files
A jsonHound rule file is just a Raku module that does `use JsonHound` at the top, and contains
identification and validation setup. It's fine to use Raku language features to help factor out
re-use within the ruleset, and even to spread the rules over multiple modules, and `use` those.
## Identification
The identification state is set up by declaring Raku `subset` types, which pick out "subsets"
of the JSON document to check. The simplest way to identify part of the document that should be
considered is by using JSONPath:
```
subset ArpInspection
is json-path(q[$['Cisco-IOS-XE-native:native'].ip.arp.inspection.vlan]);
```
A `where` clause can be applied in order to further constrain what is matched, by looking
into the deserialized JSON that was matched by the JSONPath query.
```
subset GigabitEthernet
is json-path(q[$['Cisco-IOS-XE-native:native'].interface.GigabitEthernet[*]])
where {
[&&] .keys > 1, # Not just a name
.<name> ne '0/0',
(.<description> // '') ne '__SKIP__'
}
```
It's also possible to add further constraints (but *not* further JSONPath) using a
derived `subset` type:
```
sub get-vlan($ge) {
$ge<switchport><Cisco-IOS-XE-switch:access><vlan><vlan>
}
subset VLan31
of GigabitEthernet
where { get-vlan($_) == 31 };
```
## Validations
Validations are set up by calling the `validate` sub, passing it a name for the validation
(to be displayed upon failure) and one or more identified document sections. For example:
```
validate 'dot1x-not-set', -> VLan31 $ge {
$ge<Cisco-IOS-XE-dot1x:dot1x>:exists
}
```
The block should evaluate to a true value if the validation is successful. If it evalutes
to a false value, then validation fails and this will be reported. The JSON that was
matched in the identification phase is passed using the variable declared in the signature.
The `validate` block will be called once for each matching item. In the event that multiple
parameters are specified, then it will be called with the product of them (e.g. all of the
combinations). For example, given:
```
validate 'Missing global DHCP snooping', -> ArpInspection $inspection, GigabitEthernet $ge {
$ge<switchport><Cisco-IOS-XE-switch:access><vlan><vlan> ~~ any(ranges($inspection))
}
sub ranges($range-list) {
$range-list.split(',').map({ /(\d+)['-'(\d+)]?/; $1 ?? (+$0 .. +$1) !! +$0 })
}
```
If `ArpInspection` matches 1 time and `GigabitEthernet` matches 4 times, then it will be
called `1 * 4 = 4` times (the most typical use here is to pick out sections to match up
with some global value).
It is possible on report extra information by placing it into the validation rule's name.
This is done by:
1. Passing a block that takes named parameters and uses them to build up the name of the
rule, which will then be reported. It's neatest to do this using the `$:name` named
parameter placeholder syntax.
2. In case of validation failure, providing arguments for use in that reporting by passing
them to the `report` function.
For example:
```
validate {"Wrong reauthentication value (was $:value)"}, -> Authentication $auth {
my $value = $auth<timer><reauthenticate><value>;
if $value == 1800 {
True
}
else {
report :$value;
False
}
}
```
However, since `report` returns `False`, simple rules like this may instead be written
as simply:
```
validate {"Wrong reauthentication value (was $:value)"}, -> Authentication $auth {
my $value = $auth<timer><reauthenticate><value>;
$value == 1800 or report :$value
}
```
It is allowed to have multiple such parameters, which may be provided with a single
call to `report` or multiple calls to `report` over time. Do as is most comfortable
for the rule being implemented.
## Disjunctions of identifiers
It's possible to use the `Either[...]` construct to produce a disjunction of two
or more identifiers. For example, given:
```
subset MegabitEthernet
is json-path(q[$['Cisco-IOS-XE-native:native'].interface.MegabitEthernet[*]]);
subset GigabitEthernet
is json-path(q[$['Cisco-IOS-XE-native:native'].interface.GigabitEthernet[*]]);
```
One could write a validation rule that applies to either by doing:
```
validate 'Ethernet correctly configured', -> Either[MegabitEthernet, GigabitEthernet] $eth {
...
}
```
If the same `Either` expression would be repeated multiple times, it may be factored
out by declaring a `constant`:
```
my constant Ethernet = Either[MegabitEthernet, GigabitEthernet];
validate 'Ethernet correctly configured', -> Ethernet $eth {
...
}
```
A validation rule using multiple `Either` types will be invoked for all
permutations of matches, as is usually the case with multi-parameter rules.
## The command line interface
Once installed, run with:
```
jsonhound RuleFile.pm6 file1.json file2.json
```
It's possible to read the json data from `STDIN` directly using `-`
```
cat t/03-wrong-reauth.json | jsonhound examples/GigabitEthernetChecks.pm6 -
```
To run it within the repository (e.g. for development), do:
```
raku -Ilib bin/jsonhound RuleFile.pm file1.json file2.json
```
If more than one JSON input file is specified, then they will be parsed and validated
in parallel.
The default is to send a report to STDERR and to exit with 0 if all validation rule
passed, or 1 if there is a validation rule failure. However, this can be controlled
by passing the `--reporter=...` command line option. Valid options are:
* `cli` - the default human-friendly output to STDERR, with exit code 0 or 1 as
appropriate
* `nagios` - Nagios plugin output and exit code
* `syslog` - Report any validation rule failures to syslog as warnings; has no
impact on exit code
It is allowed to combine these by listing them comma-separated. However, note that
**the first reporter that provides an exit code will be the one that gets to decide
the exit code**. Thus this:
```
raku -Ilib bin/jsonhound --reporter=nagios,cli,syslog RuleFile.pm file1.json
```
Is probably correct (the `nagios` reporter controls the exit code), while:
```
raku -Ilib bin/jsonhound --reporter=cli,nagios,syslog RuleFile.pm file1.json
```
Is probably not what's wanted (however, in this case one would probably also get
away with it, in so far as `0` and `1` are quite sensible exit codes for a Nagios
plugin anyway).
## Debug messages
To produce a debug message in a validation rule, call `debug` and pass the
message (whatever is passed will be coerced to a string, if it is not one
already).
```
validate 'Missing global DHCP snooping', -> ArpInspection $inspection, GigabitEthernet $ge {
my $vlan = $ge<switchport><Cisco-IOS-XE-switch:access><vlan><vlan>;
debug "VLan is $vlan";
$vlan ~~ any(ranges($inspection))
}
```
By default, these are not reported. However, they can be reported by the
`cli` reporter by passing `--debug=failed` (only report debug output from
failed validation rules) or `--debug=all` (report all debug output).
## Running with Docker
You can also run the tool with docker directly from the git checkout
without installing raku locally.
```
docker-compose build
docker-compose run jsonhound examples/GigabitEthernetChecks.pm6 t/00-Switch1-OK.json
```
|
## dist_cpan-KOBOLDWIZ-Random-Hawking-Boltzmann.md
# p6-Random-Hawking-Boltzmann
A random number generator based on a Boltzmann function
filling in a Hawking Temperature
|
## dist_github-kjkuan-Proc-Feed.md
# Introduction
`Proc::Feed` provides a couple wrappers for `Proc::Async` that are
more convenient to use than the `run` and `shell` subs. Specifically, these
wrappers let you easily feed data to them and also from them to other
callables using the feed operator (`==>` or `<==`).
---
## `sub proc`
```
sub proc(
\command where Str:D|List:D,
$input? is raw,
Bool :$check = False,
:$bin where 'IN' | {! .so} = False, # i.e., only :bin<IN> or :!bin
:$stderr where Any|Callable:D|Str:D|IO::Handle:D,
:$shell where Bool:D|Str:D = False,
:$cwd = $*CWD,
Hash() :$env = %*ENV,
:$scheduler = $*SCHEDULER
--> Proc:D
) is export(:DEFAULT, :proc);
```
Use the `proc` sub to run a command when you don't need to capture its
output(`STDOUT`):
```
proc <<ls -la "READ ME.txt">>;
```
Here we passed a list, of which the first element is the executable, while the
rest are arguments passed to the executable.
> **NOTE**: `proc` blocks until the external command is completed and returns
> a `Proc` object, which when sunk throws an exception if the command exited
> with a non-zero status.
It's also possible to redirect `STDERR` if desired:
```
# Redirect STDERR to /dev/null
proc <ls whatever>, :stderr('/dev/null/');
# Same thing; but with a file we opened
my $black-hole = open('/dev/null', :w);
proc <ls whatever>, :stderr($black-hole);
$black-hole.close;
# Same effect that ignores error messages; this time, with a callable
# that just ignores the lines from STDERR.
proc <ls whatever>, :stderr({;});
```
Sometimes it can be convenient to run a command via a shell (defaults to
`/bin/bash`) if you need to use the features (e.g., globbing, I/O redirection,
... etc) it provides:
```
proc(['ls -la ~/.*'], :shell);
```
One can also simply pass a single string (recommended when using `:shell`)
instead of a list if not passing any arguments to the command from Perl 6:
```
proc('ls -la ~/.*', :shell);
```
However, if a list is passed, any remaining elements of the list are passed to
the shell as positional arguments, which will be available as `$1`, `$2`, ...,
and so on, in the shell command/script:
```
proc(['md5sum "$1" | cut -d" " -f1 > "$1.md5"', "$*PROGRAM"], :shell);
# ~/.* is not expanded here because it will be passed as an argument to bash.
proc(<<ls -la ~/.*>>, :shell); # runs: bash -c 'ls' - bash '-la' '~/.*'
# prints an empty line
proc(<<echo hello world>>, :shell)
# prints hello world
proc(<<'echo "$@"' hello world>>, :shell)
# prints the passed args; also shows you can specify the shell to use.
proc([q:to/EOF/, 'arg1', 'arg2'], :shell</usr/local/bin/bash>);
echo "Using SHELL - $0"
echo "First argument is: $1"
echo "Second argument is: $2"
EOF
```
---
## `sub capture`
```
sub capture(
\command where Str:D|List:D,
$input? is raw,
Bool :$check = True,
Bool :$chomp = True,
Bool :$merge,
:$bin where 'IN' | {! .so} = False, # i.e., only :bin<IN> or :!bin
:$stderr where Any|Callable:D|Str:D|IO::Handle:D,
:$shell where Bool:D|Str:D = False,
Str:D :$enc = 'UTF-8',
Bool :$translate-nl = True,
:$cwd = $*CWD,
Hash() :$env = %*ENV,
:$scheduler = $*SCHEDULER
--> Str:D
) is export(:DEFAULT, :capture);
```
To capture the `STDOUT` of a command use the `capture` sub, which returns a `Str:D`
instead of a `Proc`:
```
capture(<<md5sum "$*PROGRAM">>).split(' ')[0] ==> spurt("$*PROGRAM.md5");
# You can still run command via a shell
my $ls = capture('ls -la ~/.*', :shell);
my $err = capture(<<ls -la "doesn't exist">>, :merge);
#
# :merge redirects STDERR to STDOUT, so error messages are also
# captured in this case.
```
> **NOTE**: By default, similar to *command substitution* in Bash, any trailing
> newline of the captured output is removed. You can disable this behavior by
> specifying `:!chomp`.
> **NOTE**: If the command run by `capture` fails with a non-zero exit
> status, an exception will be thrown. You can disable this behavior with
> `:!check`, and in which case, an empty string will be returned if the command
> fails.
You can easily feed iterable inputs to a `capture`: (you can do the same with
`proc` or `pipe` too):
```
my $data = slurp("$*HOME/.bashrc");
my $chksum = ($data ==> capture('md5sum')).split(' ')[0];
```
By default, both input and output are assumed to be lines of strings, but you
can specify both to be binary with `:bin`, or only one of which to be binary
with either `:bin<IN>` or `:bin<OUT>`:
> **NOTE**: For `capture` and `proc`, only `:bin<IN>` (default) and `:!bin`
> are possible.
```
# Binary (Blob) in; string (Str) out.
my $blob = Blob.new(slurp("/bin/bash", :bin));
my $chksum = ($blob ==> capture('md5sum', :bin<IN>)).split(' ')[0];
# String (Str) in; binary (Blob) out.
# See below for more details on using 'run' and 'pipe'.
run {
my $f = "$*HOME/.bashrc";
my $gzipped = open("$f.gz", :w:bin);
LEAVE $gzipped.close;
slurp($f) \
==> pipe(<gzip -c>, :bin<OUT>)
==> each { spurt $gizpped, :bin }
}
```
> **NOTE**: It makes no sense to feed from a `proc` (i.e., `proc(…) ==> …`) because
> `proc(…)` returns a `Proc`, which is not iterable.
---
## `sub pipe`
```
sub pipe(
\command where Str:D|List:D,
$input? is raw,
Bool :$chomp is copy,
:$bin where {
$_ ~~ Bool:D|'IN'|'OUT' and (
# if :bin or :bin<OUT> then :chomp shouldn't be specified.
! ($_ eq 'OUT' || ($_ ~~ Bool && $_))
|| !$chomp
)
} = False,
:$stderr where Any|Callable:D|Str:D|IO::Handle:D,
Bool :$merge,
Str:D :$enc = 'UTF-8',
Bool :$translate-nl = True,
:$cwd = $*CWD,
Hash() :$env = %*ENV,
:$shell where Bool:D|Str:D = False,
:$scheduler = $*SCHEDULER
--> List:D
) is export(:DEFAULT, :pipe);
```
Finally, `pipe` returns an iterable of the output from the `STDOUT` of the
external process, so you can feed it to another callable. By default, text
output is assumed and the output is an iterable of lines. If binary output
is specified, then the output will be an iterable of `Blob`'s.
`pipe` should be used within a `Block` passed to the `run` sub, and it should
not be used at the end of a pipeline where nothing consumes its output. The
`run { ... }` returns the result returned by the run block. Examples:
```
# Example
my $chksum = run {
slurp("/bin/bash", :bin) \
==> pipe('gzip', :bin)
==> pipe('md5sum', :bin<IN>)
==> split(' ')
==> *.[0]()
}
# Example
run {
my $tarball = open("./somedir.tgz", :w);
LEAVE $tarball.close;
pipe «ssh my.remote-host.com "tar -czf - ./somedir"», :bin \
==> each { spurt $tarball, $_ }
}
# Example
my $total = run {
[+] (pipe «find /var/log -type f» ==> map(*.IO.s))
}
```
You must extract the data you want in the `run` block because `run` terminates
all external processes started by `pipe`'s at the end of the block by sending
them the `SIGCHLD` signal.
> **NOTE**: Subs like `map` and `grep` are lazy by default, so they are not
> suitable to be used at the end of a pipeline, unless you also consume the
> entire pipeline with somethig like the `[+]` operator in the above example.
> To consume a pipeline, you can also assign or feed the pipeline to an array,
> or listify the pipeline by using a `==> @` at the end of the pipeline, or
> feed it to a `proc(...)` that consumes STDIN.
By default, `run` throws a `BrokenPipeline` exception if any of the `pipe`
calls fails or exits with non-zero status, or if an exception is propagated
from the block. You can prevent an exception from being thrown with the
`:!check` option of `run`, in which case it returns a two-element list instead:
```
my ($result, $err) = run :!check, {
pipe(<<cat "$*HOME/.bashrc">>) \
==> pipe(<gunzip -c>) # <-- fails because input is not gzipped
==> join('')
}
if $err {
put 'Failed decompressing file...';
say $err; # $err.gist will show you the errors and stack traces.
} else {
put $result;
}
```
The first item is the return value of the block you passed to `run`; the second
item is a `BrokenPipeline` exception object if there's any.
> **NOTE**: Many code snippets in this doc are made to demo how the various
> functions from this module can be used. They are usually not the most
> efficient way to do the same thing if data have to flow from an external
> process to Perl 6, without any processing, just to flow back to another
> external process. For example, with `run { pipe(<<ls -la>>) ==> proc('nl') }`
> this module currently is not smart enough to connect the `STDOUT` of the first
> process to the `STDIN` of the second process, and therefore the data have to
> go through Perl 6.
## Other helpers
```
sub each(&code, $input? is raw) is export(:each);
multi sub map(Range \range, &code, $input? is raw) is export(:map);
```
`each`, often used for side effects, makes feeding into a block that
just wants to be called for each item of the iterable fed to it easier:
```
# using each:
(1,2,3,4) ==> each { .say }
# without each:
(1,2,3,4) ==> { .say for $_ }()
```
The `map` multi sub exported by this module takes a `Range` parameter so that
you can limit the code to only a certain range of input a block:
```
# using ranged map:
1,1, * + * ... Inf ==> map ^10, { $_ ** 2 }
# without ranged map:
1,1, * + * ... Inf ==> { gather for $_[^10] { take $_ ** 2 } }()
```
```
sub quote(Str $s --> Str) is export(:quote);
```
`quote` will single-quote a string so that it can be used in a shell script/command
literally:
```
my $file = q/someone's file is > than 1GB;
put capture("echo {quote $file}", :shell);
```
|
## dist_zef-raku-community-modules-Test-Notice.md
[](https://github.com/raku-community-modules/Test-Notice/actions/workflows/test.yaml)
# NAME
Test::Notice - Display noticable messages to users during tests
# SYNOPSIS
```
use Test::Notice;
notice 'Install Foo::Bar::Baz for extra awesome features!';
# Do not use colors
notice 'Now without colors!', :!try-color;
```
# DESCRIPTION
This module lets you display highly visible messages to users during
the run of your test, pausing long enough for them to read it.

# EXPORTED SUBROUTINES
## `notice( Str $message, Bool :$try-color = True )`
```
notice 'Install Foo::Bar::Baz for extra awesome features!';
```
Takes one mandatory argument: the string to display in the message.
Does not return anything meaningful. The message will be coloured if optional
`Terminal::ANSIColor` is installed. The output also pauses long enough
for an average reader to read the entire message (regardless of its length),
unless `NONINTERACTIVE_TESTING` environmental variable is set.
You can turn detection of the coloring module by setting `:try-color` to
`False`.
# LIMITATIONS
The current implementation always assumes the terminal width of 80 characters.
If you can figure out how to get the actual width when test is run with
`prove`, patches are more than welcome.
Currently, any amount of whitespace in the displayed message will be squashed
into a single space.
---
# REPOSITORY
Fork this module on GitHub:
<https://github.com/raku-community-modules/Test-Notice>
# BUGS
To report bugs or request features, please use
<https://github.com/raku-community-modules/Test-Notice/issues>
# AUTHOR
Zoffix Znet (<http://zoffix.com/>)
Currently maintained by the Raku Community Adoption devs.
# LICENSE
You can use and distribute this module under the terms of the
The Artistic License 2.0. See the `LICENSE` file included in this
distribution for complete details.
|
## dist_zef-tony-o-Event-Emitter.md
# Event::Emitter
An extendable JS like event emitter but way more fun. Can use supplies or channels and is basically just some syntax sugar on already implemented Perl6 features.
## Syntax
Out of the box functionality
### Single thread
`Event::Emitter` uses a `Supply` in the back end
```
use Event::Emitter;
my Event::Emitter $e .= new;
# hey, i work with regex
$e.on(/^^ "Some regex"/, -> $data {
qw<do something with your $data here>;
});
# your own callables to match events
my $event = { 'some flag' => 3, 'some other flag' => 5 };
$e.on({ $event<some flag> // Nil eq $*STATE }, -> $data {
qw<do something with your $data here>;
});
# plain ol strings, just like mom used to make
$e.on('some str', -> $data {
qw<do something with your $data here>;
});
# runs the some str listener
$e.emit('some str', @(1 .. 5));
# runs the regex because it matches the regex;
$e.emit('Some regex', { conn => IO::Socket::INET });
$e.emit({ 'some flag' => 5 }, { });
```
### Thread
`Event::Emitter` uses a `Channel` in the back end
```
use Event::Emitter;
my Event::Emitter $e .= new(:threaded);
```
## Rolling your own Event::Emitter
Want to make your own receiver/emitter? Here's a template
### Your new .pm6 file
```
use Event::Emitter::Role::Handler;
unit class My::Own::Emitter does Event::Emitter::Role::Handler;
method on($event, $data) {
qw<do your thing>;
}
method emit($event, $data?) {
qw<do your thing here>;
}
```
### Later in your .pl6
```
use Event::Emitter;
my $e = Event::Emitter.new(:class<My::Own::Emitter>);
```
# License
Free for all.
|
## dist_github-finanalyst-Algorithm-Tarjan.md
# p6-Algorithm-Tarjan
A perl6 implementation of Tarjan's algorithm for finding strongly connected components in a directed graph.
More information can be found at wikipedia.org/wiki/Tarjan's\_strongly\_connected\_components\_algorithm.
If there is a cycle, then it will be within a strongly connected component. This implies that the absence of strongly connected components (other than a node with itself) means there are no cycles. It is possible there may be no cycles, but a strongly connected component may still exist (if I have interpreted the theory correctly). I was interested in the absence of cycles.
```
use Algorithm::Tarjan;
my Algorithm::Tarjan $a .= new();
my %h;
# code to fill %h node->[successor nodes]
$a.init(%h);
say 'There are ' ~ $a.find-cycles() ~ ' cycle(s) in the input graph';
```
If there is a need for the sets of strongly connected components, they can be retrieved from $a.strongly-connected (an array of node names).
|
## dist_cpan-MARTIMM-XML-Actions.md
# XML Actions on every node
[](https://travis-ci.org/MARTIMM/XmlActions) [](https://ci.appveyor.com/project/MARTIMM/XmlActions/branch/master) [](http://www.perlfoundation.org/artistic_license_2_0)
## Synopsis
```
use Test;
use XML::Actions;
my Str $file = "a.xml";
$file.IO.spurt(Q:q:to/EOXML/);
<scxml xmlns="http://www.w3.org/2005/07/scxml"
version="1.0"
initial="hello">
<final id="hello">
<onentry>
<log expr="'hello world'" />
</onentry>
</final>
</scxml>
EOXML
class A is XML::Actions::Work {
method final:start ( Array $parent-path, :$id ) {
is $id, 'hello', "final called: id = $id";
is $parent-path[*-1].name, 'final', 'this node is final';
is $parent-path[*-2].name, 'scxml', 'parent node is scxml';
method log:start ( Array $parent-path, :$expr ) {
is $expr, "'hello world'", "log called: expr = $expr";
is-deeply @$parent-path.map(*.name), <scxml final onentry log>,
"<scxml final onentry log> found in parent array";
}
}
my XML::Actions $a .= new(:$file);
isa-ok $a, XML::Actions, 'type ok';
$a.process(:actions(A.new()));
```
Result would be like
```
ok 1 - type ok
ok 2 - final called: id = hello
ok 3 - this node is final
ok 4 - parent node is scxml
ok 5 - log called: expr = 'hello world'
ok 6 - <scxml final onentry log> found in parent array
```
## Documentation
Users who wish to process **XML::Elements** (from the XML package) must provide an instantiated class which inherits from **XML::Actions::Work**. In that class, methods named after the elements can be defined. Those methods must have `:start` or `:end` attached to have them called when `<someElement>` or `</someElement>` is encountered.
```
class A is XML::Actions::Work {
method someElement:start ( Array $parent-path, *%attrs --> ActionResult )
method someElement:end ( Array $parent-path, *%attrs )
method someOtherElement:start ( Array $parent-path, *%attrs --> ActionResult )
method someOtherElement:end ( Array $parent-path, *%attrs )
}
```
* The `$parent-path` is an array holding the **XML::Elements** of the parent elements with the root on the first position and the current element on the last.
* The `%*attrs` is a Hash of the found attributes on the element.
* The action may return a ActionResult value. When defined and set to `Truncate`, the caller will not recurse further into this element if there were any.
There are also text-, comment-, cdata- and pi-nodes. They can be processed as
```
method xml:text ( Array $parent-path, Str $text ) {...}
method xml:comment ( Array $parent-path, Str $comment ) {...}
method xml:cdata ( Array $parent-path, Str $cdata ) {...}
method xml:pi ( Array $parent-path, Str $pi-target, Str $pi-content ) {...}
```
## Large files
When you have to process a large file (e.g. an XML file holding POI data of Turkey from osm planet is about 6.2 Gb), one cannot use the **XML::Actions** module because the DOM tree is build in memory. Since version 0.4.0 the package is extended with module **XML::Actions::Stream** which eats the file in chunks of 128 Kb and chops it up into parseble parts. There will be no check on proper XML because it will slow down too much. You can use other tools for that. There are a few more methods possible to be defined by the user. The arguments to the methods are the same but the first argument, which is an array, has other type of elements.
### User definable methods
The user can define the methods in a class which inherits from **XML::Actions::Stream::Work**. The methods which the user may define are;
* `xml:prolog ( *%prolog-attributes )`. Found only at the start of a document. It might have attributes `version`, `encoding` and/or `standalone`.
* `xml:doctype ( *%doctype-attributes )`. Alsp found only at the start of document. It might have an internal or external DTD. The arguments can be: `Str :$dtd`, `Str :$url`, `Bool :$empty`, `Bool: $public`, `Bool: $system`, `Str :$fpi`. $empty is True when there is no DTD, SYSTEM or PUBLIC defined. $fpi (Formal Public Identifier) should be defined when $public is True. $url should be defined when $system is True but doesn't have to be defined if $public is True.
* `xml:pi ( Str $target, Str $program )`. For `<?target program?>`.
* `xml:comment ( Str $comment-text )`. For `<!-- comment text -->`.
* `xml:cdata ( Str $data )`. For `<[CDATA[ data ]]>`.
* `xml:text ( Str $text )`. All text as content of an element.
* `someElement:start ( Array $parent-path, Bool :$startend, *%element-attributes )`. The named argument `:startend` is a boolean; when `True`, there is no content in this element.
* `someElement:end ( Array $parent-path, *%element-attributes )`
The array is a list of pairs. The key of each pair is the element name and the value is a hash of its attributes. Entry `$parent-path[*-1]` is the currently called element, so its parent is at `*-2`. The root element is at 0 and is always available.
### Changes
One can find the changes document [in ./doc/CHANGES.md](https://github.com/MARTIMM/XmlActions/blob/master/doc/CHANGES.md)
## Installing
Use zef to install the package: `zef install XML::Actions`
## AUTHORS
Current maintainer **Marcel Timmerman** (MARTIMM on github)
## License
**Artistic-2.0**
|
## dist_zef-pmqs-Archive-SimpleZip.md
# Archive::SimpleZip
Raku (Perl6) module to write Zip archives.



## Synopsis
```
use Archive::SimpleZip;
# Create a zip file in the filesystem
my $z = SimpleZip.new: "mine.zip";
# Add a file to the zip archive
$z.add: "/some/file.txt";
# Add multiple files in one step
# the 'add' method will consume anything that is an Iterable
$z.add: @list_of_files;
# change the compression method to STORE
$z.add: 'somefile', :method(Zip-CM-Store);
# add knows what to do with IO::Glob
use IO::Glob;
$z.add: glob("*.c");
# add a file, but call it something different in the zip file
$z.add: "/some/file.txt", :name<better-name>;
# algorithmically rename the files by passing code to the name option
# in this instance chage file extension from '.tar.gz' to ;.tgz'
$z.add: @list_of_files, :name( *.subst(/'.tar.gz' $/, '.tgz') ), :method(Zip-CM-Store);
# when used in a method chain it will accept an Iterable and output a Seq of filenames
# add all files matched by IO::Glob
glob("*.c").dir.$z ;
# or like this
glob("*.c").$z ;
# contrived example
glob("*.c").grep( ! *.d).$z.uc.sort.say;
# Create a zip entry from a string/blob
$z.create(:name<data1>, "payload data here");
$z.create(:name<data2>, Blob.new([2,4,6]));
# Drop a filehandle into the zip archive
my $handle = "/another/file".IO.open;
$z.create("data3", $handle);
# use Associative interface to call 'create' behind the secenes
$z<data4> = "more payload";
# can also use Associative interface to add a file from the filesystem
# just make sure it is of type IO
$z<data5> = "/real/file.txt".IO;
# or a filehandle
$z<data5> = $handle;
# create a directory
$z.mkdir: "dir1";
$z.close;
```
## Description
Simple write-only interface to allow creation of Zip files.
See the full documentation at the end of the file `lib/Archive/SimpleZip.rakumod`.
## 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 Archive::SimpleZip
```
## Support
Suggestions/patches are welcome at [Archive-SimpleZip](https://github.com/pmqs/Archive-SimpleZip)
## License
Please see the LICENSE file in the distribution
(C) Paul Marquess 2016-2023
|
## dist_zef-andinus-lacerta.md
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
LACERTA
Lacerta parses WhatsApp exported logs
Andinus
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Table of Contents
─────────────────
Installation
Documentation
News
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Website
Source
GitHub (mirror)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Installation
════════════
Lacerta is released to `fez', you can get it from there or install it
from source. In any case, `zef' is required to install the
distribution.
You can run Lacerta without `zef'. Just run `raku -Ilib bin/lacerta'
from within the source directory.
Release
───────
1. Run `zef install lacerta'.
Lacerta should be installed, try running `lacerta --version' to
confirm.
From Source
───────────
You can either download the release archive generated by cgit/GitHub
or clone the project if you have `git' installed.
Without `git'
╌╌╌╌╌╌╌╌╌╌╌╌╌
1. Download the release:
•
•
2. Extract the file.
3. Run `zef install .' in source directory.
With `git'
╌╌╌╌╌╌╌╌╌╌
All commits will be signed by my [PGP Key].
┌────
│ # Clone the project.
│ git clone https://git.tilde.institute/andinus/lacerta
│ cd lacerta
│
│ # Install lacerta.
│ zef install .
└────
[PGP Key]
Documentation
═════════════
Implementation
──────────────
It reads the log line by line and tries to match it with `WhatsApp'
grammar.
Options
───────
input
╌╌╌╌╌
Exported WhatsApp log.
profile-name
╌╌╌╌╌╌╌╌╌╌╌╌
Your WhatsApp profile name. This is required to get stats for /Left/
and /Deleted/ column.
Caveats
───────
/Words/ count can be less than the actual count. If the message
contains new lines then they have them in the log too. We read the log
line by line, so it'll miss parts of messages with newline in them.
News
════
v0.1.0 - 2021-07-29
───────────────────
Initial Implementation.
```
|
## pop.md
pop
Combined from primary sources listed below.
# [In role Buf](#___top "go to top of document")[§](#(role_Buf)_method_pop "direct link")
See primary documentation
[in context](/type/Buf#method_pop)
for **method pop**.
```raku
method pop()
```
Returns and removes the last element of the buffer.
```raku
my $bú = Buf.new( 1, 1, 2, 3, 5 );
say $bú.pop(); # OUTPUT: «5»
say $bú.raku; # OUTPUT: «Buf.new(1,1,2,3)»
```
# [In Array](#___top "go to top of document")[§](#(Array)_method_pop "direct link")
See primary documentation
[in context](/type/Array#method_pop)
for **method pop**.
```raku
method pop(Array:D:) is nodal
```
Removes and returns the last item from the array. Fails if the array is empty.
Like many `Array` methods, method `pop` may be called via the corresponding [subroutine](/type/independent-routines#sub_pop). For example:
```raku
my @foo = <a b>; # a b
@foo.pop; # b
pop @foo; # a
pop @foo;
CATCH { default { put .^name, ': ', .Str } };
# OUTPUT: «X::Cannot::Empty: Cannot pop from an empty Array»
```
# [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_sub_pop "direct link")
See primary documentation
[in context](/type/independent-routines#sub_pop)
for **sub pop**.
```raku
multi pop(@a) is raw
```
Calls method `pop` on the [`Positional`](/type/Positional) argument. That method is supposed to remove and return the last element, or return a [`Failure`](/type/Failure) wrapping an [`X::Cannot::Empty`](/type/X/Cannot/Empty) if the collection is empty.
See the documentation of the [`Array` method](/routine/pop#(Array)_method_pop) for an example.
|
## atan.md
atan
Combined from primary sources listed below.
# [In Cool](#___top "go to top of document")[§](#(Cool)_routine_atan "direct link")
See primary documentation
[in context](/type/Cool#routine_atan)
for **routine atan**.
```raku
sub atan(Numeric(Cool))
method atan()
```
Coerces the invocant (or in sub form, the argument) to [`Numeric`](/type/Numeric), and returns its [arc-tangent](https://en.wikipedia.org/wiki/Inverse_trigonometric_functions) in radians.
```raku
say atan(3); # OUTPUT: «1.24904577239825»
say 3.atan; # OUTPUT: «1.24904577239825»
```
|
## dist_github-azawawi-Net-Curl.md
# Net::Curl
Net::Curl provides a Perl 6 interface to libcurl.
The plan is support the libcurl Easy interface first
and run all the libcurl website examples
and then support an object-oriented interface.
libcurl is a free and easy-to-use client-side URL transfer library.
It supports DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS,
LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet
and TFTP. libcurl supports SSL certificates, HTTP POST, HTTP PUT,
FTP uploading, HTTP form based upload, proxies, cookies,
user+password authentication (Basic, Digest, NTLM, Negotiate, Kerberos),
file transfer resume, http proxy tunneling and more!
## Build Status
| Operating System | Build Status | CI Provider |
| --- | --- | --- |
| Linux / Mac OS X | [Build Status](https://travis-ci.org/azawawi/perl6-net-curl) | Travis CI |
| Windows 7 64-bit | [Build status](https://ci.appveyor.com/project/azawawi/perl6-net-curl/branch/master) | AppVeyor |
## Installation
* Since Net::Curl uses libcurl, libcurl.so must be found in /usr/lib.
To install libcurl on Debian for example, please use the following command:
```
$ sudo apt-get install libcurl3-dev
```
* On Mac OS X, Please use the following command:
```
$ brew install curl
```
* Using zef (a module management tool bundled with Rakudo Star):
```
$ zef install Net::Curl
```
## Testing
To run tests:
```
$ prove -e "perl6 -Ilib"
```
## Author
Ahmad M. Zawawi, azawawi on #perl6, <https://github.com/azawawi/>
## License
MIT License
|
## dist_cpan-TITSUKI-Algorithm-NaiveBayes.md
[](https://travis-ci.org/titsuki/raku-Algorithm-NaiveBayes)
# NAME
Algorithm::NaiveBayes - A Raku Naive Bayes classifier implementation
# SYNOPSIS
## EXAMPLE1
```
use Algorithm::NaiveBayes;
my $nb = Algorithm::NaiveBayes.new(solver => Algorithm::NaiveBayes::Multinomial);
$nb.add-document("Chinese Beijing Chinese", "China");
$nb.add-document("Chinese Chinese Shanghai", "China");
$nb.add-document("Chinese Macao", "China");
$nb.add-document("Tokyo Japan Chinese", "Japan");
my $model = $nb.train;
my @result = $model.predict("Chinese Chinese Chinese Tokyo Japan");
@result.say; # [China => -8.10769031284391 Japan => -8.90668134500126]
```
## EXAMPLE2
```
use Algorithm::NaiveBayes;
my $nb = Algorithm::NaiveBayes.new(solver => Algorithm::NaiveBayes::Bernoulli);
$nb.add-document("Chinese Beijing Chinese", "China");
$nb.add-document("Chinese Chinese Shanghai", "China");
$nb.add-document("Chinese Macao", "China");
$nb.add-document("Tokyo Japan Chinese", "Japan");
my $model = $nb.train;
my @result = $model.predict("Chinese Chinese Chinese Tokyo Japan");
@result.say; # [Japan => -3.81908500976888 China => -5.26217831993216]
```
# DESCRIPTION
Algorithm::NaiveBayes is a Raku Naive Bayes classifier implementation.
## CONSTRUCTOR
```
my $nb = Algorithm::NaiveBayes.new(); # default solver is Multinomial
my $nb = Algorithm::NaiveBayes.new(%options);
```
### OPTIONS
* `solver => Algorithm::NaiveBayes::Multinomial|Algorithm::NaiveBayes::Bernoulli`
## METHODS
### add-document
```
multi method add-document(%attributes, Str $label)
multi method add-document(Str @words, Str $label)
multi method add-document(Str $text, Str $label)
```
Adds a document used for training. `%attributes` is the key-value pair, where key is the word and value is the frequency of occurrence of the word in the document. `@words` is the bag-of-words. The bag-of-words is represented as a multiset of words occurrence in the document. `$text` is the plain text of the document. It will be splitted by whitespaces and processed as the bag-of-words internally.
### train
```
method train(--> Algorithm::NaiveBayes::Model)
```
Starts training and returns an Algorithm::NaiveBayes::Model instance.
# AUTHOR
titsuki [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2016 titsuki
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
This algorithm is from Manning, Christopher D., Prabhakar Raghavan, and Hinrich Schutze. Introduction to information retrieval. Vol. 1. No. 1. Cambridge: Cambridge university press, 2008.
|
## stubcode.md
class X::StubCode
Runtime error due to execution of stub code
```raku
class X::StubCode is Exception { }
```
Thrown when a piece of stub code (created via `!!!` or `...`) is executed.
# [Methods](#class_X::StubCode "go to top of document")[§](#Methods "direct link")
## [method message](#class_X::StubCode "go to top of document")[§](#method_message "direct link")
Returns the custom message provided to `!!!`, or a reasonable default if none was provided.
|
## dist_cpan-KAIEPI-Net-Telnet.md
[](https://travis-ci.org/Kaiepi/p6-Net-Telnet)
# NAME
Net::Telnet - TELNET library for clients and servers
# SYNOPSIS
```
use Net::Telnet::Client;
use Net::Telnet::Constants;
use Net::Telnet::Server;
my Net::Telnet::Client $client .= new:
:host<telehack.com>,
:preferred[NAWS],
:supported[SGA, ECHO];
$client.text.tap({ .print });
await $client.connect;
await $client.send-text: 'cowsay ayy lmao';
$client.close;
my Net::Telnet::Server $server .= new:
:host<localhost>,
:preferred[SGA, ECHO],
:supported[NAWS];
react {
whenever $server.listen -> $connection {
$connection.text.tap(-> $text {
say "{$connection.host}:{$connection.port} sent '$text'";
$connection.close;
}, done => {
# Connection was closed; clean up if necessary.
});
LAST {
# Server was closed; clean up if necessary.
}
QUIT {
# Handle exceptions.
}
}
whenever signal(SIGINT) {
$server.close;
}
}
```
# DESCRIPTION
`Net::Telnet` is a library for creating TELNET clients and servers.
Before you get started, read the documentation in the `docs` directory and read the example code in the `examples` directory.
If you are using `Net::Telnet::Client` and don't know what options the server will attempt to negotiate with, run `bin/p6telnet-grep-options` using the server's host and port to grep the list of options it attempts to negotiate with when you first connect to it.
The following options are currently supported:
* TRANSMIT\_BINARY
* SGA
* ECHO
* NAWS
# AUTHOR
Ben Davies (Kaiepi)
# COPYRIGHT AND LICENSE
Copyright 2018 Ben Davies
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_cpan-KOBOLDWIZ-Game-Stats.md
This software is a minimal statistics package which includes probabiltiy
calculation based on populations which sometimes are a Distribution themselves.
It is to be used in games and was built for speed not general OOP.
Features are populations and distributions of probabilities wherefor an
estimate and variance can be calculated. A Covariance class provides with
2 populations the covariance. The same works for a correlation.
There is also a Probability class which uses a population of probabilities
and calculates conditional probabilities and thus a multi-variate Bayes
method. You can access the nth probability in this case and work on
towards Bayesian Inference.
Examples:
my $pp = 0.1; ### start probability
my $pop = Mathx::Stat::DistributionPopulation.new; ### list of probabilties
my @plist;
my @indices;
### We fill the distributionpopulation with probabilities
loop (my $i = $pp, my $j = 0; $i <= 1.0; $i+=0.1, $j++) {
$pop.add($i);
push(@plist, $i);
push(@indices, $j);
}
$pop.Expectance; ### yields 0.55
$pop.Variance; ## yields the variance of the probabilties in the population
$pop.GeneratedNumber ### yields a marginal distribution number based on population
my $cov = Mathx::Stat::Covariance.new;
my $corr = Mathx::Stat::Correlation.new;
### calculation of covariance and correlation
$cov.Covariance($pop,$pop);
$corr.Correlation($pop,$pop);
### make a multi-variate probability instance (again based on a population list)
my $p = Mathx::Stat::Probability.new(xpop => @plist);
### calculate Bayes on several indexed probabilities a conditional
### probability list and the index of the precondition probability
$p.Bayes(@indices, @plist, 1);
$p.Bayes(@indices, @plist, 0);
### caculate conditional probabilities (1-dimensional) of 2 indexed
### probabilities in the population ofthe variable $p
$p.CalculatedCondP(3,0);
$p.CalculatedCondP(7,4);
|
## int.md
Int
Combined from primary sources listed below.
# [In List](#___top "go to top of document")[§](#(List)_method_Int "direct link")
See primary documentation
[in context](/type/List#method_Int)
for **method Int**.
```raku
method Int(List:D: --> Int:D)
```
Returns the number of elements in the list (same as `.elems`).
```raku
say (1,2,3,4,5).Int; # OUTPUT: «5»
```
# [In Num](#___top "go to top of document")[§](#(Num)_method_Int "direct link")
See primary documentation
[in context](/type/Num#method_Int)
for **method Int**.
```raku
method Int(Num:D:)
```
Converts the number to an [`Int`](/type/Int). [Fails](/routine/fail) with `X::Numeric::CannotConvert` if the invocant [is a `NaN`](/routine/isNaN) or `Inf`/`-Inf`. No [rounding](/routine/round) is performed.
# [In enum Bool](#___top "go to top of document")[§](#(enum_Bool)_routine_Int "direct link")
See primary documentation
[in context](/type/Bool#routine_Int)
for **routine Int**.
```raku
multi method Int(Bool:D --> Int:D)
```
Returns the value part of the `enum` pair.
```raku
say False.Int; # OUTPUT: «0»
say True.Int; # OUTPUT: «1»
```
# [In IntStr](#___top "go to top of document")[§](#(IntStr)_method_Int "direct link")
See primary documentation
[in context](/type/IntStr#method_Int)
for **method Int**.
```raku
method Int
```
Returns the integer value of the `IntStr`.
# [In Match](#___top "go to top of document")[§](#(Match)_method_Int "direct link")
See primary documentation
[in context](/type/Match#method_Int)
for **method Int**.
```raku
method Int(Match:D: --> Int:D)
```
Tries to convert stringified result of the matched text into Int.
```raku
say ('12345' ~~ /234/).Int; # OUTPUT: «234»
say ('12345' ~~ /234/).Int.^name; # OUTPUT: «Int»
# the next line produces a warning about using Nil (result of a no match) in numeric context
say ('one-two' ~~ /234/).Int; # OUTPUT: «0» # because Nil.Int returns 0
```
# [In Str](#___top "go to top of document")[§](#(Str)_method_Int "direct link")
See primary documentation
[in context](/type/Str#method_Int)
for **method Int**.
```raku
method Int(Str:D: --> Int:D)
```
Coerces the string to [`Int`](/type/Int), using the same rules as [`Str.Numeric`](/type/Str#method_Numeric).
# [In role Enumeration](#___top "go to top of document")[§](#(role_Enumeration)_method_Int "direct link")
See primary documentation
[in context](/type/Enumeration#method_Int)
for **method Int**.
```raku
multi method Int(::?CLASS:D:)
```
Takes a value of an enum and returns it after coercion to [`Int`](/type/Int):
```raku
enum Numbers ( cool => '42', almost-pi => '3.14', sqrt-n-one => 'i' );
say cool.Int; # OUTPUT: «42»
say almost-pi.Int; # OUTPUT: «3»
try say sqrt-n-one.Int;
say $!.message if $!; # OUTPUT: «Cannot convert 0+1i to Int: imaginary part not zero»
```
Note that if the value cannot be coerced to [`Int`](/type/Int), an exception will be thrown.
# [In StrDistance](#___top "go to top of document")[§](#(StrDistance)_method_Int "direct link")
See primary documentation
[in context](/type/StrDistance#method_Int)
for **method Int**.
```raku
multi method Int(StrDistance:D:)
```
Returns the distance between the string before and after the transformation.
# [In Map](#___top "go to top of document")[§](#(Map)_method_Int "direct link")
See primary documentation
[in context](/type/Map#method_Int)
for **method Int**.
```raku
method Int(Map:D: --> Int:D)
```
Returns the number of pairs stored in the `Map` (same as `.elems`).
```raku
my $m = Map.new('a' => 2, 'b' => 17);
say $m.Int; # OUTPUT: «2»
```
# [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_Int "direct link")
See primary documentation
[in context](/type/IO/Path#method_Int)
for **method Int**.
```raku
method Int(IO::Path:D: --> Int:D)
```
Coerces [`.basename`](/routine/basename) to [`Int`](/type/Int). [Fails](/routine/fail) with [`X::Str::Numeric`](/type/X/Str/Numeric) if base name is not numerical.
# [In role Real](#___top "go to top of document")[§](#(role_Real)_method_Int "direct link")
See primary documentation
[in context](/type/Real#method_Int)
for **method Int**.
```raku
method Int(Real:D:)
```
Calls the [`Bridge` method](/routine/Bridge) on the invocant and then the [`Int` method](/routine/Int) on its return value.
# [In Date](#___top "go to top of document")[§](#(Date)_method_Int "direct link")
See primary documentation
[in context](/type/Date#method_Int)
for **method Int**.
```raku
multi method Int(Date:D: --> Int:D)
```
Converts the invocant to [`Int`](/type/Int). The same value can be obtained with the `daycount` method.
Available as of release 2023.02 of the Rakudo compiler.
# [In Cool](#___top "go to top of document")[§](#(Cool)_method_Int "direct link")
See primary documentation
[in context](/type/Cool#method_Int)
for **method Int**.
```raku
multi method Int()
```
Coerces the invocant to a [`Numeric`](/type/Numeric) and calls its [`.Int`](/routine/Int) method. [Fails](/routine/fail) if the coercion to a [`Numeric`](/type/Numeric) cannot be done.
```raku
say 1+0i.Int; # OUTPUT: «1»
say <2e1>.Int; # OUTPUT: «20»
say 1.3.Int; # OUTPUT: «1»
say (-4/3).Int; # OUTPUT: «-1»
say "foo".Int.^name; # OUTPUT: «Failure»
```
# [In role Rational](#___top "go to top of document")[§](#(role_Rational)_method_Int "direct link")
See primary documentation
[in context](/type/Rational#method_Int)
for **method Int**.
```raku
method Int(Rational:D: --> Int:D)
```
Coerces the invocant to [`Int`](/type/Int) by truncating non-whole portion of the represented number, if any. If the [denominator](/routine/denominator) is zero, will [fail](/routine/fail) with [`X::Numeric::DivideByZero`](/type/X/Numeric/DivideByZero).
|
## blob.md
role Blob
Immutable buffer for binary data ('Binary Large OBject')
```raku
role Blob[::T = uint8] does Positional[T] does Stringy { }
```
The `Blob` role is an immutable interface to binary types, and offers a list-like interface to lists of integers, typically unsigned integers.
However, it's a parameterized type, and you can instantiate with several integer types:
```raku
my $b = Blob[int32].new(3, -3, 0xff32, -44);
say $b; # OUTPUT: «Blob[int32]:0x<03 -3 FF32 -2C>»
```
By default, `Blob` uses 8-bit unsigned integers, that is, it is equivalent to Blob[uint8]. Some other types of `Blob`s which are used often get their own class name.
| | |
| --- | --- |
| blob8 | Blob[uint8] |
| blob16 | Blob[uint16] |
| blob32 | Blob[uint32] |
| blob64 | Blob[uint64] |
You can use these in pretty much the same way you would with `Blob`:
```raku
my $blob = blob8.new(3, 6, 254);
say $blob; # OUTPUT: «Blob[uint8]:0x<03 06 FE>»
```
# [Methods](#role_Blob "go to top of document")[§](#Methods "direct link")
## [method new](#role_Blob "go to top of document")[§](#method_new "direct link")
```raku
multi method new(Blob:)
multi method new(Blob: Blob:D $blob)
multi method new(Blob: int @values)
multi method new(Blob: @values)
multi method new(Blob: *@values)
```
Creates an empty `Blob`, or a new `Blob` from another `Blob`, or from a list of integers or values (which will have to be coerced into integers):
```raku
my $blob = Blob.new([1, 2, 3]);
say Blob.new(<1 2 3>); # OUTPUT: «Blob:0x<01 02 03>»
```
## [method Bool](#role_Blob "go to top of document")[§](#method_Bool "direct link")
```raku
multi method Bool(Blob:D:)
```
Returns `False` if and only if the buffer is empty.
```raku
my $blob = Blob.new();
say $blob.Bool; # OUTPUT: «False»
$blob = Blob.new([1, 2, 3]);
say $blob.Bool; # OUTPUT: «True»
```
## [method Capture](#role_Blob "go to top of document")[§](#method_Capture "direct link")
```raku
method Capture(Blob:D:)
```
Converts the object to a [`List`](/type/List) which is, in turn, coerced to a [`Capture`](/type/Capture).
## [method elems](#role_Blob "go to top of document")[§](#method_elems "direct link")
```raku
multi method elems(Blob:D:)
```
Returns the number of elements of the buffer.
```raku
my $blob = Blob.new([1, 2, 3]);
say $blob.elems; # OUTPUT: «3»
```
## [method bytes](#role_Blob "go to top of document")[§](#method_bytes "direct link")
```raku
method bytes(Blob:D: --> Int:D)
```
Returns the number of bytes used by the elements in the buffer.
```raku
say Blob.new([1, 2, 3]).bytes; # OUTPUT: «3»
say blob16.new([1, 2, 3]).bytes; # OUTPUT: «6»
say blob64.new([1, 2, 3]).bytes; # OUTPUT: «24»
```
## [method chars](#role_Blob "go to top of document")[§](#method_chars "direct link")
```raku
method chars(Blob:D:)
```
Throws [`X::Buf::AsStr`](/type/X/Buf/AsStr) with `chars` as payload.
## [method Str](#role_Blob "go to top of document")[§](#method_Str "direct link")
```raku
multi method Str(Blob:D:)
```
Throws [`X::Buf::AsStr`](/type/X/Buf/AsStr) with [`Str`](/type/Str) as payload. In order to convert to a [`Str`](/type/Str) you need to use [`.decode`](/routine/decode).
## [method Stringy](#role_Blob "go to top of document")[§](#method_Stringy "direct link")
```raku
multi method Stringy(Blob:D:)
```
Throws [`X::Buf::AsStr`](/type/X/Buf/AsStr) with [`Stringy`](/type/Stringy) as payload.
## [method decode](#role_Blob "go to top of document")[§](#method_decode "direct link")
```raku
multi method decode(Blob:D: $encoding = self.encoding // "utf-8")
```
```raku
multi method decode(Blob:D: $encoding, Str :$replacement!,
Bool:D :$strict = False)
```
```raku
multi method decode(Blob:D: $encoding, Bool:D :$strict = False)
```
Applies an encoding to turn the blob into a [`Str`](/type/Str); the encoding will be UTF-8 by default.
```raku
my Blob $blob = "string".encode('utf-8');
say $blob.decode('utf-8'); # OUTPUT: «string»
```
On malformed utf-8 `.decode` will throw X::AdHoc. To handle sloppy utf-8 use [`utf8-c8`](/language/unicode#UTF8-C8).
## [method list](#role_Blob "go to top of document")[§](#method_list "direct link")
```raku
multi method list(Blob:D:)
```
Returns a [`List`](/type/List) of integers:
```raku
say "zipi".encode("ascii").list; # OUTPUT: «(122 105 112 105)»
```
## [method gist](#role_Blob "go to top of document")[§](#method_gist "direct link")
```raku
method gist(Blob:D: --> Str:D)
```
Returns the string containing the "gist" of the `Blob`, **listing up to the first 100** elements, separated by space, appending an ellipsis if the `Blob` has more than 100 elements.
```raku
put Blob.new(1, 2, 3).gist; # OUTPUT: «Blob:0x<01 02 03>»
put Blob.new(1..2000).gist;
# OUTPUT:
# Blob:0x<01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15
# 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C
# 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 40 41 42 43
# 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A
# 5B 5C 5D 5E 5F 60 61 62 63 64 ...>
```
## [method subbuf](#role_Blob "go to top of document")[§](#method_subbuf "direct link")
```raku
multi method subbuf(Int $from, Int $len = self.elems --> Blob:D)
multi method subbuf(Range $range --> Blob:D)
multi method subbuf(Blob:D: &From)
multi method subbuf(Blob:D: Int:D $From, &End)
multi method subbuf(Blob:D: &From, &End)
multi method subbuf(Blob:D: \from, Whatever)
multi method subbuf(Blob:D: \from, Numeric \length)
```
Extracts a part of the invocant buffer, starting from the index with elements `$from`, and taking `$len` elements (or less if the buffer is shorter), and creates a new buffer as the result.
```raku
say Blob.new(1..10).subbuf(2, 4); # OUTPUT: «Blob:0x<03 04 05 06>»
say Blob.new(1..10).subbuf(*-2); # OUTPUT: «Blob:0x<09 0a>»
say Blob.new(1..10).subbuf(*-5,2); # OUTPUT: «Blob:0x<06 07>»
```
For convenience, also allows a [`Range`](/type/Range) to be specified to indicate which part of the invocant buffer you would like:
```raku
say Blob.new(1..10).subbuf(2..5); # OUTPUT: «Blob:0x<03 04 05 06>»
```
## [method allocate](#role_Blob "go to top of document")[§](#method_allocate "direct link")
```raku
multi method allocate(Blob:U: Int:D $elements)
multi method allocate(Blob:U: Int:D $elements, int $value)
multi method allocate(Blob:U: Int:D $elements, Int:D \value)
multi method allocate(Blob:U: Int:D $elements, Mu:D $got)
multi method allocate(Blob:U: Int:D $elements, int @values)
multi method allocate(Blob:U: Int:D $elements, Blob:D $blob)
multi method allocate(Blob:U: Int:D $elements, @values)
```
Returns a newly created `Blob` object with the given number of elements. Optionally takes a second argument that indicates the pattern with which to fill the `Blob`: this can be a single (possibly native) integer value, or any [`Iterable`](/type/Iterable) that generates integer values, including another `Blob`. The pattern will be repeated if not enough values are given to fill the entire `Blob`.
```raku
my Blob $b0 = Blob.allocate(10,0);
$b0.say; # OUTPUT: «Blob:0x<00 00 00 00 00 00 00 00 00 00>»
```
If the pattern is a general [`Mu`](/type/Mu) value, it will fail.
## [routine unpack](#role_Blob "go to top of document")[§](#routine_unpack "direct link")
This method is considered **experimental**, in order to use it you will need to do:
```raku
use experimental :pack;
multi method unpack(Blob:D: Str:D $template)
multi method unpack(Blob:D: @template)
multi unpack(Blob:D \blob, Str:D $template)
multi unpack(Blob:D \blob, @template)
```
Extracts features from the blob according to the template string, and returns them as a list.
The template string consists of zero or more units that begin with an ASCII letter, and are optionally followed by a quantifier. The quantifier can be `*` (which typically stands for "use up the rest of the Blob here"), or a positive integer (without a `+`).
Whitespace between template units is ignored.
Examples of valid templates include `"A4 C n*"` and `"A*"`.
The following letters are recognized:
| Letter | Meaning |
| --- | --- |
| A | Extract a string, where each element of the Blob maps to a codepoint |
| a | Same as 'A' |
| C | Extract an element from the blob as an integer |
| H | Extracts a hex string |
| L | Extracts four elements and returns them as a single unsigned integer |
| n | Extracts two elements and combines them in "network" (BigEndian) byte order into a single integer |
| N | Extracts four elements and combines them in "network" (BigEndian) byte order into a single integer |
| S | Extracts two elements and returns them as a single unsigned integer |
| v | Same as 'S' |
| V | Same as 'L' |
| x | Drop an element from the blob (that is, ignore it) |
| Z | Same as 'A' |
Example:
```raku
use experimental :pack;
say Blob.new(1..10).unpack("C*");
# OUTPUT: «(1 2 3 4 5 6 7 8 9 10)»
```
## [sub pack](#role_Blob "go to top of document")[§](#sub_pack "direct link")
This subroutine is considered **experimental**, in order to use it you will need to do:
```raku
use experimental :pack;
```
```raku
multi pack(Str $template, *@items)
multi pack(@template, *@items)
```
Packs the given items according to the template and returns a buffer containing the packed bytes.
The template string consists of zero or more units that begin with an ASCII letter, and are optionally followed by a quantifier. For details, see [unpack](/routine/unpack).
## [method reverse](#role_Blob "go to top of document")[§](#method_reverse "direct link")
```raku
method reverse(Blob:D: --> Blob:D)
```
Returns a Blob with all elements in reversed order.
```raku
say Blob.new([1, 2, 3]).reverse; # OUTPUT: «Blob:0x<03 02 01>»
say blob16.new([2]).reverse; # OUTPUT: «Blob[uint16]:0x<02>»
say blob32.new([16, 32]).reverse; # OUTPUT: «Blob[uint32]:0x<20 10>»
```
# [Methods on blob8 only (6.d, 2018.12 and later)](#role_Blob "go to top of document")[§](#Methods_on_blob8_only_(6.d,_2018.12_and_later) "direct link")
These methods are available on the blob8 (and `buf8`) types only. They allow low level access to reading bytes from the underlying data and interpreting them in different ways with regards to type (integer or floating point (num)), size (8, 16, 32, 64 or 128 bits), signed or unsigned (for integer values) and endianness (native, little and big endianness). The returned values are always expanded to a 64 bit native value where possible, and to a (big) integer value if that is not possible.
Endianness must be indicated by using values of the [`Endian`](/type/Endian) enum as the **second** parameter to these methods. If no endianness is specified, `NativeEndian` will be assumed. Other values are `LittleEndian` and `BigEndian`.
## [method read-uint8](#role_Blob "go to top of document")[§](#method_read-uint8 "direct link")
```raku
method read-uint8(blob8:D: uint $pos, $endian = NativeEndian --> uint)
```
Returns an unsigned native integer value for the byte at the given position. The `$endian` parameter has no meaning, but is available for consistency.
## [method read-int8](#role_Blob "go to top of document")[§](#method_read-int8 "direct link")
```raku
method read-int8(blob8:D: uint $pos, $endian = NativeEndian --> int)
```
Returns a native `int` value for the byte at the given position. The `$endian` parameter has no meaning, but is available for consistency.
## [method read-uint16](#role_Blob "go to top of document")[§](#method_read-uint16 "direct link")
```raku
method read-uint16(blob8:D: uint $pos, $endian = NativeEndian --> uint)
```
Returns a native `uint` value for the **two** bytes starting at the given position.
## [method read-int16](#role_Blob "go to top of document")[§](#method_read-int16 "direct link")
```raku
method read-int16(blob8:D: uint $pos, $endian = NativeEndian --> int)
```
Returns a native `int` value for the **two** bytes starting at the given position.
## [method read-uint32](#role_Blob "go to top of document")[§](#method_read-uint32 "direct link")
```raku
method read-uint32(blob8:D: uint $pos, $endian = NativeEndian --> uint)
```
Returns a native `uint` value for the **four** bytes starting at the given position.
## [method read-int32](#role_Blob "go to top of document")[§](#method_read-int32 "direct link")
```raku
method read-int32(blob8:D: uint $pos, $endian = NativeEndian --> int)
```
Returns a native `int` value for the **four** bytes starting at the given position.
## [method read-uint64](#role_Blob "go to top of document")[§](#method_read-uint64 "direct link")
```raku
method read-uint64(blob8:D: uint $pos, $endian = NativeEndian --> UInt:D)
```
Returns an unsigned integer value for the **eight** bytes starting at the given position.
## [method read-int64](#role_Blob "go to top of document")[§](#method_read-int64 "direct link")
```raku
method read-int64(blob8:D: uint $pos, $endian = NativeEndian --> int)
```
Returns a native `int` value for the **eight** bytes starting at the given position.
## [method read-uint128](#role_Blob "go to top of document")[§](#method_read-uint128 "direct link")
```raku
method read-uint128(blob8:D: uint $pos, $endian = NativeEndian --> UInt:D)
```
Returns an unsigned integer value for the **sixteen** bytes starting at the given position.
## [method read-int128](#role_Blob "go to top of document")[§](#method_read-int128 "direct link")
```raku
method read-int128(blob8:D: uint $pos, $endian = NativeEndian --> Int:D)
```
Returns an integer value for the **sixteen** bytes starting at the given position.
## [method read-num32](#role_Blob "go to top of document")[§](#method_read-num32 "direct link")
```raku
method read-num32(blob8:D: uint $pos, $endian = NativeEndian --> int)
```
Returns a native `num` value for the **four** bytes starting at the given position.
## [method read-num64](#role_Blob "go to top of document")[§](#method_read-num64 "direct link")
```raku
method read-num64(blob8:D: uint $pos, $endian = NativeEndian --> int)
```
Returns a native `num` value for the **eight** bytes starting at the given position.
# [Methods on blob8 only (6.d, 2019.03 and later)](#role_Blob "go to top of document")[§](#Methods_on_blob8_only_(6.d,_2019.03_and_later) "direct link")
## [method read-ubits](#role_Blob "go to top of document")[§](#method_read-ubits "direct link")
```raku
method read-ubits(blob8:D: uint $pos, uint $bits --> UInt:D)
```
Returns an unsigned integer value for the **bits** from the given **bit** offset and given number of bits. The endianness of the bits is assumed to be `BigEndian`.
## [method read-bits](#role_Blob "go to top of document")[§](#method_read-bits "direct link")
```raku
method read-bits(blob8:D: uint $pos, uint $bits --> Int:D)
```
Returns a signed integer value for the **bits** from the given **bit** offset and given number of bits. The endianness of the bits is assumed to be `BigEndian`.
## [method Buf](#role_Blob "go to top of document")[§](#method_Buf "direct link")
```raku
method Buf(Blob:D: --> Buf:D)
```
Available as of the 2021.06 Rakudo compiler release.
Coerces the invocant into a mutable [`Buf`](/type/Buf) object.
# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")
Type relations for `Blob`
raku-type-graph
Blob
Blob
Positional
Positional
Blob->Positional
Stringy
Stringy
Blob->Stringy
Buf
Buf
Buf->Blob
Mu
Mu
Any
Any
Any->Mu
utf8
utf8
utf8->Blob
utf8->Any
[Expand chart above](/assets/typegraphs/Blob.svg)
|
## dist_cpan-KAIEPI-Supply-Folds.md
[](https://travis-ci.com/Kaiepi/p6-Supply-Folds)
# NAME
Supply::Folds - Alternative fold methods for Supply
# SYNOPSIS
```
# Let's say we want to parse payloads from a TCP connection:
my Supply:D $connection = supply {
emit 'fo';
emit 'obarb';
emit 'azf';
emit 'ooba';
emit 'rbazfooba';
emit 'rbaz';
done;
};
# It's not guaranteed that these payloads will be complete messages, so our
# parser needs to keep context for where it is in the stream of payloads...
grammar Connection::Grammar {
token TOP { ( foo | bar | baz )+ }
}
class Connection::Actions {
method TOP($/) { make $0».Str }
}
# ...but this is a problem! We don't want locks slowing down communication with
# our peer, but we need to hold on to our parser as we parse each payload
# received! Psych, this isn't a problem with Supply.scan:
react whenever $connection.scan: &parse-payload, Connection::Grammar {
.made.say;
# OUTPUT:
# Nil
# [foo bar]
# [baz]
# [foo]
# [bar baz foo]
# [bar baz]
}
proto sub parse-payload(Connection::Grammar:_, Str:D --> Connection::Grammar:D) {*}
multi sub parse-payload(Connection::Grammar:U $acc, Str:D $payload --> Connection::Grammar:D) {
$acc.subparse: $payload, actions => Connection::Actions.new;
}
multi sub parse-payload(Connection::Grammar:D $acc, Str:D $payload --> Connection::Grammar:D) {
$acc.subparse: $acc.orig.substr(max $acc.pos, 0) ~ $payload, actions => $acc.actions
}
```
# DESCRIPTION
Supply::Folds is a library that provides the `Supply.fold` and `Supply.scan` methods, which can be used as an alternative to `Supply.reduce` and `Supply.produce`. The main advantage these methods have over those is that they may optionally take an initial value to begin a fold/scan with, rather than only working using values emitted by the supply.
# METHODS
## method fold
```
method fold(::?CLASS:D: &folder is raw --> ::?CLASS:D)
```
Alias for `Supply.reduce`.
```
method fold(::?CLASS:D: &folder is raw, $init is raw --> ::?CLASS:D)
```
Using `$init` as the initial result of the fold, for each value emitted from `self`, call `&folder` with the previous result and the value emitted, setting the result to the return value. This will be emitted once the supply is done.
## method scan
```
method scan(::?CLASS:D: &scanner is raw --> ::?CLASS:D)
```
Alias for `Supply.produce`.
```
method scan(::?CLASS:D: &scanner is raw, $init is raw, Bool:D :$keep = False --> ::?CLASS:D)
```
Using `$init` as the initial result of the scan, for each value emitted from `self`, call `&scanner` with the previous result and the value emitted, setting the result to the return value and emitting it. If `$keep` is set to `True`, `$init` will be emitted before the scan starts.
# AUTHOR
Ben Davies (Kaiepi)
# COPYRIGHT AND LICENSE
Copyright 2020 Ben Davies
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## complex.md
Complex
Combined from primary sources listed below.
# [In Cool](#___top "go to top of document")[§](#(Cool)_method_Complex "direct link")
See primary documentation
[in context](/type/Cool#method_Complex)
for **method Complex**.
```raku
multi method Complex()
```
Coerces the invocant to a [`Numeric`](/type/Numeric) and calls its [`.Complex`](/routine/Complex) method. [Fails](/routine/fail) if the coercion to a [`Numeric`](/type/Numeric) cannot be done.
```raku
say 1+1i.Complex; # OUTPUT: «1+1i»
say π.Complex; # OUTPUT: «3.141592653589793+0i»
say <1.3>.Complex; # OUTPUT: «1.3+0i»
say (-4/3).Complex; # OUTPUT: «-1.3333333333333333+0i»
say "foo".Complex.^name; # OUTPUT: «Failure»
```
# [In ComplexStr](#___top "go to top of document")[§](#(ComplexStr)_method_Complex "direct link")
See primary documentation
[in context](/type/ComplexStr#method_Complex)
for **method Complex**.
```raku
method Complex
```
Returns the [`Complex`](/type/Complex) value of the `ComplexStr`.
# [In role Real](#___top "go to top of document")[§](#(role_Real)_method_Complex "direct link")
See primary documentation
[in context](/type/Real#method_Complex)
for **method Complex**.
```raku
method Complex(Real:D: --> Complex:D)
```
Converts the number to a [`Complex`](/type/Complex) with the number converted to a [`Num`](/type/Num) as its real part and 0e0 as the imaginary part.
|
## dist_cpan-SPIGELL-Sparky-Plugin-Notify-Telegram.md
# SYNOPSIS
Sparky plugin to send notifications in a Telegram chat after completing your builds.
Based on a perl6 module - [TelegramBot](https://github.com/GildedHonour/TelegramBot)
# INSTALL
```
$ zef install Sparky::Plugin::Notify::Telegram
```
# USAGE
```
$ cat sparky.yaml
# send me a notifications on failed builds
plugins:
- Sparky::Plugin::Notify::Telegram:
run_scope: fail
parameters:
token: "111:222" # Your token
id: "1123213"
message: "Some fails while processing your build"
```
# Author
Spigell
|
## dist_zef-finanalyst-GTK-Simple.md

## GTK::Simple
GTK::Simple is a set of simple [GTK 3](http://www.gtk.org/) bindings using
NativeCall. Only some GTK widgets are currently implemented. However, these are
enough to create a reasonable interactive GUI for an idiomatic Raku program.
The GTK Widgets in this distribution include the following:
| Widget | Description |
| --- | --- |
| ActionBar | Group multiple buttons and arrange in 'left', 'middle', and 'right' |
| Button | A simple button with a label and a callback |
| Calendar | A calendar for selecting a date |
| CheckButton | A check button with a label |
| CheckMenuItem | A checkable menu item |
| ComboBoxText | A simple combo box |
| DrawingArea | A drawing area (requires the 'Cairo' module) |
| Entry | Allows for text to be provided by the user |
| FileChooserButton | A button that opens a file chooser dialog |
| Frame | A bin with a decorative frame and optional label |
| Grid | A table-like container for widgets for window design |
| Label | Adds a line of text |
| LevelBar | A bar that can used as a level indicator |
| LinkButton | Create buttons bound to a URL |
| ListBox | A vertical listbox where each row is selectable |
| MarkUpLabel | Adds text with GTK mark up (e.g. color and font manipulation) |
| Menu | A simple menu with a menu item label |
| MenuBar | A simple menu bar that contain one or more menus |
| MenuItem | A simple menu item that can have a sub menu |
| MenuToolButton | A menu tool button with a label or an icon |
| PlacesSidebar | Sidebar that displays frequently-used places in the file system |
| ProgressBar | Show progress via a filling bar |
| Scale | Allows for a number to be provided by the user |
| ScrolledWindow | Container for widgets needing scrolling, eg., multiline texts |
| RadioButton | A choice from multiple radio buttons |
| Spinner | Showing that something is happening |
| TextView | Adds multiple lines of text |
| ToggleButton | A toggle-able button |
| Toolbar | A tool bar that can contain one or more menu tool buttons |
| VBox, HBox | Widget containers which enable window layout design |
## Example
```
use GTK::Simple;
my $app = GTK::Simple::App.new( title => "Hello GTK!" );
$app.set-content(
GTK::Simple::VBox.new(
my $button = GTK::Simple::Button.new(label => "Hello World!"),
my $second = GTK::Simple::Button.new(label => "Goodbye!")
)
);
$app.border-width = 20;
$second.sensitive = False;
$button.clicked.tap({ .sensitive = False; $second.sensitive = True });
$second.clicked.tap({ $app.exit; });
$app.run;
```
### Using :subs option
Another approach is to specify `:subs` on import. This provides subroutine aliases for the constructors
of all of the available `GTK::Simple` widgets, converted from CamelCase to kebab-case.
`GTK::Simple::MenuToolButton` becomes `menu-tool-button`, `GTK::Simple::ProgressBar` becomes `progress-bar`, etc.
The above example can be equivalently written as:
```
use GTK::Simple :subs;
my $app = app(title => "Hello GTK!");
$app.set-content(
v-box(
my $button1 = button(label => "Hello World"),
my $button2 = button(label => "Goodbye!")
)
);
# ...
```
### Further examples
The first four examples were written as mini tutorials to show how the
system works:
* [Hello world](https://github.com/finanalyst/GTK-Simple/blob/master/examples/01-hello-world.raku)
* [Toggles](https://github.com/finanalyst/GTK-Simple/blob/master/examples/02-toggles.raku)
* [A simple grid](https://github.com/finanalyst/GTK-Simple/blob/master/examples/03-grid.raku)
* [Marked Scales](https://github.com/finanalyst/GTK-Simple/blob/master/examples/04-marked-scale.raku)
For more examples, please see the [examples/](https://github.com/finanalyst/GTK-Simple/blob/master/examples) folder.
## Limitations
The full functionality of [GTK 3](http://www.gtk.org/) is not available in
this module.
## Prerequisites
This module requires the GTK3 library to be installed. Please follow the
instructions below based on your platform:
### Debian Linux
```
sudo apt-get install libgtk-3-dev
```
### Mac OS X
```
brew update
brew install gtk+3
```
## Windows
The GTK team describes how to do this for Windows at
[Setting up GTK for Window](https://www.gtk.org/docs/installations/windows/)
## Installation and sanity tests
Use the zef package manager
```
$ zef install GTK::Simple
```
## Author
Jonathan Worthington, jnthn on #raku, <https://github.com/jnthn/>
## Contributors
The Raku team
## License
The Artistic License 2.0
|
## dist_zef-antononcube-DSL-Entity-AddressBook.md
# DSL::Entity::AddressBook
Raku grammar classes with example address book entities.
This is an example data package used in demos of
["DSL::FiniteStateMachines"](https://raku.land/zef:antononcube/DSL::FiniteStateMachines), [AAp5].
---
## Installation
From Zef ecosystem:
```
zef install DSL::Entity::AddressBook
```
From GitHub:
```
zef install https://github.com/antononcube/Raku-DSL-Entity-AddressBook.git
```
---
## Examples
Here are examples of recognizing different types of data acquisition related specifications:
```
use DSL::Entity::AddressBook;
use DSL::Entity::AddressBook::Grammar;
my &ab-parse = { DSL::Entity::AddressBook::Grammar.parse($_, args => (DSL::Entity::AddressBook::resource-access-object(),))};
say &ab-parse('Orlando Bloom');
```
```
# 「Orlando Bloom」
# addressbook-entity-spec-list => 「Orlando Bloom」
# addressbook-entity-spec => 「Orlando Bloom」
# entity-addressbook-person-name => 「Orlando Bloom」
# entity-name => 「Orlando Bloom」
# 0 => 「Orlando Bloom」
# entity-name-part => 「Orlando」
# entity-name-part => 「Bloom」
```
```
say &ab-parse('Lort of the Rings');
```
```
#ERROR: Possible misspelling of 'lord of the rings' as 'lort of the rings'.
# 「Lort of the Rings」
# addressbook-entity-spec-list => 「Lort of the Rings」
# addressbook-entity-spec => 「Lort of the Rings」
# entity-addressbook-company-name => 「Lort of the Rings」
# entity-name => 「Lort of the Rings」
# 0 => 「Lort of the Rings」
# entity-name-part => 「Lort」
# entity-name-part => 「of」
# entity-name-part => 「the」
# entity-name-part => 「Rings」
```
```
say &ab-parse('X-Men');
```
```
# 「X-Men」
# addressbook-entity-spec-list => 「X-Men」
# addressbook-entity-spec => 「X-Men」
# entity-addressbook-company-name => 「X-Men」
# entity-name => 「X-Men」
# 0 => 「X-Men」
# entity-name-part => 「X-Men」
```
---
## References
### Packages
[AAp1] Anton Antonov,
[DSL::Shared Raku package](https://github.com/antononcube/Raku-DSL-Shared),
(2020),
[GitHub/antononcube](https://github.com/antononcube).
[AAp2] Anton Antonov,
[DSL::Entity::Geographics Raku package](https://github.com/antononcube/Raku-DSL-Entity-Geographics),
(2021),
[GitHub/antononcube](https://github.com/antononcube).
[AAp3] Anton Antonov,
[DSL::Entity::Jobs Raku package](https://github.com/antononcube/Raku-DSL-Entity-Jobs),
(2021),
[GitHub/antononcube](https://github.com/antononcube).
[AAp4] Anton Antonov,
[DSL::Entity::Foods Raku package](https://github.com/antononcube/Raku-DSL-Entity-Foods),
(2021),
[GitHub/antononcube](https://github.com/antononcube).
[AAp5] Anton Antonov,
[DSL::FiniteStateMachines Raku package](https://github.com/antononcube/Raku-DSL-FiniteStateMachines),
(2022-2023),
[GitHub/antononcube](https://github.com/antononcube).
|
## dist_zef-antononcube-Data-Generators.md
# Raku Data::Generators
[](https://github.com/antononcube/Raku-Data-Generators/actions)
[](https://github.com/antononcube/Raku-Data-Generators/actions)
[](https://github.com/antononcube/Raku-Data-Generators/actions)
[](https://opensource.org/licenses/Artistic-2.0)
This Raku package has functions for generating random strings, words, pet names, vectors, arrays, and
(tabular) datasets.
### Motivation
The primary motivation for this package is to have simple, intuitively named functions
for generating random vectors (lists) and datasets of different objects.
Although, Raku has a fairly good support of random vector generation, it is assumed that commands
like the following are easier to use:
```
say random-string(6, chars => 4, ranges => [ <y n Y N>, "0".."9" ] ).raku;
```
---
## Random strings
The function `random-string` generates random strings.
Here is a random string:
```
use Data::Generators;
random-string
```
```
# rNa0FuC75aoA
```
Here we generate a vector of random strings with length 4 and characters that belong to specified ranges:
```
say random-string(6, chars => 4, ranges => [ <y n Y N>, "0".."9" ] ).raku;
```
```
# ("333N", "5N1y", "n0Y7", "7085", "6502", "y0Y7")
```
---
## Random words
The function `random-word` generates random words.
Here is a random word:
```
random-word
```
```
# psychopathy
```
Here we generate a list with 12 random words:
```
random-word(12)
```
```
# (drive-in joyless opportunistic kalian fertilize barium Malawian dingy reprobate wannabe penitential compaction)
```
Here we generate a table of random words of different types:
```
use Data::Reshapers;
my @dfWords = do for <Any Common Known Stop> -> $wt { $wt => random-word(6, type => $wt) };
say to-pretty-table(@dfWords);
```
```
# +--------+---------------+---------+-----------+----------------+-------------+--------------+
# | | 4 | 0 | 2 | 3 | 5 | 1 |
# +--------+---------------+---------+-----------+----------------+-------------+--------------+
# | Any | Anoectochilus | coltan | parhelion | heartburning | therewithal | columniation |
# | Common | explicit | beastly | cycle | overindulgence | extenuate | anaphora |
# | Known | spiritism | talaria | feeling | grapy | guru | epigon |
# | Stop | a | i've | 0 | shouldn't | X | few |
# +--------+---------------+---------+-----------+----------------+-------------+--------------+
```
**Remark:** `Whatever` can be used instead of `'Any'`.
**Remark:** The function `to-pretty-table` is from the package
[Data::Reshapers](https://modules.raku.org/dist/Data::Reshapers:cpan:ANTONOV).
All word data can be retrieved with the resources object:
```
my $ra = Data::Generators::ResourceAccess.instance();
$ra.get-word-data().elems;
```
```
# 84996
```
---
## Random pet names
The function `random-pet-name` generates random pet names.
The pet names are taken from publicly available data of pet license registrations in
the years 2015–2020 in Seattle, WA, USA. See [DG1].
Here is a random pet name:
```
random-pet-name
```
```
# Murphy
```
The following command generates a list of six random pet names:
```
srand(32);
random-pet-name(6).raku
```
```
# ("Zoe", "Bandit", "Cody", "Barb", "Barack", "Cooper")
```
The named argument `species` can be used to specify specie of the random pet names.
(According to the specie-name relationships in [DG1].)
Here we generate a table of random pet names of different species:
```
my @dfPetNames = do for <Any Cat Dog Goat Pig> -> $wt { $wt => random-pet-name(6, species => $wt) };
say to-pretty-table(@dfPetNames);
```
```
# +------+----------+------------------+----------+---------+----------+---------+
# | | 0 | 1 | 2 | 4 | 5 | 3 |
# +------+----------+------------------+----------+---------+----------+---------+
# | Any | Hamilton | Tyson Zeus Brown | Georgia | Ivy | Mochi | Ellla |
# | Cat | Ace | Felix | Dean | Georgia | Little B | Lulu |
# | Dog | Louis | Wiley | Moya | Cleo | Barkley | Buster |
# | Goat | Grayson | Junebug | Winnipeg | Lula | Abelard | Grace |
# | Pig | Atticus | Atticus | Millie | Atticus | Atticus | Atticus |
# +------+----------+------------------+----------+---------+----------+---------+
```
**Remark:** `Whatever` can be used instead of `'Any'`.
The named argument (adverb) `weighted` can be used to specify random pet name choice
based on known real-life number of occurrences:
```
srand(32);
say random-pet-name(6, :weighted).raku
```
```
# ("Claire", "Ilsa", "Tinkerbelle", "Remy", "Zoe", "Bandit")
```
The weights used correspond to the counts from [DG1].
**Remark:** The implementation of `random-pet-name` is based on the Mathematica implementation
[`RandomPetName`](https://resources.wolframcloud.com/FunctionRepository/resources/RandomPetName),
[AAf1].
All pet data can be retrieved with the resources object:
```
my $ra = Data::Generators::ResourceAccess.instance();
$ra.get-pet-data()>>.elems
```
```
# {cat => 7806, dog => 12941, goat => 40, pig => 3}
```
---
## Random pretentious job titles
The function `random-pretentious-job-title` generates random pretentious job titles.
Here is a random pretentious job title:
```
random-pretentious-job-title
```
```
# Direct Functionality Director
```
The following command generates a list of six random pretentious job titles:
```
random-pretentious-job-title(6).raku
```
```
# ("Central Data Agent", "National Team Executive", "Corporate Infrastructure Associate", "Global Accountability Agent", "National Metrics Agent", "Future Mobility Planner")
```
The named argument `number-of-words` can be used to control the number of words in the generated job titles.
The named argument `language` can be used to control in which language the generated job titles are in.
At this point, only Bulgarian and English are supported.
Here we generate pretentious job titles using different languages and number of words per title:
```
my $res = random-pretentious-job-title(12, number-of-words => Whatever, language => Whatever);
say to-pretty-table($res.rotor(3));
```
```
# +---------------------------+----------------------------------+----------------------------------+
# | 0 | 1 | 2 |
# +---------------------------+----------------------------------+----------------------------------+
# | Specialist | Администратор | Response Executive |
# | Optimization Designer | Супервайзор по Маркетинг | Interactive Applications Manager |
# | Future Response Associate | Brand Technician | Посредник на Качество |
# | Identity Administrator | Глобален Специалист на Отчетност | Integration Designer |
# +---------------------------+----------------------------------+----------------------------------+
```
**Remark:** `Whatever` can be used as values for the named arguments `number-of-words` and `language`.
**Remark:** The implementation uses the job title phrases in <https://www.bullshitjob.com> .
It is, more-or-less, based on the Mathematica implementation
[`RandomPretentiousJobTitle`](https://resources.wolframcloud.com/FunctionRepository/resources/RandomPretentiousJobTitle),
[AAf2].
---
## Random reals
This module provides the function `random-real` that can be used to generate lists of real numbers
using the uniform distribution.
Here is a random real:
```
say random-real();
```
```
# 0.6148375015300324
```
Here is a random real between 0 and 20:
```
say random-real(20);
```
```
# 13.957487542046149
```
Here are six random reals between -2 and 12:
```
say random-real([-2,12], 6);
```
```
# (-1.4191627349160865 0.7985910676295189 2.5735598216113056 8.655772458122875 -0.23141703578666983 3.2473529322039427)
```
Here is a 4-by-3 array of random reals between -3 and 3:
```
say random-real([-3,3], [4,3]);
```
```
# [[-0.7777530943688706 2.633038558227515 0.9960527665422672]
# [0.5438581449111846 0.8538444340370224 -1.2232218597405276]
# [0.24844626265222436 1.6176949918194392 -2.9106836929578517]
# [-1.1519301602208225 -2.168108140257122 1.575345624009456]]
```
**Remark:** The signature design follows Mathematica's function
[`RandomReal`](https://reference.wolfram.com/language/ref/RandomVariate.html).
---
## Random variates
This module provides the function `random-variate` that can be used to generate lists of real numbers
using distribution specifications.
Here are examples:
```
say random-variate(BernoulliDistribution.new(:p(0.3)), 1000).BagHash.Hash;
```
```
# {0 => 683, 1 => 317}
```
```
say random-variate(BinomialDistribution.new(:n(10), :p(0.2)), 10);
```
```
# (2 2 4 1 2 2 4 2 1 2)
```
```
say random-variate(NormalDistribution.new( µ => 10, σ => 20), 5);
```
```
# (-1.0372379191539256 15.88117685892444 2.3800289134125467 -16.077914554672056 21.434725308461598)
```
```
say random-variate(UniformDistribution.new(:min(2), :max(60)), 5);
```
```
# (33.12620384207506 54.54682825992015 44.703052532365824 18.662929703538268 16.99790622594807)
```
**Remark:** Only Normal distribution and Uniform distribution are implemented at this point.
**Remark:** The signature design follows Mathematica's function
[`RandomVariate`](https://reference.wolfram.com/language/ref/RandomVariate.html).
Here is an example of 2D array generation:
```
say random-variate(NormalDistribution.new, [3,4]);
```
```
# [[1.730441181600127 0.3420465932875971 -0.6275231817898077 0.7933012580974133]
# [0.7546145800662779 -0.1414053357058038 0.06128413616858158 -0.48630656184266835]
# [-0.8339285130645827 -3.0312240538258073 0.18147829328498447 1.1150963106600722]]
```
---
## Random tabular datasets
The function `random-tabular-dataset` can be used generate tabular *datasets*.
**Remark:** In this module a *dataset* is (usually) an array of arrays of pairs.
The dataset data structure resembles closely Mathematica's data structure
[`Dataset`]https://reference.wolfram.com/language/ref/Dataset.html), [WRI2].
**Remark:** The programming languages R and S have a data structure called "data frame" that
corresponds to dataset. (In the Python world the package `pandas` provides data frames.)
Data frames, though, are column-centric, not row-centric as datasets.
For example, data frames do not allow a column to have elements of heterogeneous types.
Here are basic calls:
```
random-tabular-dataset();
random-tabular-dataset(Whatever):row-names;
random-tabular-dataset(Whatever, Whatever);
random-tabular-dataset(12, 4);
random-tabular-dataset(Whatever, 4);
random-tabular-dataset(Whatever, <Col1 Col2 Col3>):!row-names;
```
Here is example of a generated tabular dataset that column names that are cat pet names:
```
my @dfRand = random-tabular-dataset(5, 3, column-names-generator => { random-pet-name($_, species => 'Cat') });
say to-pretty-table(@dfRand);
```
```
# +-----------+-----------+---------------+
# | Tonks | Bailey | Skipper |
# +-----------+-----------+---------------+
# | -0.425523 | 14.708426 | extirpate |
# | 25.249457 | 4.334753 | humanize |
# | 23.518357 | 9.309680 | eccyesis |
# | 5.089616 | 20.839470 | prevailing |
# | 17.328699 | 11.818831 | irreligionist |
# +-----------+-----------+---------------+
```
The display function `to-pretty-table` is from
[`Data::Reshapers`](https://modules.raku.org/dist/Data::Reshapers:cpan:ANTONOV).
**Remark:** At this point only
[*wide format*](https://en.wikipedia.org/wiki/Wide_and_narrow_data)
datasets are generated. (The long format implementation is high in my TOOD list.)
**Remark:** The signature design and implementation are based on the Mathematica implementation
[`RandomTabularDataset`](https://resources.wolframcloud.com/FunctionRepository/resources/RandomTabularDataset),
[AAf3].
---
## TODO
1. TODO Random tabular datasets generation
* DONE Row spec
* DONE Column spec that takes columns count and column names
* DONE Column names generator
* DONE Wide form implementation only
* DONE Generators of column values
* DONE Column-generator hash
* DONE List of generators
* DONE Single generator
* DONE Turn "generators" that are lists into sampling pure functions
* TODO Long form implementation
* TODO Max number of values
* TODO Min number of values
* TODO Form (long or wide)
* DONE Row names (automatic)
2. DONE Random reals vectors generation
3. TODO Figuring out how to handle and indicate missing values
4. TODO Random reals vectors generation according to distribution specs
* DONE Uniform distribution
* DONE Normal distribution
* TODO Poisson distribution
* TODO Skew-normal distribution
* TODO Triangular distribution
5. DONE `RandomReal`-like implementation
* See `random-real`.
6. DONE Selection between `roll` and `pick` for:
* DONE `RandomWord`
* DONE `RandomPetName`
---
## References
### Articles
[AA1] Anton Antonov,
["Pets licensing data analysis"](https://mathematicaforprediction.wordpress.com/2020/01/20/pets-licensing-data-analysis/),
(2020),
[MathematicaForPrediction at WordPress](https://mathematicaforprediction.wordpress.com).
### Functions, packages
[AAf1] Anton Antonov,
[RandomPetName](https://resources.wolframcloud.com/FunctionRepository/resources/RandomPetName),
(2021),
[Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository).
[AAf2] Anton Antonov,
[RandomPretentiousJobTitle](https://resources.wolframcloud.com/FunctionRepository/resources/RandomPretentiousJobTitle),
(2021),
[Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository).
[AAf3] Anton Antonov,
[RandomTabularDataset](https://resources.wolframcloud.com/FunctionRepository/resources/RandomTabularDataset),
(2021),
[Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository).
[SHf1] Sander Huisman,
[RandomString](https://resources.wolframcloud.com/FunctionRepository/resources/RandomString),
(2021),
[Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository).
[WRI1] Wolfram Research (2010),
[RandomVariate](https://reference.wolfram.com/language/ref/RandomVariate.html),
Wolfram Language function.
[WRI2] Wolfram Research (2014),
[Dataset](https://reference.wolfram.com/language/ref/Dataset.html),
Wolfram Language function.
### Data repositories
[DG1] Data.Gov,
[Seattle Pet Licenses](https://catalog.data.gov/dataset/seattle-pet-licenses),
[catalog.data.gov](https://catalog.data.gov).
|
## dist_zef-Air4x-Chart-EasyGnuplot.md
# Chart::EasyGnuplot
A simple modules to make simple plots, without having to think about
Gnuplot internals.
# Example
Let's plot the fuction "sin(x)-x\*cos(x)"
```
use v6.d;
use Chart::EasyGnuplot;
my @x = 0.0 .. (2*π);
my @y = gather {
for @x -> $x{
take (sin($x)-$x*cos(x));
}
}
line-plot("sin(x)-x*cos(x)", @x, @y, "Example.png");
```

|
## note.md
note
Combined from primary sources listed below.
# [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_routine_note "direct link")
See primary documentation
[in context](/type/independent-routines#routine_note)
for **routine note**.
```raku
method note(Mu: -->Bool:D)
multi note( --> Bool:D)
multi note(Str:D $note --> Bool:D)
multi note(**@args --> Bool:D)
```
Like [`say`](/routine/say) (in the sense it will invoke the `.gist` method of the printed object), except it prints output to [`$*ERR`](/language/variables#index-entry-%24%2AERR) handle (`STDERR`). If no arguments are given to subroutine forms, will use string `"Noted"`.
```raku
note; # STDERR OUTPUT: «Noted»
note 'foo'; # STDERR OUTPUT: «foo»
note 1..*; # STDERR OUTPUT: «1..Inf»
```
This command will also autothread on [`Junction`](/type/Junction)s, and is guaranteed to call `gist` on the object if it's a subclass of [`Str`](/type/Str).
|
## dist_zef-antononcube-Graph.md
# Graph
[](https://github.com/antononcube/Raku-Graph/actions)
[](https://github.com/antononcube/Raku-Graph/actions)
[](https://github.com/antononcube/Raku-Graph/actions)
[](https://raku.land/zef:antononcube/Graph)
[](https://opensource.org/licenses/Artistic-2.0)
Raku package for (discrete mathematics) graph data structures and algorithms.
For a quick introduction see the video ["Graph demo in Raku (teaser)"](https://www.youtube.com/watch?v=0uJl9q7jIf8), [AAv1], (5 min.)
**Remark:** This package is *not* for drawing and rendering images.
It is for the abstract data structure [***graph***](https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)).
---
## Installation
From Zef ecosystem:
```
zef install Graph
```
From GitHub:
```
zef install https://github.com/antononcube/Raku-Graph.git
```
---
## Design and implementation details
### Motivation
* Needless to say, Graph theory is huge.
* But certain algorithms like path and cycle finding are relatively easy to implement
and are fundamental both mathematics-wise and computer-science-wise.
* Having fast shortest path finding algorithms in graphs should be quite a booster for geography related projects.
### Design
* The central entity is the `Graph` class.
* `Graph` is as generic as possible.
* Meaning it is for directed graphs.
* Undirected graphs are represented as directed graphs.
* I.e. with twice as many edges than necessary.
* The current graph representation is with hash-of-hashes, (`adjacency-list`), that keeps from-to-weight relationships.
* For example, `$g.adjacency-list<1><2>` gives the weight of the edge connecting vertex "1" to vertex "2".
* The vertexes are only strings.
* Not a "hard" design decision.
* More general vertexes can be imitated (in the future) with vertex tags.
* This is related to having (in Raku) sparse matrices with named rows and columns.
* Since I know Mathematica / Wolfram Language (WL) very well, many of the method names and signatures are
strongly influenced by the corresponding functions in WL.
* I do not follow them too strictly, though.
* One reason is that with Raku it is much easier to have and use named arguments than with WL.
### Implementation
* I was considering re-programming Perl5’s "Graph", [JHp1], into Raku, but it turned out it was easier to write the algorithms directly in Raku.
* (To me at least...)
* The classes creating special graphs, like, grid-graph, star-graph, etc., are sub-classes of `Graph`
with files in the sub-directory "Graph".
* See usage of such classes [here](./examples/Named-graphs.raku).
### Visualization
* Visualizing the graphs (the objects of the class `Graph`) is very important.
* Has to be done from the very beginning of the development.
* (Again, for me at least...)
* The class `Graph` has the methods `dot`, `graphml`, `mermaid`, and `wl` for representing the graphs for
GraphViz, GraphML, Mermaid-JS, and Wolfram Language (WL) respectively.
* Mermaid's graph nodes and edges arrangement algorithm can produce "unexpected" images for the standard, parameterized graphs.
* Like, "grid graph", "cycle graph", etc.
### Performance
* So far, I have tested the path finding algorithms on "Graph" on small graphs and moderate size graphs.
* The largest random graph I used had 1000 vertexes and 1000 edges.
* Mathematica (aka Wolfram Language) can be 500 ÷ 10,000 faster.
* I hope good heuristic functions for the "A\* search" method would make `find-shortest-path` fast enough,
for say country / continent route systems.
* With the larger, 1,000-vertex random graphs finding paths with the method "a-star" is ≈50 faster than with the method "dijkstra".
* See [here](./examples/Performance.raku).
* Setting up comprehensive performance profiling and correctness testing is somewhat involved.
* One main impediment is that in Raku one cannot expect and specify same random numbers between different sessions.
---
## Usage examples
Here we create a dataset of edges:
```
my @edges =
{ from => '1', to => '5', weight => 1 },
{ from => '1', to => '7', weight => 1 },
{ from => '2', to => '3', weight => 1 },
{ from => '2', to => '4', weight => 1 },
{ from => '2', to => '6', weight => 1 },
{ from => '2', to => '7', weight => 1 },
{ from => '2', to => '8', weight => 1 },
{ from => '2', to => '10', weight => 1 },
{ from => '2', to => '12', weight => 1 },
{ from => '3', to => '4', weight => 1 },
{ from => '3', to => '8', weight => 1 },
{ from => '4', to => '9', weight => 1 },
{ from => '5', to => '12', weight => 1 },
{ from => '6', to => '7', weight => 1 },
{ from => '9', to => '10', weight => 1 },
{ from => '11', to => '12', weight => 1 };
@edges.elems;
```
```
# 16
```
**Remark:** If there is no `weight` key in the edge records the weight of the edge is taken to be 1.
Here we create a graph object with the edges dataset:
```
use Graph;
my $graph = Graph.new;
$graph.add-edges(@edges);
```
```
# Graph(vertexes => 12, edges => 16, directed => False)
```
Here are basic properties of the graph:
```
say 'edge count : ', $graph.edge-count;
say 'vertex count : ', $graph.vertex-count;
say 'vertex list : ', $graph.vertex-list;
```
```
# edge count : 16
# vertex count : 12
# vertex list : (1 10 11 12 2 3 4 5 6 7 8 9)
```
Here we display the graph using [Mermaid-JS](https://mermaid.js.org), (see also, [AAp1]):
```
$graph.mermaid(d=>'TD')
```
```
graph TD
10 --- 2
10 --- 9
2 --- 3
3 --- 4
3 --- 8
2 --- 4
2 --- 7
12 --- 2
2 --- 8
2 --- 6
1 --- 5
1 --- 7
6 --- 7
12 --- 5
11 --- 12
4 --- 9
```
Here we find the shortest path between nodes "1" and "4":
```
say 'find-shortest-path : ', $graph.find-shortest-path('1', '4');
```
```
# find-shortest-path : [1 7 2 4]
```
Here we find all paths between "1" and "4", (and sort them by length and vertex names):
```
say 'find-path : ' , $graph.find-path('1', '4', count => Inf).sort({ $_.elems ~ ' ' ~ $_.join(' ') });
```
```
# find-path : ([1 7 2 4] [1 5 12 2 4] [1 7 2 3 4] [1 7 6 2 4] [1 5 12 2 3 4] [1 7 2 10 9 4] [1 7 2 8 3 4] [1 7 6 2 3 4] [1 5 12 2 10 9 4] [1 5 12 2 8 3 4] [1 7 6 2 10 9 4] [1 7 6 2 8 3 4])
```
Here we find a [Hamiltonian path](https://en.wikipedia.org/wiki/Hamiltonian_path) in the graph:
```
say 'find-hamiltonian-path : ' , $graph.find-hamiltonian-path();
```
```
# find-hamiltonian-path : [10 9 4 3 8 2 6 7 1 5 12 11]
```
Here we find a cycle:
```
say 'find-cycle : ' , $graph.find-cycle().sort({ $_.elems ~ ' ' ~ $_.join(' ') });
```
```
# find-cycle : ([2 3 4 2])
```
Here we find all cycles in the graph:
```
say 'find-cycle (all): ' , $graph.find-cycle(count => Inf).sort({ $_.elems ~ ' ' ~ $_.join(' ') });
```
```
# find-cycle (all): ([2 3 4 2] [2 3 8 2] [2 6 7 2] [10 2 4 9 10] [2 4 3 8 2] [1 5 12 2 7 1] [10 2 3 4 9 10] [1 5 12 2 6 7 1] [10 2 8 3 4 9 10])
```
---
## Graph plotting
### Graph formats
The class `Graph` has the following methods of graph visualization:
* `wl` for making [Wolfram Language graphs](https://reference.wolfram.com/language/ref/Graph.html)
* `dot` for visualizing via [Graphviz](https://graphviz.org) using the [DOT language](https://graphviz.org/doc/info/lang.html)
* `graphml` for [GraphML](http://graphml.graphdrawing.org) visualizations
* `mermaid` for [Mermaid-JS](https://mermaid.js.org) visualizations
### Visualizing via DOT format
In Jupyter notebooks with a Raku kernel graph visualization can be done with the method `dot` and its adverb ":svg".
First, [install Graphviz](https://graphviz.org/download/).
On macOS the installation can be done with:
```
brew install graphviz
```
Here a wheel graph is made and its DOT format is converted into SVG format (rendered automatically in Jupyter notebooks):
```
use Graph::Wheel;
Graph::Wheel.new(12).dot(:svg)
```
For more details see notebook ["DOT-visualizations.ipynb"](./docs/DOT-visualizations.ipynb).
### Visualizing via D3.js
In Jupyter notebooks with a Raku kernel graph visualization can be done with the function `js-d3-graph-plot`
of the package ["JavaScript::D3"](https://github.com/antononcube/Raku-JavaScript-D3).
The visualizations with "JavaScript::D3" are very capricious. Currently they:
* Do not work with [JupyterLab](https://jupyter.org), but only with the "classical" Jupyter notebook.
* Work nicely with the Jupyter notebook plugin(s) of Visual Studio Code, but often require re-loading of the notebooks.
The points above were the main reasons to develop the DOT format visualization.
Most of the documentation notebooks show the graphs using both "JavaScript::D3" and DOT-SVG.
---
## TODO
### Main, core features
* TODO Object methods
* DONE Str and gist methods
* DONE Deep copy
* DONE Creation from another graph.
* TODO Ingest vertexes and edges of another `Graph` object
* TODO Comparison: `eqv` and `ne`.
* DONE Disjoint graphs
* The graphs can be disjoint as long as the components have edges.
* Related, the class `Graph` does supports "lone vertices."
* They have empty adjacency values.
* TODO Vertexes
* DONE Vertex list
* DONE Vertex count
* DONE Vertex degree
* DONE in-degree, edges-at
* DONE out-degree, edges-from
* DONE Delete vertex(es)
* DONE Add vertex
* DONE Has vertex
* TODO Vertex tags support
* TODO Edges
* DONE Edge list
* DONE Edge dataset
* DONE Edge count
* DONE Add edge
* DONE Delete edge(s)
* DONE Has edge
* TODO Edge tags support
* TODO Matrix representation
* Sparse matrices are needed before "seriously" considering this.
* Sparse matrices should be easy to create using the (already implemented) edge dataset.
* DONE Adjacency matrix (dense)
* TODO Adjacency matrix (sparse)
* Incidence matrix (dense)
* Incidence matrix (sparse)
### Graph programming
* Depth first scan / traversal
* Scan a graph in a depth-first order.
* This is already implemented, it has to be properly refactored.
* See Depth-First Search (DFS) named (private) methods.
* Breadth first scan / traversal
* Scan a graph in a breadth-first order.
### Paths, cycles, flows
* DONE Shortest paths
* DONE Find shortest path
* DONE Find Hamiltonian paths
* For both the whole graph or for a given pair of vertexes.
* Algorithms:
* Backtracking, `method => 'backtracking'`)
* Application Warnsdorf's rule for backtracking, `:warnsdorf-rule`
* Angluin-Valiant (probabilistic), `method => 'random'`
* TODO Flows
* TODO Find maximum flow
* TODO Find minimum cost flow
* TODO Distances
* DONE Graph distance
* See shortest path.
* TODO Graph distance matrix
* Again, requires choosing a matrix Raku class or package.
* DONE Longest shortest paths
* DONE Vertex eccentricity
* DONE Graph radius
* DONE Graph diameter
* DONE Graph center
* DONE Graph periphery
* DONE Weakly connected component
* DONE Strongly connected component
* DONE [Tarjan's algorithm](https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm)
* TODO [Kosaraju's algorithm](https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm)
* DONE Topological sort
* Using Tarjan's algorithm
* TODO Cycles and tours
* DONE Find cycle
* Just one cycle
* All cycles
* TODO Find shortest tour
* TODO Find postman tour
* DONE Eulerian and semi-Eulerian graphs
* TODO General graphs
* TODO Find Eulerian cycle
* TODO Find Hamiltonian cycle
* TODO Find cycle matrix
* TODO Independent paths
* DONE Find paths
* TODO Find edge independent paths
* TODO Find edge vertex paths
### Matching, coloring
* DONE Check is a graph bipartite
* DONE [Hungarian algorithm for bipartite graphs](https://en.wikipedia.org/wiki/Hungarian_algorithm)
* At [tum.de](https://algorithms.discrete.ma.tum.de/graph-algorithms/matchings-hungarian-method/index_en.html)
* TODO Perfect match for bipartite graphs
* TODO Matching edges
### Operations
* TODO Unary graph operations
* DONE Reversed graph
* DONE Complement graph
* DONE Subgraph
* For given vertices and/or edges.
* DONE Neighborhood graph
* For given vertices and/or edges.
* DONE Make undirected
* Can be implemented as `Graph.new($g, :!directed)`.
* But maybe it is more efficient to directly manipulate `adjacency-list`.
* DONE Make directed
* It is not just a flag change of `$!directed`.
* Implement the methods: `Whatever`, "Acyclic", "Random".
* TODO Edge contraction
* TODO Vertex contraction
* TODO Line graph
* TODO Dual graph
* TODO Binary graph operations
* DONE Union of graphs
* DONE Intersection of graphs
* DONE Difference of graphs
* DONE Disjoint union of graphs
* TODO Product of graphs (AKA "box product")
* TODO Cartesian
* TODO Co-normal
* TODO Lexicographic
* TODO Normal
* TODO Rooted
* TODO Strong
* TODO Tensor
### Construction
* DONE Construction of parameterized graphs
* DONE [Complete graphs](https://en.wikipedia.org/wiki/Complete_graph)
* DONE [Cycle graphs](https://en.wikipedia.org/wiki/Cycle_graph)
* DONE [Hypercube graphs](https://en.wikipedia.org/wiki/Hypercube_graph)
* DONE [Grid graphs](https://en.wikipedia.org/wiki/Lattice_graph)
* DONE [Knight tour graphs](https://en.wikipedia.org/wiki/Knight%27s_graph)
* DONE [Star graphs](https://en.wikipedia.org/wiki/Star_graph)
* DONE Path graphs
* DONE [Wheel graphs](https://en.wikipedia.org/wiki/Wheel_graph)
* DONE Indexed graphs
* DONE [Hexagonal grid graphs](https://mathworld.wolfram.com/HexagonalGridGraph.html)
* DONE Construction of random graphs
* Since different kinds of vertex-edge distributions exists, separate distributions objects are used.
* See `Graph::Distribution`.
* DONE [Barabasi-Albert distribution](https://en.wikipedia.org/wiki/Barab%C3%A1si%E2%80%93Albert_model)
* DONE Bernoulli distribution
* DONE [de Solla Price's model distribution](https://en.wikipedia.org/wiki/Price%27s_model)
* DONE "Simple" random `(m, n)` graphs with m-vertexes and n-edges between them
* This was the first version of `Graph::Random`.
* Refactored to be done via the uniform graph distribution.
* DONE [Watts–Strogatz model distribution](https://en.wikipedia.org/wiki/Watts%E2%80%93Strogatz_model)
* DONE Uniform distribution
* TODO Construction of *individual* graphs
* TODO Bull graph
* TODO Butterfly graph
* TODO Chavatal graph
* TODO Diamond graph
* TODO Durer graph
* TODO Franklin graph
* DONE [Petersen graph](https://en.wikipedia.org/wiki/Petersen_graph)
* TODO Wagner graph
* Creation from
* Adjacency matrix (dense)
* Adjacency matrix (sparse)
* Incidence matrix (dense)
* Incidence matrix (sparse)
### Tests
* TODO Unit tests
* DONE Sanity
* DONE Undirected graphs
* DONE Vertex removal
* DONE Edge removal
* DONE Bipartite graph check
* TODO Directed graphs cycles
* TODO Cross-verification with Mathematica
* DONE General workflow programming/setup
* TODO Path finding
* TODO Cycle finding
### Documentation
* DONE Basic usage over undirected graphs
* TODO Basic usage over directed graphs
* DONE Regular graphs creation (Grid, Wheel, etc.)
* [Notebook with a gallery of graphs](./docs/Named-graphs-gallery.ipynb)
* DONE Random graphs creation
* DONE DOT language visualizations
---
## References
### Articles
[Wk1] Wikipedia entry, ["Graph (discrete mathematics)"](https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)).
[Wk2] Wikipedia entry, ["Graph theory"](https://en.wikipedia.org/wiki/Graph_theory).
[Wk3] Wikipedia entry, ["Glossary of graph theory"](https://en.wikipedia.org/wiki/Glossary_of_graph_theory).
[Wk4] Wikipedia entry, ["List of graphs"](https://en.wikipedia.org/wiki/List_of_graphs) (aka "Gallery of named graphs.")
[Wk5] Wikipedia entry, ["Hamiltonian path"](https://en.wikipedia.org/wiki/Hamiltonian_path).
### Packages
[AAp1] Anton Antonov,
[WWW::MermaidInk Raku package](https://github.com/antononcube/Raku-WWW-MermaidInk),
(2023),
[GitHub/antononcube](https://github.com/antononcube).
[AAp2] Anton Antonov,
[Proc::ZMQed Raku package](https://github.com/antononcube/Raku-Proc-ZMQed),
(2022),
[GitHub/antononcube](https://github.com/antononcube).
[AAp3] Anton Antonov,
[JavaScript:3 Raku package](https://github.com/antononcube/Raku-JavaScript-D3),
(2022-2024),
[GitHub/antononcube](https://github.com/antononcube).
[JHp1] Jarkko Hietaniemi,
[Graph Perl package](https://metacpan.org/dist/Graph/view/lib/Graph.pod),
(1998-2014),
[MetaCPAN](https://metacpan.org).
### Videos
[AAv1] Anton Antonov,
["Graph demo in Raku (teaser)"](https://www.youtube.com/watch?v=0uJl9q7jIf8),
(2024),
[YouTube/@AAA4Prediction](https://www.youtube.com/@AAA4Prediction).
[AAv2] Anton Antonov,
["Graph neat examples in Raku (Set 1)"](https://www.youtube.com/watch?v=5qXgqqRZHow),
(2024),
[YouTube/@AAA4Prediction](https://www.youtube.com/@AAA4Prediction).
[AAv3] Anton Antonov,
["Sparse matrix neat examples in Raku"](https://www.youtube.com/watch?v=kQo3wpiUu6w),
(2024),
[YouTube/@AAA4Prediction](https://www.youtube.com/@AAA4Prediction).
|
## dist_zef-p6steve-CLI-Wordpress.md
[](https://opensource.org/licenses/Artistic-2.0)
# Raku CLI::Wordpress
This module provides a simple abstraction to the Wordpress command line interface (wpcli) for site launch and maintenance.
If you encounter a feature you want that's not implemented by this module (and there are many), please consider sending a pull request.
## Prerequisites
* ubuntu server with docker, docker-compose, raku and zef (e.g. by using [raws-ec2](https://github.com/p6steve/raku-CLI-AWS-EC2-Simple))
* located at a static IP address (e.g. `raws-ec2 --eip launch`) with ssh access (e.g. via `raws-ec2 connect`)
* domain name DNS set with A records @ and www to the target's IP address
## Getting Started
* ssh in and install CLI::Wordpress on server to get the rawp command `zef install https://github.com/p6steve/raku-CLI-Wordpress.git` *[or CLI::Wordpress]*
* edit `vi ~/.rawp-config/wordpress-launch.yaml` with your domain name and wordpress configuration
* launch a new instance of Wordpress & setup ssl certificate `rawp setup && rawp launch`
* view your new Wordpress site frontend at <https://yourdomain.com> and configure basics
* setup ssl cert renewals via letsencrypt `rawp renewal`
## wordpress-launch.yaml
```
instance:
domain-name: your_domain
admin-email: 'adminyour_domain'
db-image: mysql:8.0
wordpress-image: wordpress:php8.0-fpm-alpine
webserver-image: nginx:1.15.12-alpine
certbot-image: certbot/certbot
wpcli-image: wordpress:cli-php8.0
```
## WP CLI Examples
`rawp wp '--info'`
```
OS: Linux 5.15.0-1031-aws #35-Ubuntu SMP Fri Feb 10 02:07:18 UTC 2023 x86_64
Shell:
PHP binary: /usr/local/bin/php
PHP version: 8.0.28
php.ini used:
MySQL binary: /usr/bin/mysql
MySQL version: mysql Ver 15.1 Distrib 10.6.12-MariaDB, for Linux (x86_64) using readline 5.1
SQL modes:
WP-CLI root dir: phar://wp-cli.phar/vendor/wp-cli/wp-cli
WP-CLI vendor dir: phar://wp-cli.phar/vendor
WP_CLI phar path: /var/www/html
WP-CLI packages dir:
WP-CLI cache dir: /.wp-cli/cache
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 2.7.1
```
`rawp wp 'search-replace "test" "experiment" --dry-run'`
```
Table Column Replacements Type
wp_commentmeta meta_key 0 SQL
wp_commentmeta meta_value 0 SQL
wp_comments comment_author 0 SQL
...
wp_links link_rss 0 SQL
wp_options option_name 0 SQL
wp_options option_value 3 PHP
wp_options autoload 0 SQL
...
wp_users display_name 0 SQL
Success: 3 replacements to be made.
```
## CMDs
* setup # position all config files for docker-compose and render wordpress-launch.yaml info
* launch # docker-compose up staging server, if OK then get ssl and restart
* renewal # configure crontab for ssl cert renewal
* up # docker-compose up -d
* wp 'cmd' # run wpcli command - viz. <https://developer.wordpress.org/cli/commands/>
* down # docker-compose down
* ps # docker-compose ps
* connect # docker exec to wordpress server
* terminate # rm volumes & reset
## Usage
```
rawp <cmd> [<wp>]
<cmd> One of <setup launch renewal up wp down ps connect terminate>
[<wp>] A valid wp cli cmd (viz. https://developer.wordpress.org/cli/commands/)
```
### Copyright
copyright(c) 2023 Henley Cloud Consulting Ltd.
|
## dist_zef-bduggan-Pod-To-Raku.md
[](https://github.com/bduggan/raku-pod-to-raku/actions/workflows/linux.yml)
[](https://github.com/bduggan/raku-pod-to-raku/actions/workflows/macos.yml)
# NAME
Pod::To::Raku -- Extract Pod into standalone Raku
# SYNOPSIS
```
raku --doc=Raku in.raku > out.raku
raku --doc=Raku in.rakumod > out.raku
raku --doc=Raku::Plus in.pod > out.raku
```
# DESCRIPTION
This is a simple way of extracting pod from a file and serializing it using the `.raku` method.
This can be helpful to separate the pod from a raku module or program in which it is embedded. It is designed to be used along with the command line option `--doc` for the raku executable, as shown above.
# EXAMPLE
Given a file like this named `add.raku` with some declarator pod:
```
#| add two numbers
sub add($a, $b) {
$a + $b;
}
```
Run
```
raku --doc=Raku add.raku
```
to get
```
$[
Pod::Block::Declarator.new(
WHEREFORE => sub add ($a, $b) { #`(Sub|3053844670056) ... },
leading => [["add two numbers"],],
trailing => [],
config => {}, contents => []
)
]
```
# BONUS FEATURES
Also included: `Pod::To::Raku::Plus` and `find-raku-module`.
Use `Raku::Plus` to add the file and line to `WHEREFORE`:
```
raku --doc=Raku::Plus add.raku
```
which yields
```
$[
Pod::Block::Declarator.new(
WHEREFORE => {
:file("add.raku"),
:line(2),
:name("add"),
:sig(:($a, $b))
},
leading => [["add two numbers"],], trailing => [], config => {}, contents => [])
]
```
Use `find-raku-module` to get some metadata (including filenames) for a module:
```
find-raku-module JSON::Fast
```
yields
```
{
"repo-id": "inst",
"provides": [
{
"lib/JSON/Fast.pm6": {
"file": "F13CDD097310A0775131666979B65ADF692574DD",
"time": null
},
"file": "...moar-2024.12/share/perl6/site/sources/F13CDD097310A0775131666979B65ADF692574DD"
}
],
"meta": {
"ver": "0.19",
"source": "F13CDD097310A0775131666979B65ADF692574DD",
"auth": "cpan:TIMOTIMO",
"api": "0",
"checksum": "A498E97EDAC5D22E53386172C9A3EA5670411BCD"
},
"JSON::Fast": {
"lib/JSON/Fast.pm6": "...moar-2024.12/share/perl6/site/sources/F13CDD097310A0775131666979B65ADF692574DD"
},
"description": "A naive, fast json parser and serializer; drop-in replacement for JSON::Tiny"
}
```
# SEE ALSO
`Pod::Load`
|
## return.md
return
Combined from primary sources listed below.
# [In Control flow](#___top "go to top of document")[§](#(Control_flow)_return_return "direct link")
See primary documentation
[in context](/language/control#return)
for **return**.
The sub `return` will stop execution of a subroutine or method, run all relevant [phasers](/language/phasers#Block_phasers) and provide the given return value to the caller. The default return value is [`Nil`](/type/Nil). If a return [type constraint](/language/signatures#Constraining_return_types) is provided it will be checked unless the return value is [`Nil`](/type/Nil). If the type check fails the exception [`X::TypeCheck::Return`](/type/X/TypeCheck/Return) is thrown. If it passes a control exception is raised and can be caught with [CONTROL](/language/phasers#CONTROL).
Any `return` in a block is tied to the first [`Routine`](/type/Routine) in the outer lexical scope of that block, no matter how deeply nested. Please note that a `return` in the root of a package will fail at runtime. A `return` in a block that is evaluated lazily (e.g. inside `map`) may find the outer lexical routine gone by the time the block is executed. In almost any case `last` is the better alternative. Please check [the functions documentation](/language/functions#Return_values) for more information on how return values are handled and produced.
|
## wraphandle.md
class Routine::WrapHandle
Holds all information needed to unwrap a wrapped routine.
class WrapHandle { ... }
`WrapHandle` is a *Rakudo private class* created and returned by [wrap](/type/Routine#method_wrap). Its only use is to unwrap wrapped routines. Either call [unwrap](/type/Routine#method_unwrap) on a routine object or call the method `restore` on a `Routine::WrapHandle` object.
```raku
sub f() { say 'f was called' }
my $wrap-handle = &f.wrap({ say 'before'; callsame; say 'after' });
f; # OUTPUT: «beforef was calledafter»
$wrap-handle.restore;
f; # OUTPUT: «f was called»
```
As such private class, it may suffer any kind of changes without prior notice. It is only mentioned here since it is visible by the user who checks the return type of the `Routine.wrap` method.
# [Methods](#class_Routine::WrapHandle "go to top of document")[§](#Methods "direct link")
## [method restore](#class_Routine::WrapHandle "go to top of document")[§](#method_restore "direct link")
```raku
method restore(--> Bool:D)
```
Unwraps a wrapped routine and returns `Bool::True` on success.
|
## dist_zef-lizmat-CodeUnit.md
[](https://github.com/lizmat/CodeUnit/actions) [](https://github.com/lizmat/CodeUnit/actions) [](https://github.com/lizmat/CodeUnit/actions)
# NAME
CodeUnit - provide a unit for execution of code
# SYNOPSIS
```
use CodeUnit;
my $cu = CodeUnit.new;
$cu.eval('my $a = 42');
$cu.eval('say $a'); # 42
$cu.eval('say $b');
with $cu.exception {
note .message.chomp; # Variable '$b' is not declared...
$cu.exception = Nil;
}
```
# DESCRIPTION
The `CodeUnit` distribution provides an interface to a compiler context that allows code to be evaluated by given strings, while maintaining context between states.
As such it provides one of the underlying functionalities of a REPL (Read Evaluate Print Loop), but could be used by itself for a multitude of uses.
# METHODS
## new
```
my $cu1 = CodeUnit.new;
my $context = context;
my $cu2 = CodeUnit.new(:$context);
# start with grammar including any mixins
my $cu3 = CodeUnit.new(:lang(BEGIN $*LANG));
```
The `new` method instantiates a `CodeUnit` object. It takes the following named arguments:
### :context
Optional. The `:context` named argument can be specified with a value returned by the `context` subroutine. If not specified, will assume a fresh context without any outer / caller lexicals visible.
Used value available with the `.context` method.
### :compiler
Optional. The `:compiler` named argument can be specified to indicate the low level compiler object that sould be used. Can be specified as a string, in which case it will be used as an argument to the `nqp::getcomp` function to obtain the low level compiler object. Defaults to `"Raku"`.
Used value available with the `.compiler` method.
### :multi-line-ok
Optional, Boolean. Indicate whether it is ok to interprete multiple lines of input as a single statement to evaluate. Defaults to `True` unless the `RAKUDO_DISABLE_MULTILINE` environment variable has been specified with a true value.
Used value available with the `.multi-line-ok` method, and can be used as a left-value to change.
### :grammar
Optional. Specifies the `grammar` to be used initially. Defaults to the standard Raku grammar, or to what has been specified with `:lang`.
Value available with the `.grammar` method.
### :actions
Optional. Specifies the action class to be used. Defaults to the standard Raku actions, or to what the `.actions` method returns on what is specified with `:lang`.
### :lang
Optional. Specified which `grammar` / action class to be used. Defaults to the standard Raku `grammar` and action class. If specified, this is usually `BEGIN $*LANG`;
## eval
```
$cu.eval('my $a = 42');
$cu.eval('say $a'); # 42
```
The `eval` method evaluates the given string with Raku code within the context of the code unit, and returns the result of the evaluation.
## reset
```
$cu.reset;
```
The `reset` method resets the context of the code unit to its initial state as (implicitely) specified with `.new`.
## compiler-version
```
say $cu.compiler-version;
# Welcome to Rakudo™ v2025.01.
# Implementing the Raku® Programming Language v6.d.
# Built on MoarVM version 2025.01.
```
The `compiler-version` method returns the compiler version information, which is typically shown when starting a REPL.
## context-completions
```
.say for $cu.context-completions;
```
The `context-completions` method returns an unsorted list of context completion candidates found in the context of the code unit, which are typically used to provide completions in a REPL (hence the name).
## state
The `state` method returns one of the `Status` enums to indicate the result of the last call to `.eval`. It can also be used as a left-value to set the state (usually to `OK`).
## exception
```
with $cu.exception {
note .message.chomp; # Variable '$b' is not declared...
$cu.exception = Nil;
}
```
The `exception` method returns the `Exception` object if anything went wrong in the `.eval` call. Note that this can also be the case even if the state is `OK`. Can also be used as a left-value to (re)set.
# ENUMS
## Status
The `Status` enum is exported: it is used by the `state` method to indicate the state of the last call to `.eval`. It provides the following states:
* OK (0) - evalution ok
* MORE-INPUT (1) - string looks like incomplete code
* CONTROL (2) - some kind of control statement was executed
# SUBROUTINES
## context
```
my $context = context;
my $cu = CodeUnit.new(:$context);
```
The `context` subroutine returns a context object that can be used to initialize the context of a code unit with.
# CAVEATS
## "Invisible" variables
By default, Raku does a lot of compile-time as well as run-time optimizations. This may lead to lexical variables being optimized away, and thus become "invisible" to introspection. If that appears to be the case, then starting Raku with `--optimize=off` may make these "invisble" variables visible.
## Each call is a scope
Because each call introduces its own scope, certain side-effects of this scoping behaviour may produce unexpected results and/or errors. For example: `my $a = 42`, followed by `say $a`, is really:
```
my $a = 42;
{
say $a;
}
```
This works because the lexical variable `$a` is visible from the scope that has the `say`.
Another example which you might expect to give at least a warning, but doesn't: `my $a = 42;` followed by `my $a = 666`, which would normally produce a worry: "Redeclaration of symbol '$a'", but doesn't here because they are different scopes:
```
my $a = 42;
{
my $a = 666;
}
```
As you can see, the second `$a` shadows the first `$a`, and is not a worry as such.
Future versions of `CodeUnit` may be able to work around this scoping behaviour.
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
Source can be located at: <https://github.com/lizmat/CodeUnit> . 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 2025 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## eqv.md
eqv
Combined from primary sources listed below.
# [In Match](#___top "go to top of document")[§](#(Match)_infix_eqv "direct link")
See primary documentation
[in context](/type/Match#infix_eqv)
for **infix eqv**.
```raku
multi infix:<eqv>(Match:D \a, Match:D \b)
```
Returns `True` if the attributes `pos`, `from` and `orig` for `a` and `b` are equal, and if `made`, `Capture::list` and `Capture::hash` are either the same or both undefined.
# [In ObjAt](#___top "go to top of document")[§](#(ObjAt)_infix_eqv "direct link")
See primary documentation
[in context](/type/ObjAt#infix_eqv)
for **infix eqv**.
```raku
multi infix:<eqv>(ObjAt:D $a, ObjAt:D $b)
```
Returns True if the two ObjAt are the same, that is, if the object they identify is the same.
```raku
my @foo = [2,3,1];
my @bar := @foo;
say @foo.WHICH eqv @bar.WHICH; # OUTPUT: «True»
```
# [In Operators](#___top "go to top of document")[§](#(Operators)_infix_eqv "direct link")
See primary documentation
[in context](/language/operators#infix_eqv)
for **infix eqv**.
```raku
sub infix:<eqv>(Any, Any)
```
This could be called an equivalence operator, and it will return `True` if the two arguments are structurally the same, i.e. from the same type and (recursively) contain equivalent values.
```raku
say [1, 2, 3] eqv [1, 2, 3]; # OUTPUT: «True»
say Any eqv Any; # OUTPUT: «True»
say 1 eqv 2; # OUTPUT: «False»
say 1 eqv 1.0; # OUTPUT: «False»
```
Lazy [`Iterable`](/type/Iterable)s cannot be compared, as they're assumed to be infinite. However, the operator will do its best and return `False` if the two lazy [`Iterable`](/type/Iterable)s are of different types or if only one [`Iterable`](/type/Iterable) is lazy.
```raku
say (1…∞) eqv (1…∞).List; # Both lazy, but different types; OUTPUT: «False»
say (1…∞) eqv (1…3); # Same types, but only one is lazy; OUTPUT: «False»
(try say (1…∞) eqv (1…∞)) # Both lazy and of the same type. Cannot compare; throws.
orelse say $!.^name; # OUTPUT: «X::Cannot::Lazy»
```
In some cases, it will be able to compare lazy operands, as long as they can be iterated
```raku
my $a = lazy ^2;
my $b = $a;
$a.cache;
say $a eqv $b; # OUTPUT: «True»
```
When cached, the two lazy [`Seq`](/type/Seq)s can be iterated over, and thus compared.
The default `eqv` operator even works with arbitrary objects. E.g., `eqv` will consider two instances of the same object as being structurally equivalent:
```raku
my class A {
has $.a;
}
say A.new(a => 5) eqv A.new(a => 5); # OUTPUT: «True»
```
Although the above example works as intended, the `eqv` code might fall back to a slower code path in order to do its job. One way to avoid this is to implement an appropriate infix `eqv` operator:
```raku
my class A {
has $.a;
}
multi infix:<eqv>(A $l, A $r) { $l.a eqv $r.a }
say A.new(a => 5) eqv A.new(a => 5); # OUTPUT: «True»
```
Note that `eqv` does not work recursively on every kind of container type, e.g. [`Set`](/type/Set):
```raku
my class A {
has $.a;
}
say Set(A.new(a => 5)) eqv Set(A.new(a => 5)); # OUTPUT: «False»
```
Even though the contents of the two sets are `eqv`, the sets are not. The reason is that `eqv` delegates the equality check to the [`Set`](/type/Set) object which relies on element-wise `===` comparison. Turning the class `A` into a value type ([`ValueObjAt`](/type/ValueObjAt)) by giving it a `WHICH` method produces the expected behavior:
```raku
my class A {
has $.a;
method WHICH {
ValueObjAt.new: "A|$!a.WHICH()"
}
}
say Set(A.new(a => 5)) eqv Set(A.new(a => 5)); # OUTPUT: «True»
```
You can call a single-argument version of the operator by using its full name; it will always return true.
```raku
say infix:<eqv>(33); # OUTPUT: «True»
say infix:<eqv>(False); # OUTPUT: «True»
```
# [In Allomorph](#___top "go to top of document")[§](#(Allomorph)_infix_eqv "direct link")
See primary documentation
[in context](/type/Allomorph#infix_eqv)
for **infix eqv**.
```raku
multi infix:<eqv>(Allomorph:D $a, Allomorph:D $b --> Bool:D)
```
Returns `True` if the two `Allomorph` `$a` and `$b` are of the same type, their [`Numeric`](/type/Numeric) values are [equivalent](/routine/eqv) and their [`Str`](/type/Str) values are also [equivalent](/routine/eqv). Returns `False` otherwise.
|
## dist_cpan-AZAWAWI-MagickWand.md
# MagickWand
This provides a Perl 6 object-oriented [NativeCall](http://doc.perl6.org/language/nativecall)-based API for ImageMagick's
[MagickWand C API](http://www.imagemagick.org/script/magick-wand.php).
## Build Status
| Operating System | Build Status | CI Provider |
| --- | --- | --- |
| Linux / Mac OS X | [Build Status](https://travis-ci.org/azawawi/perl6-magickwand) | Travis CI |
| Windows 7 64-bit | [Build status](https://ci.appveyor.com/project/azawawi/perl6-magickwand/branch/master) | AppVeyor |
## Example
```
use v6;
use MagickWand;
# A new magic wand
my $wand = MagickWand.new;
# Read an image
$wand.read("examples/images/aero1.jpg");
# Lighten dark areas
$wand.auto-gamma;
# And then write a new image
$wand.write("output.png");
# And cleanup on exit
LEAVE {
$wand.cleanup if $wand.defined;
}
```
For more examples, please see the <examples> folder.
For examples of available image effects, please click
[here](http://www.imagemagick.org/script/examples.php).
## Prerequisites
Please follow the instructions below based on your platform:
### Linux (Debian)
* To install ImageMagick libraries, please run:
```
$ sudo apt install libmagickwand-dev
```
### MacOSX (Darwin)
* To install ImageMagick libraries via [Homebrew](http://brew.sh/), please run:
```
$ brew update
$ brew install imagemagick
```
* To install ImageMagick libraries via [MacPorts](https://www.macports.org/),
please run:
```
$ sudo port install ImageMagick
```
### Windows
For 64-bit Windows, please install the [`64-bit`](https://www.imagemagick.org/download/binaries/ImageMagick-7.0.8-14-Q16-x64-dll.exe)
DLL installer. Otherwise, use the [`32-bit`](https://www.imagemagick.org/download/binaries/ImageMagick-7.0.8-14-Q16-x86-dll.exe)
version.
Also please remember to enable **"Add to PATH"** option.
## Installation
* Install this module using [zef](https://github.com/ugexe/zef):
```
$ zef install MagickWand
```
## Testing
To run tests:
```
$ prove -ve "perl6 -Ilib"
```
## Author
Ahmad M. Zawawi, azawawi on #perl6, <https://github.com/azawawi/>
## License
MIT License
|
## formattingcode.md
class Pod::FormattingCode
Pod formatting code
```raku
class Pod::FormattingCode is Pod::Block { }
```
Class for formatting codes in a Pod document.
# [Methods](#class_Pod::FormattingCode "go to top of document")[§](#Methods "direct link")
## [method type](#class_Pod::FormattingCode "go to top of document")[§](#method_type "direct link")
```raku
method type(--> Mu)
```
## [method meta](#class_Pod::FormattingCode "go to top of document")[§](#method_meta "direct link")
```raku
method meta(--> Positional)
```
|
## dist_zef-japhb-Terminal-QuickCharts.md
[](https://github.com/japhb/Terminal-QuickCharts/actions)
# NAME
Terminal::QuickCharts - Simple charts for CLI tools
# SYNOPSIS
```
use Terminal::QuickCharts;
# Chart routines take an array of data points and return an array of
# rendered rows using ANSI terminal codes and Unicode block characters
.say for hbar-chart([5, 10, 15]);
# Horizontal bar charts support 2D data, grouping (default) or stacking the bars
.say for hbar-chart([(1, 2, 3), (4, 5, 6)], :colors< red yellow blue >);
.say for hbar-chart([(1, 2, 3), (4, 5, 6)], :colors< red yellow blue >, :stacked);
# You can also specify optional style and sizing info
.say for hbar-chart([17, 12, 16, 14], :min(10), :max(20));
.say for smoke-chart(@lots-of-data, :style{ lines-every => 5 });
# auto-chart() chooses a chart variant based on specified semantic domain,
# details of the actual data, and available screen size
.say for auto-chart('frame-time', @frame-times);
```
# EXAMPLES
Comparing an animation's performance before and after a round of optimization:

Result of many small Rakudo optimizations on a standard benchmark's runtime:

# DESCRIPTION
Terminal::QuickCharts provides a small library of simple text-output charts, suitable for sprucing up command-line reporting and quick analysis tools. The emphasis here is more on whipuptitude, and less on manipulexity.
This is a *very* early release; expect further iteration on the APIs, and if time permits, bug fixes and additional chart types.
# AUTHOR
Geoffrey Broadwell [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2019-2021 Geoffrey Broadwell
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## pipe.md
class IO::Pipe
Buffered inter-process string or binary stream
```raku
class IO::Pipe is IO::Handle {}
```
An `IO::Pipe` object closely corresponds to a UNIX pipe. It has one end where it consumes string or binary data, and another where it reproduces the same data. It is buffered, so that a write without a read doesn't immediately block.
Pipes can be easily constructed with [sub run and Proc::Async.new](/type/Proc/Async).
# [Methods](#class_IO::Pipe "go to top of document")[§](#Methods "direct link")
## [method close](#class_IO::Pipe "go to top of document")[§](#method_close "direct link")
```raku
method close(IO::Pipe: --> Proc:D)
```
Closes the pipe and returns [`Proc`](/type/Proc) object from which the pipe originates.
## [method IO](#class_IO::Pipe "go to top of document")[§](#method_IO "direct link")
```raku
method IO(IO::Pipe: --> IO::Path:U)
```
Returns an [`IO::Path`](/type/IO/Path) type object.
## [method path](#class_IO::Pipe "go to top of document")[§](#method_path "direct link")
```raku
method path(IO::Pipe: --> IO::Path:U)
```
Returns an [`IO::Path`](/type/IO/Path) type object.
## [method proc](#class_IO::Pipe "go to top of document")[§](#method_proc "direct link")
```raku
method proc(IO::Pipe: --> Proc:D)
```
Returns the [`Proc`](/type/Proc) object from which the pipe originates.
|
## dist_cpan-FRITH-Math-Libgsl-QuasiRandom.md
[](https://travis-ci.org/frithnanth/raku-Math-Libgsl-QuasiRandom)
# NAME
Math::Libgsl::QuasiRandom - An interface to libgsl, the Gnu Scientific Library - Quasi-Random Sequences.
# SYNOPSIS
```
use Math::Libgsl::QuasiRandom;
use Math::Libgsl::Constants;
my Math::Libgsl::QuasiRandom $q .= new: :type(SOBOL), :2dimensions;
$q.get».say for ^10;
```
# DESCRIPTION
Math::Libgsl::QuasiRandom is an interface to the Quasi-Random Sequences of libgsl, the Gnu Scientific Library.
### new(Int :$type, Int :$dimensions)
The constructor allows two parameters, the quasi-random sequence generator type and the dimensions. One can find an enum listing all the generator types in the Math::Libgsl::Constants module.
### init()
This method re-inits the sequence.
### get(--> List)
Returns the next item in the sequence as a List of Nums.
### name(--> Str)
This method returns the name of the current quasi-random sequence.
### copy(Math::Libgsl::QuasiRandom $src)
This method copies the source generator **$src** into the current one and returns the current object, so it can be concatenated. The generator state is also copied, so the source and destination generators deliver the same values.
### clone(--> Math::Libgsl::QuasiRandom)
This method clones the current object and returns a new object. The generator state is also cloned, so the source and destination generators deliver the same values.
```
my $q = Math::Libgsl::QuasiRandom.new;
my $clone = $q.clone;
```
# C Library Documentation
For more details on libgsl see <https://www.gnu.org/software/gsl/>. The excellent C Library manual is available here <https://www.gnu.org/software/gsl/doc/html/index.html>, or here <https://www.gnu.org/software/gsl/doc/latex/gsl-ref.pdf> in PDF format.
# Prerequisites
This module requires the libgsl library to be installed. Please follow the instructions below based on your platform:
## Debian Linux
```
sudo apt install libgsl23 libgsl-dev libgslcblas0
```
That command will install libgslcblas0 as well, since it's used by the GSL.
## Ubuntu 18.04
libgsl23 and libgslcblas0 have a missing symbol on Ubuntu 18.04. I solved the issue installing the Debian Buster version of those three libraries:
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgslcblas0_2.5+dfsg-6_amd64.deb>
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl23_2.5+dfsg-6_amd64.deb>
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl-dev_2.5+dfsg-6_amd64.deb>
# Installation
To install it using zef (a module management tool):
```
$ zef install Math::Libgsl::QuasiRandom
```
# AUTHOR
Fernando Santagata [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2020 Fernando Santagata
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## pickpairs.md
pickpairs
Combined from primary sources listed below.
# [In role Baggy](#___top "go to top of document")[§](#(role_Baggy)_method_pickpairs "direct link")
See primary documentation
[in context](/type/Baggy#method_pickpairs)
for **method pickpairs**.
```raku
multi method pickpairs(Baggy:D: --> Pair:D)
multi method pickpairs(Baggy:D: $count --> Seq:D)
```
Returns a [`Pair`](/type/Pair) or a [`Seq`](/type/Seq) of [`Pair`](/type/Pair)s depending on the version of the method being invoked. Each [`Pair`](/type/Pair) returned has an element of the invocant as its key and the element's weight as its value. The elements are 'picked' without replacement. If `*` is passed as `$count`, or `$count` is greater than or equal to the number of [elements](#method_elems) of the invocant, then all element/weight [`Pair`](/type/Pair)s from the invocant are returned in a random sequence.
Note that each `pickpairs` invocation maintains its own private state and has no effect on subsequent `pickpairs` invocations.
```raku
my $breakfast = bag <eggs bacon bacon bacon>;
say $breakfast.pickpairs; # OUTPUT: «eggs => 1»
say $breakfast.pickpairs(1); # OUTPUT: «(bacon => 3)»
say $breakfast.pickpairs(*); # OUTPUT: «(eggs => 1 bacon => 3)»
```
# [In role Setty](#___top "go to top of document")[§](#(role_Setty)_method_pickpairs "direct link")
See primary documentation
[in context](/type/Setty#method_pickpairs)
for **method pickpairs**.
```raku
multi method pickpairs(Setty:D: --> Pair:D)
multi method pickpairs(Setty:D: $count --> Seq:D)
```
Returns a [`Pair`](/type/Pair) or a [`Seq`](/type/Seq) of [`Pair`](/type/Pair)s depending on the candidate of the method being invoked. Each [`Pair`](/type/Pair) returned has an element of the invocant as its key and `True` as its value. In contrast to [grabpairs](#method_grabpairs), the elements are 'picked' without replacement.
If `*` is passed as `$count`, or `$count` is greater than or equal to the number of [elements](#method_elems) of the invocant, then all element/`True` [`Pair`](/type/Pair)s from the invocant are returned in a random sequence; i.e. they are returned shuffled;
Note that each `pickpairs` invocation maintains its own private state and has no effect on subsequent `pickpairs` invocations.
```raku
my $numbers = set (4, 2, 3);
say $numbers.pickpairs; # OUTPUT: «4 => True»
say $numbers.pickpairs(1); # OUTPUT: «(3 => True)»
say $numbers.pickpairs(*); # OUTPUT: «(2 => True 4 => True 3 => True)»
```
|
## usage.md
class Telemetry::Instrument::Usage
Instrument for collecting getrusage data
```raku
class Telemetry::Instrument::Usage { }
```
**Note:** This class is a Rakudo-specific feature and not standard Raku.
Objects of this class are generally not created by themselves, but rather through making a [snap](/type/Telemetry)shot.
## [Useful readings](#class_Telemetry::Instrument::Usage "go to top of document")[§](#Useful_readings "direct link")
This class provides the following generally usable readings (in alphabetical order):
* cpu
The total amount of CPU time (in microseconds), essentially the sum of `cpu-user` and `cpu-sys`.
* cpu-sys
The number of microseconds of CPU used by the system.
* cpu-user
The number of microseconds of CPU used by the user program.
* cpus
The number of CPU's active, essentially `cpu` divided by `wallclock`.
* max-rss
The maximum resident set size (in KiB).
* util%
Percentage of CPU utilization, essentially 100 \* `cpus` / number of CPU cores.
* wallclock
The time the program has been executing (in microseconds).
## [Less useful readings](#class_Telemetry::Instrument::Usage "go to top of document")[§](#Less_useful_readings "direct link")
The following readings may or may not contain sensible information, mostly depending on hardware and OS being used. Please check your local `getrusage` documentation for their exact meaning:
「text」 without highlighting
```
```
name getrusage struct name
==== =====================
max-rss ru_maxrss
ix-rss ru_ixress
id-rss ru_idrss
is-rss ru_isrss
minf ru_minflt
majf ru_majflt
nswp ru_nswap
inb ru_inblock
outb ru_oublock
msnd ru_msgsnd
mrcv ru_msgrcv
nsig ru_nsignals
volcsw ru_nvcsw
invcsw ru_nivcsw
```
```
|
## dist_zef-PowellDean-Locale-Codes-Country.md
# Locale::Codes::Country
Locale::Codes::Country is a first attempt at creating a pure Raku implementation
of the Perl 5 module of the same name found on CPAN. This version extends
the functionality of the original version.
# Requirements
Rakudo (Tested with the 2024.01 release).
# Installation
Use zef. The command: `zef install Locale-Codes-Country` should work.
# What's it for?
Locale::Codes::Country is an implementation of the ISO3166 standard, which defines
codes for the names of countries, dependent territories, etc. There are
essentially four types of codes associated with each country/area:
* LOCALE\_CODE\_ALPHA\_2 defines a unique 2 character code for each country/area
* LOCALE\_CODE\_ALPHA\_3 defines a unique 3 character code
* LOCALE\_CODE\_NUMERIC defines a numeric code (between 000 and 999) for each
country/area
* LOCALE\_CODE\_DOM defines the IANA assigned Top Level Domain for a country.
For most countrues this just the LOCALE\_CODE\_ALPHA\_2 code in lower case
with a leading dot, but every now and again there is a difference. I may
not have caught those yet ;-)
For each of the constants listed above there is an equivalent string. Respectively:
* 'alpha-2'
* 'alpha-3'
* 'numeric'
* 'dom'
Using Locale::Codes::Country, you may lookup a country name by its ISO3166-2,
ISO3166-3 or ISO3166-Numeric defined code. You may also look up a country's
ISO-assigned code using the full country name. You may also lookup one
of the other ISO-defined codes by passing in any of the other unique values.
# Examples
```
use Locale::Codes::Country;
say codeToCountry("BGD"); # will print 'BANGLADESH'
say codeToCountry("CA"); # will print 'CANADA'. LOCALE_CODE_ALPHA_2 is default
say countryToCode("Austria",LOCALE_CODE_NUMERIC) # will print "040"
say codeToCode(70, "alpha-3"); # will print BIH (Bosnia and Herzegovina)
```
# Future
I may in the near future add other codes such as IOC designations, or FIPS
codes to the mix.
# Testing
Basic tests. Not extensive, but there are a few.
Run `prove6 --lib t -v` or `zef test .`
# Contributing
Comments and Pull Requests are always welcome.
# License and Author
The Artistic 2.0 License (Artistic-2)
Copyright (c) 2016-2024 Dean Powell [[email protected]](mailto:[email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|
## splice.md
splice
Combined from primary sources listed below.
# [In Array](#___top "go to top of document")[§](#(Array)_routine_splice "direct link")
See primary documentation
[in context](/type/Array#routine_splice)
for **routine splice**.
```raku
multi splice(@list, $start = 0, $elems?, *@replacement --> Array)
multi method splice(Array:D: $start = 0, $elems?, *@replacement --> Array)
```
Deletes `$elems` elements starting from index `$start` from the `Array`, returns them and replaces them by `@replacement`. If `$elems` is omitted or is larger than the number of elements starting from `$start`, all the elements starting from index `$start` are deleted. If both `$start` and `$elems` are omitted, all elements are deleted from the `Array` and returned.
Each of `$start` and `$elems` can be specified as a [`Whatever`](/type/Whatever) or as a [`Callable`](/type/Callable) that returns an [`Int`](/type/Int)-compatible value: this returned value is then used as the corresponding argument to the `splice` routine.
A [`Whatever`](/type/Whatever) `$start` uses the number of elements of `@list` (or invocant). A [`Callable`](/type/Callable) `$start` is called with one argument—the number of elements in `@list` (or `self`).
A [`Whatever`](/type/Whatever) `$elems` deletes from `$start` to end of `@list` (or `self`) (same as no `$elems`). A [`Callable`](/type/Callable) `$elems` is called with one argument—the number of elements in `@list` (or `self`) minus the value of `$start`.
Example:
```raku
my @foo = <a b c d e f g>;
say @foo.splice(2, 3, <M N O P>); # OUTPUT: «[c d e]»
say @foo; # OUTPUT: «[a b M N O P f g]»
```
It can be used to extend an array by simply splicing in more elements than the current size (since version 6.d)
```raku
my @foo = <a b c d e f g>;
say @foo.splice(6, 4, <M N O P>); # OUTPUT: «[g]»
say @foo; # OUTPUT: «[a b c d e f M N O P]»
```
The following equivalences hold (assuming that `@a.elems ≥ $i`):
「text」 without highlighting
```
```
@a.push($x, $y) @a.splice: * , *, $x, $y
@a.pop @a.splice: *-1,
@a.shift @a.splice: 0 , 1,
@a.unshift($x, $y) @a.splice: 0 , 0, $x, $y
@a[$i] = $y @a.splice: $i , 1, $y,
```
```
As mentioned above, a [`Whatever`](/type/Whatever) or [`Callable`](/type/Callable) object can be provided for both the `$start` and `$elems` parameters. For example, we could use either of them to remove the second to last element from an array provided it's large enough to have one:
```raku
my @foo = <a b c d e f g>;
say @foo.splice: *-2, *-1; # OUTPUT: «[f]»
say @foo; # OUTPUT: «[a b c d e g]»
my &start = -> $n { $n - 2 };
my &elems-num = -> $m { $m - 1 };
say @foo.splice: &start, &elems-num; # OUTPUT: «[e]»
say @foo; # OUTPUT: «[a b c d g]»
```
# [In role Buf](#___top "go to top of document")[§](#(role_Buf)_method_splice "direct link")
See primary documentation
[in context](/type/Buf#method_splice)
for **method splice**.
```raku
method splice( Buf:D: $start = 0, $elems?, *@replacement --> Buf)
```
Substitutes elements of the buffer by other elements, returning a buffer with the removed elements.
```raku
my $bú = Buf.new( 1, 1, 2, 3, 5 );
say $bú.splice: 0, 3, <3 2 1>; # OUTPUT: «Buf:0x<01 01 02>»
say $bú.raku; # OUTPUT: «Buf.new(3,2,1,3,5)»
```
|
## dist_zef-FRITH-Net-Whois.md
[](https://github.com/frithnanth/Raku-Net-Whois/actions)
# NAME
Net::Whois - Raku interface to the Whois service
# SYNOPSIS
```
use Net::Whois;
my Net::Whois $w .= new;
my %h = $w.query: $who, $using;
for %h.kv -> $k, $v { say "$k => $v[*]" }
```
# DESCRIPTION
Net::Whois is an interface to the Whois service
This is a very simple module that does what I just happened to need.
### new()
The constructor takes no arguments.
### multi method query(Str:D $who where { $\_ ~~ IP | Domain or die 'Not a valid IP or domain name' }, Str:D $server, Bool :$raw! --> List)
### multi method query(Str:D $who where { $\_ ~~ IP | Domain or die 'Not a valid IP or domain name' }, Str:D $server, Bool :$multiple --> Hash)
### multi method query(Str:D $who where { $\_ ~~ IP | Domain or die 'Not a valid IP or domain name' }, \*@servers, Bool :$multiple, Bool :$raw --> Hash)
The first form of the method looks for the **$who** domain, using the chosen **$server** and returns a **List** of values. If the **:$raw** flag is used then the result is returned verbatim.
The second form returns a **Hash** of the whois fields. The whois output may consist of several sections; if the **:$multiple** flag is used the values of the same-named field are concatenated into the same value string.
The third form takes a list of servers to query. It returns a **Hash** whose keys are the name of the server and the values are the hashes returned by the second form of the method, or the lists returned by the first form of the method if the **:$raw** flag has been used.
# Installation
To install it using zef (a module management tool):
```
$ zef install Net::Whois
```
# AUTHOR
Fernando Santagata [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2023 Fernando Santagata
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-antononcube-Graphviz-DOT-Grammar.md
# Graphviz::DOT::Grammar
Raku package with a parser and interpreters of Graphviz DOT language.
Languages and formats DOT is translated to:
* DONE DOT layout formats
* SVG, EPS, JSON, plain, etc.
* DONE PlantUML
* PlantUML uses DOT language, so it was very short and easy format implementation.
* DONE Mermaid-JS
* [-] TODO Mathematica
* DONE Basic vertexes and edges
* TODO Vertex styles
* TODO Edge styles
* TODO Raku
* Translation to Raku graphs, [AAp1]
* Based on the Mathematica actions
---
## Usage examples
Here is a graph (see [AAp1]):
```
use Graph::HexagonalGrid;
my $g = Graph::HexagonalGrid.new(1, 1);
```
```
# Graph(vertexes => 6, edges => 6, directed => False)
```
Translate to Mermaid-JS:
```
use Graphviz::DOT::Grammar;
$g.dot ==> dot-interpret(a=>'mermaid')
```
```
graph TB
v0["1"]
v1["4"]
v2["5"]
v3["0"]
v4["3"]
v5["2"]
v4 --- v2
v1 --- v2
v3 --- v5
v5 --- v1
v0 --- v4
v3 --- v0
```
Translate to Mathematica:
```
$g.dot ==> dot-interpret(a=>'Mathematica')
```
```
Graph[{}, {UndirectedEdge["3", "5"], UndirectedEdge["4", "5"], UndirectedEdge["0", "2"], UndirectedEdge["2", "4"], UndirectedEdge["1", "3"], UndirectedEdge["0", "1"]}]
```
---
## CLI
The package provides the Command Line Interface (CLI) script `from-dot`. Here is its usage message:
```
from-dot --help
```
```
# Usage:
# from-dot <text> [-t|--to=<Str>] [-o|--output=<Str>] -- Converts Graphviz DOT language texts or files into Mermaid-JS, Mathematica, Markdown, JSON, Raku, or SVG files.
#
# <text> Input file or DOT spec.
# -t|--to=<Str> Format to convert to. (One of 'json', 'mathematica', 'mermaid', 'raku', 'svg', or 'Whatever'.) [default: 'Whatever']
# -o|--output=<Str> Output file; if an empty string then the result is printed to stdout. [default: '']
```
---
## References
[AAp1] Anton Antonov,
[Graph Raku package](https://github.com/antononcube/Raku-Graph),
(2024),
[GitHub/antononcube](https://github.com/antononcube).
|
## dist_zef-lizmat-IRC-Client-Plugin-Rakkable.md
[](https://github.com/lizmat/IRC-Client-Plugin-Rakkable/actions) [](https://github.com/lizmat/IRC-Client-Plugin-Rakkable/actions) [](https://github.com/lizmat/IRC-Client-Plugin-Rakkable/actions)
# NAME
IRC::Client::Plugin::Rakkable - local rak searches by bot
# SYNOPSIS
```
use IRC::Client;
use IRC::Client::Plugin::Rakkable;
.run with IRC::Client.new(
:nick<Rakkable>,
:host<irc.libera.chat>,
:channels<#raku-dev #moarvm>,
:plugins(IRC::Client::Plugin::Rakkable.new(
)),
);
```
# DESCRIPTION
The `IRC::Client::Plugin::Rakkable` distribution provides an interface to run local `rak` searches and produce results of them on IRC channels (and gist results for further perusal).
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
Source can be located at: <https://github.com/lizmat/IRC-Client-Plugin-Rakkable> . 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 2025 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-lizmat-Zef-Configuration.md
[](https://github.com/lizmat/Zef-Configuration/actions) [](https://github.com/lizmat/Zef-Configuration/actions) [](https://github.com/lizmat/Zef-Configuration/actions)
# NAME
Zef::Configuration - Manipulate Zef configurations
# SYNOPSIS
```
use Zef::Configuration;
my $zc = Zef::Configuration.new; # factory settings
my $zc = Zef::Configuration.new(:user); # user settings
my $zc = Zef::Configuration.new($io); # from a config file path
```
Or use the command-line interface:
```
$ zef-configure
$ zef-configure enable something
$ zef-configure disable something
$ zef-configure reset
```
# DESCRIPTION
Zef::Configuration is a class that allows you to manipulate the configuration of Zef programmatically. Perhaps more importantly, it provides a command-line script `zef-configure` that allows you to perform simple actions to Zef's config-files.
# COMMAND-LINE INTERFACE
## General named arguments
### config-path
```
$ zef-configure --config-path=~/.zef/config.json
```
The `config-path` named argument can be used to indicate the location of the configuration to read from / write to.
### dry-run
```
$ zef-configure enable rea --dry-run
```
The `dry-run` named argument can be used to inhibit writing any changes to the configuration file.
## Possible actions
The `zef-configure` script that is installed with this module, allows for the following actions. Please note that sub-commands (such as "enable") can be shortened as long as they are not ambiguous..
## Getting an overview
```
$ zef-configure
```
Calling `zef-configure` without any parameters (except maybe the `config-path` parameter) will show an overview of all the settings in the configuration. The names shown can be used to indicate what part of the configuration you want changed.
## Enabling a setting
```
$ zef-configure enable rea
```
If a setting is disabled, then you can enable it with the `enable` directive, followed by the name of the setting you want enabled.
## Disabling a setting
```
$ zef-configure disable cpan
```
If a setting is enabled, then you can disable it with the `disable` directive, followed by the name of the setting you want disabled.
## Reset to factory settings
```
$ zef-configure reset
```
To completely reset a configuration to the "factory" settings, you can use the `reset` directive.
```
$ zef-configure reset --config-path=~/.zef/config.json
```
You can also use this function in combination with `config-=path` to create a configuration file with the "factory" settings.
# GENERAL NOTES
All of the attributes of the classes provided by this distribution, are either an `Array` (and thus mutable), or a an attribute with the `is rw` trait applied to it. This is generally ok, since it is expected that this module will mostly only be used by a relatively short-lived CLI.
Note that if you change an object that is based on one of the default objects, you will be changing the default as well. This may or may not be what you want. If it is not, then you should probably first create a `clone` of the object, or use the `clone` method with named arguments to create a clone with changed values.
# METHODS ON ALL CLASSES
All of these classes provided by this distribution provide these methods (apart from the standard methods provided by Raku).
### new
Apart from the normal way of creating objects with named arguments, one can also specify a hash as returned with `data` to create an object.
### data
Return a Raku data-structure for the object. This is usually a `Map`, but can also be a `List`.
### json
Return a pretty JSON string with sorted keys for the object. Takes named parameters `:!pretty` and `:!sorted-keys` should you not want the JSON string to be pretty, or have sorted keys.
### status
Return a string describing the status of the object.
# METHODS ON MOST CLASSES
With the exception of the `Zef::Configuration`, `Zef::Configuration::License` and `Zef::Configuration::RepositoryGroup` classes, the following attributes / methods are always provided.
### short-name
A name identifying the object. **Must** be specified in the creation of the object.
### module
The name of the Raku module to be used by this object. **Must** be specified in the creation of the object unless there is a default available for the given object.
### enabled
A boolean indicating whether the object is enabled. Defaults to `True`.
### comment
Any comments applicable to this object. Defaults to the `Str` type object.
# Zef::Configuration
The `Zef::Configuration` class contains all information about a configuration of `Zef`. A `Zef::Configuration` object can be made in 6 different ways:
## CREATION
```
my $zc = Zef::Configuration.new; # "factory settings"
my $zc = Zef::Configuration.new(:user); # from the user's Zef config
my $zc = Zef::Configuration.new($io); # from a file as an IO object
my $zc = Zef::Configuration.new($json); # a string containing JSON
my $zc = Zef::Configuration.new(%hash); # a hash, as decoded from JSON
my $zc = Zef::Configuration.new: # named arguments to set attributes
ConfigurationVersion => 2,
RootDir => 'foo/bar',
...
;
```
## ATTRIBUTES / METHODS
It contains the following attributes / methods:
### ConfigurationVersion
The version of the configuration. Defaults to `1`.
### RootDir
The directory in which Zef keeps all of its information. Defaults to `$*HOME/.zef`.
### StoreDir
The directory in which Zef keeps all of the information that has been downloaded. Defaults to `RootDir ~ "/store"`.
### TempDir
The directory in which Zef stores temporary files. Defaults to `RootDir ~ "/tmp"`.
### License
A `Zef::Configuration::License` object. Defaults to `Zef::Configuration.default-licenses<default>`.
### Repository
An array of `Zef::Configuration::RepositoryGroup` objects in the order in which they will be checked when searching for distributions. Defaults to `Zef::Configuration.default-repository-groups` in the order: `primary`, `secondary`, `tertiary`, `last`.
### Fetch
An array of `Zef::Configuration::Fetch` objects. Defaults to `Zef::Configuration.default-fetch`.
### Extract
An array of `Zef::Configuration::Extract` objects. Defaults to `Zef::Configuration.default-extract`.
### Build
An array of `Zef::Configuration::Build` objects. Defaults to `Zef::Configuration.default-build`.
### Test
An array of `Zef::Configuration::Test` objects. Defaults to `Zef::Configuration.default-test`.
### Report
An array of `Zef::Configuration::Report` objects. Defaults to `Zef::Configuration.default-report`.
### Install
An array of `Zef::Configuration::Install` objects. Defaults to `Zef::Configuration.default-install`.
### DefaultCUR
An array of strings indicating which `CompUnitRepository`(s) to be used when installing a module. Defaults to `Zef::Configuration.default-defaultCUR`.
## ADDITIONAL CLASS METHODS
### is-configuration-writeable
Class method that takes an `IO::Path` of a configuration file (e.g. as returned by `user-configuration`) and returns whether that file is safe to write to (files part of the installation should not be written to).
### new-user-configuration
Class method that returns an `IO::Path` with location at which a new configuration file can be stored, to be visible with future default incantations of Zef. Returns `Nil` if no such location could be found.
### user-configuration
Class method that returns an `IO::Path` object of the configuration file that Zef is using by default.
## ADDITIONAL INSTANCE METHODS
### default-...
Instance methods for getting the default state of a given aspect of the `Zef::Configuration` object.
* default-license
* default-repository
* default-repositorygroup
* default-fetch
* default-extract
* default-build
* default-test
* default-report
* default-install
* default-defaultCUR
Each of these can either called without any arguments: in that case a `Map` will be returned with each of the applicable objects, associated with a **tag**. Or it can be called with one of the valid tags, in which case the associated object will be returned.
### object-from-tag
Instance method that allows selection of an object by its tag (usually the `short-name`) in one of the attributes of the `Zef::Configuration` object.
Tags can be specified just by themselves if they are not ambiguous, else the group name should be prefixed with a hyphen inbetween (e.g. `license-default`).
If an ambiguous tag is given, then a `List` of `Pair`s will be returned in which the key is a group name, and the value is the associated object.
If only one object was found, then that will be returned. If no objects were found, then `Nil` will be returned.
## Zef::Configuration::License
Contains which licenses are `blacklist`ed and which ones are `whitelist`ed. Defaults to no blacklisted licenses, and `"*"` in the whitelist, indicating that any license will be acceptable. Does not contain any other information.
## Zef::Configuration::Repository
Contains the information about a repository in which distributions are located. It provided these additional attributes / methods:
### name
The full name of the repository. Defaults to the `short-name`.
### module
The Raku module to be used for handling the `Zef::Configuration::Repository` defaults to `Zef::Repository::Ecosystems`.
### auto-update
The number of hours that should pass until a local copy of the distribution information about a repository should be considered stale. Defaults to `1`.
### uses-path
A boolean indicating whether the `path` field in the distribution should be used to obtain a distribution. Defaults to `False`, unless the repository's `short-name` equals `zef`.
### mirrors
An array of URLs that should be used to fetch the information about all the distributions in the repository. **Must** be specified with the URL of at least one mirror if `auto-update` has been (implicitely) set to a non-zero value.
## Zef::Configuration::RepositoryGroup
Contains a list of `Zef::Configuration::Repository` objects in the order in which a search should be done for modules. Does not contain any other information.
## Zef::Configuration::Fetch
Information on how to fetch a distribution from a `Zef::Configuration::Repository`.
## Zef::Configuration::Extract
Information on how to extract information from a fetched distribution.
## Zef::Configuration::Build
Information on how to build modules from a fetched distribution.
## Zef::Configuration::Test
Information on how to perform tesing on a fetched distribution.
## Zef::Configuration::Report
Information about how a report of a distribution test should be reported.
## Zef::Configuration::Install
Information about how a distribution should be installed.
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
Source can be located at: <https://github.com/lizmat/Zef-Configuration> . 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, 2023, 2024, 2025 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## 5to6-overview.md
Perl to Raku guide - overview
How do I do what I used to do?
These documents should not be mistaken for a beginner tutorial or a promotional overview of Raku (née Perl 6); it is intended as a technical reference for Raku learners with a strong Perl background and for anyone porting Perl code to Raku.
# [Raku in a nutshell](#Perl_to_Raku_guide_-_overview "go to top of document")[§](#Raku_in_a_nutshell "direct link")
[Raku in a Nutshell](/language/5to6-nutshell) provides a quick overview of things changed in syntax, operators, compound statements, regular expressions, command-line flags, and various other bits and pieces.
# [Syntactic differences](#Perl_to_Raku_guide_-_overview "go to top of document")[§](#Syntactic_differences "direct link")
The [Syntax section](/language/5to6-perlsyn) provides an overview of the syntactic differences between Perl and Raku: how it is still mostly free form, additional ways to write comments, and how `switch` is very much a Raku thing.
# [Operators in Raku](#Perl_to_Raku_guide_-_overview "go to top of document")[§](#Operators_in_Raku "direct link")
The [Operators section](/language/5to6-perlop) guides you from the operators in [Perl's perlop](https://metacpan.org/pod/distribution/perl/pod/perlop.pod) to the equivalent in Raku.
# [Functions in Raku](#Perl_to_Raku_guide_-_overview "go to top of document")[§](#Functions_in_Raku "direct link")
The [Functions section](/language/5to6-perlfunc) describes all of the Perl functions and their Raku equivalent and any differences in behavior. It also provides references to ecosystem modules that provide the Perl behavior of functions, either existing in Raku with slightly different semantics (such as `shift`), or non-existing in Raku (such as `tie`).
# [Special variables in Raku](#Perl_to_Raku_guide_-_overview "go to top of document")[§](#Special_variables_in_Raku "direct link")
The [Special Variables section](/language/5to6-perlvar) describes if and how a lot of Perl's special (punctuation) variables are supported in Raku.
|
## dist_zef-jjmerelo-GitHub-Actions.md
# GitHub::Actions for Raku [Test in a Raku container - template](https://github.com/JJ/raku-github-actions/actions/workflows/test.yaml)
Use the GitHub actions console API easily from Raku. Essentially, a port to
Raku of the [equivalent Perl module](https://metacpan.org/pod/GitHub::Actions). It's mainly intended to be run inside the [Raku
container for GitHub actions](https://github.com/JJ/alpine-raku), but can of
course be used independently.
## Installing
Install it the usual way, using `zef`:
```
zef install GitHub::Actions
```
Also use it from the companion Docker image,
```
docker pull --rm -it --entrypoint=/bin/sh ghcr.io/jj/raku-github-actions:latest
```
## Running
This is a version derived from the base [Raku image for
GHA](ghcr.io/jj/raku-zef-gha) with this module and its dependencies
installed. You can use it directly in your GitHub actions, for instance like
this:
```
- name: Test output
id: output_test
shell: raku {0}
run:
use GitHub::Actions;
set-output( 'FOO', 'BAR');
```
Check [the Pod6 here](lib/GitHub/Actions.rakumod) for methods available.
## Synopsis
```
use GitHub::Actions:
say %github; # Contains all GITHUB_xyz variables
set-output('FOO','BAR');
set-output('FOO'); # Empty value
set-env("FOO", "bar");
debug('FOO');
error('FOO');
warning('FOO');
error-on-file('FOO', 'foo.pl', 1,1 );
warning-on-file('FOO', 'foo.raku', 1,1 );
# sets group
start-group( "foo" );
warning("bar");
end-group;
```
## See also
Created from the
[Raku distribution template](https://github.com/JJ/raku-dist-template).
## License
(c) JJ Merelo, [[email protected]](mailto:[email protected]), 2022
Licensed, under the Artistic 2.0 License (the same as Raku itself).
|
## dist_zef-lizmat-ValueTypeCache.md
[](https://github.com/lizmat/ValueTypeCache/actions) [](https://github.com/lizmat/ValueTypeCache/actions) [](https://github.com/lizmat/ValueTypeCache/actions)
# NAME
ValueTypeCache - A role to cache Value Type classes
# SYNOPSIS
```
use ValueTypeCache;
sub id(%h --> Str:D) {
%h<x> //= 0;
%h<y> //= 0;
"%h<x>,%h<y>"
}
class Point does ValueTypeCache[&id] {
has $.x;
has $.y;
}
say Point.new.WHICH; # Point|0,0
# fill a bag with random Points
my $bag = bag (^1000).map: {
Point.new: x => (-10..10).roll, y => (-10..10).roll
}
say $bag.elems; # less than 1000
```
# DESCRIPTION
The `ValueTypeCache` distribution provides a `ValueTypeCache` role that mixes the logic of creating a proper ValueType class **and** making sure that each unique ValueType only exists once in memory, into a single class.
The role takes a `Callable` parameterization to indicate how a unique ID should be created from the parameters given (as a hash) with the call to the `new` method. You can also adapt the given hash making sure any default values are properly applied. If there's already an object created with the returned ID, then no new object will be created but the one from the cache will be returned.
A class is considered to be a value type if the `.WHICH` method returns an object of the `ValueObjAt` class: that then indicates that objects that return the same `WHICH` value, are in fact identical and can be used interchangeably.
This is specifically important when using set operators (such as `(elem)`, or `Set`s, `Bag`s or `Mix`es, or any other functionality that is based on the `===` operator functionality, such as `unique` and `squish`.
The format of the value that is being returned by `WHICH` is only valid during a run of a process. So it should **not** be stored in any permanent medium.
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
Source can be located at: <https://github.com/lizmat/ValueTypeCache> . Comments and Pull Requests are welcome.
If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!
# COPYRIGHT AND LICENSE
Copyright 2020, 2021, 2024, 2025 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-jjmerelo-IO-Capture-Simple.md
# IO::Capture::Simple
This is a Raku implementation of IO capturing module.
It provides two modules, [`IO::Capture::Simple`](lib/IO/Capture/Simple.pm6) and [`Test::IO::Capture`](lib/Test/IO/Capture.pm6), to capture and test the output of commands.
## Original author
This module was created originally by [Filip Sergot](https://github.com/sergot/IO-Capture-Simple), and has been forked respecting its free License
## License
This code is (c) Filip Sergot, 2018, JJ Merelo 2022. It's released under the
Artistic 2.0 license.
|
## dist_zef-jonathanstowe-Pg-Notify.md
# PG::Notify
Raku interface to PostgresQL notifies.

## Synopsis
```
use Pg::Notify;
use DBIish;
my $db = DBIish.connect('Pg', database => "dbdishtest");
my $channel = "test";
my $notify = Pg::Notify.new(:$db, :$channel );
react {
whenever $notify -> $notification {
say $notification.extra;
}
# Provide a notification
whenever Supply.interval(1) -> $v {
$db.do("NOTIFY $channel, '$v'");
}
}
```
## Description
This provides a simple mechanism to get a supply of the PostgresQL
notifications for a particular *channel*. The supply will emit a stream
of `pg-notify` objects corresponding to a `NOTIFY` executed on
the connected Postgres database.
Typically the `NOTIFY` will be invoked in a trigger or other server
side code but could just as easily be in some other user code (as in
the Synopsis above,)
The objects of type `Pg::Notify` have a `Supply` method that
allows coercion in places that expect a Supply (such as `whenever`
in the Synopsis above.) but you can this Supply directly if you want to
`tap` it for instance.
## Install
This relies on [DBIish](https://github.com/raku-community-modules/DBIish) and ideally
you will have a working PostgreSQL database connection for the user that you will run the tests as.
For the tests you can control how it connects to the database with the
environment variables:
* $PG\_NOTIFY\_DB - the name of the database you want to use, otherwise `dbdishtest`
* $PG\_NOTIFY\_USER - the username to be used, (otherwise will connect as the current user,)
* $PG\_NOTIFY\_PW - the password to be used, (otherwise no password will be used.)
* $PG\_NOTIFY\_HOST - the host to which the DB connection will made, the default is to connect to a local PG server.
These should be set before the tests (or install,) are run.
Assuming you have a working Rakudo installation you should just be able to use *zef* :
```
zef install Pg::Notify
# or from a local copy
zef install .
```
But I can't think there should be any problem with any installer that may come along in the future.
## Support
This relies on the `poll` C library function, on Linux this is part
of the runtime library that is always loaded but it might not be on other
operating systems, if you have one of those systems I'd be grateful for
a patch to make it work there.
If you have any other suggestions or problems please report at
<https://github.com/jonathanstowe/Pg-Notify/issues>
## Copyright and Licence
This is free software, please see the <LICENCE> file in the distribution.
© Jonathan Stowe 2017 - 2021
|
## dist_cpan-FCO-Cro-HTTP-Session-Red.md
[](https://travis-ci.org/FCO/Cro-HTTP-Session-Red)
# NAME
Cro::HTTP::Session::Red - Plugin for Cro to use Red as session manager
# SYNOPSIS
```
# service.pl
use Cro::HTTP::Log::File;
use Cro::HTTP::Server;
use Routes;
use Red;
$GLOBAL::RED-DB = database "SQLite", :database("{%*ENV<HOME>}/test.db");
$GLOBAL::RED-DEBUG = so %*ENV<RED_DEBUG>;
User.^create-table: :if-not-exists;
UserSession.^create-table: :if-not-exists;
try User.^create: :name<CookieMonster>, :email<[email protected]>, :password("1234");
my Cro::Service $http = Cro::HTTP::Server.new(
http => <1.1>,
host => %*ENV<CLASSIFIED_HOST> ||
die("Missing CLASSIFIED_HOST in environment"),
port => %*ENV<CLASSIFIED_PORT> ||
die("Missing CLASSIFIED_PORT in environment"),
application => routes(),
after => [
Cro::HTTP::Log::File.new(logs => $*OUT, errors => $*ERR)
]
);
$http.start;
say "Listening at http://%*ENV<CLASSIFIED_HOST>:%*ENV<CLASSIFIED_PORT>";
react {
whenever signal(SIGINT) {
say "Shutting down...";
$http.stop;
done;
}
}
# lib/Routes.pm6
use Cro::HTTP::Router;
use Cro::HTTP::Session::Red;
use Red;
model UserSession { ... }
model User is table<account> {
has UInt $!id is serial;
has Str $.name is column;
has Str $.email is column{ :unique };
has Str $.password is column;
has UserSession @.sessions is relationship{ .uid }
method check-password($password) {
$password eq $!password
}
}
model UserSession is table<logged_user> does Cro::HTTP::Auth {
has Str $.id is id;
has UInt $.uid is referencing{ User.id };
has User $.user is relationship{ .uid } is rw;
}
sub routes() is export {
route {
before Cro::HTTP::Session::Red[UserSession].new: cookie-name => 'MY_SESSION_COOKIE_NAME';
get -> UserSession $session (User :$user, |) {
content 'text/html', "<h1> Logged User: $user.name() </h1>";
}
get -> 'login' {
content 'text/html', q:to/HTML/;
<form method="POST" action="/login">
<div>
Username: <input type="text" name="email" />
</div>
<div>
Password: <input type="password" name="password" />
</div>
<input type="submit" value="Log In" />
</form>
HTML
}
post -> UserSession $session, 'login' {
request-body -> (Str() :$email, Str() :$password, *%) {
my $user = User.^load: :$email;
if $user.?check-password: $password {
$session.user = $user;
$session.^save;
redirect '/', :see-other;
}
else {
content 'text/html', "Bad username/password";
}
}
}
}
}
```
# DESCRIPTION
Cro::HTTP::Session::Red is a Plugin for Cro to use Red as session manager. You can create any custom Red model to store the Cro session, but its id must be a Str and the generated session string will be used as the id.
# AUTHOR
Fernando Correa de Oliveira [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2019 Fernando Correa de Oliveira
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## embedded.md
class X::Syntax::Comment::Embedded
Compilation error due to a malformed inline comment
```raku
class X::Syntax::Comment::Embedded does X::Syntax { }
```
Syntax error thrown when `#`` is encountered and it is not followed by an opening curly brace.
For example
```raku
#`
```
dies with
「text」 without highlighting
```
```
===SORRY!===
Opening bracket is required for #` comment
```
```
|
## packagehow.md
class Metamodel::PackageHOW
Metaobject representing a Raku package.
```raku
class Metamodel::PackageHOW
does Metamodel::Naming
does Metamodel::Documenting
does Metamodel::Stashing
does Metamodel::TypePretense
does Metamodel::MethodDelegation { }
```
*Warning*: this class is part of the Rakudo implementation, and is not a part of the language specification.
`Metamodel::PackageHOW` is the metaclass behind the `package` keyword.
```raku
package P {};
say P.HOW; # OUTPUT: «Perl6::Metamodel::PackageHOW.new»
```
# [Methods](#class_Metamodel::PackageHOW "go to top of document")[§](#Methods "direct link")
## [method archetypes](#class_Metamodel::PackageHOW "go to top of document")[§](#method_archetypes "direct link")
```raku
method archetypes()
```
Returns the archetypes for this model, that is, the properties a metatype can implement.
## [method new](#class_Metamodel::PackageHOW "go to top of document")[§](#method_new "direct link")
```raku
method new(*%named)
```
Creates a new `PackageHOW`.
## [method new\_type](#class_Metamodel::PackageHOW "go to top of document")[§](#method_new_type "direct link")
```raku
method new_type(:$name = '<anon>', :$repr, :$ver, :$auth)
```
Creates a new package, with optional representation, version and auth field.
## [compose](#class_Metamodel::PackageHOW "go to top of document")[§](#compose "direct link")
```raku
method compose($obj, :$compiler_services)
```
Sets the metapackage as composed.
## [is\_composed](#class_Metamodel::PackageHOW "go to top of document")[§](#is_composed "direct link")
```raku
method is_composed($obj)
```
Returns the composed status of the metapackage.
|
## fallback.md
FALLBACK
Combined from primary sources listed below.
# [In Nil](#___top "go to top of document")[§](#(Nil)_method_FALLBACK "direct link")
See primary documentation
[in context](/type/Nil#method_FALLBACK)
for **method FALLBACK**.
```raku
method FALLBACK(| --> Nil) {}
```
The [fallback method](/language/typesystem#index-entry-FALLBACK_(method)) takes any arguments and always returns a `Nil`.
|
## invalidformat.md
class X::Temporal::InvalidFormat
Error due to using an invalid format when creating a DateTime or Date
```raku
class X::Temporal::InvalidFormat does X::Temporal is Exception { }
```
This exception is thrown when code tries to create a [`DateTime`](/type/DateTime) or [`Date`](/type/Date) object using an invalid format.
```raku
my $dt = Date.new("12/25/2015");
CATCH { default { put .^name, ': ', .Str } };
# OUTPUT: «X::Temporal::InvalidFormat: Invalid Date string '12/25/2015'; use yyyy-mm-dd instead»
```
# [Methods](#class_X::Temporal::InvalidFormat "go to top of document")[§](#Methods "direct link")
## [method invalid-str](#class_X::Temporal::InvalidFormat "go to top of document")[§](#method_invalid-str "direct link")
Returns the invalid format string (`12/25/2015` in the example above)
## [method target](#class_X::Temporal::InvalidFormat "go to top of document")[§](#method_target "direct link")
Returns the target type ([`Date`](/type/Date) in the example above)
## [method format](#class_X::Temporal::InvalidFormat "go to top of document")[§](#method_format "direct link")
Returns valid format strings for the target type in question, (`yyyy-mm-dd` in the example above)
|
## dist_zef-FRITH-Math-Libgsl-Statistics.md
[](https://github.com/frithnanth/raku-Math-Libgsl-Statistics/actions)
# NAME
Math::Libgsl::Statistics - An interface to libgsl, the Gnu Scientific Library - Statistics
# SYNOPSIS
```
use Math::Libgsl::Statistics;
my @data = ^10;
say "mean = { mean(@data) }, variance = { variance(@data) }";
```
# DESCRIPTION
Math::Libgsl::Statistics is an interface to the Statistics functions of libgsl, the Gnu Scientific Library.
The functions in this module come in 10 data types:
* Math::Libgsl::Statistics (default: num64)
* Math::Libgsl::Statistics::Num32
* Math::Libgsl::Statistics::Int8
* Math::Libgsl::Statistics::Int16
* Math::Libgsl::Statistics::Int32
* Math::Libgsl::Statistics::Int64
* Math::Libgsl::Statistics::UInt8
* Math::Libgsl::Statistics::UInt16
* Math::Libgsl::Statistics::UInt32
* Math::Libgsl::Statistics::UInt64
All the following functions are available in the modules correspondiing to each datatype, except where noted.
### mean(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function returns the arithmetic mean of @data.
### variance(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function returns the estimated variance of @data. This function computes the mean, if you already computed the mean, use the next function.
### variance-m(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride)
This function returns the sample variance of @data relative to the given value of $mean.
### sd(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function returns the estimated standard deviation of @data.
### sd-m(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function returns the sample standard deviation of @data relative to the given value of $mean.
### tss(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
These functions return the total sum of squares (TSS) of @data.
### tss-m(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
These functions return the total sum of squares (TSS) of @data relative to the given value of $mean.
### variance-with-fixed-mean(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes an unbiased estimate of the variance of @data when the population mean $mean of the underlying distribution is known a priori.
### sd-with-fixed-mean(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function calculates the standard deviation of @data for a fixed population mean $mean.
### absdev(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the absolute deviation from the mean of @data.
### absdev-m(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the absolute deviation of the dataset @data relative to the given value of $mean.
### skew(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the skewness of @data.
### skew-m-sd(@data!, Num() $mean!, Num() $sd!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the skewness of the dataset @data using the given values of the mean $mean and standard deviation $sd,
### kurtosis(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the kurtosis of @data.
### kurtosis-m-sd(@data!, Num() $mean!, Num() $sd!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the kurtosis of the dataset @data using the given values of the mean $mean and standard deviation $sd,
### autocorrelation(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the lag-1 autocorrelation of the dataset @data.
### autocorrelation-m(@data!, Num() $mean!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the lag-1 autocorrelation of the dataset @data using the given value of the mean $mean.
### covariance(@data1!, @data2! where \*.elems == @data1.elems, Int() :$stride1? = 1, Int() :$stride2? = 1, Int() :$n? = (@data1.elems / $stride1).Int --> Num)
This function computes the covariance of the datasets @data1 and @data2.
### covariance-m(@data1!, @data2! where \*.elems == @data1.elems, Num() $mean1!, Num() $mean2!, Int() :$stride1? = 1, Int() :$stride2? = 1, Int() :$n? = (@data1.elems / $stride1).Int --> Num)
This function computes the covariance of the datasets @data1 and @data2 using the given values of the means, $mean1 and $mean2.
### correlation(@data1!, @data2! where \*.elems == @data1.elems, Int() :$stride1? = 1, Int() :$stride2? = 1, Int() :$n? = (@data1.elems / $stride1).Int --> Num)
This function efficiently computes the Pearson correlation coefficient between the datasets @data1 and @data2.
### spearman(@data1!, @data2! where \*.elems == @data1.elems, Int() :$stride1? = 1, Int() :$stride2? = 1, Int() :$n? = (@data1.elems / $stride1).Int --> Num)
This function computes the Spearman rank correlation coefficient between the datasets @data1 and @data2.
### wmean(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function returns the weighted mean of the dataset @data using the set of weights @w. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wvariance(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function returns the estimated variance of the dataset @data using the set of weights @w. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wvariance-m(@w!, @data!, Num() $wmean!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function returns the estimated variance of the weighted dataset @data using the given weighted mean $wmean. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wsd(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function returns the standard deviation of the weighted dataset @data. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wsd-m(@w!, @data!, Num() $wmean!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function returns the standard deviation of the weighted dataset @data using the given weighted mean $wmean. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wvariance-with-fixed-mean(@w!, @data!, Num() $mean!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes an unbiased estimate of the variance of the weighted dataset @data when the population mean $mean of the underlying distribution is known a priori. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wsd-with-fixed-mean(@w!, @data!, Num() $mean!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes an unbiased estimate of the standard deviation of the weighted dataset @data when the population mean $mean of the underlying distribution is known a priori. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wtss(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
These functions return the weighted total sum of squares (TSS) of @data. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wtss-m(@w!, @data!, Num() $wmean!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
These functions return the weighted total sum of squares (TSS) of @data when the population mean $mean of the underlying distribution is known a priori. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wabsdev(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the weighted absolute deviation from the weighted mean of @data. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wabsdev-m(@w!, @data!, Num() $wmean!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the absolute deviation of the weighted dataset @data about the given weighted mean $wmean. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wskew(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the weighted skewness of the dataset @data. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wskew-m-sd(@w!, @data!, Num() $wmean!, Num() $wsd!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the weighted skewness of the dataset @data using the given values of the weighted mean and weighted standard deviation, $wmean and $wsd. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wkurtosis(@w!, @data!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the weighted kurtosis of the dataset @data. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### wkurtosis-m-sd(@w!, @data!, Num() $wmean!, Num() $wsd!, Int() :$wstride? = 1, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function computes the weighted kurtosis of the dataset @data using the given values of the weighted mean and weighted standard deviation, $wmean and $wsd. This function is available only for Numeric types, so only when using Math::Libgsl::Statistics or Math::Libgsl::Statistics::Num32.
### smax(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function returns the maximum value in @data.
### smin(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function returns the minimum value in @data.
### sminmax(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> List)
This function returns both the minimum and maximum values in @data in a single pass.
### smax-index(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Int)
This function returns the index of the maximum value in @data.
### smin-index(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Int)
This function returns the index of the minimum value in @data.
### sminmax-index(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> List)
This function returns the indexes of the minimum and maximum values in @data in a single pass.
### median-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num)
This function returns the median value of @sorted-data.
### median(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function returns the median value of @data.
### quantile-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Num() $percentile!, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num)
This function returns a quantile value of @sorted-data. The quantile is determined by the $percentile, a fraction between 0 and 1. For example, to compute the value of the 75th percentile $percentile should have the value 0.75.
### select(@data!, Int() $k, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
This function finds the k-th smallest element of the input array @data.
### trmean-from-sorted-data(Num() $alpha, @sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num)
This function returns the trimmed mean of @sorted-data.
### gastwirth-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num)
This function returns the Gastwirth location estimator of @sorted-data.
### mad0(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
### mad(@data!, Int() :$stride? = 1, Int() :$n? = (@data.elems / $stride).Int --> Num)
These functions return the median absolute deviation of @data. The mad0 function calculates the MAD statistic without the bias correction scale factor.
### Sn0-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num)
### Sn-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num)
These functions return the Sₙ statistic of @sorted-data. The Sn0 function calculates the Sₙ statistic without the bias correction scale factors.
### Qn0-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num)
### Qn-from-sorted-data(@sorted-data! where { [<] @sorted-data }, Int() :$stride? = 1, Int() :$n? = (@sorted-data.elems / $stride).Int --> Num)
These functions return the Qₙ statistic of @sorted-data. The Qn0 function calculates the Qₙ statistic without the bias correction scale factors.
# C Library Documentation
For more details on libgsl see <https://www.gnu.org/software/gsl/>. The excellent C Library manual is available here <https://www.gnu.org/software/gsl/doc/html/index.html>, or here <https://www.gnu.org/software/gsl/doc/latex/gsl-ref.pdf> in PDF format.
# Prerequisites
This module requires the libgsl library to be installed. Please follow the instructions below based on your platform:
## Debian Linux and Ubuntu 20.04+
```
sudo apt install libgsl23 libgsl-dev libgslcblas0
```
That command will install libgslcblas0 as well, since it's used by the GSL.
## Ubuntu 18.04
libgsl23 and libgslcblas0 have a missing symbol on Ubuntu 18.04. I solved the issue installing the Debian Buster version of those three libraries:
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgslcblas0_2.5+dfsg-6_amd64.deb>
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl23_2.5+dfsg-6_amd64.deb>
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl-dev_2.5+dfsg-6_amd64.deb>
# Installation
To install it using zef (a module management tool):
```
$ zef install Math::Libgsl::Statistics
```
# AUTHOR
Fernando Santagata [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2020 Fernando Santagata
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## ratstr.md
class RatStr
Dual value rational number and string
```raku
class RatStr is Allomorph is Rat {}
```
`RatStr` is a dual value type, a subclass of both [`Allomorph`](/type/Allomorph), hence [`Str`](/type/Str), and [`Rat`](/type/Rat).
See [`Allomorph`](/type/Allomorph) for further details.
```raku
my $rat-str = <42.1>;
say $rat-str.^name; # OUTPUT: «RatStr»
my Rat $rat = $rat-str; # OK!
my Str $str = $rat-str; # OK!
# ∈ operator cares about object identity
say 42.1 ∈ <42.1 55 1>; # OUTPUT: «False»
```
# [Methods](#class_RatStr "go to top of document")[§](#Methods "direct link")
## [method new](#class_RatStr "go to top of document")[§](#method_new "direct link")
```raku
method new(Rat $i, Str $s)
```
The constructor requires both the [`Rat`](/type/Rat) and the [`Str`](/type/Str) value, when constructing one directly the values can be whatever is required:
```raku
my $f = RatStr.new(42.1, "forty two and a bit");
say +$f; # OUTPUT: «42.1»
say ~$f; # OUTPUT: «"forty two and a bit"»
```
## [method Capture](#class_RatStr "go to top of document")[§](#method_Capture "direct link")
```raku
method Capture(RatStr:D: --> Capture:D)
```
Equivalent to [`Mu.Capture`](/type/Mu#method_Capture).
## [method Numeric](#class_RatStr "go to top of document")[§](#method_Numeric "direct link")
```raku
multi method Numeric(RatStr:D: --> Rat:D)
multi method Numeric(RatStr:U: --> Rat:D)
```
The `:D` variant returns the numeric portion of the invocant. The `:U` variant issues a warning about using an uninitialized value in numeric context and then returns value `0.0`.
## [method Rat](#class_RatStr "go to top of document")[§](#method_Rat "direct link")
```raku
method Rat
```
Returns the [`Rat`](/type/Rat) value of the `RatStr`.
## [method Real](#class_RatStr "go to top of document")[§](#method_Real "direct link")
```raku
multi method Real(Real:D: --> Rat:D)
multi method Real(Real:U: --> Rat:D)
```
The `:D` variant returns the numeric portion of the invocant. The `:U` variant issues a warning about using an uninitialized value in numeric context and then returns value `0.0`.
# [Operators](#class_RatStr "go to top of document")[§](#Operators "direct link")
## [infix `===`](#class_RatStr "go to top of document")[§](#infix_=== "direct link")
```raku
multi infix:<===>(RatStr:D $a, RatStr:D $b)
```
`RatStr` Value identity operator. Returns `True` if the [`Rat`](/type/Rat) values of `$a` and `$b` are [identical](/routine/===) and their [`Str`](/type/Str) values are also [identical](/routine/===). Returns `False` otherwise.
# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")
Type relations for `RatStr`
raku-type-graph
RatStr
RatStr
Allomorph
Allomorph
RatStr->Allomorph
Rat
Rat
RatStr->Rat
Mu
Mu
Any
Any
Any->Mu
Cool
Cool
Cool->Any
Stringy
Stringy
Str
Str
Str->Cool
Str->Stringy
Allomorph->Str
Numeric
Numeric
Real
Real
Real->Numeric
Rational
Rational
Rational->Real
Rat->Cool
Rat->Rational
[Expand chart above](/assets/typegraphs/RatStr.svg)
|
## dist_github-FCO-Test-Time.md
[](https://travis-ci.org/FCO/test-time)
# Test::Time
Use **Test::Scheduler** to use on your tests, not only Promises, but **sleep**, **now** and time.
```
my $started = now;
$*SCHEDULER = mock-time :auto-advance;
sleep 10;
say "did it passed { now - $started } seconds?";
unmock-time;
say "No, just passed { now - $started } seconds!";
#`{{{
Output:
did it passed 10.0016178 seconds?
No, just passed 0.07388266 seconds!
}}}
```
Or you can use `$*SCHEDULER.advance-by: 10` as you would when using **Test::Scheduler**
|
## dist_github-skinkade-Crypt-Bcrypt.md
# Crypt::Bcrypt
[](https://travis-ci.org/skinkade/p6-Crypt-Bcrypt)
Easy `bcrypt` password hashing in Perl6.
## Synopsis
Password hashing and verification are one function each, and utilize a
crypt()-style output string:
```
> use Crypt::Bcrypt;
> my $hash = bcrypt-hash("password")
$2b$12$EFUDTFQAf/6YwmnN/FKyX.kH0BsE/YNExuIQcI1WZXO/rwkmD8G2S
> bcrypt-match("password", $hash)
True
> bcrypt-match("wrong", $hash)
False
> bcrypt-hash("password", :rounds(15))
$2b$15$BcxIqbIcb1bDt3SHkEjO/ePcdeNV8f2xeFSQTyoiidYGUA03lptrm
```
## Credit
This module uses the Openwall crypt\_blowfish library by Solar Designer. See <http://www.openwall.com/crypt/> and the header of
[crypt\_blowfish.c](ext/crypt_blowfish-1.3/crypt_blowfish.c) for details.
## License
The Openwall library is licensed and redistributed under the terms outlined in the header of [crypt\_blowfish.c](ext/crypt_blowfish-1.3/crypt_blowfish.c). Any modifications are released under the same terms.
This module is released under the terms of the ISC License.
See the <LICENSE> file for details.
|
## dist_github-mj41-SP6.md
# SP6 - Simple Raku templates
## Examples
```
> cat t/templ/base.sp6 ; echo
foobar
> raku -Ilib bin/sp6 --templ_dir=t/templ -e='aa {include "base.sp6"} bb'
aa foobar bb
> cat t/templ/inside-outher.sp6 ; echo
outherA {main_part} outherB
> raku -Ilib bin/sp6 --templ_dir=t/templ -e='aa {include "base.sp6"} bb' --inside=inside-outher.sp6
outherA aa foobar bb outherB
raku -Ilib bin/sp6 --templ_dir=../BrnoPM-Web/templ/ --templ=index.sp6 --inside=inc/html.sp6
```
## How it works
```
> raku -Ilib bin/sp6 --templ_dir=t/templ --debug include.sp6
Template fpath: 't/templ/include.sp6'
code: "Qc 「aa \{include 'inc/include-inner.sp6'} cc」;"
Template fpath: 't/templ/inc/include-inner.sp6'
code: "Qc 「inner-text」;"
output:
aa inner-text cc
```
## Know issues
Characters '「' and '」' are forbidden.
|
## sibling.md
sibling
Combined from primary sources listed below.
# [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_sibling "direct link")
See primary documentation
[in context](/type/IO/Path#method_sibling)
for **method sibling**.
```raku
method sibling(IO::Path:D: Str() $sibling --> IO::Path:D)
```
Allows to reference a sibling file or directory. Returns a new `IO::Path` based on the invocant, with the [`.basename`](/type/IO/Path#method_basename) changed to `$sibling`. The `$sibling` is allowed to be a multi-part path fragment; see also [`.add`](/type/IO/Path#method_add).
```raku
say '.bashrc'.IO.sibling: '.bash_aliases'; # OUTPUT: «.bash_aliases".IO»
say '/home/camelia/.bashrc'.IO.sibling: '.bash_aliases';
# OUTPUT: «/home/camelia/.bash_aliases".IO»
say '/foo/' .IO.sibling: 'bar'; # OUTPUT: «/bar".IO»
say '/foo/.'.IO.sibling: 'bar'; # OUTPUT: «/foo/bar".IO»
```
|
## dist_cpan-MORITZ-Math-RungeKutta.md
[](https://travis-ci.org/moritz/Math-RungeKutta)
|
## dist_zef-raku-community-modules-OO-Monitors.md
[](https://github.com/raku-community-modules/OO-Monitors/actions) [](https://github.com/raku-community-modules/OO-Monitors/actions) [](https://github.com/raku-community-modules/OO-Monitors/actions)
# NAME
OO::Monitors - Objects with mutual exclusion and condition variables
# SYNOPSIS
```
use OO::Monitors;
monitor Foo {
has $.bar
# accessible by one thread at a time
method frobnicate() { }
}
```
# DESCRIPTION
A monitor provides per-instance mutual exclusion for objects. This means that for a given object instance, only one thread can ever be inside its methods at a time. This is achieved by a lock being associated with each object. The lock is acquired automatically at the entry to each method in the monitor. Condition variables are also supported.
## Basic Usage
A monitor looks like a normal class, but declared with the `monitor` keyword.
```
use OO::Monitors;
monitor IPFilter {
has %!active;
has %!blacklist;
has $.limit = 10;
has $.blocked = 0;
method should-start-request($ip) {
if %!blacklist{$ip}
|| (%!active{$ip} // 0) == $.limit {
$!blocked++;
return False;
}
else {
%!active{$ip}++;
return True;
}
}
method end-request($ip) {
%!active{$ip}--;
}
}
```
That's about all there is to it. The monitor meta-object enforces mutual exclusion.
## Circular waiting
Monitors are vulnerable to deadlock, if you set up a circular dependency. Keep object graphs involving monitors simple and cycle-free, so far as is possible.
# AUTHOR
Jonathan Worthington
Source can be located at: <https://github.com/raku-community-modules/OO-Monitors> . Comments and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2014 - 2021 Jonathan Worthington
Copyright 2024, 2025 Raku Community
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-FRITH-Math-Libgsl-Matrix.md
## Chunk 1 of 2
[](https://github.com/frithnanth/raku-Math-Libgsl-Matrix/actions)
# NAME
Math::Libgsl::Matrix Math::Libgsl::Vector - An interface to libgsl, the Gnu Scientific Library - Vector and matrix algebra.
# SYNOPSIS
```
use Math::Libgsl::Vector;
use Math::Libgsl::Matrix;
```
# DESCRIPTION
Math::Libgsl::Matrix provides an interface to the vector and matrix algebra functions of libgsl - the GNU Scientific Library.
This package provides both the low-level interface to the C library (Raw) and a more comfortable interface layer for the Raku programmer.
This module comes with two classes, Vector and Matrix, available in 12 data types, so it offers 24 classes:
* Math::Libgsl::Vector - default, corresponding to a Math::Libgsl::Vector::Num64
* Math::Libgsl::Vector::Num32
* Math::Libgsl::Vector::Int32
* Math::Libgsl::Vector::UInt32
* Math::Libgsl::Vector::Int64
* Math::Libgsl::Vector::UInt64
* Math::Libgsl::Vector::Int16
* Math::Libgsl::Vector::UInt16
* Math::Libgsl::Vector::Int8
* Math::Libgsl::Vector::UInt8
* Math::Libgsl::Vector::Complex32
* Math::Libgsl::Vector::Complex64
* Math::Libgsl::Matrix - default, corresponding to a Math::Libgsl::Matrix::Num64
* Math::Libgsl::Matrix::Num32
* Math::Libgsl::Matrix::Int32
* Math::Libgsl::Matrix::UInt32
* Math::Libgsl::Matrix::Int64
* Math::Libgsl::Matrix::UInt64
* Math::Libgsl::Matrix::Int16
* Math::Libgsl::Matrix::UInt16
* Math::Libgsl::Matrix::Int8
* Math::Libgsl::Matrix::UInt8
* Math::Libgsl::Matrix::Complex32
* Math::Libgsl::Matrix::Complex64
All the following methods are available for the classes correspondig to each datatype, except where noted.
## Vector
### new(Int $size!)
### new(Int :$size!)
The constructor accepts one parameter: the vector's size; it can be passed as a Pair or as a single value.
### list(--> List)
This method returns all the elements of the Vector as a Raku List.
### gist(--> Str)
This method returns the first 100 elements of the Vector interpolated in a Raku Str. The .gist method is used by the Raku say() function and method to print a representation of an object.
### Str(--> Str)
This method returns all the elements of the Vector interpolated in a Raku Str. The .Str method is used by the Raku put() function and method to print an object.
### get(Int:D $index! where \* < $!vector.size --> Num)
This method returns the value of a vector's element. It is possible to address a vector element as a Raku array element:
```
say $vector[1];
```
or even:
```
say $vector[^10];
```
### set(Int:D $index! where \* < $!vector.size, Num(Cool)
This method sets the value of a vector's element. This method can be chained. It is possible to address a vector element as a Raku array element:
```
$vector[1] = 3;
```
Note that it's not possible to set a range of elements (yet). When used as a Raku array, this method can't be chained.
### setall(Num(Cool))
Sets all the elements of the vector to the same value. This method can be chained.
### zero()
Sets all the elements of the vector to zero. This method can be chained.
### basis(Int:D $index! where \* < $!vector.size)
Sets all the elements of the vector to zero except for the element at $index, which is set to one. This method can be chained.
### size(--> UInt)
This method outputs the vector's size.
### write(Str $filename!)
Writes the vector to a file in binary form. This method can be chained.
### read(Str $filename!)
Reads the vector from a file in binary form. This method can be chained.
### printf(Str $filename!, Str $format!)
Writes the vector to a file using the specified format. This method can be chained.
### scanf(Str $filename!)
Reads the vector from a file containing formatted data. This method can be chained.
### copy(Math::Libgsl::Vector $src where $!vector.size == .vector.size)
This method copies the vector $src into the current object. This method can be chained.
### swap(Math::Libgsl::Vector $w where $!vector.size == .vector.size)
This method exchanges the elements of the current vector with the ones of the vector $w. This method can be chained.
### swap-elems(Int $i where \* < $!vector.size, Int $j where \* < $!vector.size)
This method exchanges the $i-th and $j-th elements in place. This method can be chained.
### reverse()
This method reverses the order of the elements of the vector. This method can be chained.
### add(Math::Libgsl::Vector $b where $!vector.size == .vector.size)
### sub(Math::Libgsl::Vector $b where $!vector.size == .vector.size)
### mul(Math::Libgsl::Vector $b where $!vector.size == .vector.size)
### div(Math::Libgsl::Vector $b where $!vector.size == .vector.size)
These methods perform operations on the elements of two vectors. The object on which the method is called is the one whose values are changed. All these methods can be chained.
### scale(Num(Cool) $x)
This method multiplies the elements of the vector by a factor $x. This method can be chained.
### add-constant(Num(Cool) $x)
This method adds a constant to the elements of the vector. This method can be chained.
### sum(--> Num)
This method returns the sum of the elements of the vector. This method fails if the underlying C library's version is less than 2.7.
### axpby(Num(Cool) $alpha, Num(Cool) $beta, Math::Libgsl::Vector $b where $!vector.size == .vector.size)
This method performs the operation αx + βy and returns the result in the vector $b. This method can be chained. This method fails if the underlying C library's version is less than 2.7.
### max(--> Num)
### min(--> Num)
These two methods return the min and max value in the vector. Not available in Math::Libgsl::Vector::Complex32 and Math::Libgsl::Vector::Complex64.
### minmax(--> List)
This method returns a list of two values: the min and max value in the vector. Not available in Math::Libgsl::Vector::Complex32 and Math::Libgsl::Vector::Complex64.
### max-index(--> Int)
### min-index(--> Int)
These two methods return the index of the min and max value in the vector. Not available in Math::Libgsl::Vector::Complex32 and Math::Libgsl::Vector::Complex64.
### minmax-index(--> List)
This method returns a list of two values: the indices of the min and max value in the vector. Not available in Math::Libgsl::Vector::Complex32 and Math::Libgsl::Vector::Complex64.
### is-null(--> Bool)
### is-pos(--> Bool)
### is-neg(--> Bool)
### is-nonneg(--> Bool)
These methods return True if all the elements of the vector are zero, strictly positive, strictly negative, or non-negative.
### is-equal(Math::Libgsl::Vector $b --> Bool)
This method returns True if the two vectors are equal element-wise.
## Views
Views are extremely handy, but their C-language interface uses a couple of low-level tricks that makes difficult to write a simple interface for high-level languages. A View is a reference to data in a Vector, Matrix, or array, so it makes possible to work on a subset of that data without having to duplicate it in memory or do complex address calculation to access it. Since a View is a reference to an object, the programmer needs to take care that the original object doesn't go out of scope, or the virtual machine might deallocate its memory causing the underlying C library to crash. Look in the **examples/** directory for more programs showing what can be done with views.
## Vector View
```
use Math::Libgsl::Vector;
my Math::Libgsl::Vector $v .= new(30); # Create a 30-element vector
my Math::Libgsl::Vector::View $vv .= new; # Create a Vector View
my Math::Libgsl::Vector $v1 = $vv.subvector-stride($v, 0, 3, 10); # Get a subvector view with stride
$v1.setall(42); # Set all elements of the subvector view to 42
say $v[^30]; # output: (42 0 0 42 0 0 42 0 0 42 0 0 42 0 0 42 0 0 42 0 0 42 0 0 42 0 0 42 0 0)
```
There are two kinds of Vector Views: a Vector View on a Vector or a Vector View on a Raku array. These are Views of the first kind:
### subvector(Math::Libgsl::Vector $v, size\_t $offset where \* < $v.vector.size, size\_t $n --> Math::Libgsl::Vector)
Creates a view on a subset of the vector, starting from $offset and of length $n. This method returns a new Vector object. Any operation done on this view affects the original vector as well.
### subvector-stride(Math::Libgsl::Vector $v, size\_t $offset where \* < $v.vector.size, size\_t $stride, size\_t $n --> Math::Libgsl::Vector)
Creates a view on a subset of the vector, starting from $offset and of length $n, with stride $stride. This method returns a new Vector object. Any operation done on this view affects the original vector as well.
Views on a Raku array are a bit more complex, because it's not possible to simply pass a Raku array to a C-language function. So for this to work the programmer has to *prepare* the array to be passed to the library. Both the View object and the *prepared* array must not go out of scope.
There are three ways to access a Raku array as a Math::Libgsl::Vector object:
* The hard way - use NativeCall's CArray to create a C-language-happy array.
* The easy way - use the \*-prepvec sub to convert a Raku array into a C array.
* The easiest way - use the \*-array-vec sub, pass it the Raku array or list and a closure or anonymous sub.
This is an example of the "hard way":
```
use Math::Libgsl::Vector;
use NativeCall;
my CArray[num64] $array .= new: (1 xx 10)».Num; # define a CArray
my Math::Libgsl::Vector::View $vv .= new; # view: an object that will contain the view information
my Math::Libgsl::Vector $v = $vv.array($array); # create an Math::Libgsl::Vector object
$v[0] = 2; # assign a value to the first vector element
say $v[^10]; # output: (2 1 1 1 1 1 1 1 1 1)
```
This is an example of the "easy way":
```
use Math::Libgsl::Vector;
my @array = 1 xx 10; # define an array
my $parray = num64-prepvec(@array); # prepare the array to be used as a Math::Libgsl::Vector
my Math::Libgsl::Vector::View $vv .= new; # view: an object that will contain the view information
my Math::Libgsl::Vector $v = $vv.array($parray); # create an Math::Libgsl::Vector object
$v[0] = 2; # assign a value to the first vector element
say $v[^10]; # output: (2 1 1 1 1 1 1 1 1 1)
```
Here are some examples of the "easiest way":
```
use Math::Libgsl::Vector;
my @array = ^10; # initialize an array
my ($min, $max) = num64-array-vec(-> $vec { $vec.minmax }, @array); # find min and max value
say "$min $max"; # output: 0 9
```
```
use Math::Libgsl::Constants;
use Math::Libgsl::Vector;
use Math::Libgsl::MovingWindow;
my @array = ^10; # initialize an array
my Math::Libgsl::MovingWindow $mw .= new: :samples(5); # initialize a MovingWindow object with a 5-sample window
# compute the moving-window mean of the array
my $w = num64-array-vec(-> $vec { $mw.mean($vec, :endtype(GSL_MOVSTAT_END_PADVALUE)) }, @array);
say $w[^10]; # output: (0.6 1.2 2 3 4 5 6 7 7.8 8.4)
```
Even using this last construct, if the Vector object is to be used outside of the closure it must be declared before calling array-vec.
```
use Math::Libgsl::Vector;
my @array = 1 xx 10; # define an array
my Math::Libgsl::Vector $v .= new: 10; # declare a Math::Libgsl::Vector
num64-array-vec(-> $vec { $v.copy($vec); $v[0] = 2; }, @array); # assign a value to the first vector element
say $v[^10]; # output: (2 1 1 1 1 1 1 1 1 1)
```
### num64-prepvec(@array)
This is just a sub, not a method; it gets a regular array and outputs a *prepared* array, kept in a scalar variable. There are similar functions for every data type, so for example if one is working with int16 Vectors, one will use the **int16-prepvec** sub. The num64, being the default data type, has a special **prepvec** alias. Once *prepared*, the original array can be discarded.
### array($parray --> Math::Libgsl::Vector)
This method gets a *prepared* array and returns a Math::Libgsl::Vector object.
### array-stride($array, size\_t $stride --> Math::Libgsl::Vector)
This method gets a *prepared* array and a **$stride** and returns a Math::Libgsl::Vector object.
### sub num64-array-vec(Block $bl, \*@data)
This sub arguments are a Block to execute and a regular Raku array. Internally it uses a vector view to convert the array into libgsl's own vector data type, obtains the Math::Libgsl::Vector from the View, and passes it to the Block. When the Block exits the Math::Libgsl::Vector object ceases to exist, so it must be consumed inside the Block, or copied into another externally defined variable. The num64, being the default data type, has a special **array-vec** alias.
### sub num64-array-stride-vec(Block $bl, size\_t $stride, \*@data)
This sub arguments are a Block to execute, a stride, and a regular Raku array. Internally it uses a vector view to convert the array into libgsl's own vector data type, obtains the Math::Libgsl::Vector from the View, and passes it to the Block. When the Block exits the Math::Libgsl::Vector object ceases to exist, so it must be consumed inside the Block, or copied into another externally defined variable. The num64, being the default data type, has a special **array-stride-vec** alias.
## Matrix
### new(Int $size1!, Int $size2!)
### new(Int :$size1!, Int :$size2!)
The constructor accepts two parameters: the matrix sizes; they can be passed as Pairs or as single values.
All the following methods *throw* on error if they return **self**, otherwise they *fail* on error.
### list(--> List)
This method returns all the elements of the Matrix as a Raku List of Lists.
### gist(--> Str)
This method returns the first 10 elements of the first 10 rows of the Matrix interpolated in a Raku Str. The .gist method is used by the Raku say() function and method to print a representation of an object.
### Str(--> Str)
This method returns all the elements of the Matrix interpolated in a Raku Str. The .Str method is used by the Raku put() function and method to print an object.
### get(Int:D $i! where \* < $!matrix.size1, Int:D $j! where \* < $!matrix.size2 --> Num)
This method returns the value of a matrix element. It is possible to address a matrix element as a Raku shaped array element:
```
say $matrix[1;2];
```
### set(Int:D $i! where \* < $!matrix.size1, Int:D $j! where \* < $!matrix.size2, Num(Cool)
This method sets the value of a matrix element. This method can be chained. It is possible to address a matrix element as a Raku shaped array element:
```
$matrix[1;3] = 3;
```
### setall(Num(Cool))
Sets all the elements of the matrix to the same value. This method can be chained.
### zero()
Sets all the elements of the matrix to zero. This method can be chained.
### identity()
Sets all elements of the matrix to the corrisponding elements of the identity matrix.
### size1(--> UInt)
### size2(--> UInt)
### size(--> List)
These methods return the first, second, or both the matrix sizes.
### write(Str $filename!)
Writes the matrix to a file in binary form. This method can be chained.
### read(Str $filename!)
Reads the matrix from a file in binary form. This method can be chained.
### printf(Str $filename!, Str $format!)
Writes the matrix to a file using the specified format. This method can be chained.
### scanf(Str $filename!)
Reads the matrix from a file containing formatted data. This method can be chained.
### copy(Math::Libgsl::Matrix $src where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2)
This method copies the $src matrix into the current one. This method can be chained.
### swap(Math::Libgsl::Matrix $src where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2)
This method swaps elements of the $src matrix and the current one. This method can be chained.
### tricpy(Math::Libgsl::Matrix $src where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2, Int $Uplo, Int $Diag)
This method copies the upper or lower trianglular matrix from **$src** to **self**. Use the **cblas-uplo** enumeration to specify which triangle copy. Use the **cblas-diag** enumeration to specify whether to copy the matrix diagonal. This method can be chained.
### get-row(Int:D $i where \* < $!matrix.size1)
This method returns an array from row number $i.
### get-col(Int:D $j where \* < $!matrix.size2)
This method returns an array from column number $j.
### set-row(Int:D $i where \* ≤ $!matrix.size1, @row where \*.elems == $!matrix.size2)
### set-row(Int:D $i where \* ≤ $!matrix.size1, Math::Libgsl::Vector $v where .vector.size == $!matrix.size2)
These methods set row number $i of the matrix from a Raku array or a Vector object. This method can be chained.
### set-col(Int:D $j where \* ≤ $!matrix.size2, @col where \*.elems == $!matrix.size1)
### set-col(Int:D $j where \* ≤ $!matrix.size2, Math::Libgsl::Vector $v where .vector.size == $!matrix.size1)
These methods set column number $j of the matrix from a Raku array or a Vector object. This method can be chained.
### swap-rows(Int:D $i where \* ≤ $!matrix.size1, Int:D $j where \* ≤ $!matrix.size1)
This method swaps rows $i and $j. This method can be chained.
### swap-cols(Int:D $i where \* ≤ $!matrix.size2, Int:D $j where \* ≤ $!matrix.size2)
This method swaps columns $i and $j. This method can be chained.
### swap-rowcol(Int:D $i where \* ≤ $!matrix.size1, Int:D $j where \* ≤ $!matrix.size1)
This method exchanges row number $i with column number $j of a square matrix. This method can be chained.
### copy-transpose(Math::Libgsl::Matrix $src where $!matrix.size1 == .matrix.size2 && $!matrix.size2 == .matrix.size1)
This method copies a matrix into the current one, while transposing the elements. This method can be chained.
### transpose()
This method transposes the current matrix. This method can be chained.
### transpose-tricpy(Math::Libgsl::Matrix $src where $!matrix.size1 == .matrix.size2 && $!matrix.size2 == .matrix.size1, Int $Uplo, Int $Diag)
This method copies a triangle from the **$src** matrix into the current one, while transposing the elements. Use the **cblas-uplo** enumeration to specify which triangle copy. Use the **cblas-diag** enumeration to specify whether to copy the matrix diagonal. This method can be chained.
### add(Math::Libgsl::Matrix $b where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2)
This method adds a matrix to the current one element-wise. This method can be chained.
### sub(Math::Libgsl::Matrix $b where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2)
This method subtracts a matrix from the current one element-wise. This method can be chained.
### mul(Math::Libgsl::Matrix $b where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2)
This method multiplies a matrix to the current one element-wise. This method can be chained.
### div(Math::Libgsl::Matrix $b where $!matrix.size1 == .matrix.size1 && $!matrix.size2 == .matrix.size2)
This method divides the current matrix by another one element-wise. This method can be chained.
### scale(Num(Cool) $x)
This method multiplies the elements of the current matrix by a constant value. This method can be chained.
### scale-rows(Math::Libgsl::Vector $x where .size == $!matrix.size1)
This method scales the rows of the M-by-N matrix by the elements of the vector $x, of length N. The i-th row of the matrix is multiplied by $xᵢ. This method can be chained. This method fails if the underlying C library's version is less than 2.7.
### scale-columns(Math::Libgsl::Vector $x where .size == $!matrix.size1)
This method scales the columns of the M-by-N matrix by the elements of the vector $x, of length N. The j-th column of the matrix is multiplied by $xⱼ. This method can be chained. This method fails if the underlying C library's version is less than 2.7.
### add-constant(Num(Cool) $x)
This method adds a constant to the elements of the current matrix. This method can be chained.
### max(--> Num)
### min(--> Num)
These two methods return the min and max value in the matrix. Not available in Math::Libgsl::Matrix::Complex32 and Math::Libgsl::Matrix::Complex64.
### minmax(--> List)
This method returns a list of two values: the min and max value in the matrix. Not available in Math::Libgsl::Matrix::Complex32 and Math::Libgsl::Matrix::Complex64.
### max-index(--> Int)
### min-index(--> Int)
These two methods return the index of the min and max value in the matrix. Not available in Math::Libgsl::Matrix::Complex32 and Math::Libgsl::Matrix::Complex64.
### minmax-index(--> List)
This method returns a list of two values: the indices of the min and max value in the matrix. Not available in Math::Libgsl::Matrix::Complex32 and Math::Libgsl::Matrix::Complex64.
### is-null(--> Bool)
### is-pos(--> Bool)
### is-neg(--> Bool)
### is-nonneg(--> Bool)
These methods return True if all the elements of the matrix are zero, strictly positive, strictly negative, or non-negative.
### is-equal(Math::Libgsl::Matrix $b --> Bool)
This method returns True if the matrices are equal element-wise.
### norm1(--> Num)
This method returns the 1-norm of the m-by-n matrix, defined as the maximum column sum. This method fails if the underlying C library's version is less than 2.7.
## Matrix View
```
use Math::Libgsl::Matrix;
my Math::Libgsl::Matrix $m1 .= new(:size1(3), :size2(4)); # create a 3x4 matrix
$m1.setall(1); # set all elements to 1
my Math::Libgsl::Matrix::View $mv .= new; # create a Matrix View
my Math::Libgsl::Matrix $m2 = $mv.submatrix($m1, 1, 1, 2, 2); # get a submatrix
$m2.setall(12); # set the submatrix elements to 12
$m1.get-row($_)».fmt('%2d').put for ^3; # print the original matrix
# output:
# 1 1 1 1
# 1 12 12 1
# 1 12 12 1
```
There are three kinds of Matrix Views: a Matrix View on a Matrix, a Matrix View on a Vector, and a Matrix View on a Raku array.
This is the View of the first kind:
### submatrix(Math::Libgsl::Matrix $m, size\_t $k1 where \* < $m.size1, size\_t $k2 where \* < $m.size2, size\_t $n1, size\_t $n2 --> Math::Libgsl::Matrix)
Creates a view on a subset of the matrix, starting from coordinates ($k1, $k2) with $n1 rows and $n2 columns. This method returns a new Matrix object. Any operation done on the returned matrix affects the original matrix as well.
These three methods create a matrix view on a Raku array:
There are three ways to view a Raku array as a Math::Libgsl::Vector object:
* The hard way - use NativeCall's CArray to create a C-language-happy array.
* The easy way - use the \*-prepvec sub to convert a Raku array into a C array.
* The easiest way - use the \*-array-vec sub, pass it the Raku array or list and a closure or anonymous sub.
This is an example of the "hard way":
```
use Math::Libgsl::Matrix;
use NativeCall;
my CArray[num64] $array .= new: (1..6)».Num; # define a CArray
my Math::Libgsl::Matrix::View $mv .= new; # view: an object that will contain the view information
my Math::Libgsl::Matrix $m = $mv.array($array, 2, 3); # create an Math::Libgsl::Matrix object
$m[0;0] = 2; # assign a value to the first matrix element
say $m.get-row($_) for ^2;
# output:
# 2 2 3
# 4 5 6
```
This is an example of the "easy way":
Views on a Raku array are a bit more complex, because it's not possible to simply pass a Raku array to a C-language function. So for this to work the programmer has to *prepare* the array to be passed to the library. Both the View object and the *prepared* array must not go out of scope.
```
use Math::Libgsl::Matrix;
my @array = 1 xx 10; # define an array
my $parray = prepmat(@array); # prepare the array to be used as a Math::Libgsl::Matrix
my Math::Libgsl::Matrix::View $mv .= new; # view: an object that will contain the view information
my Math::Libgsl::Matrix $m = $mv.array($parray, 2, 5); # create an Math::Libgsl::Matrix object
$m[0;0] = 2; # assign a value to the first matrix element
$m.get-row($_).put for ^2;
# output:
# 2 1 1 1 1
# 1 1 1 1 1
```
This is an example of the "easiest way":
```
use Math::Libgsl::Matrix;
my @array = 1..6; # initialize an array
my Math::Libgsl::Matrix $matrix .= new: 2, 3; # declare a Math::Libgsl::Matrix
num64-array-mat(-> $mat { $matrix.copy($mat); $matrix[0;0] = 0 }, 2, 3, @array); # assign 0 to matrix element [0;0]
$matrix.get-row($_).put for ^2;
# output:
# 0 2 3
# 4 5 6
```
### num64-prepmat(@array)
This is just a sub, not a method; it gets a regular array and outputs a *prepared* array, kept in a scalar variable. There are similar functions for every data type, so for example if one is working with int16 Vectors, one will use the **int16-prepmat** sub. The num64, being the default data type, has a special **prepmat** alias. Once *prepared*, the original array can be discarded.
### array($array, UInt $size1, UInt $size2 --> Math::Libgsl::Matrix)
This method gets a *prepared* array and returns a Math::Libgsl::Matrix object.
### array-tda($array, UInt $size1, UInt $size2, size\_t $tda where \* > $size2 --> Math::Libgsl::Matrix)
This method gets a *prepared* array with a number of physical columns **$tda**, which may differ from the corresponding dimension of the matrix, and returns a Math::Libgsl::Matrix object.
### sub num64-array-mat(Block $bl, UInt $size1, UInt $size2, \*@data)
This sub arguments are a Block to execute, the sizes of the desired resulting matrix, and a regular Raku array. Internally it uses a matrix view to convert the array into libgsl's own matrix data type, obtains the Math::Libgsl::Matrix from the View, and passes it to the Block. When the Block exits the Math::Libgsl::Matrix object ceases to exist, so it must be consumed inside the Block, or copied into another externally defined variable. The num64, being the default data type, has a special **array-mat** alias.
### sub num64-array-tda-mat(Block $bl, UInt $size1, UInt $size2, size\_t $tda where \* > $size2, \*@data)
This sub arguments are a Block to execute, the sizes of the desired resulting matrix, the number of physical columns **$tda**, and a regular Raku array. Internally it uses a matrix view to convert the array into libgsl's own matrix data type, obtains the Math::Libgsl::Matrix from the View, and passes it to the Block. When the Block exits the Math::Libgsl::Matrix object ceases to exist, so it must be consumed inside the Block, or copied into another externally defined variable. The num64, being the default data type, has a special **array-tda-mat** alias.
There are two methods to create a Matrix View on a Vector:
### vector(Math::Libgsl::Vector $v, size\_t $n1, size\_t $n2 --> Math::Libgsl::Matrix)
This method creates a Matrix object from a Vector object. The resultimg matrix will have $n1 rows and $n2 columns.
### vector-tda(Math::Libgsl::Vector $v, size\_t $n1, size\_t $n2, size\_t $tda where \* > $n2 --> Math::Libgsl::Matrix)
This method creates a Matrix object from a Vector object, with a physical number of columns $tda which may differ from the correspondig dimension of the matrix. The resultimg matrix will have $n1 rows and $n2 columns.
## Vector View on a Matrix
There is a fourth kind of View that involves a Matrix: a Vector View on a Matrix. The following are methods of the Matrix class, not of the Matrix::View class, take a Vector::View argument, and deliver a Vector object. The Matrix object must not go out of scope while one is operating on the resulting Vector.
### row-view(Math::Libgsl::Vector::View $vv, size\_t $i where \* < $!matrix.size1 --> Math::Libgsl::Vector)
This method creates a Vector object from row $i of the matrix.
### col-view(Math::Libgsl::Vector::View $vv, size\_t $j where \* < $!matrix.size2 --> Math::Libgsl::Vector)
This method creates a Vector object from column $j of the matrix.
### subrow-view(Math::Libgsl::Vector::View $vv, size\_t $i where \* < $!matrix.size1, size\_t $offset, size\_t $n --> Math::Libgsl::Vector)
This method creates a Vector object from row $i of the matrix, starting from $offset and containing $n elements.
### subcol-view(Math::Libgsl::Vector::View $vv, size\_t $j where \* < $!matrix.size2, size\_t $offset, size\_t $n --> Math::Libgsl::Vector)
This method creates a Vector object from column $j of the matrix, starting from $offset and containing $n elements.
### diagonal-view(Math::Libgsl::Vector::View $vv --> Math::Libgsl::Vector)
This method creates a Vector object from the diagonal of the matrix.
### subdiagonal-view(Math::Libgsl::Vector::View $vv, size\_t $k where \* < min($!matrix.size1, $!matrix.size2) --> Math::Libgsl::Vector)
This method creates a Vector object from the subdiagonal number $k of the matrix.
### superdiagonal-view(Math::Libgsl::Vector::View $vv, size\_t $k where \* < min($!matrix.size1, $!matrix.size2) --> Math::Libgsl::Vector)
This method creates a Vector object from the superdiagonal number $k of the matrix.
# C Library Documentation
For more details on |
## dist_zef-FRITH-Math-Libgsl-Matrix.md
## Chunk 2 of 2
libgsl see <https://www.gnu.org/software/gsl/>. The excellent C Library manual is available here <https://www.gnu.org/software/gsl/doc/html/index.html>, or here <https://www.gnu.org/software/gsl/doc/latex/gsl-ref.pdf> in PDF format.
# Prerequisites
This module requires the libgsl library to be installed. Please follow the instructions below based on your platform:
## Debian Linux and Ubuntu 20.04
```
sudo apt install libgsl23 libgsl-dev libgslcblas0
```
That command will install libgslcblas0 as well, since it's used by the GSL.
## Ubuntu 18.04
libgsl23 and libgslcblas0 have a missing symbol on Ubuntu 18.04. I solved the issue installing the Debian Buster version of those three libraries:
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgslcblas0_2.5+dfsg-6_amd64.deb>
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl23_2.5+dfsg-6_amd64.deb>
* <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl-dev_2.5+dfsg-6_amd64.deb>
# Installation
To install it using zef (a module management tool):
```
$ zef install Math::Libgsl::Matrix
```
# AUTHOR
Fernando Santagata [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2020 Fernando Santagata
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_github-Skarsnik-IRC-Art.md
[](https://travis-ci.org/Skarsnik/perl6-irc-art)
# Name IRC::Art
# Synopsis
```
use IRC::Art;
use YourFavoriteIrcClient;
my $art = IRC::Art.new(4, 4); # A 4x4
$art.rectangle(0, 0, 3, 3, :color(4)); #draw a red square
$art.text("6.c", 1, 1, :color(13), :bold); # put the 6.c text starting at 1,1
for $art.result {
$irc.send-message('#perl6', $_);
}
```
# Description
IRC::Art offers you a way to create basic art on IRC. It works mainly like a small graphics library with methods to "draw" like pixel, text or rectangle.
# Usage
Create an `IRC::Art` object and use the various drawing methods on it. Every change writes over the previous of the existing execpt for the text method.
## new(?width, ?height)
Create a new canvas filled with blanks (space), sized according to the width and height information.
## result
Returns the canvas as an array of irc strings that you can put in a loop to send the art.
## Str
The `Str` method returns the first row of the canvas as a single string.
## pixel($x, $y, :$color, $clear)
Place or clear the pixel at the given x/y coordinate
## rectangle($x1, $y1, $x2, $y2, :$color, $clear)
Place or clear a rectangle of pixels from x1/y1 to x2/y2 corners
## text($text, $x, $y, :$color, $bold, $bg)
Place some text, starting at the x/y coordonates.
$color is the color of the text
$bg is the color of the background
## save($filename) load($filename)
Save the canvas in a Perl 6. Use load to load it.
# Colors
These color are mainly indicative, it depends too much on the irc client configuration.
```
0 : light grey
1 : Black
2 : Dark Blue
3 : Dark Green
4 : Red
5 : Dark red
6 : Violet
7 : Orange
8 : Yellow
9 : Light Green
10 : Dark light blue
11 : Lighter blue
12 : Blue
13 : Pink
14 : Dark Grey
15 : Grey
```
|
## dist_zef-rbt-File-Temp.md
[](https://ci.appveyor.com/project/perlpilot/p6-File-Temps/branch/master)
# NAME
File::Temp
# SYNOPSIS
```
# Generate a temp file in a temp dir
my ($filename,$filehandle) = tempfile;
# specify a template for the filename
# * are replaced with random characters
my ($filename,$filehandle) = tempfile("******");
# Automatically unlink files at DESTROY (this is the default)
my ($filename,$filehandle) = tempfile("******", :unlink);
# Specify the directory where the tempfile will be created
my ($filename,$filehandle) = tempfile(:tempdir("/path/to/my/dir"));
# don't unlink this one
my ($filename,$filehandle) = tempfile(:tempdir('.'), :!unlink);
# specify a prefix and suffix for the filename
my ($filename,$filehandle) = tempfile(:prefix('foo'), :suffix(".txt"));
```
# DESCRIPTION
This module exports two routines:
* `tempfile` creates a temporary file and returns a filehandle to that file
opened for writing and the filename of that temporary file
* `tempdir` creates a temporary directory and returns the directory name.
# AUTHOR
Jonathan Scott Duff [[email protected]](mailto:[email protected])
|
## mixhash.md
class MixHash
Mutable collection of distinct objects with Real weights
```raku
class MixHash does Mixy { }
```
A `MixHash` is a mutable mix, meaning a collection of distinct elements in no particular order that each have a real-number weight assigned to them. (For *immutable* mixes, see [`Mix`](/type/Mix) instead.)
Objects/values of any type are allowed as mix elements. Within a `MixHash`, items that would compare positively with the [===](/routine/===) operator are considered the same element, with a combined weight.
```raku
my $recipe = (butter => 0.22, sugar => 0.1,
flour => 0.275, sugar => 0.02).MixHash;
say $recipe.elems; # OUTPUT: «3»
say $recipe.keys.sort; # OUTPUT: «butter flour sugar»
say $recipe.pairs.sort; # OUTPUT: «"butter" => 0.22 "flour" => 0.275 "sugar" => 0.12»
say $recipe.total; # OUTPUT: «0.615»
```
`MixHash`es can be treated as object hashes using the [`{ }` postcircumfix operator](/language/operators#postcircumfix_{_}), or the [`< >` postcircumfix operator](/language/operators#postcircumfix_<_>) for literal string keys, which returns the corresponding numeric weight for keys that are elements of the mix, and `0` for keys that aren't. It can also be used to modify weights; Setting a weight to `0` automatically removes that element from the mix, and setting a weight to a non-zero number adds that element if it didn't already exist:
```raku
my $recipe = (butter => 0.22, sugar => 0.1,
flour => 0.275, sugar => 0.02).MixHash;
say $recipe<butter>; # OUTPUT: «0.22»
say $recipe<sugar>; # OUTPUT: «0.12»
say $recipe<chocolate>; # OUTPUT: «0»
$recipe<butter> = 0;
$recipe<chocolate> = 0.30;
say $recipe.pairs; # OUTPUT: «"sugar" => 0.12 "flour" => 0.275 "chocolate" => 0.3»
```
# [Creating `MixHash` objects](#class_MixHash "go to top of document")[§](#Creating_MixHash_objects "direct link")
`MixHash`es can be composed using `MixHash.new`. Any positional parameters, regardless of their type, become elements of the mix - with a weight of `1` for each time the parameter occurred:
```raku
my $n = MixHash.new: "a", "a", "b" => 0, "c" => 3.14;
say $n.keys.map(&WHAT); # OUTPUT: «((Str) (Pair) (Pair))»
say $n.pairs; # OUTPUT: «(a => 2 (c => 3.14) => 1 (b => 0) => 1)»
```
Alternatively, the `.MixHash` coercer (or its functional form, `MixHash()`) can be called on an existing object to coerce it to a `MixHash`. Its semantics depend on the type and contents of the object. In general it evaluates the object in list context and creates a mix with the resulting items as elements, although for Hash-like objects or Pair items, only the keys become elements of the mix, and the (cumulative) values become the associated numeric weights:
```raku
my $n = ("a", "a", "b" => 0, "c" => 3.14).MixHash;
say $n.keys.map(&WHAT); # OUTPUT: «((Str) (Str))»
say $n.pairs; # OUTPUT: «(a => 2 c => 3.14)»
```
Since 6.d (2019.03 and later) it is also possible to specify the type of values you would like to allow in a `MixHash`. This can either be done when calling `.new`:
```raku
# only allow strings
my $n = MixHash[Str].new: <a b b c c c>;
```
or using the masquerading syntax:
```raku
# only allow strings
my %mh is MixHash[Str] = <a b b c c c>;
say %mh<b>; # OUTPUT: «2»
say %mh<d>; # OUTPUT: «0»
# only allow whole numbers
my %mh is MixHash[Int] = <a b b c c c>;
# Type check failed in binding; expected Int but got Str ("a")
```
# [Operators](#class_MixHash "go to top of document")[§](#Operators "direct link")
See [Operators with set semantics](/language/setbagmix#Operators_with_set_semantics) for a complete list of "set operators" applicable to, among other types, `MixHash`.
Examples:
```raku
my ($a, $b) = MixHash(2 => 2, 4), MixHash(2 => 1.5, 3 => 2, 4);
say $a (<) $b; # OUTPUT: «False»
say $a (<=) $b; # OUTPUT: «False»
say $a (^) $b; # OUTPUT: «MixHash(2(0.5) 3(2))»
say $a (+) $b; # OUTPUT: «MixHash(2(3.5) 4(2) 3(2))»
# Unicode versions:
say $a ⊂ $b; # OUTPUT: «False»
say $a ⊆ $b; # OUTPUT: «False»
say $a ⊖ $b; # OUTPUT: «MixHash(2(0.5) 3(2))»
say $a ⊎ $b; # OUTPUT: «MixHash(2(3.5) 4(2) 3(2))»
```
# [Note on `reverse` and ordering.](#class_MixHash "go to top of document")[§](#Note_on_reverse_and_ordering. "direct link")
MixHash inherits `reverse` from [Any](/type/Any#routine_reverse), however, [`Mix`](/type/Mix)es do not have an inherent order and you should not trust it returning a consistent output.
If you sort a MixHash, the result is a list of pairs, at which point `reverse` makes perfect sense:
```raku
my $a = MixHash.new(2, 2, 18, 3, 4);
say $a; # OUTPUT: «MixHash(18 2(2) 3 4)»
say $a.sort; # OUTPUT: «(2 => 2 3 => 1 4 => 1 18 => 1)»
say $a.sort.reverse; # OUTPUT: «(18 => 1 4 => 1 3 => 1 2 => 2)»
```
# [Methods](#class_MixHash "go to top of document")[§](#Methods "direct link")
## [method Bag](#class_MixHash "go to top of document")[§](#method_Bag "direct link")
```raku
method Bag (--> Bag:D)
```
Coerces the `MixHash` to a [`Bag`](/type/Bag). The weights are converted to [`Int`](/type/Int), which means the number of keys in the resulting [`Bag`](/type/Bag) can be fewer than in the original `MixHash`, if any of the weights are negative or truncate to zero.
## [method BagHash](#class_MixHash "go to top of document")[§](#method_BagHash "direct link")
```raku
method BagHash (--> BagHash:D)
```
Coerces the `MixHash` to a [`BagHash`](/type/BagHash). The weights are converted to [`Int`](/type/Int), which means the number of keys in the resulting [`BagHash`](/type/BagHash) can be fewer than in the original `MixHash`, if any of the weights are negative or truncate to zero.
# [See Also](#class_MixHash "go to top of document")[§](#See_Also "direct link")
[Sets, Bags, and Mixes](/language/setbagmix)
# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")
Type relations for `MixHash`
raku-type-graph
MixHash
MixHash
Any
Any
MixHash->Any
Mixy
Mixy
MixHash->Mixy
Mu
Mu
Any->Mu
Associative
Associative
QuantHash
QuantHash
QuantHash->Associative
Baggy
Baggy
Baggy->QuantHash
Mixy->Baggy
[Expand chart above](/assets/typegraphs/MixHash.svg)
|
## uint.md
Subset UInt
Unsigned integer (arbitrary-precision)
The `UInt` is defined as a subset of [`Int`](/type/Int):
```raku
my subset UInt of Int where {not .defined or $_ >= 0};
```
Consequently, it cannot be instantiated or subclassed; however, that shouldn't affect most normal uses.
Some examples of its behavior and uses:
```raku
say UInt ~~ Int; # OUTPUT: «True»
my UInt $u = 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff; # 64-bit unsigned value
say $u.base(16); # OUTPUT: «FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF» (32 digits)
++$u;
say $u.base(16); # OUTPUT: «100000000000000000000000000000000» (33 digits!)
my Int $i = $u;
say $i.base(16); # same as above
say $u.^name; # OUTPUT: «Int» - UInt is a subset, so the type is still Int.
say $i.^name; # OUTPUT: «Int»
# Difference in assignment
my UInt $a = 5; # nothing wrong
my UInt $b = -5; # Exception about failed type check
my UInt $c = 0;
--$c; # Exception again
CATCH { default { put .^name, ': ', .Str } };
# OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $b; expected UInt but got Int (-5)»
# Non-assignment operations are fine
my UInt $d = 0;
say $d - 3; # OUTPUT: «-3»
```
# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")
Type relations for `UInt`
raku-type-graph
UInt
UInt
Any
Any
UInt->Any
Mu
Mu
Any->Mu
[Expand chart above](/assets/typegraphs/UInt.svg)
|
## dist_cpan-BDUGGAN-Geo-Basic.md
# 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
```
# 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
* `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
# AUTHOR
Brian Duggan
Original geohash code by Thundergnat on Rosetta Code
|
## date.md
class Date
Calendar date
```raku
class Date { }
```
A `Date` is an immutable object identifying a day in the Gregorian calendar.
`Date` objects support addition and subtraction of integers, where an integer is interpreted as the number of days. You can compare `Date` objects with the numeric comparison operators `==, <, <=, >, >=, !=`. Their stringification in `YYYY-MM-DD` format means that comparing them with the string operators `eq, lt, le` etc. also gives the right result.
`Date.today` creates an object the current day according to the system clock.
```raku
my $d = Date.new(2015, 12, 24); # Christmas Eve!
say $d; # OUTPUT: «2015-12-24»
say $d.year; # OUTPUT: «2015»
say $d.month; # OUTPUT: «12»
say $d.day; # OUTPUT: «24»
say $d.day-of-week; # OUTPUT: «4» (Thursday)
say $d.later(days => 20); # OUTPUT: «2016-01-13»
my $n = Date.new('2015-12-31'); # New Year's Eve
say $n - $d; # OUTPUT: «7», 7 days between New Years/Christmas Eve
say $n + 1; # OUTPUT: «2016-01-01»
```
**Note** since version 6.d, .raku can be called on `Date`. It will also reject synthetic numerics such as 7̈ .
# [Methods](#class_Date "go to top of document")[§](#Methods "direct link")
## [method new](#class_Date "go to top of document")[§](#method_new "direct link")
```raku
multi method new($year, $month, $day, :&formatter --> Date:D)
multi method new(:$year!, :$month = 1, :$day = 1 --> Date:D)
multi method new(Str $date --> Date:D)
multi method new(Instant:D $dt --> Date:D)
multi method new(DateTime:D $dt --> Date:D)
```
Creates a new `Date` object, either from a triple of (year, month, day) that can be coerced to integers, or from a string of the form `YYYY-MM-DD` ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), or from an Instant or DateTime object. Optionally accepts a formatter as a named parameter.
```raku
my $date = Date.new(2042, 1, 1);
$date = Date.new(year => 2042, month => 1, day => 1);
$date = Date.new("2042-01-01");
$date = Date.new(Instant.from-posix: 1482155532);
$date = Date.new(DateTime.now);
```
Since Rakudo 2022.03, the "day" argument can also be a callable, with `*` representing the last day in a month, and the possibility of getting to the day counting from the last one:
```raku
say Date.new(2042, 2, *); # OUTPUT: «2042-02-28»
say Date.new(2044, 2, *); # OUTPUT: «2044-02-29»
```
## [method new-from-daycount](#class_Date "go to top of document")[§](#method_new-from-daycount "direct link")
```raku
method new-from-daycount($daycount,:&formatter --> Date:D)
```
Creates a new `Date` object given `$daycount` which is the number of days from epoch Nov. 17, 1858, i.e. the [Modified Julian Day](https://en.wikipedia.org/wiki/Julian_day). Optionally accepts a formatter as a named parameter.
```raku
say Date.new-from-daycount(49987); # OUTPUT: «1995-09-27»
```
## [method daycount](#class_Date "go to top of document")[§](#method_daycount "direct link")
```raku
method daycount(Date:D: --> Int:D)
```
Returns the number of days from epoch Nov. 17, 1858, i.e. the [Modified Julian Day](https://en.wikipedia.org/wiki/Julian_day).
## [method last-date-in-month](#class_Date "go to top of document")[§](#method_last-date-in-month "direct link")
```raku
method last-date-in-month(Date:D: --> Date:D)
```
Returns the last date in the month of the `Date` object. Otherwise, returns the invocant if the day value is already the last day of the month.
```raku
say Date.new('2015-11-24').last-date-in-month; # OUTPUT: «2015-11-30»
```
This should allow for much easier ranges like
```raku
$date .. $date.last-date-in-month
```
for all remaining dates in the month.
## [method first-date-in-month](#class_Date "go to top of document")[§](#method_first-date-in-month "direct link")
```raku
method first-date-in-month(Date:D: --> Date:D)
```
Returns the first date in the month of the `Date` object. Otherwise, returns the invocant if the day value is already the first day of the month.
```raku
say Date.new('2015-11-24').first-date-in-month; # OUTPUT: «2015-11-01»
```
## [method clone](#class_Date "go to top of document")[§](#method_clone "direct link")
```raku
method clone(Date:D: :$year, :$month, :$day, :&formatter)
```
Creates a new `Date` object based on the invocant, but with the given arguments overriding the values from the invocant.
```raku
say Date.new('2015-11-24').clone(month => 12); # OUTPUT: «2015-12-24»
```
## [method today](#class_Date "go to top of document")[§](#method_today "direct link")
```raku
method today(:&formatter --> Date:D)
```
Returns a `Date` object for the current day. Optionally accepts a formatter named parameter.
```raku
say Date.today;
```
## [method truncated-to](#class_Date "go to top of document")[§](#method_truncated-to "direct link")
```raku
method truncated-to(Date:D: Cool $unit)
```
Returns a `Date` truncated to the first day of its year, month or week. For example
```raku
my $c = Date.new('2012-12-24');
say $c.truncated-to('year'); # OUTPUT: «2012-01-01»
say $c.truncated-to('month'); # OUTPUT: «2012-12-01»
say $c.truncated-to('week'); # OUTPUT: «2012-12-24», because it's Monday already
```
## [method succ](#class_Date "go to top of document")[§](#method_succ "direct link")
```raku
method succ(Date:D: --> Date:D)
```
Returns a `Date` of the following day. "succ" is short for "successor".
```raku
say Date.new("2016-02-28").succ; # OUTPUT: «2016-02-29»
```
## [method pred](#class_Date "go to top of document")[§](#method_pred "direct link")
```raku
method pred(Date:D: --> Date:D)
```
Returns a `Date` of the previous day. "pred" is short for "predecessor".
```raku
say Date.new("2016-01-01").pred; # OUTPUT: «2015-12-31»
```
## [method Str](#class_Date "go to top of document")[§](#method_Str "direct link")
```raku
multi method Str(Date:D: --> Str:D)
```
Returns a string representation of the invocant, as specified by [the formatter](/type/Dateish#method_formatter). If no formatter was specified, an ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)) date will be returned.
```raku
say Date.new('2015-12-24').Str; # OUTPUT: «2015-12-24»
my $fmt = { sprintf "%02d/%02d/%04d", .month, .day, .year };
say Date.new('2015-12-24', formatter => $fmt).Str; # OUTPUT: «12/24/2015»
```
## [method gist](#class_Date "go to top of document")[§](#method_gist "direct link")
```raku
multi method gist(Date:D: --> Str:D)
```
Returns the date in `YYYY-MM-DD` format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601))
```raku
say Date.new('2015-12-24').gist; # OUTPUT: «2015-12-24»
```
## [method Date](#class_Date "go to top of document")[§](#method_Date "direct link")
```raku
method Date(--> Date)
```
Returns the invocant.
```raku
say Date.new('2015-12-24').Date; # OUTPUT: «2015-12-24»
say Date.Date; # OUTPUT: «(Date)»
```
## [method DateTime](#class_Date "go to top of document")[§](#method_DateTime "direct link")
```raku
multi method DateTime(Date:U: --> DateTime:U)
multi method DateTime(Date:D: --> DateTime:D)
```
Converts the invocant to [`DateTime`](/type/DateTime)
```raku
say Date.new('2015-12-24').DateTime; # OUTPUT: «2015-12-24T00:00:00Z»
say Date.DateTime; # OUTPUT: «(DateTime)»
```
## [method Int](#class_Date "go to top of document")[§](#method_Int "direct link")
```raku
multi method Int(Date:D: --> Int:D)
```
Converts the invocant to [`Int`](/type/Int). The same value can be obtained with the `daycount` method.
Available as of release 2023.02 of the Rakudo compiler.
## [method Real](#class_Date "go to top of document")[§](#method_Real "direct link")
```raku
multi method Real(Date:D: --> Int:D)
```
Converts the invocant to [`Int`](/type/Int). The same value can be obtained with the `daycount` method.
Available as of release 2023.02 of the Rakudo compiler.
## [method Numeric](#class_Date "go to top of document")[§](#method_Numeric "direct link")
```raku
multi method Numeric(Date:D: --> Int:D)
```
Converts the invocant to [`Int`](/type/Int). The same value can be obtained with the `daycount` method. This allows `Date` objects to be used directly in arithmetic operations.
Available as of release 2023.02 of the Rakudo compiler.
# [Functions](#class_Date "go to top of document")[§](#Functions "direct link")
## [sub sleep](#class_Date "go to top of document")[§](#sub_sleep "direct link")
```raku
sub sleep($seconds = Inf --> Nil)
```
Attempt to sleep for the given number of `$seconds`. Returns [`Nil`](/type/Nil) on completion. Accepts [`Int`](/type/Int), [`Num`](/type/Num), [`Rat`](/type/Rat), or [`Duration`](/type/Duration) types as an argument since all of these also do [`Real`](/type/Real).
```raku
sleep 5; # Int
sleep 5.2; # Num
sleep (5/2); # Rat
sleep (now - now + 5); # Duration
```
It is thus possible to sleep for a non-integer amount of time. For instance, the following code shows that `sleep (5/2)` sleeps for 2.5 seconds and `sleep 5.2` sleeps for 5.2 seconds:
```raku
my $before = now;
sleep (5/2);
my $after = now;
say $after-$before; # OUTPUT: «2.502411561»
$before = now;
sleep 5.2;
$after = now;
say $after-$before; # OUTPUT: «5.20156987»
```
## [sub sleep-timer](#class_Date "go to top of document")[§](#sub_sleep-timer "direct link")
```raku
sub sleep-timer(Real() $seconds = Inf --> Duration:D)
```
This function is implemented like `sleep`, but unlike the former it does return a [`Duration`](/type/Duration) instance with the number of seconds the system did not sleep.
In particular, the returned [`Duration`](/type/Duration) will handle the number of seconds remaining when the process has been awakened by some external event (e.g., Virtual Machine or Operating System events). Under normal condition, when sleep is not interrupted, the returned [`Duration`](/type/Duration) has a value of `0`, meaning no extra seconds remained to sleep. Therefore, in normal situations:
```raku
say sleep-timer 3.14; # OUTPUT: «0»
```
The same result applies to edge cases, when a negative or zero time to sleep is passed as argument:
```raku
say sleep-timer -2; # OUTPUT: 0
say sleep-timer 0; # OUTPUT: 0
```
See also [sleep-until](/routine/sleep-until).
## [sub sleep-until](#class_Date "go to top of document")[§](#sub_sleep-until "direct link")
```raku
sub sleep-until(Instant $until --> Bool)
```
Works similar to `sleep` but checks the current time and keeps sleeping until the required instant in the future has been reached. It uses internally the `sleep-timer` method in a loop to ensure that, if accidentally woken up early, it will wait again for the specified amount of time remaining to reach the specified instant. goes back to sleep
Returns `True` if the [`Instant`](/type/Instant) in the future has been achieved (either by mean of sleeping or because it is right now), `False` in the case an [`Instant`](/type/Instant) in the past has been specified.
To sleep until 10 seconds into the future, one could write something like this:
```raku
say sleep-until now+10; # OUTPUT: «True»
```
Trying to sleep until a time in the past doesn't work:
```raku
my $instant = now - 5;
say sleep-until $instant; # OUTPUT: «False»
```
However if we put the instant sufficiently far in the future, the sleep should run:
```raku
my $instant = now + 30;
# assuming the two commands are run within 30 seconds of one another...
say sleep-until $instant; # OUTPUT: «True»
```
To specify an exact instant in the future, first create a [`DateTime`](/type/DateTime) at the appropriate point in time, and cast to an [`Instant`](/type/Instant).
```raku
my $instant = DateTime.new(
year => 2023,
month => 9,
day => 1,
hour => 22,
minute => 5);
say sleep-until $instant.Instant; # OUTPUT: «True» (eventually...)
```
This could be used as a primitive kind of alarm clock. For instance, say you need to get up at 7am on the 4th of September 2015, but for some reason your usual alarm clock is broken and you only have your laptop. You can specify the time to get up (being careful about time zones, since `DateTime.new` uses UTC by default) as an [`Instant`](/type/Instant) and pass this to `sleep-until`, after which you can play an mp3 file to wake you up instead of your normal alarm clock. This scenario looks roughly like this:
```raku
# DateTime.new uses UTC by default, so get time zone from current time
my $timezone = DateTime.now.timezone;
my $instant = DateTime.new(
year => 2015,
month => 9,
day => 4,
hour => 7,
minute => 0,
timezone => $timezone
).Instant;
sleep-until $instant;
qqx{mplayer wake-me-up.mp3};
```
## [sub infix:<->](#class_Date "go to top of document")[§](#sub_infix:<-> "direct link")
```raku
multi infix:<-> (Date:D, Int:D --> Date:D)
multi infix:<-> (Date:D, Date:D --> Int:D)
```
Takes a date to subtract from and either an [`Int`](/type/Int), representing the number of days to subtract, or another `Date` object. Returns a new `Date` object or the number of days between the two dates, respectively.
```raku
say Date.new('2016-12-25') - Date.new('2016-12-24'); # OUTPUT: «1»
say Date.new('2015-12-25') - Date.new('2016-11-21'); # OUTPUT: «-332»
say Date.new('2016-11-21') - 332; # OUTPUT: «2015-12-25»
```
## [sub infix:<+>](#class_Date "go to top of document")[§](#sub_infix:<+> "direct link")
```raku
multi infix:<+> (Date:D, Int:D --> Date:D)
multi infix:<+> (Int:D, Date:D --> Date:D)
```
Takes an [`Int`](/type/Int) and adds that many days to the given `Date` object.
```raku
say Date.new('2015-12-25') + 332; # OUTPUT: «2016-11-21»
say 1 + Date.new('2015-12-25'); # OUTPUT: «2015-12-26»
```
# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")
Type relations for `Date`
raku-type-graph
Date
Date
Any
Any
Date->Any
Dateish
Dateish
Date->Dateish
Mu
Mu
Any->Mu
[Expand chart above](/assets/typegraphs/Date.svg)
|
## dist_github-Xliff-Audio-OggVorbis.md
# Audio::OggVorbis
Perl 6 Bindings for libogg, libvorbis, and libvorbisenc.
This module depends on native libraries. You can insure that these are
properly installed on Debian environments by using the following command:
```
sudo apt-get install -y libogg-dev libvorbis-dev
```
Right now, this library only consists of library bindings, however subsequent
releases will include a Perlish API.
Special thanks go to #perl6 on freenode. Their contributions got me this far.
|
## dist_zef-massa-Config-Parser-NetRC.md
[](https://github.com/massa/Config-Parser-NetRC/actions)
# NAME
Config::Parser::NetRC - A NetRC parser for [Config](https://github.com/scriptkitties/p6-Config)
# SYNOPSIS
```
use Config;
my Config $c .= new {}, :name<config>;
$c.=read('', Config::Parser::NetRC); # read from default "~/.netrc" file
```
# DESCRIPTION
Config::Parser::NetRC is a simple NetRC parser for NetRC-style files
# AUTHOR
Humberto Massa [[email protected]](mailto:[email protected])
# INSTALLATION
```
$ zef install Config::Parser::NetRC
```
# COPYRIGHT AND LICENSE
Copyright 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-japhb-Terminal-LineEditor.md
[](https://github.com/japhb/Terminal-LineEditor/actions)
# NAME
Terminal::LineEditor - Generalized terminal line editing
# SYNOPSIS
```
### PREP
use Terminal::LineEditor;
use Terminal::LineEditor::RawTerminalInput;
# Create a basic CLI text input object
my $cli = Terminal::LineEditor::CLIInput.new;
### BASICS
# Preload some input history
$cli.load-history($history-file);
$cli.add-history('synthetic input', 'more synthetic input');
# Prompt for input, supporting common edit commands,
# scrolling the field to stay on one line
my $input = $cli.prompt('Please enter your thoughts: ');
# Prompt for a password, masking with asterisks (suppresses history)
my $pass = $cli.prompt('Password: ', mask => '*');
# Prompt defaults to empty
my $stuff = $cli.prompt;
# Review and save history
.say for $cli.history;
$cli.save-history($history-file);
### TYPICAL USE
loop {
# Get user's input
my $in = $cli.prompt("My prompt >");
# Exit loop if user indicated finished
last without $in;
# Add line to history if it is non-empty
$cli.add-history($in) if $in.trim;
# Do something with the input line; here we just echo it
say $in;
}
```
# DESCRIPTION
`Terminal::LineEditor` is a terminal line editing package similar to `Linenoise` or `Readline`, but **not** a drop-in replacement for either of them. `Terminal::LineEditor` has a few key design differences:
* Implemented in pure Raku; `Linenoise` and `Readline` are NativeCall wrappers.
* Features strong separation of concerns; all components are exposed and replaceable.
* Useable both directly for simple CLI apps and embedded in TUI interfaces.
## Use with Rakudo REPL
A [PR for Rakudo](https://github.com/rakudo/rakudo/pull/4623) has been created to allow `Terminal::LineEditor` to be used as the REPL line editor when Rakudo is used in interactive mode. If your Rakudo build includes this PR, you can set the following in your environment to use `Terminal::LineEditor` by default:
```
export RAKUDO_LINE_EDITOR=LineEditor
```
If the environment variable is *not* specified, but `Terminal::LineEditor` is the only line editing module installed, Rakudo will auto-detect and enable it.
## Default Keymap
The latest version of the default keymap is specified in `Terminal::LineEditor::KeyMappable.default-keymap()`, but the below represents the currently implemented, commonly used keys:
Commonly Used Keys
| KEY | FUNCTION | NOTES |
| --- | --- | --- |
| Ctrl-A | move-to-start | |
| Ctrl-B | move-char-back | |
| Ctrl-C | abort-input | |
| Ctrl-D | abort-or-delete | Abort if empty, or delete-char-forward |
| Ctrl-E | move-to-end | |
| Ctrl-F | move-char-forward | |
| Ctrl-H | delete-char-back | |
| Ctrl-J | finish | LF (Line Feed) |
| Ctrl-K | delete-to-end | |
| Ctrl-L | refresh-all | |
| Ctrl-M | finish | CR (Carriage Return) |
| Ctrl-N | history-next | |
| Ctrl-P | history-prev | |
| Ctrl-T | swap-chars | |
| Ctrl-U | delete-to-start | |
| Ctrl-V | literal-next | |
| Ctrl-W | delete-word-back | |
| Ctrl-Y | yank | |
| Ctrl-Z | suspend | |
| Ctrl-\_ | undo | Ctrl-Shift-<hyphen> on some keyboards |
| Backspace | delete-char-back | |
| CursorLeft | move-char-back | |
| CursorRight | move-char-forward | |
| CursorHome | move-to-start | |
| CursorEnd | move-to-end | |
| CursorUp | history-prev | |
| CursorDown | history-next | |
| Alt-b | move-word-back | |
| Alt-c | tclc-word | Readline treats this as Capitalize |
| Alt-d | delete-word-forward | |
| Alt-f | move-word-forward | |
| Alt-l | lowercase-word | |
| Alt-t | swap-words | |
| Alt-u | uppercase-word | |
| Alt-< | history-start | Alt-Shift-<comma> on some keyboards |
| Alt-> | history-end | Alt-Shift-<period> on some keyboards |
All bindable edit functions are defined in the `Terminal::LineEditor::SingleLineTextInput` role (in each corresponding method beginning with `edit-`) or is one of the following special actions:
Special Actions
| ACTION | MEANING |
| --- | --- |
| abort-input | Throw away input so far and return an undefined Str |
| abort-or-delete | abort-input if empty, otherwise delete-char-forward |
| finish | Accept and return current input line |
| literal-next | Insert a literal control character into the buffer |
| suspend | Suspend the program with SIGTSTP, wait for SIGCONT |
| history-start | Switch input to first line in history |
| history-prev | Switch input to previous line in history |
| history-next | Switch input to next line in history |
| history-end | Switch input to last line in history (the partial input) |
## Architecture
`Terminal::LineEditor` is built up in layers, starting from the most abstract:
* `EditableBuffer` -- Basic interface role for editable buffers of all sorts
* `SingleLineTextBuffer` -- An `EditableBuffer` that knows how to apply simple insert/delete/replace operations at arbitrary positions/ranges, tracks a yank item (the most recently deleted text), and creates and manages undo/redo information to allow infinite undo
* `SingleLineTextBuffer::Cursor` -- A cursor class that knows how to move around within a `SingleLineTextBuffer` without moving outside the content area, and knows whether edit operations should automatically adjust its position
* `SingleLineTextBuffer::WithCursors` -- A wrapper of `SingleLineTextBuffer` that supports multiple simultaneous cursors, and handles automatically updating them appropriately whenever applying a basic edit operation
* `SingleLineTextInput` -- An input field role that tracks its own insert position as an auto-updating cursor, and provides a range of edit methods that operate relative to the current insert position
* `ScrollingSingleLineInput` -- A `SingleLineTextInput` that knows how to scroll within a limited horizontal display width to ensure that the insert position is always visible, no longer how long the input
* `ScrollingSingleLineInput::ANSI` -- A further extension of `ScrollingSingleLineInput` that is aware of cursor position and movement using ANSI/VT escape codes
* `CLIInput` -- A driver for `ScrollingSingleLineInput::ANSI` that deals with raw terminal I/O, detects terminal size and cursor position, supports a control key map for common edit operations, and handles suspend/resume without corrupting terminal state
## Edge Cases
There are a few edge cases for which `Terminal::LineEditor` chose one of several possible behaviors. Here's the reasoning for each of these otherwise arbitrary decisions:
* Attempting to apply an edit operation or create a new cursor outside the buffer contents throws an exception, because these indicate a logic error elsewhere.
* Attempting to move a previously correct cursor outside the buffer contents silently clips the new cursor position to the buffer endpoints, because users frequently hold down cursor movement keys (and thus repeatedly try to move past an endpoint).
* Undo'ing a delete operation, where one or more cursors were within the deleted region, results in all such cursors moving to the end of the undo; this is consistent with the behavior of an insert operation at the same position as the delete undo.
* For the same reason as for delete operations, replace operations that overlap cursor locations will move them to the end of the replaced text.
## Unmapped Functionality
Some of the functionality supported by lower layers of `Terminal::LineEditor` is not exposed in the default keymap of `Terminal::LineEditor::KeyMappable`. This is generally because no commonly-agreed shell keys map to this functionality.
For example, `Terminal::LineEditor::SingleLineTextBuffer` can treat replace as an atomic operation, but basic POSIX shells generally don't; they instead expect the user to delete and insert as separate operations.
That said, if I've missed a commonly-supported key sequence for any of the unmapped functionality, please open an issue for this repository with a link to the relevant docs so I can expand the default keymap.
# AUTHOR
Geoffrey Broadwell [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2021-2024 Geoffrey Broadwell
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## classhow.md
class Metamodel::ClassHOW
Metaobject representing a Raku class.
```raku
class Metamodel::ClassHOW
does Metamodel::Naming
does Metamodel::Documenting
does Metamodel::Versioning
does Metamodel::Stashing
does Metamodel::AttributeContainer
does Metamodel::MethodContainer
does Metamodel::PrivateMethodContainer
does Metamodel::MultiMethodContainer
does Metamodel::RoleContainer
does Metamodel::MultipleInheritance
does Metamodel::DefaultParent
does Metamodel::C3MRO
does Metamodel::MROBasedMethodDispatch
does Metamodel::MROBasedTypeChecking
does Metamodel::Trusting
does Metamodel::BUILDPLAN
does Metamodel::Mixins
does Metamodel::ArrayType
does Metamodel::BoolificationProtocol
does Metamodel::REPRComposeProtocol
does Metamodel::Finalization
{ }
```
*Warning*: this class is part of the Rakudo implementation, and is not a part of the language specification.
`Metamodel::ClassHOW` is the metaclass behind the `class` keyword.
```raku
say so Int.HOW ~~ Metamodel::ClassHOW; # OUTPUT: «True»
say Int.^methods(:all).pick.name; # OUTPUT: «random Int method name»
```
# [Methods](#class_Metamodel::ClassHOW "go to top of document")[§](#Methods "direct link")
## [method add\_fallback](#class_Metamodel::ClassHOW "go to top of document")[§](#method_add_fallback "direct link")
```raku
method add_fallback($obj, $condition, $calculator)
```
Installs a method fallback, that is, add a way to call methods that weren't statically added.
Both `$condition` and `$calculator` must be callables that receive the invocant and the method name once a method is called that can't be found in the method cache.
If `$condition` returns a true value, `$calculator` is called with the same arguments, and must return the code object to be invoked as the method, and is added to the method cache.
If `$condition` returns a false value, the next fallback (if any) is tried, and if none matches, an exception [of type X::Method::NotFound](/type/X/Method/NotFound) is thrown.
User-facing code (that is, code not dabbling with metaclasses) should use method `FALLBACK` instead.
## [method can](#class_Metamodel::ClassHOW "go to top of document")[§](#method_can "direct link")
```raku
method can($obj, $method-name)
```
Given a method name, it returns a [`List`](/type/List) of methods that are available with this name.
```raku
class A { method x($a) {} };
class B is A { method x() {} };
say B.^can('x').elems; # OUTPUT: «2»
for B.^can('x') {
say .arity; # OUTPUT: «1, 2»
}
```
In this example, class `B` has two possible methods available with name `x` (though a normal method call would only invoke the one installed in `B` directly). The one in `B` has arity 1 (i.e. it expects one argument, the invocant (`self`)), and the one in `A` expects 2 arguments (`self` and `$a`).
## [method lookup](#class_Metamodel::ClassHOW "go to top of document")[§](#method_lookup "direct link")
```raku
method lookup($obj, $method-name --> Method:D)
```
Returns the first matching [`Method`](/type/Method) with the provided name. If no method was found, returns a VM-specific sentinel value (typically a low-level NULL value) that can be tested for with a test for [definedness](/routine/defined). It is potentially faster than `.^can` but does not provide a full list of all candidates.
```raku
say Str.^lookup('Int').raku; # OUTPUT: «method Int (Str:D $: *%_) { #`(Method|39910024) ... }»
for <uppercase uc> {
Str.^lookup: $^meth andthen .("foo").say
orelse "method `$meth` not found".say
}
# OUTPUT:
# method `uppercase` not found
# FOO
```
## [method compose](#class_Metamodel::ClassHOW "go to top of document")[§](#method_compose "direct link")
```raku
method compose($obj)
```
A call to `compose` brings the metaobject and thus the class it represents into a fully functional state, so if you construct or modify a class, you must call the compose method before working with the class.
It updates the method cache, checks that all methods that are required by roles are implemented, does the actual role composition work, and sets up the class to work well with language interoperability.
## [method new\_type](#class_Metamodel::ClassHOW "go to top of document")[§](#method_new_type "direct link")
```raku
method (:$name, :$repr = 'P6opaque', :$ver, :$auth)
```
Creates a new type from the metamodel, which we can proceed to build
```raku
my $type = Metamodel::ClassHOW.new_type(name => "NewType",
ver => v0.0.1,
auth => 'github:raku' );
$type.HOW.add_method($type,"hey", method { say "Hey" });
$type.hey; # OUTPUT: «Hey»
$type.HOW.compose($type);
my $instance = $type.new;
$instance.hey; # OUTPUT: «Hey»
```
We add a single method by using [Higher Order Workings](/language/mop#HOW) methods, and then we can use that method directly as class method; we can then `compose` the type, following which we can create already an instance, which will behave in the exact same way.
|
## dist_cpan-SAMGWISE-Reaper-Control.md
[](https://travis-ci.org/samgwise/Reaper-control)
# NAME
Reaper::Control - An OSC controller interface for Reaper
# SYNOPSIS
```
use Reaper::Control;
# Start listening for UDP messages from sent from Reaper.
my $listener = reaper-listener(:host<127.0.0.1>, :port(9000));
# Respond to events from Reaper:
react whenever $listener.reaper-events {
when Reaper::Control::Event::Play {
put 'Playing'
}
when Reaper::Control::Event::Stop {
put 'stopped'
}
when Reaper::Control::Event::PlayTime {
put "seconds: { .seconds }\nsamples: { .samples }\nbeats: { .beats }"
}
when Reaper::Control::Event::Mixer {
put "levels: ", join ',', .master.vu, .tracks.map( *.vu ).Slip
}
when Reaper::Control::Event::Unhandled {
.perl.say
}
}
```
# DESCRIPTION
Reaper::Control is an [OSC controller interface](https://www.reaper.fm/sdk/osc/osc.php) for [Reaper](https://www.reaper.fm), a digital audio workstation. Current features are limited and relate to listening for play/stop, playback position and mixer levels but there is a lot more which can be added in the future.
To start listening call the `reaper-listener` subroutine, you can then obtain a `Supply` of events from the listener's `.reaper-events` method. All events emitted from the supply are subclasses of the `Reaper::Control::Event` role. Messages not handled by the default message handler are emitted as `Reaper::Control::Unhandled` objects, their contents can be accessed in the message attribute.
To skip the default message handler you may instead tap the lister's `.reaper-raw` method. This supply emits `Net::OSC::Bundle` objects, see the Net::OSC module for more on this object.
# AUTHOR
Sam Gillespie [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2018 Sam Gillespie
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### sub reaper-listener
```
sub reaper-listener(
Str :$host,
Int :$port,
Str :$protocol = "UDP"
) returns Reaper::Control::Listener
```
Create a Listener object which encapsulates message parsing and event parsing. The protocol argument currently only accepts UDP. Use the reaper-events method to obtain a Supply of events received, by the Listener, from Reaper.
### Reaper::Control::Listener
This class bundles up a series of tapped supplies which define a listener workflow. To construct a new listener call the listener-udp method to initialise a UDP listener workflow.
### Reaper::Control::Event
Base class for all reaper events. No functionality here, just an empty class.
### Reaper::Control::Event::PlayState
An abstract class defining the methods of Play and Stop classes. Use this type if you need to accept either Play or Stop objects.
### Reaper::Control::Event::Play
The Play version of the PlayState role. This object is emitted when playback is started.
### Reaper::Control::Event::Stop
The Stop version of the PlayState role. This object is emitted when playback is stopped.
### Reaper::Control::Event::PlayTime
This message bundles up elapsed seconds, elapsed samples and a string of the current beat position.
### Reaper::Control::Event::Level
This message bundles up audio levels from the mixer.
### Reaper::Control::Event::Mixer
This message bundles up audio level information from the mixer. Master level is held in the master attribute and tracks are stored in the tracks attribute.
### Reaper::Control::Event::Unhandled
A generic wrapper for messages not handled by the core interface
|
## dist_zef-bduggan-WebService-Nominatim.md
[](https://github.com/bduggan/raku-webservice-nominatim/actions/workflows/linux.yml)
[](https://github.com/bduggan/raku-webservice-nominatim/actions/workflows/macos.yml)
# NAME
WebService::Nominatim - Client for the OpenStreetMap Nominatim Geocoding API
# SYNOPSIS
```
use WebService::Nominatim;
my \n = WebService::Nominatim.new;
say n.search('Grand Central Station').first.<name lat lon>;
# (Grand Central Terminal 40.75269435 -73.97725295036929)
my $geo = n.search: '221B Baker Street, London, UK';
my $geo = n.search: query => '221B Baker Street, London, UK';
my $geo = n.search: query => { street => '221B Baker Street', city => 'London', country => 'UK' };
say $geo.head.<lat lon>;
# (51.5233879 -0.1582367)
say n.search: 'Grand Place, Brussels', :format<geojson>, :raw;
{"type":"FeatureCollection", ...
```
```
{"type":"FeatureCollection","licence":"Data © OpenStreetMap contributors, ODbL 1.0. http://osm.org/copyright","features":[{"type":"Feature","properties":{"place_id":97663568,"osm_type":"way","osm_id":991425177,"place_rank":25,"category":"boundary","type":"protected_area","importance":0.4874302285645721,"addresstype":"protected_area","name":"Grand-Place - Grote Markt","display_name":"Grand-Place - Grote Markt, Quartier du Centre - Centrumwijk, Pentagone - Vijfhoek, Bruxelles - Brussel, Brussel-Hoofdstad - Bruxelles-Capitale, Région de Bruxelles-Capitale - Brussels Hoofdstedelijk Gewest, 1000, België / Belgique / Belgien"},"bbox":[4.3512177,50.8460246,4.3537194,50.8474356],"geometry":{"type": "Point","coordinates": [4.352408060161565, 50.84672905]}}]}
```
# DESCRIPTION
This is an interface to OpenStreetMap's Nominatim Geocoding API, <https://nominatim.org>.
# EXPORTS
```
use WebService::Nominatim;
my \n = WebService::Nominatim.new;
```
Equivalent to:
```
use WebService::Nominatim 'n';
```
Add debug output:
```
use WebService::Nominatim 'n' '-debug';
```
If an argument is provided, a new instance will be returned. If `-debug` is provided, the instance will send logs to stderr. Note this is different from the `debug` attribute, which gets debug information from the server.
# ATTRIBUTES
## url
The base URL for the Nominatim API. Defaults to `https://nominatim.openstreetmap.org`.
## email
The email address to use in the `email` query parameter. Optional, but recommended if you are sending a lot of requests.
## debug
Optionally send debug => 1 in search requests. Responses will be HTML.
## dedupe
Optionally send dedupe => 1 to search request.
# EXPORTS
If an argument is given to the module, it is assumed to be a name and the module creates a new `WebService::Nominatim` object. Also "-debug" will send debug output to stderr. These are equivalent:
```
use WebService::Nominatim 'nom', '-debug';
```
and
```
use WebService::Nominatim;;
my \nom = WebService::Nominatim.new;
nom.logger.send-to: $*ERR;
```
# METHODS
## search
Search for a location using either a string search or a structured search. This will always return a list. The items in the list may be strings or hashes, depending on the format (json formats will be parsed into hashes). Use `:raw` to return strings.
### Usage
```
$n.search('Grand Central Station');
say .<display_name> for $n.search: 'Main St', :limit(5);
$n.search: '221B Baker Street, London, UK';
$n.search: query => '221B Baker Street, London, UK';
$n.search: query => { street => '221B Baker Street', city => 'London', country => 'UK' }, limit => 5;
```
### Parameters
See <https://nominatim.org/release-docs/develop/api/Search/> for details about meanings of the parameters.
* `$query`
The search query. This can be a string or a hash of search parameters.
It can be a named parameter, or the first positional parameter.
* `:raw`
If set to a true value, the raw response will be returned as a string, without JSON parsing.
* `:format`
The format of the response. Defaults to jsonv2. Other options are xml, json, geojson, and geocodejson.
Other parameters:
* `:layer`
* `:featureType`
* `:addressdetails`
* `:limit`
* `:extratags`
* `:namedetails`
* `:accept-language`
* `:countrycodes`
* `:exclude_place_ids`
* `:viewbox`
* `:bounded`
* `:polygon_geojson`
* `:polygon_kml`
* `:polygon_svg`
* `:polygon_text`
* `:polygon_threshold`
## lookup
Look up an object.
```
say n.lookup('R1316770', :format<geojson>);
say n.lookup(relation-id => '1316770', :format<geojson>);
say n.lookup(relation-ids => [ 1316770, ], :format<geojson>, :polygon_geojson);
```
### Parameters
Many of the same parameters as `search` are available.
Additionally, `node-ids`, `way-ids`, and `relation-ids` can be used to look up multiple objects. And `node-id`, `way-id`, and `relation-id` can be used to look up a single object.
See <https://nominatim.org/release-docs/develop/api/Lookup/> for more details.
## status
Get the status of the Nominatim server.
```
say n.status;
```
# SEE ALSO
<https://nominatim.org/release-docs/develop/api/Search/>
# AUTHOR
Brian Duggan
|
## dist_zef-lizmat-List-AllUtils.md
[](https://github.com/lizmat/List-AllUtils/actions)
# NAME
Raku port of Perl's List::AllUtils module 0.14
# SYNOPSIS
```
use List::AllUtils qw( first any );
# _Everything_ from List::Util, List::MoreUtils, and List::UtilsBy
use List::AllUtils qw( :all );
my @numbers = ( 1, 2, 3, 5, 7 );
# or don't import anything
return List::AllUtils::first { $_ > 5 } @numbers;
```
# DESCRIPTION
This module tries to mimic the behaviour of Perl's `List::AllUtils` module as closely as possible in the Raku Programming Language.
Are you sick of trying to remember whether a particular helper is defined in List::Util, List::MoreUtils or List::UtilsBy? Now you don't have to remember. This module will export all of the functions that either of those three modules defines.
## Which One Wins?
`List::AllUtils` always favors the version provided by List::Util, List::MoreUtils or List::UtilsBy in that order.
## Where is the documentation?
Rather than copying the documentation and running the risk of getting out of date, please check the original documentation using the following mapping:
### List::Util
```
all any first max maxstr min minstr none notall pairfirst pairgrep pairkeys
pairmap pairs pairvalues product reduce shuffle sum sum0 uniq uniqnum uniqstr
unpairs
```
### List::MoreUtils
```
after after_incl all_u any_u apply arrayify before before_incl binsert
bremove bsearch bsearch_index bsearch_insert bsearch_remove bsearchidx
distinct duplicates each_array each_arrayref equal_range false first_index
first_result first_value firstidx firstres firstval frequency indexes
insert_after insert_after_string last_index last_result last_value lastidx
lastres lastval listcmp lower_bound mesh minmax minmaxstr mode natatime
none_u notall_u nsort_by occurrences one one_u only_index only_result
only_value onlyidx onlyres onlyval pairwise part qsort reduce_0 reduce_1
reduce_u samples singleton sort_by true upper_bound zip zip6 zip_unflatten
```
### List::UtilsBy
```
bundle_by count_by extract_by extract_first_by max_by min_by minmax_by
nmax_by nmin_by nminmax_by partition_by rev_nsort_by rev_sort_by uniq_by
unzip_by weighted_shuffle_by zip_by
```
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
Source can be located at: <https://github.com/lizmat/List-AllUtils> . Comments and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2018, 2019, 2020, 2021 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
Re-imagined from the Perl version as part of the CPAN Butterfly Plan. Perl version developed by Dave Rolsky.
|
## dist_zef-tony-o-System-Query.md
# WELCOME TO WARTHOG
I does build decisions.
## Usage
```
use System::Query;
use JSON::Fast;
my $json = from-json("build.json".IO.slurp);
my $decisions = system-collapse($json);
qw<...>;
```
## Input
Calling `parse` with the following JSON will run through and choose what it thinks is the best options in the environment.
```
{
"nested": {
"test": "data"
},
"nested2": {
"test2": "data2"
},
"options": {
"run": {
"by-distro.name": {
"macosx": {
"by-distro.version": {
"10.0+": "10make",
"9.0+": "9make",
"8.0+": "8make"
}
},
"win32": {
"by-distro.version": {
"6+": "6winmake",
"5+": "5winmake"
}
},
"": "null-make"
}
}
},
"default-test": {
"second-test": "string-val, no decisions",
"first-test": {
"by-distro.name": {
"": "default-option1"
}
}
}
}
```
## Output
This is the result of the parse; notice that the distro/kernel/etc queries collapse to show the decisions based on variables.
```
{
default-test => {
first-test => "default-option1".Str,
second-test => "string-val, no decisions".Str,
},
nested => {
test => "data".Str,
},
nested2 => {
test2 => "data2".Str,
},
options => {
run => "10make".Str,
},
}
```
|
## dist_cpan-JMERELO-Pod-Load.md
[](https://travis-ci.com/JJ/p6-pod-load) [](https://ci.appveyor.com/project/JJ/p6-pod-load)
# NAME
Pod::Load - Loads and compiles the Pod documentation of an external file
# SYNOPSIS
```
use Pod::Load;
# Read a file handle.
my $pod = load("file-with.pod6".IO);
say $pod.perl; # Process it as a Pod
# Or use simply the file name
my @pod = load("file-with.pod6");
say .perl for @pod;
my $string-with-pod = q:to/EOH/;
```
This ordinary paragraph introduces a code block:
EOH
```
say load( $string-with-pod ).perl;
```
# DESCRIPTION
Pod::Load is a module with a simple task: obtain the documentation of an external file in a standard, straighworward way. Its mechanism is inspired by [`Pod::To::BigPage`](https://github.com/perl6/perl6-pod-to-bigpage), from where the code to use the cache is taken from.
### multi sub load
```
multi sub load(
Str $string
) returns Mu
```
Loads a string, returns a Pod.
### multi sub load
```
multi sub load(
Str $file where { ... }
) returns Mu
```
If it's an actual filename, loads a file and returns the pod
### multi sub load
```
multi sub load(
IO::Path $io
) returns Mu
```
Loads a IO::Path, returns a Pod.
# INSTRUCTIONS
This is mainly a reminder to myself, although it can help you if you create a distribution just like this one.
Write:
```
export VERSION=0.x.x
```
And
```
make dist
```
To create a tar file ready for CPAN.
# AUTHOR
JJ Merelo [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
Copyright 2018, 2019 JJ Merelo
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-tony-o-Mux.md
# mux
use this to obtain great parallel powers. also to alleviate the headache that comes with queues and managing workers.
## Mux.new(:callable, :channels)
`:callable` should be something callable. this is the method you write that is going to do all of your work for you and it should take one argument. eg. `sub ($elem) { }`
`:channels` this should be the maximum level of parallelization that you'd like. defaults to `int(max_threads / 1.5)`. this will warn but not puke if you specify higher than max\_threads parallelization and be warned that if you exceed the scheduler you may find your application locked.
## .demux(callable)
this sets what demuxes the return values from your workers should you so need them.
```
my Mux $m .=new(
:callable(sub (Int() $x) { $x * 2; }),
);
$m.demux(-> $rval {
#rval will be 2, then 2, then 4, then 6, etc
});
$q.start: 1,1,2,3; #etc;
```
## .error(callable)
this is a `sub ($error) { }` to be called when there is an unhandled error in the worker (if it's not in your sub then please open a ticket).
## .drain(callable)
this is a `sub (Mux:D) { }` called when the work queue is complete.
## .pause
for pausing the queue, you can still feed the muxer but don't put your fingers in its mouth.
## .paused
will let you know if the muxer is paused
## .unpause
let's the hedonistic muxer consume
## .unpaused
lets you know whether you should keep your hands away from the cage
## .block
finally, if you want to block until the muxer is done processing the queue
## .feed(\*@ )
you can feed the muxer while its running, this will not reset the queue or alter current processing but it will cause `.drain` to be called later
|
## dist_github-codesections-Pod-Weave.md
[](https://github.com/codesections/pod-weave/actions)
# NAME
Pod::Weave - Weave documentation from Raku source
# SYNOPSIS
Installation (assuming you already have Raku and [zef](https://github.com/ugexe/zef) installed):
```
zef install Pod::Weave
```
You can use Pod::Weave via it's command-line tool, `pod-weave`
```
pod-weave source.raku > woven.md
```
# DESCRIPTION
Pod::Weave renders documentation from Raku source files. The documentation consists of formatted pod blocks interwoven with formatted code blocks containing all of the source code from the Raku file. The goal of doing so is to support basic [literate programming](https://en.wikipedia.org/wiki/Literate_programming) in Raku. You can use Pod::Weave to generate any of the output formats located in the Pod::Weave::To module.
For additional details, please see the announcement blog post: [www.codesections.com/blog/weaving-raku](https://www.codesections.com/blog/weaving-raku).
# AUTHOR
codesections [[email protected]](mailto:[email protected])
# COPYRIGHT AND LICENSE
ⓒ 2020 Daniel Sockwell
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## announcements.md
Announcements page
A date-stamped list of notes relevant to the Raku documentation site.
This Block name is not known, could be a typo or missing plugin
# [Note](#Announcements_page "go to top of document")
Contents are
An announcements page is now available. The most recent announcement will pop up when the website is loaded, but it will not appear again.
Announcements can contain all the RakuDoc elements, including:
* lists as here
* format / markup codes such `inline code`, **bolded text**, *Italics*, ***bolded italics***.
The only constraint is how much space is used in the popup.
|
## dist_github-nige123-jmp.md
# jmp.nigelhamilton.com
jmp - jump to files in your workflow
Usage:
```
jmp -- show most recent
jmp to '[<search-terms> ...]' -- lines matching search terms in files
# jmp on files in command output. For example:
jmp locate README -- files in the filesystem
jmp tail /some.log -- files mentioned in log files
jmp ls -- files in a directory
jmp find . -- files returned from the find command
jmp git status -- files in git
jmp perl test.pl -- Perl output and errors
jmp raku test.raku -- Raku output and errors
jmp config -- edit ~/.jmp config to set the editor
-- and search commands
jmp help -- show this help
jmp edit <filename> [<line-number>] -- start editing at a line number
jmp edit <filename> '[<search-terms> ...]' -- start editing at a matching line
```

|
## dist_cpan-TYIL-Ops-SI.md
# Ops::SI
Add postfix operators for [SI
prefixes](https://en.wikipedia.org/wiki/Metric_prefix).
## Installation
Installation can be done through [zef](https://github.com/ugexe/zef):
```
$ zef install Ops::SI
```
## Usage
In your Perl 6 code, use the module and you're all set.
```
use Ops::SI;
dd 1k; # 1000
dd 2T; # 2000000000000
dd 3µ; # 0.000003
dd 4y; # 4e-24
```
## License
This module is distributed under the terms of the AGPL version 3.0. You can
find it in the `LICENSE` file distributed with the module.
|
## dist_zef-FCO-SixPM.md
# 🕕 - 6pm
6pm is a NPM for raku
## Create META6.json
```
$ mkdir TestProject
$ cd TestProject/
$ 6pm init
Project name [TestProject]:
Project tags:
raku version [6.*]:
```
## Locally install a Module
```
$ 6pm install Heap
===> Searching for: Heap
===> Testing: Heap:ver('0.0.1')
===> Testing [OK]: Heap:ver('0.0.1')
===> Installing: Heap:ver('0.0.1')
```
## Locally install a Module and add it on depends of META6.json
```
$ 6pm install Heap --save
===> Searching for: Heap
===> Testing: Heap:ver('0.0.1')
===> Testing [OK]: Heap:ver('0.0.1')
===> Installing: Heap:ver('0.0.1')
```
## Run code using the local dependencies
```
$ 6pm exec -- raku -MHeap -e 'say Heap.new: <q w e r>'
Heap.new: [e r q w]
```
## Run a file using the local dependencies
```
$ echo "use Heap; say Heap.new: <q w e r>" > bla.p6
$ 6pm exec-file bla.p6
Heap.new: [e r q w]
```
## Make your code always use 6pm
```
$ echo "use SixPM; use Heap; say Heap.new: <q w e r>" > bla.p6
$ raku bla.p6
Heap.new: [e r q w]
```
## Running scripts
Add your script at your META6.json scripts field and run it with:
```
$ cat META6.json
{
"name": "TestProject",
"source-url": "",
"perl": "6.*",
"resources": [
],
"scripts": {
"test": "zef test .",
"my-script": "raku -MHeap -e 'say Heap.new: ^10'"
},
"depends": [
],
"test-depends": [
"Test",
"Test::META"
],
"provides": {
},
"tags": [
],
"version": "0.0.1",
"authors": [
"fernando"
],
"description": ""
}
$ 6pm run my-script
Heap.new: [0 1 2 3 4 5 6 7 8 9]
```
|
## dist_cpan-TYIL-Config.md
# Config
Extensible configuration class for the Raku programming language.
## Installation
This module can be installed using `zef`:
```
zef install Config
```
Depending on the type of configuration file you want to work on, you will need a
`Config::Parser::` module as well. If you just want an easy-to-use configuration
object without reading/writing a file, no parser is needed.
## Usage
To start off, specify a *template* of your configuration. `Config` will check
a couple of directories for a configuration file (based on the XDG base
directory spec), and will also automatically try to see if there's any
configuration specified in environment variables.
To specify a template, pass it as an argument to `new`.
```
my $config = Config.new({
keyOne => Str,
keyTwo => {
NestedKey => "default value",
},
keyThree => Int,
}, :name<foobar>);
```
Important to note here is the `name` attribute which is being set. This name
is used to look up configuration files in default locations and the
environment. For this particular example, it will check any directory specified
in `$XDG_CONFIG_DIRS` for files matching `foobar.*` and `foobar/config.*`.
Afterwards, it will check `$XDG_CONFIG_HOME` for the same files. If these
variables are not set, it will just check `$HOME/.config` for those files.
Additionally, the environment will be checked for `$FOOBAR_KEYONE`,
`$FOOBAR_KEYTWO_NESTEDKEY`, and `$FOOBAR_KEYTHREE`. The former two will be cast
to `Str` appropriately, with `$FOOBAR_KEYTHREE` being cast to an `Int`. This
ensures that the values are of the correct type, even if they're pulled from a
shell environment. This also works for `IO::Path`!
*If you're using the Raku `Log` module, you can set `RAKU_LOG_LEVEL` to `7` to
see which places it actually checks and reads for values.*
You can also manually read configuration files or hashes of values.
```
# Load a simple configuration hash
$config.=read({
keyOne => 'value',
keyTwo => {
NestedKey => 'other value'
}
});
# Load a configuration files
$config.=read('/etc/config.yaml');
# Load a configuration file with a specific parser
$config.=read('/etc/config', Config::Parser::ini);
```
Do note the use of `.=` here. `Config` returns a new `Config` object if you
change its values, it is an immutable object. The `.=` operator provided by
Raku is a shorthand for `$config = $config.read(...)`.
To read values from the `Config` object, you can use the `get` method, or treat
it as a `Hash`.
```
# Retrieve a value
$config.get('keyOne');
# Same as above, but treating it as a Hash
$config<keyOne>;
# Retrieve a value by nested key
$config.get('keyTwo.NestedKey');
```
The `Config` object can also write it's current configuration back to a file.
You must specify a particular `Config::Parser` implementation as well.
```
# Write out the configuration using the json parser
$config.write($*HOME.add('.config/foobar/config.json', Config::Parser::json);
```
### Available parsers
Because there's so many ways to structure your configuration files, the parsers
for these are their own modules. This allows for easy implementing new parsers,
or providing a custom parser for your project's configuration file.
The parser will be loaded during runtime, but you have to make sure it is
installed yourself.
The following parsers are available:
* json:
* [`Config::Parser::json`](https://github.com/arjancwidlak/p6-Config-Parser-json)
* [`Config::Parser::json`](https://github.com/robertlemmen/perl6-config-json)
* [`Config::Parser::toml`](https://github.com/scriptkitties/p6-Config-Parser-toml)
* [`Config::Parser::yaml`](https://github.com/scriptkitties/p6-Config-Parser-yaml)
### Writing your own parser
If you want to make your own parser, simply make a new class which extends the
`Config::Parser` class, and implements the `read` and `write` methods. The
`read` method *must* return a `Hash`. The `write` method *must* return a
`Bool`, `True` when writing was successful, `False` if not. Throwing
`Exception`s to indicate the kind of failure is recommended.
## Contributing
If you want to contribute to `Config`, you can do so by mailing your patches to
`~tyil/[email protected]`. Any questions or other forms of feedback are
welcome too!
## License
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License version 3, as published by
the Free Software Foundation.
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 General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.