txt
stringlengths 93
37.3k
|
---|
## dist_zef-FRITH-Math-FFT-Libfftw3.md
[](https://github.com/frithnanth/perl6-Math-FFT-Libfftw3/actions)
# NAME
Math::FFT::Libfftw3::C2C - High-level bindings to libfftw3 Complex-to-Complex transform
```
use v6;
use Math::FFT::Libfftw3::C2C;
use Math::FFT::Libfftw3::Constants; # needed for the FFTW_BACKWARD constant
my @in = (0, π/100 … 2*π)».sin;
put @in».Complex».round(10⁻¹²); # print the original array as complex values rounded to 10⁻¹²
my Math::FFT::Libfftw3::C2C $fft .= new: data => @in;
my @out = $fft.execute;
put @out; # print the direct transform output
my Math::FFT::Libfftw3::C2C $fftr .= new: data => @out, direction => FFTW_BACKWARD;
my @outr = $fftr.execute;
put @outr».round(10⁻¹²); # print the backward transform output rounded to 10⁻¹²
```
```
use v6;
use Math::FFT::Libfftw3::C2C;
use Math::FFT::Libfftw3::Constants; # needed for the FFTW_BACKWARD constant
# direct 2D transform
my Math::FFT::Libfftw3::C2C $fft .= new: data => 1..18, dims => (6, 3);
my @out = $fft.execute;
put @out;
# reverse 2D transform
my Math::FFT::Libfftw3::C2C $fftr .= new: data => @out, dims => (6,3), direction => FFTW_BACKWARD;
my @outr = $fftr.execute;
put @outr».round(10⁻¹²);
```
# DESCRIPTION
**Math::FFT::Libfftw3::C2C** provides an OO interface to libfftw3 and allows you to perform Complex-to-Complex Fast Fourier Transforms.
## new(:@data!, :@dims?, Int :$direction? = FFTW\_FORWARD, Int :$flag? = FFTW\_ESTIMATE, Int :$dim?, Int :$thread? = NONE, Int :$nthreads? = 1)
## new(:$data!, Int :$direction? = FFTW\_FORWARD, Int :$flag? = FFTW\_ESTIMATE, Int :$dim?, Int :$thread? = NONE, Int :$nthreads? = 1)
The first constructor accepts any Positional of type Int, Rat, Num, Complex (and IntStr, RatStr, NumStr, ComplexStr); it allows List of Ints, Array of Complex, Seq of Rat, shaped arrays of any base type, etc.
The only mandatory argument is **@data**. Multidimensional data are expressed in row-major order (see [C Library Documentation](C Library Documentation)) and the array **@dims** must be passed to the constructor, or the data will be interpreted as a 1D array. If one uses a shaped array, there's no need to pass the **@dims** array, because the dimensions will be read from the array itself.
The **$direction** parameter is used to specify a direct or backward transform; it defaults to FFTW\_FORWARD.
The **$flag** parameter specifies the way the underlying library has to analyze the data in order to create a plan for the transform; it defaults to FFTW\_ESTIMATE (see [C Library Documentation](C Library Documentation)).
The **$dim** parameter asks for an optimization for a specific matrix rank. The parameter is optional and if present must be in the range 1..3.
The **$thread** parameter specifies the kind of threaded operation one wants to get; this argument is optional and if not specified is assumed as **NONE**. There are three possibile values:
* NONE
* THREAD
* OPENMP
**THREAD** will use specific POSIX thread library while **OPENMP** will select an OpenMP library.
The **$nthreads** specifies the number of threads to use; it defaults to 1.
The second constructor accepts a scalar: an object of type **Math::Matrix** (if that module is installed, otherwise it returns a **Failure**); the meaning of all the other parameters is the same as in the other constructor.
## execute(Int :$output? = OUT-COMPLEX --> Positional)
Executes the transform and returns the output array of values as a normalized row-major array. The parameter **$output** can be optionally used to specify how the array is to be returned:
* OUT-COMPLEX
* OUT-REIM
* OUT-NUM
The default (**OUT-COMPLEX**) is to return an array of Complex. **OUT-REIM** makes the `execute` method return the native representation of the data: an array of couples of real/imaginary values. **OUT-NUM** makes the `execute` method return just the real part of the complex values.
## Attributes
Some of this class' attributes are readable:
* @.out
* $.rank
* @.dims
* $.direction
* $.dim (used when a specialized tranform has been requested)
* $.flag (how to compute a plan)
* $.adv (normal or advanced interface)
* $.howmany (only for the advanced interface)
* $.istride (only for the advanced interface)
* $.ostride (only for the advanced interface)
* $.idist (only for the advanced interface)
* $.odist (only for the advanced interface)
* @.inembed (only for the advanced interface)
* @.onembed (only for the advanced interface)
* $.thread (only for the threaded model)
## Wisdom interface
This interface allows to save and load a plan associated to a transform (There are some caveats. See [C Library Documentation](C Library Documentation)).
### plan-save(Str $filename --> True)
Saves the plan into a file. Returns **True** if successful and a **Failure** object otherwise.
### plan-load(Str $filename --> True)
Loads the plan from a file. Returns **True** if successful and a **Failure** object otherwise.
## Advanced interface
This interface allows to compose several transformations in one pass. See [C Library Documentation](C Library Documentation).
### advanced(Int $rank!, @dims!, Int $howmany!, @inembed!, Int $istride!, Int $idist!, @onembed!, Int $ostride!, Int $odist!)
This method activates the advanced interface. The meaning of the arguments are detailed in the [C Library Documentation](C Library Documentation).
This method returns **self**, so it can be concatenated to the **.new()** method:
```
my $fft = Math::FFT::Libfftw3.new(data => (1..30).flat)
.advanced: $rank, @dims, $howmany,
@inembed, $istride, $idist,
@onembed, $ostride, $odist;
```
# NAME
Math::FFT::Libfftw3::R2C - High-level bindings to libfftw3 Real-to-Complex transform
```
use v6;
use Math::FFT::Libfftw3::R2C;
use Math::FFT::Libfftw3::Constants; # needed for the FFTW_BACKWARD constant
my @in = (0, π/100 … 2*π)».sin;
put @in».Complex».round(10⁻¹²); # print the original array as complex values rounded to 10⁻¹²
my Math::FFT::Libfftw3::R2C $fft .= new: data => @in;
my @out = $fft.execute;
put @out; # print the direct transform output
my Math::FFT::Libfftw3::R2C $fftr .= new: data => @out, direction => FFTW_BACKWARD;
my @outr = $fftr.execute;
put @outr».round(10⁻¹²); # print the backward transform output rounded to 10⁻¹²
```
```
use v6;
use Math::FFT::Libfftw3::R2C;
use Math::FFT::Libfftw3::Constants; # needed for the FFTW_BACKWARD constant
# direct 2D transform
my Math::FFT::Libfftw3::R2C $fft .= new: data => 1..18, dims => (6, 3);
my @out = $fft.execute;
put @out;
# reverse 2D transform
my Math::FFT::Libfftw3::R2C $fftr .= new: data => @out, dims => (6,3), direction => FFTW_BACKWARD;
my @outr = $fftr.execute;
put @outr».round(10⁻¹²);
```
# DESCRIPTION
**Math::FFT::Libfftw3::R2C** provides an OO interface to libfftw3 and allows you to perform Real-to-Complex Fast Fourier Transforms.
The direct transform accepts an array of real numbers and outputs a half-Hermitian array of complex numbers. The reverse transform accepts a half-Hermitian array of complex numbers and outputs an array of real numbers.
## new(:@data!, :@dims?, Int :$direction? = FFTW\_FORWARD, Int :$flag? = FFTW\_ESTIMATE, Int :$dim?, Int :$thread? = NONE, Int :$nthreads? = 1)
## new(:$data!, Int :$direction? = FFTW\_FORWARD, Int :$flag? = FFTW\_ESTIMATE, Int :$dim?, Int :$thread? = NONE, Int :$nthreads? = 1)
The first constructor accepts any Positional of type Int, Rat, Num, Complex (and IntStr, RatStr, NumStr, ComplexStr); it allows List of Ints, Array of Complex, Seq of Rat, shaped arrays of any base type, etc.
The only mandatory argument is **@data**. Multidimensional data are expressed in row-major order (see [C Library Documentation](C Library Documentation)) and the array **@dims** must be passed to the constructor, or the data will be interpreted as a 1D array. If one uses a shaped array, there's no need to pass the **@dims** array, because the dimensions will be read from the array itself.
The **$direction** parameter is used to specify a direct or backward transform; it defaults to FFTW\_FORWARD.
The **$flag** parameter specifies the way the underlying library has to analyze the data in order to create a plan for the transform; it defaults to FFTW\_ESTIMATE (see [C Library Documentation](C Library Documentation)).
The **$dim** parameter asks for an optimization for a specific matrix rank. The parameter is optional and if present must be in the range 1..3.
The **$thread** parameter specifies the kind of threaded operation one wants to get; this argument is optional and if not specified is assumed as **NONE**. There are three possibile values:
* NONE
* THREAD
* OPENMP
**THREAD** will use specific POSIX thread library while **OPENMP** will select an OpenMP library.
The **$nthreads** specifies the number of threads to use; it defaults to 1.
The second constructor accepts a scalar: an object of type **Math::Matrix** (if that module is installed, otherwise it returns a **Failure**); the meaning of all the other parameters is the same as in the other constructor.
## execute(Int :$output? = OUT-COMPLEX --> Positional)
Executes the transform and returns the output array of values as a normalized row-major array. The parameter **$output** can be optionally used to specify how the array is to be returned:
* OUT-COMPLEX
* OUT-REIM
* OUT-NUM
The default (**OUT-COMPLEX**) is to return an array of Complex. **OUT-REIM** makes the `execute` method return the native representation of the data: an array of couples of real/imaginary values. **OUT-NUM** makes the `execute` method return just the real part of the complex values.
When performing the reverse transform, the output array has only real values, so the `:$output` parameter is ignored.
## Attributes
Some of this class' attributes are readable:
* @.out
* $.rank
* @.dims
* $.direction
* $.dim (used when a specialized tranform has been requested)
* $.adv (normal or advanced interface)
* $.howmany (only for the advanced interface)
* $.istride (only for the advanced interface)
* $.ostride (only for the advanced interface)
* $.idist (only for the advanced interface)
* $.odist (only for the advanced interface)
* @.inembed (only for the advanced interface)
* @.onembed (only for the advanced interface)
* $.thread (only for the threaded model)
## Wisdom interface
This interface allows to save and load a plan associated to a transform (There are some caveats. See [C Library Documentation](C Library Documentation)).
### plan-save(Str $filename --> True)
Saves the plan into a file. Returns **True** if successful and a **Failure** object otherwise.
### plan-load(Str $filename --> True)
Loads the plan from a file. Returns **True** if successful and a **Failure** object otherwise.
## Advanced interface
This interface allows to compose several transformations in one pass. See [C Library Documentation](C Library Documentation).
### advanced(Int $rank!, @dims!, Int $howmany!, @inembed!, Int $istride!, Int $idist!, @onembed!, Int $ostride!, Int $odist!)
This method activates the advanced interface. The meaning of the arguments are detailed in the [C Library Documentation](C Library Documentation).
This method returns **self**, so it can be concatenated to the **.new()** method:
```
my $fft = Math::FFT::Libfftw3::R2C.new(data => (1..30).flat)
.advanced: $rank, @dims, $howmany,
@inembed, $istride, $idist,
@onembed, $ostride, $odist;
```
# NAME
Math::FFT::Libfftw3::R2R - High-level bindings to libfftw3 Real-to-Complex transform
```
use v6;
use Math::FFT::Libfftw3::R2R;
use Math::FFT::Libfftw3::Constants; # needed for the FFTW_R2HC and FFTW_HC2R constants
my @in = (0, π/100 … 2*π)».sin;
put @in».round(10⁻¹²); # print the original array as complex values rounded to 10⁻¹²
my Math::FFT::Libfftw3::R2R $fft .= new: data => @in, kind => FFTW_R2HC;
my @out = $fft.execute;
put @out; # print the direct transform output
my Math::FFT::Libfftw3::R2R $fftr .= new: data => @out, kind => FFTW_HC2R;
my @outr = $fftr.execute;
put @outr».round(10⁻¹²); # print the backward transform output rounded to 10⁻¹²
```
```
use v6;
use Math::FFT::Libfftw3::R2R;
use Math::FFT::Libfftw3::Constants; # needed for the FFTW_R2HC and FFTW_HC2R constants
# direct 2D transform
my Math::FFT::Libfftw3::R2R $fft .= new: data => 1..18, dims => (6, 3), kind => FFTW_R2HC;
my @out = $fft.execute;
put @out;
# reverse 2D transform
my Math::FFT::Libfftw3::R2R $fftr .= new: data => @out, dims => (6, 3), kind => FFTW_HC2R;
my @outr = $fftr.execute;
put @outr».round(10⁻¹²);
```
# DESCRIPTION
**Math::FFT::Libfftw3::R2R** provides an OO interface to libfftw3 and allows you to perform Real-to-Real Halfcomplex Fast Fourier Transforms.
The direct transform accepts an array of real numbers and outputs a half-complex array of real numbers. The reverse transform accepts a half-complex array of real numbers and outputs an array of real numbers.
## new(:@data!, :@dims?, Int :$flag? = FFTW\_ESTIMATE, :$kind!, Int :$dim?, Int :$thread? = NONE, Int :$nthreads? = 1)
## new(:$data!, Int :$flag? = FFTW\_ESTIMATE, :$kind!, Int :$dim?, Int :$thread? = NONE, Int :$nthreads? = 1)
The first constructor accepts any Positional of type Int, Rat, Num (and IntStr, RatStr, NumStr); it allows List of Ints, Seq of Rat, shaped arrays of any base type, etc.
The only mandatory argument are **@data** and **$kind**. Multidimensional data are expressed in row-major order (see [C Library Documentation](C Library Documentation)) and the array **@dims** must be passed to the constructor, or the data will be interpreted as a 1D array. If one uses a shaped array, there's no need to pass the **@dims** array, because the dimensions will be read from the array itself.
The **kind** argument, of type **fftw\_r2r\_kind**, specifies what kind of trasform will be performed on the input data. **fftw\_r2r\_kind** constants are defined as an **enum** in **Math::FFT::Libfftw3::Constants**. The values of the **fftw\_r2r\_kind** enum are:
* FFTW\_R2HC
* FFTW\_HC2R
* FFTW\_DHT
* FFTW\_REDFT00
* FFTW\_REDFT01
* FFTW\_REDFT10
* FFTW\_REDFT11
* FFTW\_RODFT00
* FFTW\_RODFT01
* FFTW\_RODFT10
* FFTW\_RODFT11
The Half-Complex transform uses the symbol FFTW\_R2HC for a Real to Half-Complex (direct) transform, while the corresponding Half-Complex to Real (reverse) transform is specified by the symbol FFTW\_HC2R. The reverse transform of FFTW\_R*DFT10 is FFTW\_R*DFT01 and vice versa, of FFTW\_R*DFT11 is FFTW\_R*DFT11, and of FFTW\_R*DFT00 is FFTW\_R*DFT00.
The **$flag** parameter specifies the way the underlying library has to analyze the data in order to create a plan for the transform; it defaults to FFTW\_ESTIMATE (see [C Library Documentation](C Library Documentation)).
The **$dim** parameter asks for an optimization for a specific matrix rank. The parameter is optional and if present must be in the range 1..3.
The **$thread** parameter specifies the kind of threaded operation one wants to get; this argument is optional and if not specified is assumed as **NONE**. There are three possibile values:
* NONE
* THREAD
* OPENMP
**THREAD** will use specific POSIX thread library while **OPENMP** will select an OpenMP library.
The **$nthreads** specifies the number of threads to use; it defaults to 1.
The second constructor accepts a scalar: an object of type **Math::Matrix** (if that module is installed, otherwise it returns a **Failure**), a **$flag**, and a list of the kind of trasform one wants to be performed on each dimension; the meaning of all the other parameters is the same as in the other constructor.
## execute(--> Positional)
Executes the transform and returns the output array of values as a normalized row-major array.
## Attributes
Some of this class' attributes are readable:
* @.out
* $.rank
* @.dims
* $.direction
* @.kind
* $.dim (used when a specialized tranform has been requested)
* $.flag (how to compute a plan)
* $.adv (normal or advanced interface)
* $.howmany (only for the advanced interface)
* $.istride (only for the advanced interface)
* $.ostride (only for the advanced interface)
* $.idist (only for the advanced interface)
* $.odist (only for the advanced interface)
* @.inembed (only for the advanced interface)
* @.onembed (only for the advanced interface)
* $.thread (only for the threaded model)
## Wisdom interface
This interface allows to save and load a plan associated to a transform (There are some caveats. See [C Library Documentation](C Library Documentation)).
### plan-save(Str $filename --> True)
Saves the plan into a file. Returns **True** if successful and a **Failure** object otherwise.
### plan-load(Str $filename --> True)
Loads the plan from a file. Returns **True** if successful and a **Failure** object otherwise.
## Advanced interface
This interface allows to compose several transformations in one pass. See [C Library Documentation](C Library Documentation).
### advanced(Int $rank!, @dims!, Int $howmany!, @inembed!, Int $istride!, Int $idist!, @onembed!, Int $ostride!, Int $odist!)
This method activates the advanced interface. The meaning of the arguments are detailed in the [C Library Documentation](C Library Documentation).
This method returns **self**, so it can be concatenated to the **.new()** method:
```
my $fft = Math::FFT::Libfftw3::R2R.new(data => 1..30)
.advanced: $rank, @dims, $howmany,
@inembed, $istride, $idist,
@onembed, $ostride, $odist;
```
# C Library Documentation
For more details on libfftw see <http://www.fftw.org/>. The manual is available here <http://www.fftw.org/fftw3.pdf>
# Prerequisites
This module requires the libfftw3 library to be installed. Please follow the instructions below based on your platform:
## Debian Linux
```
sudo apt-get install libfftw3-double3
```
The module looks for a library called libfftw3.so.
# Installation
To install it using zef (a module management tool):
```
$ zef install Math::FFT::Libfftw3
```
# Testing
To run the tests:
```
$ prove -e "raku -Ilib"
```
# Notes
Math::FFT::Libfftw3 relies on a C library which might not be present in one's installation, so it's not a substitute for a pure Raku module. If you need a pure Raku module, Math::FourierTransform works just fine.
This module needs Raku ≥ 2018.09 only if one wants to use shaped arrays as input data. An attempt to feed a shaped array to the `new` method using `$*RAKU.compiler.version < v2018.09` results in an exception.
# Author
Fernando Santagata
# License
The Artistic License 2.0
|
## dist_zef-tony-o-HTTP-Server-Middleware-JSON.md
# HTTP::Server::Middleware::JSON
A JSON parser middleware for `HTTP::Server`s.
## Setup
```
use HTTP::Server::Async;
use HTTP::Server::Middleware::JSON;
my HTTP::Server::Async $app .=new;
body-parse-json $app;
$app.handler: sub ($req, $res) {
# may or may not have parsed JSON depending on Content-Type
}
$app.handler: $sub ($req, $res) is json-consumer {
# trait<json-consumer>: calls a default or custom error handler for
# invalid JSON found in the body of the request
# if the request gets here then $req.params<body> represents the
# parsed JSON data passed in the request body
}
# this is how to set a custom error handler for invalid or missing JSON
json-error sub ($req, $res) {
#do your thing, the returned value is returned to the underlying HTTP::Server
# so it knows whether or not to continue processing
}
```
|
## dist_zef-FRITH-Math-Libgsl-Sort.md
[](https://github.com/frithnanth/raku-Math-Libgsl-Sort/actions)
# NAME
Math::Libgsl::Sort - An interface to libgsl, the Gnu Scientific Library - Sort.
# SYNOPSIS
```
use Math::Libgsl::Raw::Sort :ALL;
use Math::Libgsl::Sort;
```
# DESCRIPTION
Math::Libgsl::Sort provides an interface to the sort 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 package comes with the Sort module tailored to all the real and integer types:
* Math::Libgsl::Sort - default, corresponding to a Math::Libgsl::Sort::Num64
* Math::Libgsl::Sort::Num32
* Math::Libgsl::Sort::Int32
* Math::Libgsl::Sort::UInt32
* Math::Libgsl::Sort::Int64
* Math::Libgsl::Sort::UInt64
* Math::Libgsl::Sort::Int16
* Math::Libgsl::Sort::UInt16
* Math::Libgsl::Sort::Int8
* Math::Libgsl::Sort::UInt8
All the subs of each package have their name prefixed by the relative data type:
Math::Libgsl::Sort has a sub num64sort, while Math::Libgsl::Sort::Int8 has a sub int8sort, and so on.
### num64sort(:@data, Int :$stride? = 1 --> List)
This sub takes two named arguments: the data array and the stride. The sub returns a List of values: the element of the original array sorted in ascending order.
For example:
```
my @data = (10…0)».Num;
say @data; # output: [10 9 8 7 6 5 4 3 2 1 0]
my @out = num64sort(:@data, :stride(2)); # sort the elements of @data, with a stride of 2: 10, 8, 6, 4, 2
say @out; # output: [0 9 2 7 4 5 6 3 8 1 10]
```
### num64sort2(:@data1, Int :$stride1? = 1, :@data2, Int :$stride2? = 1 --> List)
This sub takes four named arguments: two data arrays and the relative strides. The sub returns a List of Pairs: 'data1' and the element of the first array taken with a stride $stride1, sorted in ascending order, and 'data2' and the elements of the second array taken with a stride $stride2, rearranged as the first array.
For example:
```
my @data1 = (10…0)».Num;
my @data2 = (20…0)».Num;
say @data1; # output: [10 9 8 7 6 5 4 3 2 1 0]
say @data2; # output: [20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0]
my %out = num64sort2(:@data1, :stride1(2), :@data2, :stride2(3));
say %out<data1>; # output: (0 9 2 7 4 5 6 3 8 1 10)
say %out<data2>; # output: (5 19 18 8 16 15 11 13 12 14 10 9 17 7 6 20 4 3 2 1 0)
```
### num64sort-index(:@data, Int :$stride? = 1 --> List)
This sub indirectly sorts the elements of the array with stride into ascending order, returning the resulting permutation.
### num64sort-vector(Math::Libgsl::Vector $v)
This sub sorts in place the elements of the Math::Libgsl::Vector $v into ascending numerical order.
### num64sort2-vector(Math::Libgsl::Vector $v1, Math::Libgsl::Vector $v2)
This sub sorts the elements of the Math::Libgsl::Vector $v1 into ascending numerical order, while making the same rearrangement of the vector $v2.
### num64sort-vector-index(Math::Libgsl::Vector $v, Math::Libgsl::Permutation $p where $v.vector.size == $p.p.size)
This sub indirectly sorts the elements of the Math::Libgsl::Vector $v, storing the resulting permutation in $p. The vector and the permutation must have the same number of elements.
### num64smallest(:@data, Int :$stride? = 1, Int :$k? where \* ≤ (@data.elems / $stride).ceiling = @data.elems --> List)
This sub returns the $k smallest elements of the array, extracted with $stride, in ascending numerical order.
### num64largest(:@data, Int :$stride? = 1, Int :$k? where \* ≤ (@data.elems / $stride).ceiling = @data.elems --> List)
This sub returns the $k largest elements of the array, extracted with $stride, in ascending numerical order.
### num64smallest-index(:@data, Int :$stride? = 1, Int :$k? where \* ≤ (@data.elems / $stride).ceiling = @data.elems --> List)
This sub returns the indices of the $k smallest elements of the array, extracted with $stride, in ascending numerical order.
### num64largest-index(:@data, Int :$stride? = 1, Int :$k? where \* ≤ (@data.elems / $stride).ceiling = @data.elems --> List)
This sub returns the indices of the $k largest elements of the array, extracted with $stride, in ascending numerical order.
### num64vector-smallest(Math::Libgsl::Vector $v, Int $k? where \* < $v.vector.size = $v.vector.size --> List)
This sub returns the $k smallest elements of the vector, extracted with $stride, in ascending numerical order.
### num64vector-largest(Math::Libgsl::Vector $v, Int $k? where \* < $v.vector.size = $v.vector.size --> List)
This sub returns the $k largest elements of the vector, extracted with $stride, in ascending numerical order.
### num64vector-smallest-index(Math::Libgsl::Vector $v, Int $k? where \* < $v.vector.size = $v.vector.size --> List)
This sub returns the indices of the $k largest elements of the vector, extracted with $stride, in ascending numerical order.
### num64vector-largest-index(Math::Libgsl::Vector $v, Int $k? where \* < $v.vector.size = $v.vector.size --> List)
This sub returns the indices of the $k largest elements of the vector, extracted with $stride, in ascending numerical order.
# 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::Sort
```
# 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_zef-lucs-File-TreeBuilder.md
[](https://github.com/lucs/File-TreeBuilder/actions)
# NAME
```
File::TreeBuilder - Build text-scripted trees of files
```
## SYNOPSIS
```
use File::TreeBuilder;
my $tree-desc = Q:to/EoDesc/;
# Note that this heredoc string is literal ('Q'), so no
# interpolation occurs at all. The program will replace
# the literal '\n', '\t', '\s' (representing a space), and
# '\\' by the correct characters.
# Also, empty lines and lines starting with '#'
# will be discarded and ignored.
# It is invalid for any real tab characters to appear in
# this string, so indentation must be accomplished with
# spaces only. And the indentation must be coherent (bad
# examples are shown later).
# What follows is an example of an actual tree of files
# and directories that one might want to build. It has
# examples of pretty much all the features the program
# supports, described in detail later.
/ D1
. F1
. F2 . File\n\twith tab, newlines and 2 trailing space.\n\s\s
/_ D_2
.x Fx3
/600 D3
. F4 % f4-key
.755é Fé5
. F6 . \sLine continued, \
and backslash and 't': \\t.
EoDesc
my %file-contents = (
f4-key => "File contents from hash.".uc,
);
my $parent-dir = '/home/lucs/File-TreeBuilder.demo'.IO;
build-tree(
$parent-dir,
$tree-desc,
%file-contents,
);
```
The example code would create the following directories and files under the parent directory, which must already exist:
```
D1/
F1
F2
D 2/
F 3
D3/
F4
F 5
F6
Note that:
The 'D1' directory will have default permissions.
The 'F1' file will be empty and have default permissions.
The 'F2' file will contain :
"File\n\twith tab, newlines and 2 trailing spaces.\n ".
The 'D 2' directory has a space in its name.
The 'F 3' file has a space in its name.
The 'D3' directory will have permissions 0o600.
The 'F4' file will contain "FILE CONTENTS FROM HASH.".
The 'F 5' file has a space in its name and will have permissions
0o755.
The 'F6' file will contain " Line continued, and backslash and 't': \\t."
```
## DESCRIPTION
This module exports the `build-tree` function, used for building and populating simple trees of files and directories. I have found this useful to build test data for programs that need such things. Invoke the function like this:
```
build-tree(
IO::Path $parent-dir,
Str $tree-desc,
%file-contents?,
)
```
`$parent-dir` is the directory under which the needed files and directories will be created. It must already exist and have write permission.
`$tree-desc` is a multiline string describing a hierarchy of needed directories and files and their contents.
The optional `%file-contents` argument can be used to specify arbitrary file contents, as will be explained below.
### The tree description
Within the `$tree-desc` string, blank or empty lines are discarded and ignored. The string must also not contain any tab characters. The first non-blank character of each remaining line must be one of:
```
# : Comment line, will be discarded and ignored.
/ : The line describes a wanted directory.
. : The line describes a wanted file.
```
Any other first non-blank is invalid.
#### Directory descriptions
Directory descriptions must mention a directory name. The leading ‹/› can optionally be immmediately followed by a three-digit octal representation of the desired permissions of the directory and/or by a space-representing character to be used if the directory name is to contain spaces, and must then be followed by whitespace and the directory name. For example:
```
/ d : Directory 'd'.
/X dXc : Directory 'd c'; spaces in its name are represented by 'X'.
/600 e : Directory 'e', permissions 600 (octal always).
/755_ a_b : Directory 'a b', permissions 755.
/ : Error: Missing directory name.
/644 : Error: Missing directory name.
/ abc de : Error: unexpected data (here, 'de').
```
#### File descriptions
File descriptions must mention a file name. The leading ‹.› can optionally be immmediately followed by a three-digit octal representation of the desired permissions of the file and/or by a space-representing character to be used if the file name is to contain spaces, and must then be followed by whitespace and the file name, and then optionally be followed by whitespace and by a specification of their wanted contents, as one of either:
```
. ‹literal contents›
% ‹key of contents to be retrieved from the %file-contents argument›
```
A ‹.› means to place the trimmed rest of the line into the created file. The program will replace `\t`, `\n`, `\s`, and `\\` with actual tabs, newlines, spaces, and backslashes in the file inserted content. If a line ends with a single ‹\›, the line that follows it will be concatenated to it, having its leading spaces removed.
A ‹%› means to take the trimmed rest of the line as a key into the instance's `%file-contents` and to use the corresponding found value as the file contents.
For example:
```
. f : File "f", contents empty (default), default permissions.
._ f_a : File "f a": spaces in its name are represented by '_'.
.444Z fZb : File "f b", permission 444.
. f . me ow : File "f", literal contents: "me ow".
. f % k9 : File "f", contents retrieved from %file-contents<k9>.
. f . This line \
continues.\n
: File "f", contents are "This line continues.\n".
. : Error: missing filename.
. f x : Error: unrecognized ‹x›.
. f % baz : Error if %file-contents wasn't specified
or if key ‹baz› is missing from it.
. f % : Error: No key specified.
```
#### Hierarchy
Directories are created hierarchically, according to the indentation. Files are created in the directory hierarchically above them. In the hierarchy then, these are okay:
```
Directories and files intermixed on the same level.
/ d1
/ d2
. f1
. f2
/ d3
A directory holding a subdirectory or a file.
/ d1
/ d2
. f1
Returning to a previously established level, here at ‹. f2›.
/ d1
/ d2
/ d3
. f1
. f2
```
But these are not:
```
A file cannot hold a file.
. f1
. f2
Nor can it hold a directory.
. f1
/ d1
‹/ d3›'s indentation conflicts with those of ‹/ d1› and ‹/ d2›.
/ d1
/ d2
/ d3
‹/ d5›'s indentation conflicts with those of ‹/ d2› and ‹/ d3›.
/ d1
/ d2
/ d3
/ d4
/ d5
```
## AUTHOR
Luc St-Louis [[email protected]](mailto:[email protected])
## COPYRIGHT AND LICENSE
Copyright 2023
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## keep.md
keep
Combined from primary sources listed below.
# [In Promise](#___top "go to top of document")[§](#(Promise)_method_keep "direct link")
See primary documentation
[in context](/type/Promise#method_keep)
for **method keep**.
```raku
multi method keep(Promise:D: \result = True)
```
Keeps a promise, optionally setting the result. If no result is passed, the result will be `True`.
Throws an exception of type [`X::Promise::Vowed`](/type/X/Promise/Vowed) if a vow has already been taken. See method `vow` for more information.
```raku
my $p = Promise.new;
if Bool.pick {
$p.keep;
}
else {
$p.break;
}
```
|
## dist_zef-lizmat-P5chomp.md
[](https://github.com/lizmat/P5chomp/actions)
# NAME
Raku port of Perl's chomp() / chop() built-ins
# SYNOPSIS
```
use P5chomp; # exports chomp() and chop()
chomp $a;
chomp @a;
chomp %h;
chomp($a,$b);
chomp(); # bare chomp may be compilation error to prevent P5isms in Raku
chop $a;
chop @a;
chop %h;
chop($a,$b);
chop(); # bare chop may be compilation error to prevent P5isms in Raku
```
# DESCRIPTION
This module tries to mimic the behaviour of the Perl's `chomp` and `chop` built-ins in Raku as closely as possible.
# ORIGINAL PERL 5 DOCUMENTATION
```
chop VARIABLE
chop( LIST )
chop Chops off the last character of a string and returns the character
chopped. It is much more efficient than "s/.$//s" because it
neither scans nor copies the string. If VARIABLE is omitted, chops
$_. If VARIABLE is a hash, it chops the hash's values, but not its
keys, resetting the "each" iterator in the process.
You can actually chop anything that's an lvalue, including an
assignment.
If you chop a list, each element is chopped. Only the value of the
last "chop" is returned.
Note that "chop" returns the last character. To return all but the
last character, use "substr($string, 0, -1)".
chomp VARIABLE
chomp( LIST )
chomp This safer version of "chop" removes any trailing string that
corresponds to the current value of $/ (also known as
$INPUT_RECORD_SEPARATOR in the "English" module). It returns the
total number of characters removed from all its arguments. It's
often used to remove the newline from the end of an input record
when you're worried that the final record may be missing its
newline. When in paragraph mode ("$/ = """), it removes all
trailing newlines from the string. When in slurp mode ("$/ =
undef") or fixed-length record mode ($/ is a reference to an
integer or the like; see perlvar) chomp() won't remove anything.
If VARIABLE is omitted, it chomps $_. Example:
while (<>) {
chomp; # avoid \n on last field
@array = split(/:/);
# ...
}
If VARIABLE is a hash, it chomps the hash's values, but not its
keys, resetting the "each" iterator in the process.
You can actually chomp anything that's an lvalue, including an
assignment:
chomp($cwd = `pwd`);
chomp($answer = <STDIN>);
If you chomp a list, each element is chomped, and the total number
of characters removed is returned.
Note that parentheses are necessary when you're chomping anything
that is not a simple variable. This is because "chomp $cwd =
`pwd`;" is interpreted as "(chomp $cwd) = `pwd`;", rather than as
"chomp( $cwd = `pwd` )" which you might expect. Similarly, "chomp
$a, $b" is interpreted as "chomp($a), $b" rather than as
"chomp($a, $b)".
```
# PORTING CAVEATS
In future language versions of Raku, it will become impossible to access the `$_` variable of the caller's scope, because it will not have been marked as a dynamic variable. So please consider changing:
```
chomp;
```
to either:
```
chomp($_);
```
or, using the subroutine as a method syntax, with the prefix `.` shortcut to use that scope's `$_` as the invocant:
```
.&chomp;
```
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!
Source can be located at: <https://github.com/lizmat/P5chomp> . Comments and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2018, 2019, 2020, 2021, 2023 Elizabeth Mattijsen
Re-imagined from Perl as part of the CPAN Butterfly Plan.
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-raku-community-modules-CoreHackers-Sourcery.md
[](https://github.com/raku-community-modules/CoreHackers-Sourcery/actions)
# NAME
CoreHackers::Sourcery - Show source locations of core methods and subs
# SYNOPSIS
```
use CoreHackers::Sourcery;
&say.sourcery("foo").put;
# OUTPUT:
# src/core/io_operators.pm:22 https://github.com/rakudo/rakudo/blob/c843682/src/core/io_operators.pm#L22
put sourcery Int, 'abs'; # method called on a type object
put sourcery 42, 'split'; # method called on an Int object
put sourcery 42, 'base', \(16); # method call with args
```
# DESCRIPTION
This module provides the *actual* location of the sub or method definition in Rakudo's source code.
# BLOG POST
Related [blog post](https://github.com/Raku/CCR/blob/main/Remaster/Zoffix%20Znet/Raku-Core-Hacking-Wheres-Da-Sauce-Boss.md#raku-core-hacking-wheres-da-sauce-boss).
# METHODS
```
&say.sourcery.put; # location of the `proto`
&say.sourcery('foo').put; # location of the candidate that can do 'foo'
```
The core `Code` class and its core subclasses get augmented with a `.sourcery` method. Calling this method without arguments provides the location of the method or sub, or the `proto` of the multi.
When called with arguments, returns the location of the narrowest candidate, possibly `die`ing if no candidate can be found.
Returns a list of two strings: the `file:line-number` referring to the core file and the GitHub URL.
# EXPORTED SUBROUTINES
## sourcery
```
put sourcery &say; # just Code object
put sourcery &say, \('foo'); # find best candidate for a Code object
put sourcery Int, 'abs'; # method `abs` on a type object
# find best candidate for method `base` on object 42, with argument `16`
put sourcery 42, 'base', \(16);
```
Operates similar to the method form, except allows more flexibility, such as passing object/method names. Returns a list of two strings: the `file:line-number` referring to the core file and the GitHub URL.
# ENVIRONMENT VARIABLES
## SOURCERY\_SETTING
The location of the setting file. Defaults to:
```
$*EXECUTABLE.parent.parent.parent.child(&say.file)
```
This will generally work for most installs.
# AUTHOR
Zoffix Znet
# COPYRIGHT AND LICENSE
Copyright 2016 - 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-jonathanstowe-Audio-Fingerprint-Chromaprint.md
# Audio::Fingerprint::Chromaprint
Get audio fingerprint using the chromaprint / AcoustID library

## Synopsis
```
use Audio::Fingerprint::Chromaprint;
use Audio::Sndfile;
my $fp = Audio::Fingerprint::Chromaprint.new;
my $wav = Audio::Sndfile.new(filename => 'some.wav', :r);
$fp.start($wav.samplerate, $wav.channels);
# Read the whole file at once
my ( $data, $frames ) = $wav.read-short($wav.frames, :raw);
# You can feed multiple times
$fp.feed($data, $frames);
# call finish to indicate done feeding
$fp.finish;
say $fp.fingerprint;
```
## Description
This provides a mechanism for obtaining a fingerprint of some audio data
using the [Chromaprint library](https://acoustid.org/chromaprint), you
can use this to identify recorded audio or determine whether two audio
files are the same for instance.
You need several seconds worth of data in order to be able to get a
usable fingerprint, and for comparison of two files you will need to
ensure that you have the same number of samples, ideally you should
fingerprint the entire audio file, but this may be slow if you have
a large file.
Depending on how the Chromaprint library was built, it may or may not
be safe to have multiple instances created at the same time, so it
is probably safest to take care you only have a single instance in
your application.
## Installation
You will need the chromaprint library v1 installed for this to work,
many operating system distributions will have a package that you
can install with appropriate software. If you do not have a package
available you may be able to build it from the source which can be
found at <https://acoustid.org/chromaprint>.
Assuming you have a working Rakudo installation (and the
chromaprint library,) then you should be able to install the module
with `zef` :
```
zef install Audio::Fingerprint::Chromaprint
```
## Support
This is a fairly simple library, but if you find a problem with it
or have a suggestion how it can be improved then please raise a
ticket at [github](https://github.com/jonathanstowe/Audio-Fingerprint-Chromaprint/issues).
## Copyright & Licence
This is free software.
See the <LICENCE> file in the distribution.
© Jonathan Stowe 2016 - 2021
|
## dist_zef-lizmat-P5length.md
[](https://github.com/lizmat/P5length/actions)
# NAME
Raku port of Perl's length() built-in
# SYNOPSIS
```
use P5length; # exports length()
say length("foobar"); # 6
say length(Str); # Str
$_ = "foobar";
say length; # 6
```
# DESCRIPTION
This module tries to mimic the behaviour of Perl's `length` built-in as closely as possible in the Raku Programming Language.
# ORIGINAL PERL 5 DOCUMENTATION
```
length EXPR
length Returns the length in characters of the value of EXPR. If EXPR is
omitted, returns the length of $_. If EXPR is undefined, returns
"undef".
This function cannot be used on an entire array or hash to find
out how many elements these have. For that, use "scalar @array"
and "scalar keys %hash", respectively.
Like all Perl character operations, length() normally deals in
logical characters, not physical bytes. For how many bytes a
string encoded as UTF-8 would take up, use
"length(Encode::encode_utf8(EXPR))" (you'll have to "use Encode"
first). See Encode and perlunicode.
```
# PORTING CAVEATS
## Characters vs codepoints
Since the Perl documentation mentions `characters` rather than codepoints, `length` will return the number of characters, as seen using Normalization Form Grapheme (NFG).
## Handling of type objects
`length` in Perl is supposed to return `undef` when given `undef`. Since undefined values are type objects in Raku, and it looks like `length` is simply returning what it was given in the undefined case, it felt appropriate to simply return the given type object rather than `Nil`.
## $\_ no longer accessible from caller's scope
In future language versions of Raku, it will become impossible to access the `$_` variable of the caller's scope, because it will not have been marked as a dynamic variable. So please consider changing:
```
length;
```
to either:
```
length($_);
```
or, using the subroutine as a method syntax, with the prefix `.` shortcut to use that scope's `$_` as the invocant:
```
.&length;
```
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!
Source can be located at: <https://github.com/lizmat/P5length> . Comments and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2018, 2019, 2020, 2021, 2023 Elizabeth Mattijsen
Re-imagined from Perl as part of the CPAN Butterfly Plan.
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_github-grondilu-Symbol.md
# Symbol
ECMAScript 2015's primitive type `Symbol` for Perl 6.
# Synopsis
```
use Symbol;
my Symbol $foo .= new(:name('foo'));
# A s:symbol notation is exported
say s:foo;
```
|
## multipleinheritance.md
role Metamodel::MultipleInheritance
Metaobject that supports multiple inheritance
```raku
role Metamodel::MultipleInheritance {}
```
*Warning*: this role is part of the Rakudo implementation, and is not a part of the language specification.
Classes, roles and grammars can have parent classes, that is, classes to which method lookups fall back to, and to whose type the child class conforms to.
This role implements the capability of having zero, one or more parent (or *super*) classes.
In addition, it supports the notion of *hidden* classes, whose methods are excluded from the normal dispatching chain, so that for example `nextsame` ignores it.
This can come in two flavors: methods from a class marked as `is hidden` are generally excluded from dispatching chains, and `class A hides B` adds `B` as a parent class to `A`, but hides it from the method resolution order, so that [mro\_unhidden](/type/Metamodel/C3MRO#method_mro_unhidden) skips it.
# [Methods](#role_Metamodel::MultipleInheritance "go to top of document")[§](#Methods "direct link")
## [method add\_parent](#role_Metamodel::MultipleInheritance "go to top of document")[§](#method_add_parent "direct link")
```raku
method add_parent($obj, $parent, :$hides)
```
Adds `$parent` as a parent type. If `$hides` is set to a true value, the parent type is added as a hidden parent.
`$parent` must be a fully [composed](/language/mop#Composition_time_and_static_reasoning) typed. Otherwise an exception of type [`X::Inheritance::NotComposed`](/type/X/Inheritance/NotComposed) is thrown.
## [method ^parents](#role_Metamodel::MultipleInheritance "go to top of document")[§](#method_^parents "direct link")
```raku
method ^parents($obj, :$all, :$tree)
```
Returns the list of parent classes. By default it stops at [`Cool`](/type/Cool), [`Any`](/type/Any) or [`Mu`](/type/Mu), which you can suppress by supplying the `:all` adverb. With `:tree`, a nested list is returned.
```raku
class D { };
class C1 is D { };
class C2 is D { };
class B is C1 is C2 { };
class A is B { };
say A.^parents(:all).raku;
# OUTPUT: «(B, C1, C2, D, Any, Mu)»
say A.^parents(:all, :tree).raku;
# OUTPUT: «[B, ([C1, [D, [Any, [Mu]]]], [C2, [D, [Any, [Mu]]]])]»
```
## [method hides](#role_Metamodel::MultipleInheritance "go to top of document")[§](#method_hides "direct link")
```raku
method hides($obj)
```
Returns a list of all hidden parent classes.
## [method hidden](#role_Metamodel::MultipleInheritance "go to top of document")[§](#method_hidden "direct link")
```raku
method hidden($obj)
```
Returns a true value if (and only if) the class is marked with the trait `is hidden`.
## [method set\_hidden](#role_Metamodel::MultipleInheritance "go to top of document")[§](#method_set_hidden "direct link")
```raku
method set_hidden($obj)
```
Marks the type as hidden.
|
## dist_cpan-BDUGGAN-Crypt-RSA.md
# Crypt::RSA
[](https://travis-ci.org/bduggan/p6-Crypt-RSA)
## SYNOPSIS
Pure Perl 6 implementation of RSA public key encryption.
```
my $crypt = Crypt::RSA.new;
my ($public,$private) = $crypt.generate-keys;
my $message = 123456789;
my $encrypted = $crypt.encrypt($message);
my $decrypted = $crypt.decrypt($encrypted);
my $message = 123456789;
my $signature = $crypt.generate-signature($message);
die unless $crypt.verify-signature($message,$signature);
```
## DESCRIPTION
This is a very simplistic implementation of the RSA algorithm
for public key encryption.
By default, it relies on Perl 6 built-ins for randomness,
but the constructor takes two optional arguments:
`random-prime-generator(UInt $digits)` and `random-range-picker(Range $range)`
that can be used instead. Any arguments to `generate-keys`
(such as the number of digits or number of bits) will be passed
on to `random-prime-generator`.
## EXAMPLES
```
use Crypt::Random;
use Crypt::Random::Extra;
my $crypt = Crypt::RSA.new(
random-prime-generator => sub {
crypt_random_prime()
},
random-range-picker => sub ($range) {
my $size = log($range, 10).Int;
my $rand = crypt_random_uniform($range.max,$size);
return $range[$rand];
}
);
```
## References
* <https://people.csail.mit.edu/rivest/Rsapaper.pdf>
* <https://www.promptworks.com/blog/public-keys-in-perl-6>
|
## dist_zef-CIAvash-Test-Run.md
# NAME
Test::Run - A module for testing output of processes.
# DESCRIPTION
Test::Run is a module for testing `STDOUT`, `STDERR` and `exitcode` of processes.
By default it uses `cmp-ok` test function with smartmatch operator. But custom operators and test functions
can be used.
# SYNOPSIS
```
use Test::Run :runs_ok;
runs_ok :args«$*EXECUTABLE -e 'put "Hi!"'», :out("Hi!\n"), 'Simple STDOUT test';
# or
Test::Run::runs_ok :args«$*EXECUTABLE -e 'put "Hi!"'», :out("Hi!\n"), 'Simple STDOUT test with full sub name';
# Smartmatching against a regex
runs_ok :args«$*EXECUTABLE -I. bin/program -v», :out(/'program-name v' [\d+ %% '.'] ** 3 .+/), 'Prints version';
# Smartmatching against Whatevercode
runs_ok :args«$*EXECUTABLE -e 'note "some long error message"; exit 1;'»,
:err(*.contains('error message')),
:exitcode(* > 0);
runs_ok :args«$*EXECUTABLE -»,
:in('put "Hi!"; note "Bye!"; exit 1'), :out("Hi!\n"), :err("Bye!\n"), :exitcode(1),
'Output test';
# Using custom test function
use Test::Differences;
runs_ok :args«@args[] $command», :out($expected_data), "Prints correctly", :test_stdout(&eq_or_diff);
```
# INSTALLATION
You need to have [Raku](https://www.raku-lang.ir/en) and [zef](https://github.com/ugexe/zef), then run:
```
zef install 'Test::Run:auth<zef:CIAvash>'
```
or if you have cloned the repo:
```
zef install .
```
# TESTING
```
prove -ve 'raku -I.' --ext rakutest
```
# SUBS
## sub runs\_ok
```
sub runs_ok(
Str $description?, :@args!, :$in, :$out, :$err, Int :$exitcode = 0,
Bool:D :$bin = Bool::False,
Bool:D :$bin_stdout = $bin,
Bool:D :$bin_stderr = $bin,
:$op = &[~~],
:$op_stdout is copy = $op,
:$op_stderr is copy = $op,
:&test_stdout,
:&test_stderr
) returns Mu
```
Takes program arguments, optionally `STDIN`, expected `STDOUT` and `STDERR` and `exitcode`, binary mode(can be separate for `STDOUT` and `STDERR`), operator used for `cmp-ok` (can be separate for `STDOUT` and `STDERR`), custom test function to run on `STDOUT` and/or `STDERR`.
Then runs 3 tests for `exitcode`, `STDERR`, `STDOUT` in a `subtest`
### Bool:D :$bin
Whether output is binary(`Blob`)
### Bool:D :$bin\_stdout
Whether STDOUT is binary(`Blob`)
### Bool:D :$bin\_stderr
Whether STDERR is binary(`Blob`)
### Mu $op
Comparison operator for `cmp-ok`
### Mu $op\_stdout
Comparison operator for `cmp-ok` and `STDOUT`
### Mu $op\_stderr
Comparison operator for `cmp-ok` and `STDERR`
### Callable &test\_stdout
Custom test function for `STDOUT`
### Callable &test\_stderr
Custom test function for `STDERR`
## sub run\_proc
```
sub run_proc(:@args, :$in, Bool:D :$bin = Bool::False) returns List
```
Runs process with `Proc`, returns a list of `STDOUT`, `STDERR`, `exitcode`.
Currently unused because it returns exitcode 1 for nonexistent programs,
sinks & dies when handles are closed
See <https://github.com/rakudo/rakudo/issues/1590> and <https://github.com/rakudo/rakudo/issues/3720>
## sub run\_proc\_async
```
sub run_proc_async(
:@args,
:$in,
Bool:D :$bin = Bool::False,
Bool:D :$bin_stdout = $bin,
Bool:D :$bin_stderr = $bin
) returns List
```
Runs process with `Proc::Async`, returns a list of `STDOUT`, `STDERR`, `exitcode`
# REPOSITORY
<https://codeberg.org/CIAvash/Test-Run/>
# BUG
<https://codeberg.org/CIAvash/Test-Run/issues>
# AUTHOR
Siavash Askari Nasr - <https://siavash.askari-nasr.com>
# COPYRIGHT
Copyright © 2021 Siavash Askari Nasr
# LICENSE
This file is part of Test::Run.
Test::Run is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
Test::Run 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with Test::Run. If not, see <http://www.gnu.org/licenses/>.
|
## dist_zef-librasteve-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/librasteve/raku-CLI-AWS-EC2-Simple))
* located at a static IP address (e.g. via `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/librasteve/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 with `rawp setup && rawp launch && rawp renewal`
* configure your new Wordpress site frontend at <https://yourdomain.com>
## wordpress-launch.yaml
```
instance:
domain-name: your_domain
admin-email: 'admin@your_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
file_uploads: On
memory_limit: 64M
upload_max_filesize: 64M
post_max_size: 64M
max_execution_time: 600
client_max_body_size: 64M
```
## WP CLI Examples
More examples can be found [here](./literature/wpcli.md)
`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.
```
## WP Git Example
More details can be found [here](./literature/wpgit.md)
Setup git & gcm (first time only)...
* `rawp ps` <= check that the `git` service is `Up`
* `rawp git-setup`
* `rawp git` <= **connect** to the git service, then...
* `gpg --gen-key` <= start manual GNU GPG keygen procedure
* `pass init your_name`
* `exit` <= when done return to the main Wordpress server prompt
* `rawp git-chown` <= fix up Wordpress file permissions (IMPORTANT)
Typical git sequence...
* `rawp git` <= **connect** to the git service, then...
* `export GPG_TTY=$(tty)` <= tell the gpg key which tty we are using
* `echo 'test' > test`
* `git add test`
* `git status`
* `git pull`
* `git commit -m 'note'`
* `git push`
* `exit` <= when done return to the main Wordpress server prompt
* `rawp git-chown` <= fix up Wordpress file permissions (IMPORTANT)
## CMDs
* setup # prepare config files from wordpress-launch.yaml
* 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
* down # docker-compose down
* ps # docker-compose ps
* connect # docker exec to *wordpress* service (get cmd as string)
* wp 'cmd' # run wpcli command - viz. <https://developer.wordpress.org/cli/commands/>
* git # docker exec to *git* service (get cmd as string)
* git-setup # install git & gcm on running git server
* git-chown # adjust file permissions
* terminate # rm volumes & reset
## Usage
```
rawp <cmd> [<wp>]
<cmd> One of <setup launch renewal up down ps wp connect git git-setup git-chown terminate>
[<wp>] A valid wp cli cmd (viz. https://developer.wordpress.org/cli/commands/)
```
### Copyright
copyright(c) 2023 Henley Cloud Consulting Ltd.
|
## dist_github-azawawi-Electron.md
# Electron [Build Status](https://travis-ci.org/azawawi/perl6-electron) [Build status](https://ci.appveyor.com/project/azawawi/perl6-electron/branch/master)
The goal is to write cross-platform Perl 6 desktop applications using
JavaScript, HTML and CSS on top of the [Electron](https://github.com/atom/electron) platform. It is based on [io.js](http://iojs.org) and [Chromium](http://www.chromium.org) and is used in
the [Atom editor](https://github.com/atom/atom).
## Installation
To install it using zef (a module management tool bundled with Rakudo Star):
```
$ zef install Electron
```
### Dependencies
Please follow the instructions below based on your platform:
#### Linux
* Install nodejs using apt
```
$ sudo apt-get install nodejs
```
* Install pre-built electron for your platform using the following command
line:
```
$ sudo npm install electron -g
```
After a successful installation, electron should be installed in
`/usr/local/bin/electron`.
#### Windows
If that fails, please download the correct electron platform from
<https://github.com/atom/electron/releases>. and make sure that `electron`
can be called from the command line.
* Install the installer from <https://nodejs.org/>
* Install pre-built electron for your platform using the following command
line:
```
$ npm install electron -g
```
After a success installation, electron should be installed in
`%USERPROFILE%\AppData\Roaming\npm\electron.cmd`
## Testing
To run tests:
```
$ prove -v -e "perl6 -Ilib"
```
## Author
Ahmad M. Zawawi, azawawi on #perl6, <https://github.com/azawawi/>
## License
MIT License
|
## comb.md
comb
Combined from primary sources listed below.
# [In IO::Handle](#___top "go to top of document")[§](#(IO::Handle)_method_comb "direct link")
See primary documentation
[in context](/type/IO/Handle#method_comb)
for **method comb**.
```raku
method comb(IO::Handle:D: Bool :$close, |args --> Seq:D)
```
Read the handle and processes its contents the same way [`Str.comb`](/type/Str#routine_comb) does, taking the same arguments, closing the handle when done if `$close` is set to a true value. Implementations may slurp the file in its entirety when this method is called.
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
my $fh = 'path/to/file'.IO.open;
say "The file has {+$fh.comb: '♥', :close} ♥s in it";
```
# [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_comb "direct link")
See primary documentation
[in context](/type/IO/Path#method_comb)
for **method comb**.
```raku
method comb(IO::Path:D: |args --> Seq:D)
```
Opens the file and processes its contents the same way [`Str.comb`](/type/Str#routine_comb) does, taking the same arguments. Implementations may slurp the file in its entirety when this method is called.
# [In IO::CatHandle](#___top "go to top of document")[§](#(IO::CatHandle)_method_comb "direct link")
See primary documentation
[in context](/type/IO/CatHandle#method_comb)
for **method comb**.
```raku
method comb(IO::CatHandle:D: |args --> Seq:D)
```
Read the handle and processes its contents the same way [`Str.comb`](/type/Str#routine_comb) does, taking the same arguments. **Implementations may slurp the contents of all the source handles** in their entirety when this method is called.
```raku
(my $f1 = 'foo'.IO).spurt: 'foo';
(my $f2 = 'bar'.IO).spurt: 'bar';
IO::CatHandle.new($f1, $f2).comb(2).raku.say;
# OUTPUT: «("fo", "ob", "ar").Seq»
```
# [In Allomorph](#___top "go to top of document")[§](#(Allomorph)_method_comb "direct link")
See primary documentation
[in context](/type/Allomorph#method_comb)
for **method comb**.
```raku
method comb(Allomorph:D: |c)
```
Calls [`Str.comb`](/type/Str#routine_comb) on the invocant's [`Str`](/type/Str) value.
# [In Str](#___top "go to top of document")[§](#(Str)_routine_comb "direct link")
See primary documentation
[in context](/type/Str#routine_comb)
for **routine comb**.
```raku
multi comb(Str:D $matcher, Str:D $input, $limit = Inf)
multi comb(Regex:D $matcher, Str:D $input, $limit = Inf, Bool :$match)
multi comb(Int:D $size, Str:D $input, $limit = Inf)
multi method comb(Str:D $input:)
multi method comb(Str:D $input: Str:D $matcher, $limit = Inf)
multi method comb(Str:D $input: Regex:D $matcher, $limit = Inf, Bool :$match)
multi method comb(Str:D $input: Int:D $size, $limit = Inf)
```
Searches for `$matcher` in `$input` and returns a [`Seq`](/type/Seq) of non-overlapping matches limited to at most `$limit` matches.
If `$matcher` is a Regex, each [`Match`](/type/Match) object is converted to a `Str`, unless `$match` is set (available as of the 2020.01 release of the Rakudo compiler).
If no matcher is supplied, a Seq of characters in the string is returned, as if the matcher was `rx/./`.
Examples:
```raku
say "abc".comb.raku; # OUTPUT: «("a", "b", "c").Seq»
say "abc".comb(:match).raku; # OUTPUT: «(「a」 「b」 「c」)»
say 'abcdefghijk'.comb(3).raku; # OUTPUT: «("abc", "def", "ghi", "jk").Seq»
say 'abcdefghijk'.comb(3, 2).raku; # OUTPUT: «("abc", "def").Seq»
say comb(/\w/, "a;b;c").raku; # OUTPUT: «("a", "b", "c").Seq»
say comb(/\N/, "a;b;c").raku; # OUTPUT: «("a", ";", "b", ";", "c").Seq»
say comb(/\w/, "a;b;c", 2).raku; # OUTPUT: «("a", "b").Seq»
say comb(/\w\;\w/, "a;b;c", 2).raku; # OUTPUT: «("a;b",).Seq»
say comb(/.<(.)>/, "<>[]()").raku; # OUTPUT: «(">", "]", ")").Seq»
```
If the matcher is an integer value, `comb` behaves as if the matcher was `rx/ . ** {1..$matcher} /`, but which is optimized to be much faster.
Note that a Regex matcher may control which portion of the matched text is returned by using features which explicitly set the top-level capture.
```raku
multi comb(Pair:D $rotor, Str:D $input, $limit = Inf, Bool :$partial)
multi method comb(Str:D $input: Pair:D $rotor, $limit = Inf, Bool :$partial)
```
Available as of 6.e language version (early implementation exists in Rakudo compiler 2022.12+). The `rotor` pair indicates the number of characters to fetch as the key (the "size"), and the number of "steps" forward to take afterwards. Its main intended use is to provide a way to create [N-grams](https://en.wikipedia.org/wiki/N-gram) from strings in an efficient manner. By default only strings of the specified size will be produced. This can be overridden by specifying the named argument `:partial` with a true value.
Examples:
```raku
say "abcde".comb(3 => -2); # OUTPUT: «(abc bcd cde)»
say "abcde".comb(3 => -2, :partial); # OUTPUT: «(abc bcd cde de e)»
say "abcdefg".comb(3 => -2, 2); # OUTPUT: «(abc bcd)»
say comb(3 => -2, "abcde"); # OUTPUT: «(abc bcd cde)»
say comb(5 => -2, "abcde", :partial); # OUTPUT: «(abc bcd cde de e)»
say comb(5 => -2, "abcdefg", 2); # OUTPUT: «(abc bcd)»
```
# [In Cool](#___top "go to top of document")[§](#(Cool)_routine_comb "direct link")
See primary documentation
[in context](/type/Cool#routine_comb)
for **routine comb**.
```raku
multi comb(Regex $matcher, Cool $input, $limit = *)
multi comb(Str $matcher, Cool $input, $limit = *)
multi comb(Int:D $size, Cool $input, $limit = *)
multi method comb(|c)
```
Returns a [`Seq`](/type/Seq) of all (or if supplied, at most `$limit`) matches of the invocant (method form) or the second argument (sub form) against the [`Regex`](/type/Regex), string or defined number.
```raku
say "6 or 12".comb(/\d+/).join(", "); # OUTPUT: «6, 12»
say comb(/\d <[1..9]> /,(11..30)).join("--");
# OUTPUT:
# «11--12--13--14--15--16--17--18--19--21--22--23--24--25--26--27--28--29»
```
The second statement exemplifies the first form of `comb`, with a [`Regex`](/type/Regex) that excludes multiples of ten, and a [`Range`](/type/Range) (which is `Cool`) as `$input`. `comb` stringifies the [`Range`](/type/Range) before applying `.comb` on the resulting string. Check [`Str.comb`](/type/Str#routine_comb) for its effect on different kind of input strings. When the first argument is an integer, it indicates the (maximum) size of the chunks the input is going to be divided in
```raku
say comb(3,[3,33,333,3333]).join("*"); # OUTPUT: «3 3*3 3*33 *333*3»
```
In this case the input is a list, which after transformation to [`Str`](/type/Str) (which includes the spaces) is divided in chunks of size 3.
|
## dist_cpan-FRITH-Math-Libgsl-Random.md
[](https://travis-ci.org/frithnanth/raku-Math-Libgsl-Random)
# NAME
Math::Libgsl::Random - An interface to libgsl, the Gnu Scientific Library - Random Number Generation.
# SYNOPSIS
```
use Math::Libgsl::Random;
my Math::Libgsl::Random $r .= new;
$r.get-uniform.say for ^10;
```
# DESCRIPTION
Math::Libgsl::Random is an interface to the Random Number Generation routines of libgsl, the Gnu Scientific Library.
### new(Int :$type?)
The constructor allows one optional parameter, the random number generator type. One can find an enum listing all the generator types in the Math::Libgsl::Constants module.
### get(--> Int)
Returns the next random number as an Int.
### get-uniform(--> Num)
Returns the next random number as a Num in the interval [0, 1).
### get-uniform-pos(--> Num)
Returns the next random number as a Num in the interval (0, 1).
### get-uniform-int(Int $n --> Int)
This method returns an Int in the range [0, n - 1].
### seed(Int $seed)
This method initializes the random number generator. This method returns **self**, so it can be concatenated to the **.new()** method:
```
my $r = Math::Libgsl::Random.new.seed(42);
$r.get.say;
# or even
Math::Libgsl::Random.new.seed(42).get.say;
```
### name(--> Str)
This method returns the name of the current random number generator.
### min(--> Int)
This method returns the minimum value the current random number generator can generate.
### max(--> Int)
This method returns the maximum value the current random number generator can generate.
### copy(Math::Libgsl::Random $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::Random)
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 $r = Math::Libgsl::Random.new;
my $clone = $r.clone;
```
### write(Str $filename!)
Writes the generator to a file in binary form. This method can be chained.
### read(Str $filename!)
Reads the generator from a file in binary form. This method can be chained.
# 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::Random
```
# 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_zef-jonathanstowe-Test-Util-ServerPort.md
# Test::Util::ServerPort
Get a free server port for testing with

## Synopsis
```
use Test::Util::ServerPort;
my $port = get-unused-port();
# .. start some server with the port
```
## Description
This is a utility to help with the testing of TCP server software.
It exports a single subroutine `get-unused-port` that will return
a port number in the range 1025 - 65535 (or a specified range
as an argument,) that is free to be used by a listening socket. It
checks by attempting to `listen` on a random port on the range
until it finds one that is not already bound.
## 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 Test::Util::ServerPort
```
## Support
Suggestions and patches that may make it more useful in your software
are welcomed via github at:
<https://github.com/jonathanstowe/Test-Util-ServerPort>
## Licence
This is free software.
Please see the <LICENCE> file in the distribution for details.
© Jonathan Stowe 2016 - 2021
|
## dist_zef-melezhik-SparrowCI.md
[](https://ci.sparrowhub.io)
# SparrowCI
SparrowCI - super fun and flexible CI system with many programming languages support.
## Why yet another pipeline DSL?
Read [why?](docs/why.md) manifest.
## Quick start
See [quickstart.md](docs/quickstart.md) document.
## DAG of tasks
See [dag.md](docs/dag.md) document to understand the main idea of SparrowCI flow.
## Deep dive
See [dsl.md](docs/dsl.md) document for a full SparrowCI pipelines tutorial.
## Environment variables
See [variables.md](docs/variables.md) document.
## Self-hosted deployment
See [selfhosted.md](docs/selfhosted.md) document.
## Development
See [development.md](docs/development.md) document.
## Sparman
Sparman is a cli to ease SparrowCI management. See [sparman.md](docs/sparman.md) document.
## Vault
On Hashicorp vault service integration see [vault.md](docs/vault.md) document.
## External systems integration
See [reporters.md](docs/reporters.md) document.
# Thanks to
God and Jesus Christ who inspires me
|
## dist_github-azawawi-File-HomeDir.md
# File::HomeDir
[](https://github.com/azawawi/raku-file-homedir/actions)
This is a Raku port of [File::HomeDir](https://metacpan.org/pod/File::HomeDir).
File::HomeDir is a module for locating the directories that are "owned" by a
user (typically your user) and to solve the various issues that arise trying to
find them consistently across a wide variety of platforms.
The end result is a single API that can find your resources on any platform,
making it relatively trivial to create Perl software that works elegantly and
correctly no matter where you run it.
## Example
```
use v6;
use File::HomeDir;
say File::HomeDir.my-home;
say File::HomeDir.my-desktop;
say File::HomeDir.my-documents;
say File::HomeDir.my-pictures;
say File::HomeDir.my-videos;
```
## Installation
To install it using zef (a module management tool bundled with Rakudo Star):
```
zef install File::HomeDir
```
## Testing
* To run tests:
```
$ prove --ext .rakutest -ve "raku -I."
```
* To run all tests including author tests (Please make sure
[Test::Meta](https://github.com/jonathanstowe/Test-META) is installed):
```
$ zef install Test::META
$ TEST_AUTHOR=1 prove --ext .rakutest -ve "raku -I."
```
## Author
Raku version:
* Ahmad M. Zawawi, azawawi on #raku, <https://github.com/azawawi/>
* Tadeusz Sośnierz, tadzik on #raku, <https://github.com/tadzik/>
* Steve Dondley, sdondley on #raku, <https://github.com/sdondley>
Perl 5 version:
* Adam Kennedy (2005 - 2012)
* Chris Nandor (2006)
* Stephen Steneker (2006)
* Jérôme Quelin (2009-2011)
* Sean M. Burke (2000)
## License
MIT License
|
## devnull.md
devnull
Combined from primary sources listed below.
# [In IO::Spec::Unix](#___top "go to top of document")[§](#(IO::Spec::Unix)_method_devnull "direct link")
See primary documentation
[in context](/type/IO/Spec/Unix#method_devnull)
for **method devnull**.
```raku
method devnull(--> Str:D)
```
Returns the string `"/dev/null"` representing the ["Null device"](https://en.wikipedia.org/wiki/Null_device):
```raku
$*SPEC.devnull.IO.spurt: "foo bar baz";
```
# [In IO::Spec::Win32](#___top "go to top of document")[§](#(IO::Spec::Win32)_method_devnull "direct link")
See primary documentation
[in context](/type/IO/Spec/Win32#method_devnull)
for **method devnull**.
```raku
method devnull(--> Str:D)
```
Returns the string `"nul"` representing the ["Null device"](https://en.wikipedia.org/wiki/Null_device):
```raku
$*SPEC.devnull.IO.spurt: "foo bar baz";
```
|
## dist_zef-dwarring-Base64-Native.md
## Base64-Native-raku
Faster than average Base 64 encoding and decoding.
[](https://github.com/pdf-raku/Base64-Native-raku/actions)
## Synopsis
```
use Base64::Native;
## Encoding ##
my buf8 $buf = base64-encode("Lorem ipsum");
say $buf;
# Buf[uint8]:0x<54 47 39 79 5a 57 30 67 61 58 42 7a 64 57 30 3d>
say base64-encode("Lorem ipsum", :str);
# TG9yZW0gaXBzdW0=
## Decoding ##
say base64-decode($buf);
# Buf[uint8]:0x<4c 6f 72 65 6d 20 69 70 73 75 6d>
say base64-decode("TG9yZW0gaXBzdW0=").decode;
# "Lorem ipsum"
```
### URI Encoding
By default, codes 62 and 63 are encoded to '+' and '/'. The `:uri` option
maps these to '-' and '\_'.
```
use Base64::Native;
my $data = base64-decode("AB+/");
say base64-encode( $data, :str );
# AB+/
say base64-encode( $data, :str, :uri );
# AB-_
```
### URI Decoding
URI and standard (MIME) mappings are both recognized by the `base64-decode` routine.
```
use Base64::Native;
say base64-decode("AB+/");
# Buf[uint8]:0x<00 1f bf>
say base64-decode("AB-_");
# Buf[uint8]:0x<00 1f bf>
```
|
## dist_cpan-JMERELO-Wikidata-API.md
# Wikidata API in Perl 6
[](https://travis-ci.org/JJ/p6-wikidata-API)
Perl6 module to query the wikidata API. Install it the usual way
```
zef install Wikidata::API
```
Use it:
```
use Wikidata::API;
my $query = q:to/END/;
SELECT ?person ?personLabel WHERE {
?person wdt:P69 wd:Q1232180 .
?person wdt:P21 wd:Q6581072 .
SERVICE wikibase:label {
bd:serviceParam wikibase:language "en" .
}
} ORDER BY ?personLabel
END
my $UGR-women = query( $query );
my $to-file= q:to/END/;
SELECT ?person ?personLabel ?occupation ?occupationLabel WHERE {
?person wdt:P69 wd:Q1232180.
?person wdt:P21 wd:Q6581072.
?person wdt:P106 ?occupation
SERVICE wikibase:label {
bd:serviceParam wikibase:language "es" .
}
}
END
spurt "ugr-women-by-job.sparql", $to-file;
say query-file( $to-file );
```
|
## 01-debugging.md
Debugging
Modules and applications used to debug Raku programs
# [Core debugging features](#Debugging "go to top of document")[§](#Core_debugging_features "direct link")
## [The `trace` pragma](#Debugging "go to top of document")[§](#The_trace_pragma "direct link")
The `trace` pragma causes the program to print out step-by-step which lines get executed:
```raku
use trace;
sub foo { say "hi" }
foo;
# OUTPUT:
# 2 (/tmp/script.raku line 2)
# sub foo { say "hi" }
# 5 (/tmp/script.raku line 3)
# foo
# 3 (/tmp/script.raku line 2)
# say "hi"
# hi
```
# [Dumper function (`dd`)](#Debugging "go to top of document")[§](#Dumper_function_(dd) "direct link")
[[1]](#fn1)
The *Tiny Data Dumper*: This function takes the input list of variables and `note`s them (on `$*ERR`) in an easy to read format, along with the `name` of the variable. For example, this prints to the standard error stream the variables passed as arguments:
```raku
my $a = 42;
my %hash = "a" => 1, "b" => 2, "c" => 3;
dd %hash, $a;
#`( OUTPUT:
Hash %hash = {:a(1), :b(2), :c(3)}
Int $a = 42
)
```
Please note that `dd` will ignore named parameters. You can use a [`Capture`](/type/Capture) or [`Array`](/type/Array) to force it to dump everything passed to it.
```raku
dd \((:a(1), :b(2)), :c(3));
dd [(:a(1), :b(2)), :c(3)];
```
If you don't specify any parameters at all, it will just print the type and name of the current subroutine / method to the standard error stream:
```raku
sub a { dd }; a # OUTPUT: «sub a()»
```
This can be handy as a cheap trace function.
## [Using backtraces](#Debugging "go to top of document")[§](#Using_backtraces "direct link")
The [`Backtrace`](/type/Backtrace) class gets the current call stack, and can return it as a string:
```raku
my $trace = Backtrace.new;
sub inner { say ~Backtrace.new; }
sub outer { inner; }
outer;
# OUTPUT:
# raku /tmp/script.raku
# in sub inner at /tmp/script.raku line 2
# in sub outer at /tmp/script.raku line 3
# in block <unit> at /tmp/script.raku line 4
```
## [Environment variables](#Debugging "go to top of document")[§](#Environment_variables "direct link")
See [Raku Environment Variables](https://github.com/rakudo/rakudo/wiki/dev-env-vars) and [Running rakudo from the command line](https://github.com/rakudo/rakudo/wiki/Running-rakudo-from-the-command-line) for more information.
# [Ecosystem debugging modules](#Debugging "go to top of document")[§](#Ecosystem_debugging_modules "direct link")
There are at least two useful debuggers and two tracers available for Rakudo (the Raku compiler). For more information on these modules, please refer to their documentation.
Historically other modules have existed and others are likely to be written in the future. Please check the [Raku Modules](https://raku.land/) website for more modules like these.
## [`Debugger::UI::CommandLine`](https://raku.land/github:jnthn/Debugger::UI::CommandLine)[§](#Debugger::UI::CommandLine "direct link")
A command-line debugger frontend for Rakudo. This module installs the `raku-debug-m` command-line utility, and is bundled with the Rakudo Star distributions. Please check [its repository](https://github.com/jnthn/rakudo-debugger) for instructions and a tutorial.
## [`Grammar::Debugger`](https://raku.land/github:jnthn/Grammar::Debugger) (and `Grammar::Tracer` in the same distribution)[§](#Grammar::Debugger_(and_Grammar::Tracer_in_the_same_distribution) "direct link")
Simple tracing and debugging support for Raku grammars.
## [`Trait::Traced`](https://raku.land/cpan:KAIEPI/Trait::Traced)[§](#Trait::Traced "direct link")
This provides the `is traced` trait, which automatically traces usage of features of whatever the trait is applied to. What features of whatever the trace is applied to get traced and how traces are handled are customizable. Refer to its documentation for more information on how this works.
1 [[↑]](#fnret1) This routine is a Rakudo-specific debugging feature and not standard Raku.
|
## dist_github-skids-X-Protocol.md
# perl6xproto
X::Protocol:: Perl 6 modules for protocol exceptions
## Purpose
The X::Protocol superclass is a convenience for working with status results
in protocol code. It allows one to reap the benefits of typed exceptions
without having to type out their names very often. You simply feed the
error code from the protocol in as an argument to X::Protocol.new (or,
more usually, to a subclass) and it is automatically paired with a human
readable error message, producing an object that can be printed, thrown,
or inspected.
One can easily tell a protocol error apart from an internal code error
by whether it matches X::Protocol, and tell which protocol an error came
from either by looking at the .protocol attribute, or checking which
subclass it belongs to.
Better yet, you can simply smart match the object against integers, strings
and regular expressions in your error handling code.
For commonly used protocols, the X::Protocol module repository serves as a
place for protocol-specific subclasses to store long lists of human-readable
error messages so they can be shared by different protocol implementations
and maintained in one place.
More finicky features are also available. See the embedded pod.
## Idioms
The most common use will be something like this in a module:
```
class X::Protocol::BoxTruckOfFlashDrives is X::Protocol {
method protocol { "BoxTruckOfFlashDrives" }
method codes {
{
100 => "Out of gas";
200 => "Petabytes per hour. Beat that!";
300 => "Now you have to plug them all in by hand";
400 => "Hit a guard rail";
}
}
method severity {
when 200 { "success" };
"error";
}
}
```
...and then the user of the module would do something like this:
```
{
# stuff that results in a status code in $result
X::Protocol::BoxTruckOfFlashDrives.new(:status($result)).toss;
# More stuff that happens if the exception is resumed or .toss
# did not throw an exception.
CATCH {
when X::Protocol::BoxTruckOfFlashDrives {
when 300 { plug_lots_of_flash_drives_in(); }
when 100 { get_gas(); $_.resume }
}
# Handle other kinds of errors
}
}
```
|
## dist_zef-lizmat-Array-Circular.md
[](https://github.com/lizmat/Array-Circular/actions) [](https://github.com/lizmat/Array-Circular/actions) [](https://github.com/lizmat/Array-Circular/actions)
# NAME
Array::Circular - add "is circular" trait to Arrays
# SYNOPSIS
```
use Array::Circular;
# limit to 3 elements at compile time
my @a is circular(3);
# random size picked at runtime
my $size = (^10).roll;
my @b is circular(-> { $size });
```
# DESCRIPTION
This module adds a `is circular` trait to `Arrays`. This limits the size of the array to the given number of elements, similar to shaped arrays. However, unlike shaped arrays, you **can** `push`, `append`, `unshift` and `prepend` to arrays with the `is circular` trait. Then, if the resulting size of the array is larger than the given size, elements will be removed "from the other end" until the array has the given size again.
The size of the circular array must be given by a value that is known at compile time. This can either be a literal value, a numeric constant or a code block that will return the required size when it is called (without any arguments).
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
Source can be located at: <https://github.com/lizmat/Array-Circular> . Comments and Pull Requests are welcome.
If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me!
# COPYRIGHT AND LICENSE
Copyright 2018, 2020, 2021, 2022, 2024, 2025 Elizabeth Mattijsen
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## wrongorder.md
class X::Parameter::WrongOrder
Compilation error due to passing parameters in the wrong order
```raku
class X::Parameter::WrongOrder does X::Comp { }
```
Compile time error that is thrown when parameters in a signature in the wrong order (for example if an optional parameter comes before a mandatory parameter).
For example
```raku
sub f($a?, $b) { }
```
dies with
「text」 without highlighting
```
```
===SORRY!===
Cannot put required parameter $b after optional parameters
```
```
# [Methods](#class_X::Parameter::WrongOrder "go to top of document")[§](#Methods "direct link")
## [method misplaced](#class_X::Parameter::WrongOrder "go to top of document")[§](#method_misplaced "direct link")
Returns the kind of misplaced parameter (for example `"mandatory"`, `"positional"`).
## [method parameter](#class_X::Parameter::WrongOrder "go to top of document")[§](#method_parameter "direct link")
Returns the name of the (first) misplaced parameter
## [method after](#class_X::Parameter::WrongOrder "go to top of document")[§](#method_after "direct link")
Returns a string describing other parameters after which the current parameter was illegally placed (for example `"variadic"`, `"positional"` or `"optional"`).
|
## dist_zef-lizmat-P5__FILE__.md
[](https://github.com/lizmat/P5__FILE__/actions)
# NAME
Raku port of Perl's **FILE** and associated functionality
# SYNOPSIS
```
use P5__FILE__; # exports __FILE__, __LINE__, __PACKAGE__, __SUB__
```
# DESCRIPTION
This module tries to mimic the behaviour of Perl's `__FILE__`, `__LINE__`, `__PACKAGE__` and `__SUB__` functionality as closely as possible in Raku.
# TERMS
## **PACKAGE**
A special token that returns the name of the package in which it occurs.
### Raku
```
$?PACKAGE.^name
```
Because `$?PACKAGE` gives you the actual `Package` object (which can be used for introspection), you need to call the `.^name` method to get a string with the name of the package.
## **FILE**
A special token that returns the name of the file in which it occurs.
### Raku
```
$?FILE
```
## **LINE**
A special token that compiles to the current line number.
### Raku
```
$?LINE
```
## **SUB**
A special token that returns a reference to the current subroutine, or "undef" outside of a subroutine.
### Raku
```
&?ROUTINE
```
Because `&?ROUTINE` gives you the actual `Routine` object (which can be used for introspection), you need to call the `.name` method to get a string with the name of the subroutine.
# AUTHOR
Elizabeth Mattijsen [[email protected]](mailto:[email protected])
Source can be located at: <https://github.com/lizmat/P5__FILE>\_\_ . Comments and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2018, 2019, 2020, 2021 Elizabeth Mattijsen
Re-imagined from Perl as part of the CPAN Butterfly Plan.
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## dist_zef-Marcool04-delete-old-until-size.md
# Synopsis
```
$ delete-old-until-size.raku --older-than "30 days"
Not enforcing any space requirement, --free-up=0
Looking for candidates to prune, older than 30 days (2592000 seconds)
Found 4 file(s) that are older than 30 days.
Offering to delete:
880 | ./file1
8.4Kb | ./file2
5.0Kb | ./file3
320 | ./folder1
There are 4 older than 30 days – files, occupying 14.5Kb
❓ Proceed? Y/n:^C
$ delete-old-until-size.raku --free-up=10K --older-than="1 second"
Folder is using more than 10.0Kb
Looking for candidates to prune, older than 1 second (1 seconds)
Found 9 file(s) that are older than 1 second.
Offering to delete:
880 | ./file1
8.4Kb | ./file2
786 | ./file4
If we delete the 3 largest – older than 1 second – files, that'll free 10.0Kb, which is more than the 10.0Kb objective.
❓ Proceed? Y/n:^C
```
# Description
Given at least a duration (`--older-than`) and a folder (by default, present working directory `./`), and optionally a size (`--free-up`), the script will determine a list of files to delete, all older than older-than, the size of which total at most free-up. Alternatively a prune-down-to option can replace free-up and will be the target size to obtain after deletion of old files. Priority is given to older files in all cases.
Note that the script works on all files and folders contained in the folder passed as positional argument, and considers the effective disk-usage of folders as their "size". So if you have a folder occupying 28Mb of disk space, that will effectively be treated as a 28Mb file, for the purpose of sorting / determining what to delete.
# Use case
I personally use this on a macOS machine where I run it on my "Trash" folder regularly, so that I can free up space while conserving traces of old files I might conceivably still need. Other uses could be thought of no doubt.
# AUTHOR
Mark Collins <https://gitlab.com/Marcool04>
# COPYRIGHT AND LICENCE
Copyright 2020 Mark Collins
This work is free. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See the LICENCE file for more details.
|
## notfound.md
class X::Method::NotFound
Error due to calling a method that isn't there
```raku
class X::Method::NotFound is Exception {}
```
Thrown when the user tries to call a method that isn't there.
For example
```raku
1.no-such
```
throws
「text」 without highlighting
```
```
No such method 'no-such' for invocant of type 'Int'
```
```
# [Methods](#class_X::Method::NotFound "go to top of document")[§](#Methods "direct link")
## [method method](#class_X::Method::NotFound "go to top of document")[§](#method_method "direct link")
```raku
method method(--> Str:D)
```
Returns the method name that was invoked.
## [method typename](#class_X::Method::NotFound "go to top of document")[§](#method_typename "direct link")
```raku
method typename(--> Str:D)
```
Returns the name of the invocant type.
## [method private](#class_X::Method::NotFound "go to top of document")[§](#method_private "direct link")
```raku
method private(--> Bool:D)
```
Returns `True` for private methods, and `False` for public methods.
## [method addendum](#class_X::Method::NotFound "go to top of document")[§](#method_addendum "direct link")
```raku
method addendum(--> Str:D)
```
Returns additional explanations or hints.
*Note*: `addendum` was introduced in Rakudo 2019.03.
|
## dist_zef-atroxaper-TimeUnit.md
[](https://github.com/atroxaper/raku-TimeUnit/actions/workflows/ubuntu.yml)
[](https://github.com/atroxaper/raku-TimeUnit/actions/workflows/macos.yml)
[](https://github.com/atroxaper/raku-TimeUnit/actions/workflows/windows.yml)
[](https://coveralls.io/github/atroxaper/raku-TimeUnit?branch=master)
# NAME
`TimeUnit` - library for conversion a time from one unit to another.
# SYNOPSIS
```
use TimeUnit;
sub beep-after(TimeUnit:D $time) {
Promise.in($time.to-seconds).then: { beep() }
}
Promise.in(timeunit(:3days :1hour :3sec).to-seconds).then: { send-email() }
days(4) + hours(3).minus(nanos(3)) < timeunit(:4d :3h);
minutes(15).to(hours) == 0.25;
```
# INSTALLATION
If you use zef, then `zef install TimeUnit`, or `pakku add TimeUnit` if you use Pakku.
# DESCRIPTION
`TimeUnit` library provides a simple way for conversion time without any 'magic numbers' in code. Also, `TimeUnit` can help you to write a more intuitive API in part of using time.
You may use the following routines to create corresponding `TimeUnit` object: `nanos`, `micros`, `millis`, `seconds`, `minutes`, `hours` and `days`. All of them take a single `Numeric()` argument. Additionally, you may create `TimeUnit` object through `timeunit` routing in a relaxed way like `timeunit(:1day :3h :6nanoseconds)`.
`TimeUnit` object can be compared as ordinary Numerics. Also, you may add and subtract them with `infix:<+>` and `infix:<->` routines and `plus` and `minus` methods.
To convert `TimeUnit` object to some numeric representation use one of the following method: `to-nanos`, `to-micros`, `to-millis`, `to-seconds`, `to-hours`, `to-days` or simply `to('days')`. It is possible to pass a name of unit to `to` method with or without quotation.
# AUTHOR
Mikhail Khorkov <atroxaper[at]cpan.org>
Sources can be found at: [github](https://github.com/atroxaper/raku-TimeUnit). The new Issues and Pull Requests are welcome.
# COPYRIGHT AND LICENSE
Copyright 2022 Mikhail Khorkov
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
## scalar.md
class Scalar
A mostly transparent container used for indirections
```raku
class Scalar {}
```
A `Scalar` is an internal indirection, that is, a way to refer indirectly to a value, which is, for most purposes, invisible during ordinary use of Raku. It is the default container type associated with the `$` sigil. A literal `Scalar` may be placed around any literal by enclosing the value in `$(…)`. This notation will appear in the output of a `.raku` method in certain places where it is important to note the presence of `Scalar`s.
When a value is assigned to a `$`-sigiled variable, the variable will actually bind to a `Scalar`, which in turn will bind to the value. When a `Scalar` is assigned to a `$`-sigiled variable, the value bound to by that `Scalar` will be bound to the `Scalar` which that variable was bound to (a new one will be created if necessary.)
In addition, `Scalar`s delegate all method calls to the value which they contain. As such, `Scalar`s are for the most part invisible. There is, however, one important place where `Scalar`s have a visible impact: a `Scalar` container will shield its content from [flattening](/language/subscripts#index-entry-flattening_) by most Raku core list operations.
```raku
say |(1,2,$(3,4)); # OUTPUT: «12(3 4)»
```
These `Scalar` containers can also be created on the fly by assigning to an [anonymous scalar variable](/language/variables#The_$_variable):
```raku
say |(1,2, $ = (3,4)); # OUTPUT: «12(3 4)»
```
A `$`-sigiled variable may be bound directly to a value with no intermediate `Scalar` using the binding operator `:=`. You can tell if this has been done by examining the output of the introspective pseudo-method `.VAR`:
```raku
my $a = 1;
$a.^name.say; # OUTPUT: «Int»
$a.VAR.^name.say; # OUTPUT: «Scalar»
my $b := 1;
$b.^name.say; # OUTPUT: «Int»
$b.VAR.^name.say; # OUTPUT: «Int»
```
This same thing happens when values are assigned to an element of an [`Array`](/type/Array), however, [`List`](/type/List)s directly contain their values:
```raku
my @a = 1, 2, 3;
@a[0].^name.say; # OUTPUT: «Int»
@a[0].VAR.^name.say; # OUTPUT: «Scalar»
[1, 2, 3][0].^name.say; # OUTPUT: «Int»
[1, 2, 3][0].VAR.^name.say; # OUTPUT: «Scalar»
(1, 2, 3)[0].^name.say; # OUTPUT: «Int»
(1, 2, 3)[0].VAR.^name.say; # OUTPUT: «Int»
```
Array elements may be bound directly to values using `:=` as well; however, this is discouraged as it may lead to confusion. Doing so will break exact round-tripping of `.raku` output – since [`Array`](/type/Array)s are assumed to place `Scalar`s around each element, `Scalar`s are not denoted with `$` in the output of `Array.raku`.
```raku
[1, $(2, 3)].raku.say; # OUTPUT: «[1, (2, 3)]»
(1, $(2, 3)).raku.say; # OUTPUT: «(1, $(2, 3))»
```
Binding a `Scalar` to a `$`-sigiled variable replaces the existing `Scalar` in that variable, if any, with the given `Scalar`. That means more than one variable may refer to the same `Scalar`. Because the `Scalar` may be mutated, this makes it possible to alter the value of both variables by altering only one of them:
```raku
my $a = 1;
my $b := $a;
$b = 2;
$a.say; # OUTPUT: «2»
```
Raku allows the use of constants with a [static single assignment (SSA)](https://en.wikipedia.org/wiki/Static_single_assignment_form) style which bind directly to their value with no intervening `Scalar` container, even when assignment (`=`) is used. They may be forced to use a `Scalar` by assigning a `$`-sigiled variable to them, at which point, they behave entirely like `$`-sigiled variables.
```raku
my \c = 1;
c.^name.say; # OUTPUT: «Int»
c.VAR.^name.say; # OUTPUT: «Int»
my $a = 1;
my \d = $a; # just "my \d = $ = 1" works, too
d.^name.say; # OUTPUT: «Int»
d.VAR.^name.say; # OUTPUT: «Scalar»
d = 2; # ok
c = 2; # fails
CATCH { default { put .^name, ': ', .Str } };
# OUTPUT: «X::Assignment::RO: Cannot modify an immutable Int»
```
# [Atomic operations on Scalar](#class_Scalar "go to top of document")[§](#Atomic_operations_on_Scalar "direct link")
A `Scalar` can have its value changed using a hardware-supported atomic compare and swap operation. This is useful when implementing lock free data structures and algorithms. It may also be fetched and assigned to in an "atomic" fashion, which ensures appropriate memory barriering and prevents unwanted optimizations of memory accesses.
A `Scalar` that will be used with an atomic operation should **always** be explicitly initialized with a value before any atomic operations are performed upon it. This is to avoid races with lazy allocation and auto-vivification. For example:
```raku
cas(@a[5], $expected, $value)
```
Will work in principle since an [`Array`](/type/Array) consists of `Scalar` containers. However, the container is only bound into the array upon initial assignment. Therefore, there would be a race to do that binding. The `Scalar` atomic operations will never check for or do any such auto-vivification, so as to make such bugs much more evident (rather than only observed under stress).
# [Introspection](#class_Scalar "go to top of document")[§](#Introspection "direct link")
## [method of](#class_Scalar "go to top of document")[§](#method_of "direct link")
```raku
method of(Scalar:D: --> Mu)
```
Returns the type constraint of the container.
Example:
```raku
my Cool $x = 42;
say $x.VAR.of; # OUTPUT: «(Cool)»
```
## [method default](#class_Scalar "go to top of document")[§](#method_default "direct link")
```raku
method default(Scalar:D: --> Str)
```
Returns the default value associated with the container.
Example:
```raku
my $x is default(666) = 42;
say $x.VAR.default; # OUTPUT: «666»
```
## [method name](#class_Scalar "go to top of document")[§](#method_name "direct link")
```raku
method name(Scalar:D: --> Str)
```
Returns the name associated with the container.
Example:
```raku
my $x = 42;
say $x.VAR.name; # OUTPUT: «$x»
```
## [method dynamic](#class_Scalar "go to top of document")[§](#method_dynamic "direct link")
```raku
method dynamic(Scalar:D: --> Bool)
```
It will return `False` for scalars.
Example:
```raku
my $*FOO = 42;
say $*FOO.VAR.dynamic; # OUTPUT: «True»
```
Note that you have to use the `VAR` method in order to get that information.
```raku
my $s is dynamic = [1, 2, 3];
say $s.dynamic; # OUTPUT: «False» (wrong, don't do this)
say $s.VAR.dynamic; # OUTPUT: «True» (correct approach)
```
# [Routines](#class_Scalar "go to top of document")[§](#Routines "direct link")
## [sub atomic-assign](#class_Scalar "go to top of document")[§](#sub_atomic-assign "direct link")
```raku
multi atomic-assign($target is rw, $value)
```
Performs an atomic assignment of `$value` into the `Scalar` `$target`. The `atomic-assign` routine ensures that any required barriers are performed such that the changed value will be "published" to other threads.
## [sub atomic-fetch](#class_Scalar "go to top of document")[§](#sub_atomic-fetch "direct link")
```raku
multi atomic-fetch($target is rw)
```
Performs an atomic read of the value in the `Scalar` `$target` and returns the read value. Using this routine instead of simply using the variable ensures that the latest update to the variable from other threads will be seen, both by doing any required hardware barriers and also preventing the compiler from lifting reads. For example:
```raku
my $started = False;
start { atomic-assign($started, True) }
until atomic-fetch($started) { }
```
Is certain to terminate, while in:
```raku
my $started = False;
start { atomic-assign($started, True) }
until $started { }
```
It would be legal for a compiler to observe that `$started` is not updated in the loop, and so lift the read out of the loop, thus causing the program to never terminate.
## [sub cas](#class_Scalar "go to top of document")[§](#sub_cas "direct link")
```raku
multi cas(Mu $target is rw, Mu \expected, Mu \value)
multi cas(Mu $target is rw, &operation)
```
Performs an atomic compare and swap of the value in the `Scalar` `$target`. The first form has semantics like:
```raku
my $seen = $target;
if $seen<> =:= $expected<> {
$target = $value;
}
return $seen;
```
Except it is performed as a single hardware-supported atomic instruction, as if all memory access to `$target` were blocked while it took place. Therefore it is safe to attempt the operation from multiple threads without any other synchronization. Since it is a reference comparison, this operation is usually not sensible on value types.
For example:
```raku
constant NOT_STARTED = Any.new;
constant STARTED = Any.new;
my $master = NOT_STARTED;
await start {
if cas($master, NOT_STARTED, STARTED) === NOT_STARTED {
say "Master!"
}
} xx 4
```
Will reliably only ever print `Master!` one time, as only one of the threads will be successful in changing the `Scalar` from `NOT_STARTED` to `STARTED`.
The second form, taking a code object, will first do an atomic fetch of the current value and invoke the code object with it. It will then try to do an atomic compare and swap of the target, using the value passed to the code object as `expected` and the result of the code object as `value`. If this fails, it will read the latest value, and retry, until a CAS operation succeeds.
Therefore, an item could be added to the head of a linked list in a lock free manner as follows:
```raku
class Node {
has $.value;
has Node $.next;
}
my Node $head = Node;
await start {
for ^1000 -> $value {
cas $head, -> $next { Node.new(:$value, :$next) }
}
} xx 4;
```
This will reliably build up a linked list of 4000 items, with 4 nodes with each value ranging from 0 up to 999.
**Note**: Before Rakudo version 2020.12, `$target`, `expected` and `value` had an [`Any`](/type/Any) type constraint.
# [Operators](#class_Scalar "go to top of document")[§](#Operators "direct link")
## [infix ⚛=](#class_Scalar "go to top of document")[§](#infix_⚛= "direct link")
```raku
multi infix:<⚛=>($target is rw, $value)
```
Performs an atomic assignment of `$value` into the `Scalar` `$target`. The `⚛=` operator ensures that any required barriers are performed such that the changed value will be "published" to other threads.
## [prefix ⚛](#class_Scalar "go to top of document")[§](#prefix_⚛ "direct link")
```raku
multi prefix:<⚛>($target is rw)
```
Performs an atomic read of the value in the `Scalar` `$target` and returns the read value. Using this operator instead of simply using the variable ensures that the latest update to the variable from other threads will be seen, both by doing any required hardware barriers and also preventing the compiler from lifting reads. For example:
```raku
my $started = False;
start { $started ⚛= True }
until ⚛$started { }
```
Is certain to terminate, while in:
```raku
my $started = False;
start { $started ⚛= True }
until $started { }
```
It would be legal for a compiler to observe that `$started` is not updated in the loop, and so lift the read out of the loop, thus causing the program to never terminate.
# [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")
Type relations for `Scalar`
raku-type-graph
Scalar
Scalar
Any
Any
Scalar->Any
Mu
Mu
Any->Mu
[Expand chart above](/assets/typegraphs/Scalar.svg)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.