## dist_cpan-JNTHN-Cro-OpenAPI-RoutesFromDefinition.md
# Cro::OpenAPI::RoutesFromDefinition Build Status

Takes an existing OpenAPI Document and allows straightforward implementation
of the API defined within it using the Cro libraries.

## Synopsis

```
# Implement the OpenAPI defined in schema.yaml.
my $routes = openapi 'schema.yaml'.IO, {
    # Given an operation defined like this:
    #
    #   summary: Updates a pet in the store with form data
    #   operationId: updatePetWithForm
    #   parameters:
    #   - name: petId
    #     in: path
    #     description: ID of pet that needs to be updated
    #     required: true
    #     schema:
    #   	type: string
    #   requestBody:
    #     content:
    #   	'application/x-www-form-urlencoded':
    #   	  schema:
    #   	   properties:
    #   		  name:
    #   			description: Updated name of the pet
    #   			type: string
    #   		  status:
    #   			description: Updated status of the pet
    #   			type: string
    #   	   required:
    #   		 - status
    #   responses:
    #     '200':
    #   	description: Pet updated.
    #   	content:
    #   	  'application/json': {}
    #     '400':
    #   	description: Invalid input
    #   	content:
    #   	  'application/json': {}
    #
    # We can implement it by receiving the route parameter as a positional
    # argument; other literal route segments need not be mentioned.
    operation 'updatePetWithForm', -> $id {
        # The request body will already have been validated, so just grab
        # it, perhaps using destructuring.
        request-body -> (:$name, :$status) {
            # Do something with it.
            $some-store.update-pet($id, $name, $status);

            # Respond (response automatically checked against schema too).
            content 'application/json', {};
        }
    }
}

```

The `$routes` object is a subclass of `Cro::HTTP::Router::RouteSet`, and so
can be included into a route block:

```
my $api-routes = openapi 'schema.yaml'.IO, {
    ...
}
my $app = route {
    include 'api' => $api-routes;
}

```

Since it is also a `Cro::Transform`, then it may be hosted directly as the
application using `Cro::HTTP::Server`.

```
my $service = Cro::HTTP::Server:
    :host<0.0.0.0>, :port(10000),
    :application($api-routes);

```

## The openapi sub

The `openapi` sub works somewhat like `route` from `Cro::HTTP::Router`. As in
a `route` block, it is possible to:

* Use `before` and `after` to add middleware. The `before` middleware will be
  *after* the validation of a request takes place, and the `after` middleware
  will be run *before* the validation of a response takes place. This means
  that middleware can rely on processing a request that has passed validation,
  while `after` middleware can add, for example, standard headers (such as
  rate limiting) to responses.
* Use `body-parser` and `body-serializer` to specify body parsers and
  serializers. The body parsers will be put in place before validation of
  the body, to ensure deserialization works as desired.

By contrast, `get`, `put`, `post` and so forth are not valid in the context
of an `openapi` block, and using them will produce an error. Instead, the
`operation` sub should be used to specify the implementations of operations
defined by the OpenAPI document. The URI patterns to match will be taken from
the OpenAPI document, and need not be repeated. Similarly, `include` and
`delegate` are not available either (a form of `include` may be supported in
the future in order to allow for breaking up the definition of a large API
over multiple files).

The `openapi` sub may be passed a string containing an OpenAPI document in
either YAML or JSON:

```
openapi $json-doc, {
    ...
}

```

Or an `IO` object pointing to a file to read the document from:

```
openapi "api.yaml".IO, {
    ...
}

```

In either case, JSON will be detected by looking at the data that is read and
seeing if it starts with `{` (with leading whitespace allowed); failing that,
it will be parsed as YAML.

The `openapi` sub may be passed the following options:

* `:ignore-unimplemented` - by default, an operation in the OpenAPI document
  that does not have an implementation in the `openapi` block will result in
  an error being raised by the `openapi` sub. This is to help you understand
  when an API has not been completely implemented. Setting this option will
  cause unimplemented operations to be ignored instead.
* `:!validate-responses` - this option defaults to True, but may be set to
  `False`. If set to False, then responses will not be validated. This may be
  useful for increasing production performance, once confident the API has
  been correctly implemented.
* `:%formats` and `:%add-formats` - passed to `OpenAPI::Schema::Validate` to
  control format validation (`%add-formats` adds additional formats or
  overrides existing ones which `%formats` allows for a full replacement of
  the available formats).
* `:%document` - used to configure how the OpenAPI document itself is served.
  It defaults to `{ '/openapi.json' => 'json', '/openapi.yaml' => 'yaml' }`,
  which means that the OpenAPI specification will be served as both JSON and
  YAML on requests to `/openapi.json` and `/openapi.yaml` respectively. To
  serve a format at the root of the API, pass `:document{ json => '/' }` (this
  also means it will not be served at `/openapi.json` and `/openapi.yaml` any
  longer). It is fine to register multiple paths to serve the document for a
  given format at.

All operations in the OpenAPI document should have an `operationId` in order
to be implementable. Unless configured with `:ignore-unimplemented`, such
operations will be complained about, with a note that it is not even possible
to implement them.

## The operation sub

The `operation` sub is used to specify the implementation of an operation in
the OpenAPI file. It takes a string operation ID and a block that will be run
per request to that operation.

If the string operation ID does not match an `operationId` in the OpenAPI
definition, an error will be raised.

The signature of the block may be used in order to unpack various properties
of the request. This works similarly to signatures on `get` and similar in
`Cro::HTTP::Router`, but with some differences.

* The first parameter may be a session or auth object, populated according to
  the usual `Cro::HTTP::Router` rules.
* Route parameters, from the request target, will be passed as positional
  arguments. Thus, the signature of the operation **must** be able to accept
  them, and cope with optional route parameters. An error will be given if
  the signature of any operation block is not suitable. Note that literal
  route parameters must not be mentioned, and the parameter variable names
  are not significant (the route parameters are passed in the order they
  appear in the URI).
* Query string parameters **may** be unpacked into named arguments (either
  those with no applicable source trait or those marked with `is query` will
  be considered). There is no requirement to unpack all of the query string
  parameters. However, it is an error to name one that does not exist in the
  OpenAPI document.
* Headers and cookies **may** be unpacked into named arguments (using the
  `is header` and `is cookie` parameter traits). There is no requirement to
  unpack these here, and it is allowed to unpack others not mentioned in the
  OpenAPI specification (to provide access to "standard" headers, for
  example).

Otherwise, it is just like being inside a normal `get`, `post`, etc. block as
with `Cro::HTTP::Router`. The `request` and `response` terms provide access to
the request and response objects, the `request-body` sub is available, and the
various response helpers (such as `content`) are also available.

## Automatic Validation

A request will be validated against the OpenAPI definition. The following
aspects of the request will be validated:

* Method (`GET`, `POST`, etc.) (failure to match will result in an automatic
  405 response).
* Route (path) arguments from the target URI (failure to match these will
  result in an automatic 404 response).
* Query string arguments, headers, and cookies (failure to match these will
  result in an automatic 400 response).
* The content type of the request body (failure to match this will result in
  an automatic 400 response).
* The request body. Cro has built-in support for JSON, `multipart/form-data`
  and `application/x-www-form-urlencoded` request bodies, and validation will
  work out of the box. For other body formats, a `body-parser` will be
  required, and it should produce output that can be traversed like a JSON
  data structure in order for schema validation to work. Failure to match the
  schema for the request body will result in an autoamtic 400 response.

A response will (unless response validation is disabled) be validated for:

* The status code of the response. Note that 400, 404, and 405 errors that
  are automatically produced as a result of request validation will always be
  allowed through.
* That the required headers are present and match the schema.
* The content type of the response body.
* The response body. Cro has built-in support for JSON response bodies, and
  validation will work out of the box. For other formats, a `body-serializer`
  will be needed, and the data structure to serialize should be a JSON-like
  tree of hashes/arrays so it can be validated against the schema.

Failure to validate the response indicates an implementation error. A 500
error will be returned to the client, and the error will be logged.

## Manually handling request validation errors

It may in some cases be desirable to handle request validation errors as part
of the operation implementation. Note that this does not apply to an incorrect
method or non-matching route parameters. Further, it presumes that any named
unpacks in the operation signature are liberal enough to cope with the invalid
data.

To manually handle request validation errors, pass `:allow-invalid` to the
`operation` sub. The `request-validation-error` sub can then be used in order
to check if there is a validation error. If there is, then it will be populated
with an instance of `X::Cro::OpenAPI::RoutesFromDefinition::CheckFailed`, which
is a subclass of `Exception`. It has the properties:

* `http-message` - the request that failed to parse. Same as `request` in the
  scope of a handler.
* `reason` - a string explaining the reason that validation failed

If there is no request validation error, then `Nil` is returned, meaning it can be
tested using `with` or `without`.

```
operation 'foo', :allow-invalid, -> $path-param {
    with request-validation-error() -> $error {
        content 'application/json', { :result('error'), :reason($error.reason) };
    }
    else {
        ???;
        content 'application/json', { :result("ok") };
    }
}

```

## Security requirements

Enforcing security requirements involves:

* Implementing the `Cro::OpenAPI::RoutesFromDefinition::SecurityChecker` role
* Passing that using the `security` named parameter to the `openapi` function

Implementing the role requires implementing a single method, which receives the
security scheme to enforce, the HTTP request object, an array of requirements
(optional, and only applicable to OpenID) and the operation ID (also optional).
It should return `True` if the requester satisfies the security requirements,
and `False` if not.

```
role Cro::OpenAPI::RoutesFromDefinition::SecurityChecker {
    method is-allowed(OpenAPI::Model::SecurityScheme $scheme, Cro::HTTP::Request $request,
            :@requirements, :$operation-id --> Bool) { ... }
}

```

For the case of API keys, the role provides a `get-api-key($scheme, $request)`
method that will use the scheme to look up the API key from the request. It will
return a `Failure` if the is no such header, cookie, or query string parameter, or
if the scheme type is not `apiKey`.

An example implementation of the role looks like this:

```
class KeyChecker does Cro::OpenAPI::RoutesFromDefinition::SecurityChecker {
    method is-allowed(OpenAPI::Model::SecurityScheme $scheme, Cro::HTTP::Request $request --> Bool) {
        with self.get-api-key($scheme, $request) -> $key {
            if $key.starts-with('totally-legit') {
                $request.auth = MyAuthInfo.new(:$key);
                return True;
            }
        }
        return False;
    }
}

```

Which could be used like this:

```
my $application = openapi $api-doc, security => KeyChecker, {
    operation 'public', -> {
        content 'text/plain', 'public ok';
    }
    operation 'private', -> {
        content 'text/plain', 'private ok, key=' ~ request.auth.key;
    }
}

```

## Author

Jonathan Worthington [jonathan@edument.se](mailto:jonathan@edument.se)

## Copyright and License

Copyright 2018 Edument Central Europe sro.

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


## dist_zef-librasteve-Math-Interval.md
[![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0)

## Math::Interval

* viz. <https://en.wikipedia.org/wiki/Interval_arithmetic>
* viz. <https://web.mit.edu/hyperbook/Patrikalakis-Maekawa-Cho/node45.html>

### A elementary implementation of Interval Arithmetic using raku Ranges

Check out the Wikipedia page first - sub and div may confound your expectations:

## Synopsis

```
#!/usr/bin/env raku
use lib '../lib';

use Data::Dump::Tree;
use Math::Interval;

# Range-Range Operations use interval math
say (1..2) + (2..4);        #3..6
say (2..4) - (1..2);        #0..3  (yes - this is weird!)
say (2..4) * (1..2);        #2..8
say (2..4) / (1..2);        #1.0..4.0
# strings work too! (must be numbers)
say (1..2) + ('1'..'5');    #2..7
# an Interval is returned
say ((1..2) + (2..4)) ~~ Interval;  #True

#| Interval is a child of class Range where endpoints are always Numeric
#| No cats ears, not Positional, not Iterable, no .elems
my Interval $i1 .= new(range => 2.5^..^8.5);    #3.5..7.5
my Interval $i2 .= new(2..^8);                  #2e0..7e0
my Interval $i3 .= new(1,2);                    #1..2
my Interval $i4 .= new(4.5,6.5);                #4.5..6.5

# '~~' checks if y contains x
say   2 ~~ $i2;     #True
say $i4 ~~ $i1;     #True
say $i1 ~~ $i4;     #False

# cmp checks Order
say $i1 cmp $i1;    #Same
say $i1 cmp $i3;    #More
say $i3 cmp $i1;    #Less
say $i1 cmp $i2;    #Nil   overlaps are not ordered
say $i2 cmp $i1;    #Nil            ""

# intersection ∩ [(&)] and union ∪ [(|)]
say $i3  ∩  $i4;    #∅ the null Set()
say $i4  ∪  $i3;    #union returns a disjoint multi-interval unless args intersect

# gotchas
#say +$i1;          #fails - Interval has no .elems
#say $i1.Set;       #fails - raku Sets must contain discrete items
say $i1.Range.Set;  #coerce to Range to discretize an Interval

## the -Ofun bit

# a divisor that spans 0 produces a disjoint multi-interval
my $j1 = (2..4)/(-2..4);
ddt $j1;            #any(-Inf..-1.0, 0.5..Inf).Junction
say 3 ~~ $j1;       #True

# Junction[Interval] can still be used
my $j2 = $j1 + 2;
ddt $j2;            #any(-Inf..1.0, 2.5..Inf).Junction
say 5 ~~ $j2;       #True

# but this can only go so far...
my $j3 = $j1 * (-2..4);
ddt $j3;            #any(-Inf..Inf, -Inf..Inf).Junction
say 3 ~~ $j3;       #True (but meaningless!)

```

## Explanation

We split the use cases of the built-in Range type as follows:

### class Range

* Use case
  * to generate lists of consecutive numbers or strings
  * to act as a matcher to check if a Numeric or Stringy or Range is within a certain Range
* endpoints with/out cats ears (±1)
* does Positional, does Iterable
* arithmetic +-\*/ operators with scalars are distributed to endpoints like Junction with 2 elems, then each endpoint coerced to .Int
* prefix '+' special cased to .elems
* use `~~` to check containment
  * `say 3 ~~ 1..12;` #True x1 <= a <= x2
  * `say 2..3 ~~ 1..12;` #True x1 >= y1 && x2 <= y2
  * `say 1..12 ~~ 2..3;` #False (y must contain x)
* cmp works for Range op Range (for Real op Range .elems is used)
  * `(0..2) cmp (0..12)` #Less x1 < x2 || x1 == x2 && y1 < y2
  * `(0..2) cmp (0..2)` #Same x1 == x2 && y1 == y2
  * `(1..2) cmp (0..12)` #More x1 > x2 || x1 == x2 && y1 > y2
* Set operations work for Any op Range and Range op Range by auto coercing both args via `.Set`

### class Interval

* Use case
  * to act as a matcher to check if a Numeric or Interval is within a certain range
* endpoints will ingest cats ears, x1 <= x2
* not Iterable nor Positional
* arithmetic +-\*/ operators with scalars are distributed to endpoints like Junction with 2 elems
* Rangy op Rangy --> Interval arithmetic +-\*/ operators implemented
* Rangy \*\* N --> Interval operator implemented
* prefix '+' will fail (Interval has no .elems)
* use `~~` to check containment
  * `say 3 ~~ 1..12;` #True x1 <= a <= x2
  * `say 2..3 ~~ 1..12;` #True x1 >= y1 && x2 <= y2
  * `say 1..12 ~~ 2..3;` #False (y must contain x)
* cmp works for Interval op Interval
  * UNLIKE Range, overlapping intervals are not ordered and yet not equal
  * `(1..2) cmp (3..4)` #Less x2 < y1
  * `(1..2) cmp (2..4)` #Nil x2 !< y1 !!
  * `(0..2) cmp (0..2)` #Same x1 == x2 && y1 == y2
  * `(0..3) cmp (0..2)` #Nil x1 !> y2 !!
  * `(3..4) cmp (1..2)` #More x1 > y2

Set operations
`#say $i1.Set;` #fails - in general Sets contain discrete items and Intervals are continuous
`say $i1.Range.Set;` #coerce to Range first to use all Set operators (which discretizes the Interval)

However, the following two Set operations are implemented for Intervals:

intersection (&) ∩
`∅` if x1 > y2 || y1 > x2
`max(x1,y1)..min(x2,y2)`

union (|) ∪ (of two intersecting intervals)
`min(x1,y1)..max(x2,y2)`

other
`(3..4).abs` #4 (always x2)
`(3..4).width` #1 (x2-x1)

which leads to these design points:

* `class Interval is Range {...}`

  * so can be used wherever a Range is used
  * noting lack of Iterator or Positional support
* `Interval: new $range`

  * rejects non-Real endpoints (eg. Str)
  * adjusts endpoints (±1) to strip cats ears
* `.Range` coerces to Range
* `subset Rangy of Any where * ~~ Range|Interval;`
* No provision is (yet) made for Rounded Interval Arithmetic
* No provision is (yet) made for complex intervals
* Only a handful of all possible Interval operations (eg. log, exp, trig)
* No use of standard libs such as [MPRIA](https://www.gnu.org/software/mpria/) or [MPFI](https://metacpan.org/pod/Math::MPFI)

*Please feel free to submit any of these as a PR (see TODOs below)*

## TODOs

### Additional arithmetic operations

* power (even / odd)
* log / exp
* trig
* Newton

### Copyright

copyright(c) 2023 Henley Cloud Consulting Ltd.


## dist_zef-antononcube-Math-Splines.md
# Math::Splines

Raku package for splines (piecewise polynomials), like, Bezier splines or B-splines.

---

## Installation

From [Zef ecosystem](https://raku.land):

```
zef install Math::Splines

```

From GitHub:

```
zef install https://github.com/antononcube/Raku-Math-Splines.git

```

---

## Usage examples

The subsections below show example usage for the currently implemented functions.

### B-spline basis

```
use Math::Splines;
use Text::Plot;

```

```
# (Any)

```

Using positional arguments:

```
b-spline-basis(3, 0, 0.5)

```

```
# 0.666667

```

Using named arguments:

```
my $degree = 3;
my @knots = b-spline-knots(:$degree, n => 6);
b-spline-basis(:$degree, :@knots, :1index, argument => 0.5)

```

```
# 0.03125

```

Plot the basis of degree 3:

```
my $m = @knots.elems - $degree - 2;
my @points = (0..$m).map( -> $k { (0, 0.01 ... 1).map({ [$_, b-spline-basis(:$degree, :@knots, index => $k, argument => $_)] }) })».Array;
text-list-plot(@points, width => 80, height => 20, title => 'B-spline basis')

```

```
# B-spline basis
# +---+-------------+-------------+-------------+-------------+-------------+----+
# |                                                                              |
# +   *                                                                     ▷    +  1.00
# |    *                                                                    ▷    |
# |     *                                                                  ▷     |
# +                                                                              +  0.80
# |      *                                                                ▷      |
# |      *                                                                ▷      |
# +       *    □□□□□□        ▽▽▽▽▽▽▽▽          ❍❍❍❍❍❍❍❍        ◇◇◇◇◇◇    ▷       +  0.60
# |        * □□     □□□□  ▽▽▽        ▽▽▽    ❍❍❍        ❍❍❍  ◇◇◇      ◇◇ ▷        |
# |        □□          □▽▽              ▽❍❍❍             ❍❍◇◇          ▷         |
# +        □ *        ▽▽ □□           ❍❍❍  ▽▽▽           ◇◇ ❍❍        ▷ ◇        +  0.40
# |       □  *      ▽▽     □        ❍❍        ▽▽       ◇◇     ❍❍     ▷   ◇       |
# |      □    **  ▽▽        □□□  ❍❍❍            ▽▽▽  ◇◇◇        ❍❍  ▷▷    ◇      |
# +      □      ▽▽            □❍❍                 ▽◇◇◇            ❍▷      ◇      +  0.20
# |     □     ▽▽▽**        ❍❍❍❍ □□□□            ◇◇◇  ▽▽▽        ▷▷▷❍❍❍     ◇     |
# |    □   ▽▽▽     ***❍❍❍❍❍❍        □□□□    ◇◇◇◇        ▽▽▽▽▽▽▷▷▷    ❍❍❍    ◇    |
# +   ▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷▽▽▽▽▽▽▽▽▽▽❍❍❍❍◇    +  0.00
# |                                                                              |
# +---+-------------+-------------+-------------+-------------+-------------+----+
#     0.00          0.20          0.40          0.60          0.80          1.00

```

### Functions instead of values

If the argument `:arg(:argument(:$x))` of `b-spline-basis` is `Whatever`, then a function is returned:

```
my &bf = b-spline-basis(:3degree, :0index, arg => Whatever);

&bf(0.25)

```

```
# 0.125

```

Alternatively, the subs `b-spline-basis-value` and `b-spline-basis-function` can be used to get values and functions respectively.

### Bernstein basis

```
my @points = (^4).map( -> $k { (0, 0.01 ... 1).map({ [$_, bernstein-basis(3, $k, $_)] }) })».Array;
text-list-plot(@points, width => 80, height => 20, title => 'Bernstein basis')

```

```
# Bernstein basis
# +---+-------------+-------------+-------------+-------------+-------------+----+
# |                                                                              |
# +   **                                                                    ❍    +  1.00
# |     **                                                                ❍❍     |
# |      ***                                                            ❍❍❍      |
# +        **                                                          ❍         +  0.80
# |          **                                                      ❍❍          |
# |            **                                                  ❍❍            |
# +              **                                             ❍❍❍              +  0.60
# |                **                                         ❍❍❍                |
# |                  ***   □□□□□□□                ▽▽▽▽▽▽▽   ❍❍❍                  |
# +                 □□□□□□□       □□□□□□□▽▽▽▽▽▽▽▽▽       ❍❍❍▽▽▽▽                 +  0.40
# |             □□□□       ***      ▽▽▽▽▽▽□□□□□□      ❍❍❍       ▽▽▽▽             |
# |          □□□□             **▽▽▽▽            □□❍❍❍❍             ▽▽▽           |
# +        □□□             ▽▽▽▽▽ *****        ❍❍❍❍❍ □□□□□             ▽▽         +  0.20
# |       □□          ▽▽▽▽▽          ****❍❍❍❍❍❍          □□□□□          ▽▽       |
# |     □□      ▽▽▽▽▽▽          ❍❍❍❍❍❍❍❍❍  ********           □□□□□□      ▽▽     |
# +   ❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍❍                  ****************□□□□□□□□□▽    +  0.00
# |                                                                              |
# +---+-------------+-------------+-------------+-------------+-------------+----+
#     0.00          0.20          0.40          0.60          0.80          1.00

```

---

## TODO

* TODO Implementation
  * TODO Bezier curve
* TODO Documentation
  * DONE Notebooks
    * DONE [B-spline basis](./docs/B-spline-basis.ipynb)
    * DONE [B-spline curve](./docs/B-spline-curve.ipynb)
  * TODO Demo of 2D B-spline curve with control points

---

## References

[AAp1] Anton Antonov,
[Math::Fitting Raku package](https://github.com/antononcube/Raku-Math-Fitting),
(2024),
[GitHub/antononcube](https://github.com/antononcube).

[AAp2] Anton Antonov,
[Math::Polynomial::Chebyshev Raku package](https://github.com/antononcube/Raku-Math-Polynomial-Chebyshev),
(2024),
[GitHub/antononcube](https://github.com/antononcube).


## dist_zef-jnthn-Log-Timeline.md
# Log::Timeline

When building an application with many ongoing, potentially overlapping,
tasks, we may find ourselves wishing to observe what is going on. We'd like to
log, but with a focus on things that happen over time rather than just
individual events. The `Log::Timeline` module provides a means to do that.

As well as annotating your own applications with `Log::Timeline` tasks and
events, the module can provide various events relating to the Raku standard
library, and has already been integrated in some modules, such as Cro.

## Key features

* Log tasks with start and end times
* Log individual events
* Tasks and events can be associated with an enclosing parent task
* Include data (keys mapped to values) with the logged tasks and events
* Have data logged to a file (JSON or CBOR), or exposed over a socket
* Visualize task timelines in [Comma](https://commaide.com/) (from Comma Complete
  2018.5 and Comma Community 2018.7)
* Support by [Cro](https://cro.services/), to offer insight into client
  and server request processing pipelines (from 0.8.1)
* Enable logging of various Raku standard library events: the start and end
  times of `start` blocks and `await` statements, socket connections, files
  being open, and more

Planned:

* Introspect what tasks and events a given distribution can log
* Log tasks indicating when GC happens
* Turn on/off what is logged at runtime (socket mode only)

## Turning on Raku built-ins logging

Set the `LOG_TIMELINE_RAKU_EVENTS` environment variable to a comma-separated
list of events to log. For example:

```
LOG_TIMELINE_RAKU_EVENTS=file,thread,socket,process,start,await

```

The events available are:

* `await` - logs tasks showing time spent in an `await`
* `file` - logs tasks showing the time files are open
* `process` - logs tasks showing the time that a sub-process is running
  (the logging is done on `Proc::Async`, which covers everything since the
  synchronous process API is a wrapper around the asynchronous one)
* `socket` - logs a task when a listening asynchornous socket is listening,
  and child tasks for each connection it receives; for connections, the
  connection is logged along with a child task for the time taken for the
  initial connection establishment
* `start` - logs tasks showing the time that `start` blocks are "running"
  (however, they may within that time be suspended due to an `await`)
* `thread` - logs creation of Raku `Thread`s. These are typically created by
  the thread pool when using Raku's high-level concurrency features.

## Providing tasks and events in a distribution

Providing tasks and events in your application involves the following steps:

1. Make sure that your `META6.json` contains a `depends` entry for `Log::Timeline`.
2. Create one or more modules whose final name part is `LogTimelineSchema`, which
   declares the available tasks and events. This will be used for tools to
   introspect the available set of tasks and events that might be logged, and
   to provide their metadata.
3. Use the schema module and produce timeline tasks and events in your application
   code.

### The schema module

Your application or module should specify the types of tasks and events it wishes to
log. These are specified in one or more modules, which should be registered in the
`provides` section of the `META6.json`. The **module name's final component** should be
`LogTimelineSchema`. For example, `Cro::HTTP` provides `Cro::HTTP::LogTimelineSchema`.
You may provide more than one of these per distribution.

Every task or event has a 3-part name:

* **Module** - for example, `Cro HTTP`
* **Category** - for example, `Client` and `Server`
* **Name** - for example, `HTTP Request`

These are specified when doing the role for the event or task.

To declare an event (something that happens at a single point in time), do the
`Log::Timeline::Event`. To declare an task (which happens over time) do the
`Log::Timeline::Task` role.

```
unit module MyApp::Log::LogTimelineSchema;
use Log::Timeline;

class CacheExpired does Log::Timeline::Event['MyApp', 'Backend', 'Cache Expired'] { }

class Search does Log::Timeline::Task['MyApp', 'Backend', 'Search'] { }

```

### Produce tasks and events

Use the module in which you placed the events and/or tasks you wish to log.

```
use MyApp::Log::LogTimelineSchema;

```

To log an event, simply call the `log` method:

```
MyApp::Log::LogTimelineSchema::CacheExpired.log();

```

Optionally passing extra data as named arguments:

```
MyApp::Log::LogTimelineSchema::CacheExpired.log(:$cause);

```

To log a task, also call `log`, but pass a block that will execute the task:

```
MyApp::Log::LogTimelineSchema::Search.log: -> {
    # search is performed here
}

```

Named parameters may also be passed to provide extra data:

```
MyApp::Log::LogTimelineSchema::Search.log: :$query -> {
    # search is performed here
}

```

## Collecting data

### Logging to a file in JSON lines format

Set the `LOG_TIMELINE_JSON_LINES` environment variable to the name of a file
to log to. Each line is an object with the following keys:

* `m` - module
* `c` - category
* `n` - name
* `t` - timestamp
* `d` - data (an object with any extra data)
* `k` - kind (0 = event, 1 = task start, 2 = task end)

A task start (kind 1) and task end (2) will also have:

* `i` - a unique ID for the task, starting from 1, to allow starts and ends to
  be matched up

An event (kind 0) or task start (kind 1) may also have:

* `p` - the parent task ID

### Logging to a file as a CBOR sequence

Set the `LOG_TIMELINE_CBOR_SEQUENCE` environment variable to the name of a file
to log into. The schema matches that of the JSON lines output.

### Socket logging

Set the `LOG_TIMELINE_SERVER` environment variable to either:

* A port number, to bind to `localhost` on that port
* A string of the form `host:port`, e.g. `127.0.0.1:5555`

**Warning:** Don't expose the socket server to the internet directly; there
is no authentication or encryption. If really wishing to expose it, bind it to
a local port and then use an SSH tunnel.

#### Handshake

Upon connection the client *must* send a JSON line consisting of an object that
includes the keys:

* `min` - the minimum protocol version that the client understands
* `max` - the maximum protocol version that the client understands

The client *may* include other keys in the object speculatively (for example, if
protocol version 3 supports a key "foo", but it speaks anything from 1 to 3, then
it may include the key "foo", knowing that a previous version of the server will
simply ignore it).

In response to this, the server *must* send a JSON line consisting of an object
that includes *at most one of the following*:

* `ver` - the version number of the protocol that the server will speak, if it is
  understands any of the versions in the range the client proposed
* `err` - an error string explaining why it will not accept the request

In the case of sending an `err`, the server *should* close the connection.

If the initial communication from the client to the server:

* Does not start with a `{`
* Does not reach a complete line within 1 megabyte of data

Then the server may send a *may* send a JSON line with an object containing `err` and
then close the connection.

#### Protocol version 1

No additional configuration keys from the client are recognized in this version of the
protocol.

Beyond the initial handshake line, the client should not send anything to the server. The
client may close the connection at any time.

The server sends JSON lines to the client. This lines are the same as specified for the
JSON lines file format.

## Checking if logging is active

Call `Log::Timeline.has-output` to see if some kind of logging output is set up in
this process, This is useful for avoiding introducing logging if it will never take
place.


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

# NAME

META::varauthapi - apply :ver:auth:api from META on classes

# SYNOPSIS

```
# in distribution "Frobnicate"
class Frobnicate { }

use META::verauthapi $?DISTRIBUTION, Frobnicate;

say Frobnicate.^ver;   # v1.2.3
say Frobnicate.^auth;  # zef:lizmat
say Frobnicate.^api;   # 0

```

# DESCRIPTION

META::varauthapi provides an easy way to keep the meta information of one of more classes in a distribution in sync with the information in the META6.json file of that distribution.

The `use` statement needs to be specified with the `$?DISTRIBUTION` variable, and will by default set the `:ver`, `:auth` and `:api` of the all the classes listed in the `"provides"` field in the META information.

For more control, it is also possible to list the classes to set as additional arguments in the `use` statement.

# AUTHOR

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

Source can be located at: <https://github.com/lizmat/META-verauthapi> . 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 2024 Elizabeth Mattijsen

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


## dist_cpan-VRURG-Vikna.md
# Raku Console UI Toolkit Vikna

Pronounced as *Veekna*. In Ukrainian it means 'windows'. ;)

![Demo](https://github.com/vrurg/raku-Vikna/blob/master/doc/image/demo.gif)

# **IMPORTANT!**

Vikna is in its deep, deep infancy stage. Mostly being a proof of concept now than a real thing. Yet, it already has
many of the key elements an UI framework must have. Just check out
[*./examples*](https://github.com/vrurg/raku-Vikna/tree/v0.0.1/examples) directory to get the first impression. But be
patient when trying [*threaded-rainbow.raku*](https://github.com/vrurg/raku-Vikna/blob/master/examples/threaded-rainbow.raku).

The project requires Raku to implement chained dispatching. Because my implementation of the feature for
Rakudo had to be reverted from the *master* Vikna won't work correctly with standard Rakudo releases. But it can be tried with
*v-dispatchers* branch in either [main Rakudo repository](https://github.com/rakudo/rakudo/tree/v-dispatchers) or in
[my fork of it](https://github.com/vrurg/rakudo/tree/v-dispatchers). The situation will change when Jonathan Worthington
will succeed with his total redesign of dispatching which is much awaited by many as it gonna bring a lot of new
opportunities to Rakudo.

## SEE ALSO

[`Vikna`](https://github.com/vrurg/raku-Vikna/blob/master/docs/md/Vikna.md)


## dist_zef-jforget-Date-Calendar-MayaAztec.md
# NAME

Date::Calendar::MayaAztec - conversions from / to the Maya calendar and from / to the Aztec calendar

# SYNOPSIS

When was the last time the end of the universe happened?

```
use Date::Calendar::Maya;
my Date::Calendar::Maya
        $d-maya  .= new(long-count => '13.0.0.0.0');
my Date $d-greg   = $d-maya.to-date('Date');
say $d-greg;
# --> 2012-12-21 (for 21st December 2012)

```

The Perl and Raku conference in North America was scheduled to take
place in Houston, starting on 2020-06-20. What does the southern
neighbours call this date?

```
use Date::Calendar::Maya;
use Date::Calendar::Aztec;
my Date                  $d-greg  .= new(2020, 6, 20);
my Date::Calendar::Aztec $d-aztec .= new-from-date($d-greg);
my Date::Calendar::Maya  $d-maya  .= new-from-date($d-greg);

say "{.tzolkin} {.haab} {.long-count}" with $d-maya;
# --> 12 Etznab 1 Tzec 13.0.7.10.18
$d-maya.locale = 'en';
say "{.tzolkin} {.haab}" with $d-maya;
# --> 12 Flint 1 Skull

say "{.tonalpohualli} {.xiuhpohualli}" with $d-aztec;
# --> 12 Tecpatl 20 Teotleco
$d-aztec.locale = 'en';
say "{.tonalpohualli} {.xiuhpohualli}" with $d-aztec;
# --> 12 Flint 20 God arrives

```

# DESCRIPTION

Date::Calendar::MayaAztec is a distribution with two main classes,
Date::Calendar::Maya implementing the Maya calendars (long count, Haab
and Tzolkin) and Date::Calendar::Aztec implementing the Aztec
calendars (tonalpohualli and xiuhpohualli).

# INSTALLATION

```
zef install Date::Calendar::MayaAztec

```

or

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

```

# AUTHOR

Jean Forget

# COPYRIGHT AND LICENSE

Copyright (c) 2020, 2023, 2024 Jean Forget

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


## dist_zef-raku-community-modules-Time-Duration-Parser.md
[![Actions Status](https://github.com/raku-community-modules/Time-Duration-Parser/workflows/test/badge.svg)](https://github.com/raku-community-modules/Time-Duration-Parser/actions)

# NAME

Time::Duration::Parser - Parse duration strings into seconds

# SYNOPSIS

```
use Time::Duration::Parser;

my $time-string = "5 days 4 hours 52 minutes 3 seconds";
my $s = duration-to-seconds($time-string);
say "$time-string -> $s seconds";

```

# DESCRIPTION

Time::Duration::Parser is a module exports a single subroutine `duration-to-seconds` that turns a string like "3 days 29 minutes" into a number of seconds.

Note, for **months** and **years** the values are approximated as 30 days and 365 days respectively.

# AUTHOR

Jonathan Scott Duff

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

# COPYRIGHT AND LICENSE

Copyright 2017 Jonathan Scott Duff

Copyright 2018 - 2022 Raku Community

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


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

# NAME

Raku port of Perl's fileno() built-in

# SYNOPSIS

```
use P5fileno;

say fileno $*IN;    # 0
say fileno $*OUT;   # 1
say fileno $*ERR;   # 2
say fileno $foo;    # something like 16

```

# DESCRIPTION

This module tries to mimic the behaviour of Perl's `fileno` built-in as closely as possible in the Raku Programming Language.

# ORIGINAL PERL 5 DOCUMENTATION

```
fileno FILEHANDLE
        Returns the file descriptor for a filehandle, or undefined if the
        filehandle is not open. If there is no real file descriptor at the
        OS level, as can happen with filehandles connected to memory
        objects via "open" with a reference for the third argument, -1 is
        returned.

        This is mainly useful for constructing bitmaps for "select" and
        low-level POSIX tty-handling operations. If FILEHANDLE is an
        expression, the value is taken as an indirect filehandle,
        generally its name.

        You can use this to find out whether two handles refer to the same
        underlying descriptor:

            if (fileno(THIS) != -1 && fileno(THIS) == fileno(THAT)) {
                print "THIS and THAT are dups\n";
            } elsif (fileno(THIS) != -1 && fileno(THAT) != -1) {
                print "THIS and THAT have different " .
                    "underlying file descriptors\n";
            } else {
                print "At least one of THIS and THAT does " .
                    "not have a real file descriptor\n";
            }

```

# IDIOMATIC PERL 6 WAY

The file descriptor of a file handle is exposed with the `native-descriptor` method on `IO::Handle`:

```
say $*OUT.native-descriptor;   # 1

```

# PORTING CAVEATS

When calling with an unopened `IO::Handle`, this version will return `Nil`. That's the closest thing there is to `undef` in Raku.

# AUTHOR

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

Source can be located at: <https://github.com/lizmat/P5fileno> . 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-raku-community-modules-Grammar-BNF.md
[![Actions Status](https://github.com/raku-community-modules/Grammar-BNF/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Grammar-BNF/actions) [![Actions Status](https://github.com/raku-community-modules/Grammar-BNF/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Grammar-BNF/actions) [![Actions Status](https://github.com/raku-community-modules/Grammar-BNF/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Grammar-BNF/actions)

# NAME

Grammar::BNF - Parse (A)BNF grammars and generate Raku grammars from them

# SYNOPSIS

```
use Grammar::BNF;
my $g = Grammar::BNF.generate(Q:to<END>);
  <foo2> ::= <foo> <foo>
  <foo> ::= "bar"
  END

```

# DESCRIPTION

This distribution contains modules for creating Raku Grammar objects using BNF flavored grammar definition syntax. Currently BNF and ABNF are supported.

In addition, the distribution contains Slang modules which allow use of the grammar definition syntax inline in Raku code. These modules may relax their respective syntax slightly to allow for smoother language integration.

# IDIOMS

This simple example shows how to turn a simple two-line grammar definition in BNF syntax into a grammar named `MyGrammar`, and then uses the resulting grammar to parse the string 'barbar';

```
use Grammar::BNF;
my $g = Grammar::BNF.generate(Q:to<END>);
  <foo2> ::= <foo> <foo>
  <foo> ::= "bar"
  END
                              );
$g.parse('barbar').say; # ｢barbar｣
                        #  foo2 => ｢barbar｣
                        #   foo => ｢bar｣
                        #   foo => ｢bar｣

```

Alternatively, you may use a slang to define grammars inline:

```
use Slang::BNF;
bnf-grammar MyGrammar {
    <foo2> ::= <foo> <foo>
    <foo> ::= "bar"
}; # currently you need this semicolon
MyGrammar.parse('barbar').say; # same as above

```

In either case, the first rule appearing in the grammar definition will be aliased to 'TOP', and will be the default rule applied by `.parse`. This is in most respects a true Raku, so subrules may be invoked:

```
MyGrammar.parse('bar',:rule<foo>).say; # ｢bar｣

```

...and the Grammar may be subclassed to add or replace rules with Perl 6 rules:

```
grammar MyOtherGrammar is MyGrammar {
    token foo { B <ar> }
    token ar  { ar }
}
MyOtherGrammar.parse('BarBar').say; # ｢BarBar｣
                                    #  foo2 => ｢BarBar｣
                                    #   foo => ｢Bar｣
                                    #    ar => ｢ar｣
                                    #   foo => ｢Bar｣
                                    #    ar => ｢ar｣

```

Currently you have to subclass with a Raku grammar for actions classes to be provided, but hopefully that limitation will be overcome:

```
class MyActions { method foo ($match) { "OHAI".say } }
MyOtherGrammar.parse('BarBar', :actions(MyActions)); # says OHAI twice

```

# AUTHOR

Tadeusz Sośnierz

# COPYRIGHT AND LICENSE

Copyright 2010 - 2017 Tadeusz Sośnierz

Copyright 2024 Raku Community

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


## dist_zef-thundergnat-Date-Discordian.md
[![Actions Status](https://github.com/thundergnat/Date-Discordian/actions/workflows/test.yml/badge.svg)](https://github.com/thundergnat/Date-Discordian/actions)

# NAME

Date::Discordian - Convert Gregorian Dates to Discordian

# SYNOPSIS

```
use Date::Discordian;

say discordian( '2020-03-24' ); # Pungenday, the tenth day of Discord in the YOLD 3186

say discordian( 2021, 8, 15 ); # Boomtime, the eighth day of Bureaucracy in the YOLD 3187

say discordian( Date.new("2005-01-31") ) # Sweetmorn, the thirty-first day of Chaos in the YOLD 3171

```

# DESCRIPTION

Exports a single subroutine: `discordian()`. When given a Gregorian date, returns the text description or hash of date elementsof the corresponding Discordian date.

Will accept the same parameters a the internal Date class. Will also accept the keyword today.

```
# Get textual date conversions
discordian( '2020-03-24' ); # formatted date string (ISO-8601)

discordian( 2020, 3, 24 ); # Integer year, month, day

discordian( Date.new("2020-03-24") ); # Native Date object

discordian( now ); # Instant

discordian( today ); # today

# Get a hash of date elements - supply a truthy second parameter to force hash return values
my $dd = discordian( '2020-03-24', :h );
say $dd.<weekday season day yold holy>

```

Most likely, some hash elements will be blank. If it isn't a holyday, :holy will be blank. On St Tib's day, :weekday, :season and :day will be blank.

# AUTHOR

Portions adapted from code from <http://rosettacode.org/wiki/Discordian_date#Raku>

Other code by Steve Schulze

# COPYRIGHT AND LICENSE

Copyright 2020 Steve Schulze (thundergnat)

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


## dist_github-gfldex-Shell-Piping.md
# Shell::Piping

[![Build Status](https://travis-ci.org/gfldex/raku-shell-piping.svg?branch=master)](https://travis-ci.org/gfldex/raku-shell-piping)

Shell pipes without a shell but Raku.

## SYNOPSIS

```
use v6.d;
use Shell::Piping;

my int $exitcode = 0;
my &RED = $*OUT.t ?? { „\e[31m$_\e[0m“ } !! { $_ };

sub MAIN(Str $where = ‚/tmp/.‘) {
    my @result;
    my @err;

    px«find $where» |» { /a/ ?? $_ !! Nil } |» px<sort -r> |» @result :stderr(@err) :done({$exitcode ⚛= 1 if .exitcodes});

    .say for @result.head(10);

    if $exitcode {
        $*ERR.put: @err».&RED.join(„\n“);
    }

    exit $exitcode;
}

```

## USAGE

This module provides the operator `|»` (aliased to `|>>`) to implement shell-like
piping using `Proc::Async` objects, `Code` objects, `Channel`, `Supply` and
custom objects. A quote construct like operator `px` is provided to create
`Proc::Async` instances.

### `px<>`, `px«»`, `px{}`

These operators take a single argument without a space between `px` and the
argument. It will then split the argument on white spaces. The first element is
considered a command and the remaining elements arguments to that command.
If a command does not contain a directory separator, `%*ENV<PATH>` will be searched
for that command and the first hit used to create a `Proc::Async`. If a
directory separator is used the first argument is assumed to be a `IO::Path`.
In both cases the resulting file is checked for existence and filesystem access
rights to execute it. The exceptions `X::Shell::CommandNotFound` and
`X::Shell::CommandNoAccess` will be thrown when those tests fail. Please note
that the file might be deleted between this check and the actual execution of
the command. The semantics of the provided argument follow general Raku
subscript rules. As such `px<foo bar>` and `px«foo $bar»` will generate an
argument list automatically. While the code inside `px{foo, bar}` has to return
that list by your effort.

```
my $proc = px<foo $not-interpolated>; # no interpolation, $PATH is queried
my $var = "42";
$proc = px«/usr/bin/meaning $var»; # interpolation and $PATH is not queried
$proc = px{ 'C:/WINDOWS/SYSTEM32/VIOLATE-PRIVACY'.subst('/', '\') ~ '.exe', secrets.txt };
await $proc.start;

```

It is not the resposibility of `px` to actually do anything with the resulting
`Proc::Async` instance.

The adverb `:timeout(Numerical)` takes seconds with fractions and kills the
spawned process when at least this time has passed. If the adverb is used
`Proc::Async::Timeout` will be returned instead of `Proc::Async`. When the
timeout is hit `X::Proc::Async::Timeout` will be thrown.

```
my @a;

loop {
    (px<curl https://www.raku.org>:timeout(60)) |» @a;
    last;
    CATCH {
        when X::Proc::Async::Timeout {
            put „{.command} timed out. Trying again and again and again.“;
        }
    }
}

```

### `multi infix:<|»>` and `multi infix:«|>>»`

The MMD candidates of this operator take two arguments and return a
`Shell::Pipe` object. This object implements `.sink` and `.start`, whereby the
first will call the latter. When `.sink` is called all members of a pipe will
be wired up, started in the right order and `await`ed. In sink context the
whole pipe will block until the last `Proc::Async` returned from its `.start`
method.

Members of a pipe can be `Proc::Async`, `Code` objects, `Channel`, `Supply`,
`IO::Handle`, `IO::Path` and `Array`-like objects. The latter are identified by
a subset.

```
subset Arrayish of Any where { !.isa('Code') && .^can(‚push‘) && .^can(‚list‘) }

```

`Proc::Async` has its STDOUT fed line-by-line to the next element in the pipe.
If it is a RHS argument to `|»` its STDIN is written to with the output of the
LHS. STDERR is left untouched unless the adverbs `:quiet` or `:stderr` are used.

```
px<find /tmp> |» px<sort> :quiet; # equivalent to `find /tmp 2>/dev/null | sort 2>/dev/null`;

```

To capture STDOUT and output to the terminal at the same time, set `$*echo` to
`on`.

`Code` objects can be used at any place in a pipe. The semantics however vary.
At the beginning of a pipe the object has to return an Iterable or implement
`.list`. It will be called once and iterated over its return value. As such we
support `gather/take`, sequence operators and many buildins. Each value returned
from an iteration will be added a newline, encoded as utf8 and fed to the next
member of the pipe. If a code object is in the middle of a pipe it will be
called each time a line of text is produced to its left and its return value
fed to the right. If `Nil` is returned this value will be skipped. At the end
of the pipe the code object is called with each line produced by its left
neighbour.

```
my @a;
{ 2,4,8 … 2**32 } |» px<sha256sum> |» @a;
px<find /tmp> |» { /a/ ?? .lc !! Nil } |» px<sort>;
px<find /tmp> |» { .say } :quiet;

```

`Channel` and `Supplier`/`Supply` can be used at the start and end of a pipe.
If they are closed, the entire pipe will have STDIN/STDOUT closed. This allows
a pipe to be controlled from the outside. Any case to complex for a `Code`
object should therefore be handled with a `Channel`.

```
my $c = Channel.new;
my $sort = px<sort>;
start {
    await $sort.ready; # this line is optional
    for 1..∞ {
        $c.send: $^a;
    }
}

Promise.in(60).then: { $c.close }; # a timeout
$c |» $sort |» px<uniq> |» { .say };

```

`IO::Path` objects are opened for reading at the begin of a pipe and for writing
at the end. `IO::Handle` objects are expected to be open already and must be
open for writing at the end. File handles will not be closed by the pipe.

```
px<find /tmp> |» px<sort> |» { .uc  } |» ‚/tmp/sorted.txt‘.IO :quiet;

```

`Array`-like objects can be used at both ends of a pipe. If used as a first
element its `.list` method will be called and iterated. At the end of a pipe
the `.push` method is called. That means lines from a LHS are always added to
this object.

```
class Custom {
    has @.buffer;
    method push -> \v { @.buffer.push: v; @.buffer.shift if +@.buffer > 100; self }
    method list { @.buffer.list }
}

my $c = Custom.new;
px<find /usr -iname *.txt> |» $c;
$c |» px<sort> |» { .say };

```

### Slurpy list deconstruction

List deconstruction is supported on the right hand side of `|»`, whereby a
`Whatever` is required as a first or last element of the declarator list. Used
as a first element `Whatever` indicated that elements at the beginning of the
output are to be skipped. With `Whatever` as the last element, only the first
n-elements are to be kept. This is useful if you are only interested in the
first or last few elements of the output of a script.

```
px<find /usr -iname *.txt> |» my (Whatever, $second-last, $last-line);
px<find /usr -iname *.txt> |» out ($first-line, $, $third-line, Whatever);
px<find /usr -iname *.txt> |» my $first-line-only;

```

That declarator lists don't accept `*` is a limitation of Raku (for now).

A single scalar that is not `Arrayish` will have the first ouput line assigned.
If there are more lines we `warn`.

To capture STDOUT and output to the terminal at the same time, set `$*echo` to
`on`.

## Adverbs

### `:done(&c(Shell::Pipe $pipe))`

Will be called after the last command of a pipe has exited and before
`X::Shell::NonZeroExitcode` will be thrown. The argument `$pipe` can be used
for error handling via `.exitcodes` and introspection via `.pipees`.

### `:stderr(Arrayish|Code|Channel|IO::Path|IO::Handle|Capture)`

This adverb redirects all STDERR into objects similar to what ‚|»‘ accepts.
Error text is processed line by line and forwarded as a pair of `(Int $index, Str $text)`. Whereby `$index` is the position of the pipee producing the text
starting with 0.

```
px<find /usr> |» px<sort> |» @a :stderr(@err) :done({.exitcodes});
for @err.grep({.head == 0}) {
    say ‚find warned about: ‘, .Str;
}

```

To log to a file `:stderr()` takes an `IO::Handle` that is open for writing or a
`IO::Path` that will be opened for writing. To close the handle call
`.stderr.close` in the `:done()` callback.

Multiple targets for the STDERR stream can be provides with a `Junction`. For
now only `&` junctions are supported. All targets will receive the same lines
of text. Whereby no particular order should be assumed.

```
px<find /usr> |» px<sort> |» @a :stderr('logfile.txt'.IO & @err & Capture);

```

The value `Capture` can have an `Int` mixed in to limit capturing to the last n
lines.

```
my $n = 10; # at most $n lines of STDERR are captured
px<find /usr> |» px<sort> |» @a :stderr(Capture but $n);

```

### `:quiet`

The adverb `:quiet` will gobble up all STDERR streams and discard them. This
can be made the default by setting `$*quiet` to the exported symbol `on`.

```
my $*quiet = on;
my @a;
px<find -iname *.raku> |» @a;

```

## Error handling

When any `Proc::Async` in a pipe finished with a non-zero exitcode the pipe
returns a `Failure` of `X::Shell::NonZeroExitcode`. Calling `.exitcode` on the
pipe will mark this `Failure` as handled. The callback in `:done()` is called
before the Failure can throw. Handling exitcodes by hand has to go there.
Individual exitcodes of pipe commands are stored in an Array with an index that
corresponds to the commands position in the pipe. If STDERR output is captured
with `:stderr(Capture)`. The text per command is available, again as a list of
`($idx, $text)`. This can be made the default by setting `$*capture-stderr` to
the exported symbol `on`.

```
sub error-handler($pipe) {
    my @a = $pipe.exitcodes;
    for @a {
        .command.say;
        .exitcode.say;
        .STDERR.say;
    }
}
px«find /usr» |» px«sort» :done(&error-handler) :stderr(Capture);

```

The class `Shell::Pipe::Exitcode` supports smartmatching against `Int`, `Str`
and `Regex`. This can be used for handling exceptions.

```
px«find /usr» |» px«sort» :stderr(Capture);

CATCH {
    when X::Shell::NonZeroExitcode {
        for .pipe.exitcodes {
            when ‚find‘ & 1 & /‘(<![‘]>+)‘: Permission denied/ {
                say „did not look in $0“;
            }
        }
    }

}

```

## Exceptions

```
CATCH {
    when X::Shell::CommandNotFound {
        say .cmd ~ ‚was not found‘;
    }
    when X::Shell::CommandNoAccess {
        say .cmd ~ ‚was unaccessable‘;
    }
    when X::Shell::NonZeroExitcode {
        for .pipe.exitcodes {
            say .command, .exitcode, .pipe.stderr ~~ Capture ?? .STDERR !! ‚‘;
            when ‚find‘ & 1 & /‘(<![‘]>+)‘: Permission denied/ {
                say „did not look in $0“;
            }
        }
    }
    when X::Shell::NoExitcodeYet {
        say .^name, „\n“, .message;
    }
}

```

### Refining Exceptions

The exceptions `X::Shell::CommandNotFound` and `X::Shell::CommandNoAccess` are
refinable. This means the error message can be tweaked with the class method
`.refine`. This method takes two `Callable`s. When `.message` is called with
the exception instance and expected to return `Bool`. On `True` the 2nd
callback is called with the exception instance and supposed to return a text.
This text will be used instead of the default text and returned from
`.message`. Replacing this message will act on the class and even on created
but yet to be thrown exceptions.

```
X::Shell::CommandNotFound.refine(
    (my &b = {.cmd eq ‚raku‘}),
    { ‚Please install Rakudo with `apt install rakudo`.‘ }
);
X::Shell::CommandNotFound.refine(&b, :revert);
X::Shell::CommandNotFound.refine(:revert-all);

```

The method `.revert` also takes one `Callable` and the adverb `:revert` to
remove one refinement or all refinements with `:revert-all`.

### X::Shell::CommandNotFound

Will be thrown by `px«»` or when the pipe is started if the file used as a
command is not found. The meaning of "not found" depends on the OS. If the
command was searched for in `%*ENV<PATH>`, that path will be shown in the
exception message. This exception also checks for dangling symlinks and
provides an alternate error message for this case.

### X::Shell::CommandNoAccess

Will be thrown by `px«»` or when the pipe is started if the file used as a
command exists but can not be executed. Filesystem access rights depend on the
OS.

### X::Shell::NonZeroExitcode

This will be thrown after the last pipee exits and holds a `Shell::Pipe` in
`.pipe`. If `:stderr(Capture)` is used the exception message contains all error
text grouped by the shell command names. When an `Int` is mixed in, only that
many lines will be captured.

The command line will be clipped at 180 characters. This limit can be changed
by setting `$*max-exitcode-command` to any `Int` or `Inf`.

### X::Shell::NoExitcodeYet

Will be thrown if `.exitcodes` is accessed before the pipe finished. Please
note that filling the underlying Array is not atomic. When or after `.done` is
called using `.exitcodes` is fine.

### Colour control

Exceptions will print their error messges in red to STDERR if send to a
terminal. This can be controlled by `%*ENV<SHELLPIPINGNOCOLOR>` and
`$*colored-exceptions`. The environment variable can be set to any value. The
dynamic variable to the exported symbols `on` and `off` whereby `on` is the
default when the variable is not declared by any caller.

```
use Shell::Piping;
use Shell::Piping::Whereceptions;

sub s(IO(Str) $f where &it-is-a-file) {
}

my $*colored-exceptions = off;
s('/foo/bar');

my @a;
px<find /tmp/> |» @a;

```

# Wherecetions

Are subs to be used in where clauses to test for conditions that would throw
later on. Whereceptions will output to STDERR in red unless
`%*ENV<SHELLPIPINGNOCOLOR>` is set to any value. When sensible there will be
checks for dangling symlinks and an alternate error message will be returned by
the exceptions. All exceptions are subclasses of `X::IO::Whereception`.

## SYNOPSIS

```
sub works-with-files(IO::Path(Str) $file where &it-is-a-file) {
    say ‚answer‘ for $file.lines.grep(42);
}

sub works-with-directories(IO::Path(Str) $dir where &it-is-a-directory) {
    for $dir {
        .&works-with-files when .IO.f;
        .IO.dir()».&?BLOCK when .IO.d;
    }
}

}

sub will-shell-out(IO::Path(Str) $file where &it-is-executable) {
    px<find -iname '42'> |» px«$file» |» (my @stdout);
}

```

### `sub it-is-a-file(IO() $f)`

Will call `.e` and `.f` and throw `X::IO::FileNotFound`.

### `sub it-is-a-directory(IO() $d)`

Will call `.d` and throw `X::IO::DirectoryNotFound`.

### `sub it-is-executable(IO() $exec)`

Will call `.x` and throw `X::IO::FileNotExecutable`.

## LICENSE

All files (unless noted otherwise) can be used, modified and redistributed
under the terms of the Artistic License Version 2. Examples (in the
documentation, in tests or distributed as separate files) can be considered
public domain.

ⓒ2020 Wenzel P. P. Peppmeyer


## dist_zef-jjmerelo-Git-File-History.md
# Git::File::History [Test-install and cache deps](https://github.com/JJ/raku-git-file-history/actions/workflows/test.yaml) Logo

Get all versions of a file in a git repository. Main use case for this is
when you use the repository for storage, and want to examine the progression
of some files. Or whatever. I don't really know, it was an itch I had to
scratch and here we are.

## Installing

Usual way:

```
zef install Git::File::History

```

## SYNOPSIS

```
use Git::File::History;

my $file-histories = Git::File::History.new(); # Will throw if not in a repo
say $file-histories.history-of( "README.md");

# .date contains a DateTime object, .state the contents of the file
for $file-histories.history-of( "t/01-basic.t") -> $fv {
   say $fv.date, " → ", $fv.state.split("\n").elems;
}

# Repo in another directory:
my $file-histories' = Git::File::History.new( "another/dir" );

# Limit to a few files (for big repos)
my $yet-another = Git::File::History.new( :files("t/*.t") );

```

## See also

Other [git-related stuff](https://raku.land/?q=git) in Raku land

## License

(c) JJ Merelo, [jj@raku.org](mailto:jj@raku.org)

This module will be licensed under the Artistic 2.0 License (the same as Raku itself).


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

# NAME

IO::Path::AutoDecompress - IO::Path with automatic decompression

# SYNOPSIS

```
use IO::Path::AutoDecompress;

# read lines from a gzipped file transparently
my $io = IO::Path::AutoDecompress.new("foobar.txt.gz");
.say for $io.lines;

# same, but using an .IO like subroutine as a method
my $io = "foobar.txt.gz".&IOAD;
.say for $io.lines;

```

# DESCRIPTION

IO::Path::AutoDecompress is a module that provides a subclass to `IO::Path`, that will transparently handle compressed files that are compressed with `gzip` (the `.gz` file extension) or `bzip2` (the `.bz2` extension) for the `.slurp` and `.lines` methods.

# EXPORTED SUBROUTINES

## IOAD

The `IOAD` subroutine takes one positional argument and converts that to an `IO::Path::AutoDecompress` object. It is intended to be used in a way similar to the `.IO` method in core.

```
use IO::Path::AutoDecompress;

# using the IOAD subroutine as a method
my $io = "foobar.txt.gz".&IOAD;
.say for $io.lines;

```

# PREREQUISITES

This module assumes some version of the `gunzip` and `bunzip2` programs can be executed with the `--stdout` argument.

# AUTHOR

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

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

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

# COPYRIGHT AND LICENSE

Copyright 2022, 2024 Elizabeth Mattijsen

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


## nativetypes.md
Raku native types

Using the types the compiler and hardware make available to you

Raku offers a set of *native* types with a fixed, and known, representation in memory. This page shows which ones exist and how they can be used. Please check also the page on [native numerics](/language/numerics#Native_numerics) for more information on them.

# [Types with native representation](#Raku_native_types "go to top of document")[§](#Types_with_native_representation "direct link")

Some simple types in Raku have a *native* representation, indicating that they will use the C language representation provided by the compiler, operating system and machine. These are the four native types available:

|  |  |
| --- | --- |
| int | Equivalent to Int (with limited range) |
| uint | Equivalent to Int (with limited range) with the unsigned trait |
| num | Equivalent to Num |
| str | Equivalent to Str |

However, these types do not necessarily have the size that is required by the [NativeCall](/language/nativecall) interface (e.g., Raku's `int` can be 8 bytes but C's `int` is only 4 bytes); the types below will have to be used instead of the types `int` or `num` listed above.

In general, these variables will behave in the same way as regular scalar variables, in a behavior that is called [*auto-boxing*](/language/numerics#Auto-boxing); however, there are some differences, since what you are actually declaring is how they will be represented, not their actual type. The first one is that their type will be actually their equivalent type, not their native type.

```raku
my int $intillo = 3;
say $intillo.^name; # OUTPUT: «Int␤»
```

This obviously means that they will smartmatch their equivalent (auto-boxed) type, not their native type:

```raku
my str $strillo = "tres";
say $strillo ~~ str; # OUTPUT: «False␤»
say $strillo ~~ Str; # OUTPUT: «True␤»
```

And also that they will always have a default value, unlike their non-native counterparts:

```raku
say (my Str $); # OUTPUT: «(Str)␤»
say (my str $); # OUTPUT: «␤»
say (my num $); # OUTPUT: «0␤»
```

**Note**: In v6.c, the default value for `num` would have been a NaN.

This is due to the fact that Natives don't know their types because they're just values, without any metadata. In [multi-dispatch](/language/glossary#Multi-dispatch), you can have a native candidate, but you cannot differentiate different sizes or signedness of the same native type. That is, you can have an [`Int`](/type/Int) and [int](/native/int) candidates, but there would be an ambiguity between, for instance [int](/native/int), [uint](/language/nativetypes#index-entry-uint), [`atomicint`](/type/atomicint) or [int64](/language/nativetypes#index-entry-int64) candidates.

They cannot be bound either; trying to do `my num $numillo := 3.5` will raise the exception `Cannot bind to natively typed variable '$variable-name'; use assignment instead`.

Native types can also be composite.

```raku
my int @intillos = ^10_000_000;
say [+] @intillos; # OUTPUT: «49999995000000␤»
```

In this case, *native*ness extends to the composite type, which is called `array`

```raku
my num @many-pi  = ^8 »*» π ; say @many-pi.^name;  # OUTPUT: «array[num]␤»
```

Native `array`s behave as [`Iterable`](/type/Iterable) and [`Positional`](/type/Positional), but they are not a subclass of [`List`](/type/List); thus, they behave similarly to [`Array`](/type/Array)s; for instance, they can be shaped:

```raku
my str @letter-pairs[10] = 'a'..'j' Z~ 'A'..'J';
say @letter-pairs.raku;
# OUTPUT: «array[str].new(:shape(10,), ["aA", "bB", "cC", "dD", "eE", "fF", "gG", "hH", "iI", "jJ"])␤»

```

Native arrays of `str` can only be used from version 6.d.

These native types can also be used as attributes in classes, and as such they can be used as bound targets, for instance in submethods like `BUILD`:

```raku
class Foo {
    has num $.numillo;
    submethod BUILD( :$!numillo = 3.5e0 ) {}
};
my $foo = Foo.new;
say $foo.raku; # OUTPUT: «Foo.new(numillo => 3.5e0)␤»

```

# [Types with native representation and size](#Raku_native_types "go to top of document")[§](#Types_with_native_representation_and_size "direct link")

What has been mentioned about types with native representation also applies here; they will be auto-boxed to Raku types and you will not be able to bind to them. However, these types, which are listed in the table below, have the characteristic of being usable in [NativeCall](/language/nativecall#Passing_and_returning_values) functions.

|  |  |
| --- | --- |
| int8 | (int8\_t in C) |
| int16 | (int16\_t in C) |
| int32 | (int32\_t in C) |
| int64 | (int64\_t in C) |
| byte, uint8 | (uint8\_t in C) |
| uint16 | (uint16\_t in C) |
| uint32 | (uint32\_t in C) |
| uint64 | (uint64\_t in C) |
| num32 | (float in C) |
| num64 | (double in C) |

These types have a fixed size representation which is independent of the platform, and thus can be used safely for those native calls. Nothing prevents us from using them in any other environment, if we so wish. In the same way as the types above, this size will have to be taken into account when assigning values to variables of this type:

```raku
my byte $intillo = 257;
say $intillo; # OUTPUT: «1␤»
```

Since `byte` is able to hold only 8 bits, it will *wrap over* and assign the result of the original value modulo 256, which is what is shown.

The main difference between types with declared native size and those without is the use of is nativesize in their declaration. For instance, `int8` is declared in this way:

```raku
my native int8 is repr('P6int') is Int is nativesize(8) { }
```

Indicating that it will use, besides an integer representation (`P6int`), a native size of only 8 bits. This trait, however, is not intended to be used in your programs since it is not part of the Raku specification.

# [The `void` type](#Raku_native_types "go to top of document")[§](#The_void_type "direct link")

The native `void` type corresponds to the C namesake type; being a valid type, you can use it in expressions:

```raku
use NativeCall;
my void $nothing;
say $nothing.raku; # OUTPUT: «NativeCall::Types::void␤»
```

In practice, it is an `Uninstantiable` type that can rarely be used by itself, and in fact it is [explicitly forbidden in `return` types](/language/nativecall#Passing_and_returning_values). However, it is generally found in typed pointers representing the equivalent to the `void *` pointer in C.

```raku
sub malloc( int32 $size --> Pointer[void] ) is native { * };
my Pointer[void] $for-malloc = malloc( 32 );
say $for-malloc.raku;

```

As the example shows, it's represented by a parameterized [`Pointer` role](/language/nativecall#index-entry-Pointer), using as parameter whatever the original pointer is pointing to (in this case, `void`). This role represents native pointers, and can be used wherever they need to be represented in a Raku program.

You can also [nativecast](/routine/nativecast) [`Blob`](/type/Blob)s to this kind of pointer in case you need to work with them in native functions that use the type

```raku
use NativeCall;
my Pointer[void] $native = nativecast(Pointer[void], Blob.new(0x22, 0x33));

```

However, outside that, the functionality it offers is quite limited, since pointers to void cannot be dereferenced:

```raku
use NativeCall;
my Pointer[void] $native = nativecast(Pointer[void], Buf.new(0x22, 0x33));
say $native.deref; # ERROR OUTPUT: «Internal error: unhandled target type␤»

```

# [*Atomic* types](#Raku_native_types "go to top of document")[§](#Atomic_types "direct link")

In this context, *atomic* refers to safe operation under threading. Raku provides a type, [`atomicint`](/type/atomicint), and [some operations](/type/atomicint#Routines) which, together, guarantee this. Please check [the atomic operations section on the Numerics page](/language/numerics#Atomic_operations) for more information on this.

# [Rakudo specific native types](#Raku_native_types "go to top of document")[§](#Rakudo_specific_native_types "direct link")

The types described in this section are Rakudo specific, so they are not guaranteed to be in other implementations or remain the same in future versions.

|  |  |
| --- | --- |
| long | (long in C) |
| longlong | (longlong in C) |
| ulong | (long and unsigned in C) |
| ulonglong | (longlong and unsigned in C) |
| size\_t | (size\_t and unsigned in C) |
| ssize\_t | (size\_t in C) |
| bool | (bool in C) |

You can use them in the same way they would be used in native C:

```raku
use NativeCall;

my $just-an-array = CArray[int32].new( 1, 2, 3, 4, 5 );

loop ( my size_t $i = 0; $i < $just-an-array.elems; $i++ ) {
    say $just-an-array[$i];
}

```

Which would print the five elements of the array, as it should be expected.


## dist_zef-raku-community-modules-Subsets-IO.md
[![Actions Status](https://github.com/raku-community-modules/Subsets-IO/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/Subsets-IO/actions)

# NAME

`Subsets::IO` - Subsets for various types of `IO::Path` instances

# SYNOPSIS

```
use Subsets::IO;

say "Our script is writable and readable"
    if $?FILE.IO ~~ IO::Path::frw;

```

```
use Subsets::IO;

sub make-conf($conf where IO::Path::dw | IO::Path::fw) {
    say "$conf is either a writable directory or a writable file";
}

sub make-conf-file(IO::Path::E $conf) {
    say "$conf is a non-existent path";
}
make-conf-file $?FILE.IO;
# Path must NOT exist Got /home/zoffix/CPANPRC/Subsets-IO/foo.p6
# Constraint type check failed in binding to parameter '$conf';
#   expected IO::Path::E but got IO::Path (IO::Path.new("/home/z...)

```

# DESCRIPTION

The module provides subsets of [`IO::Path:D`](https://docs.raku.org/type/IO::Path) that additionally perform file tests and either uses the new `will complain` (since Rakudo 2022.04) feature, or uses [`Subset::Helper`](https://raku.land/zef:raku-community-modules/Subset::Helper) to display useful error messages on typecheck failures.

# AVAILABLE SUBSETS

## IO::Path::e`

Path must exist.

## IO::Path::E`

Path must NOT exist.

## IO::Path::f`

Path must be an existing file.

## IO::Path::F`

Path must NOT be an existing file.

## IO::Path::d`

Path must be an existing directory.

## IO::Path::D`

Path must NOT be an existing directory.

## IO::Path::fr`

Path must be an existing, readable file.

## IO::Path::frw`

Path must be an existing, readable and writable file.

## IO::Path::frx`

Path must be an existing, readable and executable file.

## IO::Path::fwx`

Path must be an existing, writeable and executable file.

## IO::Path::frwx`

Path must be an existing, readable, writable, and executable file.

## IO::Path::dr`

Path must be an existing, readable directory.

## IO::Path::drw`

Path must be an existing, readable and writable directory.

## IO::Path::drx`

Path must be an existing, readable and executable directory.

## IO::Path::dwx`

Path must be an existing, writeable and executable directory.

## IO::Path::drwx`

Path must be an existing, readable, writable, and executable directory.

# AUTHOR

Zoffix Znet

# COPYRIGHT AND LICENSE

Copyright 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.


## complexstr.md
class ComplexStr

Dual value complex number and string

```raku
class ComplexStr is Allomorph is Complex {}
```

`ComplexStr` is a dual value type, a subclass of both [`Allomorph`](/type/Allomorph), hence [`Str`](/type/Str), and [`Complex`](/type/Complex).

See [`Allomorph`](/type/Allomorph) for further details.

```raku
my $complex-str = <42+0i>;
say $complex-str.^name;             # OUTPUT: «ComplexStr␤»

my Complex $complex = $complex-str; # OK!
my Str     $str     = $complex-str; # OK!

# ∈ operator cares about object identity
say 42+0i ∈ <42+0i  55  1>;         # OUTPUT: «False␤»

```

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

## [method new](#class_ComplexStr "go to top of document")[§](#method_new "direct link")

```raku
method new(Complex $i, Str $s)
```

The constructor requires both the [`Complex`](/type/Complex) and the [`Str`](/type/Str) value, when constructing one directly the values can be whatever is required:

```raku
my $f = ComplexStr.new(42+0i, "forty two (but complicated)");
say +$f; # OUTPUT: «42+0i␤»
say ~$f; # OUTPUT: «"forty two (but complicated)"␤»
```

## [method Capture](#class_ComplexStr "go to top of document")[§](#method_Capture "direct link")

```raku
method Capture(ComplexStr:D: --> Capture:D)
```

Equivalent to [`Mu.Capture`](/type/Mu#method_Capture).

## [method Complex](#class_ComplexStr "go to top of document")[§](#method_Complex "direct link")

```raku
method Complex
```

Returns the [`Complex`](/type/Complex) value of the `ComplexStr`.

## [method Numeric](#class_ComplexStr "go to top of document")[§](#method_Numeric "direct link")

```raku
multi method Numeric(ComplexStr:D: --> Complex:D)
multi method Numeric(ComplexStr:U: --> Complex:D)
```

The `:D` variant returns the numeric portion of the invocant. The `:U` variant issues a warning about using an uninitialized value in numeric context and then returns value `<0+0i>`.

## [method Real](#class_ComplexStr "go to top of document")[§](#method_Real "direct link")

```raku
multi method Real(ComplexStr:D: --> Num:D)
multi method Real(ComplexStr:U: --> Num:D)
```

Coerces the numeric portion of the invocant to [`Num`](/type/Num). If the imaginary part isn't [approximately](/language/operators#infix_≅) zero, coercion [fails](/routine/fail) with [`X::Numeric::Real`](/type/X/Numeric/Real).

The `:D` variant returns the result of that coercion. The `:U` variant issues a warning about using an uninitialized value in numeric context and then returns value `0e0`.

# [Operators](#class_ComplexStr "go to top of document")[§](#Operators "direct link")

## [infix `===`](#class_ComplexStr "go to top of document")[§](#infix_=== "direct link")

```raku
multi infix:<===>(ComplexStr:D $a, ComplexStr:D $b)
```

`ComplexStr` Value identity operator. Returns `True` if the [`Complex`](/type/Complex) values of `$a` and `$b` are [identical](/routine/===) and their [`Str`](/type/Str) values are also [identical](/routine/===). Returns `False` otherwise.

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

Type relations for `ComplexStr`

raku-type-graph

ComplexStr
ComplexStr

Allomorph
Allomorph

ComplexStr->Allomorph

Complex
Complex

ComplexStr->Complex

Mu
Mu

Any
Any

Any->Mu

Cool
Cool

Cool->Any

Stringy
Stringy

Str
Str

Str->Cool

Str->Stringy

Allomorph->Str

Numeric
Numeric

Complex->Cool

Complex->Numeric

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


## declaratortarget.md
class RakuAST::Doc::DeclaratorTarget

Provide leading/trailing doc functionality

```raku
role RakuAST::Doc::DeclaratorTarget { }
```

The `RakuAST::Doc::DeclaratorTarget` role is done by objects that support leading and trailing documentation.

Support for [`RakuAST`](/type/RakuAST) functionality is available in language version `6.e+` and was added in Rakudo compiler release 2023.02. In earlier language versions it is only available when specifying:

```raku
use experimental :rakuast;
```

## [Object introspection](#class_RakuAST::Doc::DeclaratorTarget "go to top of document")[§](#Object_introspection "direct link")

Objects doing the `RakuAST::Doc::DeclaratorTarget` role are typically created when parsing Raku Programming Language code for objects that allow leading (`#|`) and trailing (`#=`) documentation on them. So most developers will only need to know how to introspect the objects created.

### [method WHY](#class_RakuAST::Doc::DeclaratorTarget "go to top of document")[§](#method_WHY "direct link")

```raku
with $target.WHY {
    say "leading: $_.leading()";
    say "trailing: $_.trailing()";
}

```

Returns the [`RakuAST::Doc::Declarator`](/type/RakuAST/Doc/Declarator) object containing the declarator documentation, if any.

# [Object creation](#class_RakuAST::Doc::DeclaratorTarget "go to top of document")[§](#Object_creation "direct link")

Each object doing the `RakuAST::Doc::DeclaratorTarget` role has its own why of creation. So there's nothing general that can be said about it here.

# [Object modification](#class_RakuAST::Doc::DeclaratorTarget "go to top of document")[§](#Object_modification "direct link")

## [method set-WHY](#class_RakuAST::Doc::DeclaratorTarget "go to top of document")[§](#method_set-WHY "direct link")

```raku
$target.set-WHY($declarator);

```

Set the [`RakuAST::Doc::Declarator`](/type/RakuAST/Doc/Declarator) object to be associated.

## [method cut-WHY](#class_RakuAST::Doc::DeclaratorTarget "go to top of document")[§](#method_cut-WHY "direct link")

```raku
my $WHY := $target.cut-WHY;

```

Removes the [`RakuAST::Doc::Declarator`](/type/RakuAST/Doc/Declarator) object, if any. Intended to be used when deparsing / stringification to prevent an infinite loop because the [`RakuAST::Doc::Declarator`](/type/RakuAST/Doc/Declarator) object points to its target, and the other way around. Usually called on a clone of the original target.

## [method set-leading](#class_RakuAST::Doc::DeclaratorTarget "go to top of document")[§](#method_set-leading "direct link")

```raku
$target.set-leading;  # reset
$target.set-leading("foo", "bar");

```

Set the leading documentation. If no arguments are specified, reset to not having any leading documentation. Creates a [`RakuAST::Doc::Declarator`](/type/RakuAST/Doc/Declarator) object and sets it in the `.WHY` if there wasn't one already.

## [method add-leading](#class_RakuAST::Doc::DeclaratorTarget "go to top of document")[§](#method_add-leading "direct link")

```raku
$target.add-leading("additional");

```

Add a line to the leading documentation. Creates a [`RakuAST::Doc::Declarator`](/type/RakuAST/Doc/Declarator) object and sets it in the `.WHY` if there wasn't one already.

## [method set-trailing](#class_RakuAST::Doc::DeclaratorTarget "go to top of document")[§](#method_set-trailing "direct link")

```raku
$target.set-trailing;  # reset
$target.set-trailing("foo", "bar");

```

Set the trailing documentation. If no arguments are specified, reset to not having any trailing documentation. Creates a [`RakuAST::Doc::Declarator`](/type/RakuAST/Doc/Declarator) object and sets it in the `.WHY` if there wasn't one already.

## [method add-trailing](#class_RakuAST::Doc::DeclaratorTarget "go to top of document")[§](#method_add-trailing "direct link")

```raku
$target.add-trailing("additional");

```

Add a line to the trailing documentation. Creates a [`RakuAST::Doc::Declarator`](/type/RakuAST/Doc/Declarator) object and sets it in the `.WHY` if there wasn't one already.


## dist_cpan-YNOTO-DB-Xoos.md
# Xoos

Xoos is an ORM designed for convenience and ease of use, it is modeled after DBIx::\* if you're into that kind of thing already (note: some concepts and names have deviated).

(This module was originally named Koos until my friends in Israel let me know that that's a vulgar word in Arabic)

[![CircleCI](https://circleci.com/gh/tony-o/perl6-xoo.svg?style=svg)](https://circleci.com/gh/tony-o/perl6-xoo)

## what works

* relationships
* row object inflation (calling .first on a query returns a Xoos::Row)
* row objects inherit from the model::@columns
* model level convenience methods
* row level convenience methods
* basic handling compounded primary keys
* column validation hooks
* YAML models (auto composed)
* decouple SQL generation from Xoos::Searchable (this includes decoupling the SQL generation from the DB layer) - DB::Pg is intended to be used but epoll is not ported to OSX

## todo

* soft validation of model/table/relationships when model loads
* prefetch relationships option (currently everything is prefetched)

# Usage

Below is a minimum viable model setup for your app. Xoos does *not* create the table for you, that is up to you.

### lib/app.pm6

```
use DB::Xoos::SQLite;

my DB::Xoos::SQLite $d .=new;

$d.connect('sqlite://xyz.sqlite3');

my $customer-model = $d.model('Customer');
my $new-customer   = $customer-model.new-row;
$new-customer.name('xyz co');
$new-customer.rate(150);
$new-customer.update; # runs an insert because this is a new row

my $xyz = $customer-model.search({ name => { 'like' => '%xyz%' } }).first;
$xyz.rate( $xyz.rate * 2 ); #twice the rate!
$xyz.update; # UPDATEs the database

my $xyz-orders = $xyz.orders.count;

```

### lib/Model/Customer.pm6

```
use DB::Xoos::Model;
unit class Model::Customer does DB::Xoos::Model['customer'];

has @.columns = [
  id => {
    type           => 'integer',
    nullable       => False,
    is-primary-key => True,
    auto-increment => 1,
  },
  name => {
    type           => 'text',
  },
  rate => {
    type => 'integer',
  },
];

has @.relations = [
  orders => { :has-many, :model<Order>, :relate(id => 'customer_id') },
];

```

# role DB::Xoos::Model

What is a model? A model is essentially a table in your database. Your ::Model::X is pretty barebones, in this module you'll defined `@.columns` and `@.relations` (if there are any relations).

## Example

```
use DB::Xoos::Model;
# the second argument below is optional and also accepts a type.
# if the arg is omitted then it attempts to auto load ::Row::Customer
# if it fails to auto load then it uses an anonymous Row and adds convenience methods to that
unit class X::Model::Customer does DB::Xoos::Model['customer', 'X::Row::Customer'];

has @.columns = [
  id => {
    type           => 'integer',
    nullable       => False,
    is-primary-key => True,
    auto-increment => 1,
  },
  name => {
    type           => 'text',
  },
  contact => {
    type => 'text',
  },
  country => {
    type => 'text',
  },
];

has @.relations = [
  orders => { :has-many, :model<Order>, :relate(id => 'customer_id') },
  open_orders => { :has-many, :model<Order>, :relate(id => 'customer_id', '+status' => 'open') },
  completed_orders => { :has-many, :model<Order>, :relate(id => 'customer_id', '+status' => 'closed') },
];

# down here you can have convenience methods

method delete-all { #never do this in real life
  die '.delete-all disabled in prod or if %*ENV{in-prod} not defined'
    if !defined %*ENV{in-prod} || so %*ENV{in-prod};
  my $s = self.search({ id => { '>' => -1 } });
  $s.delete;
  !so $s.count;
}

```

In this example we're creating a customer model with columns `id, name, contact, country` and relations with specific filter criteria. You may notice the `+status => 'open'` on the open\_orders relationship, the `+` here indicates it's a filter on the original table.

### Breakdown

`class :: does DB::Xoos::Model['table-name', 'Optional String or Type'];`

Here you can see the role accepts one or two parameters, the first is the DB table name, the latter is a String or Type of the row you'd like to use for this model. If no row is found then Xoos will create a generic row and add helper methods for you using the model's column data.

`@.columns`

A list of columns in the table. It is highly recommended you have *one* `is-primary-key` or `.update` will have unexpected results.

`@.relations`

This accepts a list of key values, the key defining the accessor name, the later a hash describing the relationship. `:has-one` and `:has-many` are both used to dictate whether a Xoos model returns an inflated object (:has-one) or a filterable object (:has-many).

## Methods

### `search(%filter?, %options?)`

Creates a new filterable model and returns that. Every subsequent call to `.search` will *add* to the existing filters and options the best it can.

Example:

```
my $customer = $dbo.model('Customer').search({
  name => { like => '%bozo%' },
}, {
  order-by => [ created_date => 'DESC', 'customer_name' ],
});
# later on ...
my $geo-filtered-customers = $customer.search({ country => 'usa' });
# $geo-filtered-customers effective filter is:
#   {
#      name => { like => '%bozo%' },
#      country => 'usa',
#   }

```

### `.all(%filter?)`

Returns all rows from query (an array of inflated `::Row::XYZ`). Providing `%filter` is the same as doing `.search(%filter).all` and is provided only for convenience.

### `.first(%filter?, :$next = False)`

Returns the first row (again, inflated `::Row::XYZ`) and caches the prepared statement (this is destroyed and ignored if $next is falsey)

### `.next(%filter?)`

Same as calling `.first(%filter, :next)`

### `.count(%filter?)`

Returns the result of a `select count` for the current filter selection. Providing `%filter` results in `.search(%filter).count`

### `.delete(%filter?)`

Deletes all rows matching criteria. Providing `%filter` results in `.search(%filter).delete`

### `.new-row(%field-data?)`

Creates a new row with %field-data.

## Convenience methods

Xoos::Model inheritance allows you to have convenience methods, these methods can act on whatever the current set of filters is.

Consider the following:

Convenience model definition:

```
class X::Model::Customer does Xoos::Model['customer'];

# columns and relations

method remove-closed-orders {
  self.closed_orders.delete;
}

```

Later in your code:

```
my $customers = $dbo.model('Customer');

my $all-customers    = $customers.search({ id => { '>' => -1 } });
my $single-customers = $customers.search({ id => 5 });

$all-customers.remove-closed-orders;
# this removes all orders for customers with an id > -1
$single-customer.remove-closed-orders;
# this removes all orders for customers with id = 5

```

# role Xoos::Row

A role to apply to your `::Row::Customer`. If there is no `::Row::Customer` a generic row is created using the column and relationship data specified in the corresponding `Model` and this file is only really necessary if you want to add convenience methods.

When a `class :: does Xoos::Row`, it receives the info from the model and adds the methods for setting/getting field data.

With the model definition above:

```
my $invoice-model = $dbo.model('invoice');
my $invoice = $invoice-model.new-row({
  customer_id => $customer.id,
  amount      => 400,
});  # this $invoice is NOT in the database until .update

my $old-amount = $invoice.amount; # = 400
$invoice.amount($invoice.amount * 2);
my $new-amount = $invoice.amount; # = 800

$invoice.update;

```

If there is a collision in the naming conventions between your model and the row then you'll need to use `[set|get]-column`

## Methods

### `.duplicate`

Duplicates the row omitting the `is-primary-key` field so the subsequent `.save` results in a new row rather than updating

### `.as-hash`

Returns the current field data for the row as a hash. If there has been unsaved updates to fields then it returns *those* values instead of what is in the database. You can determine whether the row has field-changes with `is-dirty`

### `.set-column(Str $key, $value)`

Updates the field data for the column (not stored in database until `.update` is called). If you want to `.wrap` a field setter for a certain key, wrap this and filter for the key

### `.get-column(Str $key)`

Retrieves the value for `$key` with any field changes having priority over data in database, use `.is-dirty`

### `.get-relation(Str $column, :%spec?)`

It is recommended any Model with a relationship name that conflicts and causes no convenience method to be generated be renamed, but use this if you must. `$customer.orders` is calling essentially `$customer.get-relation('orders')`. Do not provide `%spec` unless you know what you're doing.

### `.update`

Saves the row in the database. If the field with a positive `is-primary-key` is *set* then it runs and `UPDATE ...` statement, otherwise it `INSERT ...`s and updates the Row's `is-primary-key` field. Ensure you set one field with `is-primary-key`

## Field validation

It's just this easy:

```
has @.columns = [
  qw<...>,
  phone => {
    type     => 'text',
    validate => sub ($new-value) {
      # return Falsey value here for validation to fail
      #   Truthy value will cause validation to succeed
    },
  },
  qw<...>,
];

```


## dist_cpan-FRITH-Math-Libgsl-RunningStatistics.md
[![Actions Status](https://github.com/frithnanth/raku-Math-Libgsl-RunningStatistics/workflows/test/badge.svg)](https://github.com/frithnanth/raku-Math-Libgsl-RunningStatistics/actions) [![Build Status](https://travis-ci.org/frithnanth/raku-Math-Libgsl-RunningStatistics.svg?branch=master)](https://travis-ci.org/frithnanth/raku-Math-Libgsl-RunningStatistics)

# NAME

Math::Libgsl::RunningStatistics - An interface to libgsl, the Gnu Scientific Library - Running Statistics

# SYNOPSIS

```
use Math::Libgsl::RunningStatistics;

my Math::Libgsl::RunningStatistics $r .= new;
$r.add($_) for (^10);
say $r.mean;
say $r.variance;
say $r.sd;

```

# DESCRIPTION

Math::Libgsl::RunningStatistics is an interface to the Running Statistics functions of libgsl, the Gnu Scientific Library.

This class is suitable for handling large datasets for which it may be inconvenient or impractical to store in memory all at once.

### new(:@quantile = 0.5,)

The constructor accepts one optional parameter, the quantile array, which defaults to just one value: 0.5 i.e. the median. The @quantile argument will be used only if one uses the quantile methods.

### add(Num() $x --> Int)

This method adds a value to the accumulator. It returns GSL\_SUCCESS if successful.

### n(--> Int)

This method returns the number of data added so far to the accumulator.

### min(--> Num)

This method returns the minimum value added to the accumulator.

### max(--> Num)

This method returns the maximum value added to the accumulator.

### mean(--> Num)

This method returns the mean of all data added to the accumulator.

### variance(--> Num)

This method returns the variance of all data added to the accumulator.

### sd(--> Num)

This method returns the standard deviation of all data added to the accumulator.

### sd-mean(--> Num)

This method returns the standard deviation of the mean.

### rms(--> Num)

This method returns the root mean square of all data added to the accumulator.

### skew(--> Num)

This method returns the skewness of all data added to the accumulator.

### kurtosis(--> Num)

This method returns the kurtosis of all data added to the accumulator.

### median(--> Num)

This method returns the median of all data added to the accumulator.

### reset(--> Int)

This method resets the accumulator.

### qadd(Num() $x --> Int)

This method adds a value to the quantile accumulators. It returns GSL\_SUCCESS if successful. If not successful it returns the first error found and the accumulators are left in an undefined state, so you're advised to .qreset() them.

### qget(Num() $x --> List)

This method returns a List of all the current estimate of the quantiles specified when the object was created.

### qreset(--> Int)

This method resets the quantile accumulators. It returns GSL\_SUCCESS if successful. If not successful it returns the first error found.

# 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::RunningStatistics

```

# AUTHOR

Fernando Santagata [nando.santagata@gmail.com](mailto:nando.santagata@gmail.com)

# 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.