txt
stringlengths
93
37.3k
## dist_zef-finanalyst-CWT-Repository-Hash.md ![github-tests-passing-badge](https://github.com/finanalyst/CWT-Repository-Hash/actions/workflows/test.yaml/badge.svg) # Cro::WebApp::Template::Repository::Hash > Using Cro templates in a Hash ## Table of Contents [Introduction](#introduction) [Usage](#usage) [Dependencies](#dependencies) [Differences from CWT documentation](#differences-from-cwt-documentation) [sub templates-from-hash( %hash-of-templates )](#sub-templates-from-hash-hash-of-templates-) [sub render-template( $template, $topic, :%parts, :build($)! )](#sub-render-template-template-topic-parts-build-) [sub modify-template-hash( %templates )](#sub-modify-template-hash-templates-) [sub wait-for-hash-template-completion](#sub-wait-for-hash-template-completion) --- # Introduction This module uses the Cro template language [Cro::WebApp::Template](https://cro.services/docs/reference/cro-webapp-template) (called **CWT** below) where the templates are in a Hash. **CWT** is aimed at templates that exist as files in some directory / folder, whether on a server or in an online resource. Consequently, each template is contained in a single file. A collection of templates exists under a root directory. The directory may be on-line or local. This paradigm implies the request-response of a server hosted website, with the template used being dependent on the request. In a Build context that is designed to be distributed via a CDN the structural HTML of a website is static. Consequently, all the templates needed for the structure are known before any incoming request. User interaction with the website is confined to `micro-service` interfaces, each of which have their own server request/responses. The structural templates can therefore be collected before creating the HTML and can be placed in a Hash. This also allows for templates to use other templates in the Hash via the `<:use>` tag. # Usage ``` use v6.d; use Cro::WebApp::Template::Repository::Hash; # gather template strings my %temps = %( 'format-b' => '<strong><.contents></strong>', 'heading' => q:to/HEADING/ , <:sub heading($level=1,:$close=False)> <?$close>/</?>h<$level></:> <<&heading(.level)> id="<.target>"> <a href="#<.top>" class="u" title="go to top of document"> <.text> </a> <<&heading(.level,:close)>> HEADING ); # the following is required to create a Build repository, otherwise the # default Filesystem repository will be used. templates-from-hash %temps; # later my $parameters = %( :1level, :target<https://docs.raku.org>, :top<__TOP>, :text("This is a title") ); say render-template('heading', $parameters, :hash); ``` # Dependencies Uses Cro::WebApp::Template # Differences from CWT documentation ## sub templates-from-hash( %hash-of-templates ) The sub must be called with each value of `%hash-of-templates` containing a valid crotmp template before using `render-template`. ## sub render-template( $template, $topic, :%parts, :build($)! ) `render-template` is used in the same way as documented **CWT**. ## sub modify-template-hash( %templates ) This sub can only be used after `templates-from-hash`, which creates a Build repository. It is NOP otherwise. The values in %templates over-ride the value in the repository if it was set by `templates-from-hash` or adds to the repository if the key did not previously exist. ## sub wait-for-hash-template-completion waits for all the compilation promises to stop returning Planned on a status call. --- Rendered from README at 2022-07-15T22:10:55Z
## dist_github-ugexe-P6TCI.md ## Demonstrate Perl6 module testing on Travis-CI ### HOWTO Just copy the .travis.yml file from this repo to yours and turn on testing for that repository on Travis-CI.org (toggle the appropriate slider on `https://travis-ci.org/profile/YOUR_GITHUB_USERNAME`) ### DESCRIPTION Runs travis-ci tests using both supported backends using the most current Rakudo built from source. Rakudo Star is not used for continuous testing purposes as Rakudo changes far too often, and you would end up testing against month old changes. It will also submit test reports for your module to testers.perl6.org, and failures from modules that show up Rakudo commits can help the Rakudo developers see what new changes may have broke. ### TODO ######bin/p6tci * Generate a .travis.yml in some location based on some arguments. ######Combined test run * Option to use rakudobrew to test multiple `$ENV{BACKEND}` in one job. Current build times for JVM make this not always possible.
## dist_zef-l10n-L10N-FR.md # NAME L10N::FR - French localization of Raku # SYNOPSIS ``` use L10N::FR; dis "Hello World"; ``` # DESCRIPTION L10N::FR contains the logic to provide a French localization of the Raku Programming Language. # AUTHORS Lucien Grondin # COPYRIGHT AND LICENSE Copyright 2023 Raku Localization Team This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-jonathanstowe-META6.md # META6 Do things with Raku [META files](http://design.raku.org/S22.html#META6.json) [![CI](https://github.com/jonathanstowe/META6/actions/workflows/main.yml/badge.svg)](https://github.com/jonathanstowe/META6/actions/workflows/main.yml) ## Synopsis The below will generate the *META6.json* for this module. ``` use META6; my $m = META6.new( name => 'META6', version => Version.new('0.0.1'), auth => 'github:jonathanstowe', api => '1.0', description => 'Work with Raku META files', raku-version => Version.new('6.*'), depends => ['JSON::Class:ver<0.0.15+>', 'JSON::Name' ], test-depends => <Test JSON::Fast>, tags => <devel meta utils>, authors => ['Jonathan Stowe <[email protected]>'], source-url => 'https://github.com/jonathanstowe/META6.git', support => META6::Support.new( source => 'https://github.com/jonathanstowe/META6.git' ), provides => { META6 => 'lib/META6.pm', }, license => 'Artistic', production => False, meta-version => 1, ); print $m.to-json; my $m = META6.new(file => './META6.json'); $m<version description> = v0.0.2, 'Work with Raku META files even better'; say 'Modules in the distribution: ' ~ $m<provides>.keys.join(', '); spurt('./META6.json', $m.to-json); ``` ## Description This provides a representation of the Raku [META files](http://design.raku.org/S22.html#META6.json) specification - the META file data can be read, created , parsed and written in a manner that is conformant with the specification. Where they are known about it also makes allowance for "customary" usage in existing software (such as installers and so forth.) The intent of this is allow the generation and testing of META files for module authors, so it can provide meta-information whether the attributes are mandatory as per the spec and where known the places that "customary" attributes are used, ### to-json See [JSON::Fast to-json()](https://github.com/timo/json_fast#to-json) for options. `sorted-keys` is recommended if you intend to modify the same file multiple times. ## Installation Assuming you have a working Rakudo installation you should be able to install this with *zef* : ``` # From the source directory zef install . # Remote installation zef install META6 ``` ## Support Suggestions/patches are welcomed via [github](https://github.com/jonathanstowe/META6) I'm particulary interested in knowing about "customary" (i.e. non-spec) fields that are being used in the wild and in what software so I can add them if necessary. ## Licence This free software. Please see the <LICENCE> file in the distribution for the details. © Jonathan Stowe 2015 - 2021
## dist_cpan-CTILMES-CroX-HTTP-Transform-GraphQL.md # Perl 6 GraphQL Cro Helpers Broke these out of the main GraphQL module. I'm still not happy with them, but I'm using them so I need to put them somewhere for now.. I'll add tests and documentation at some point.. Copyright © 2017 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. No copyright is claimed in the United States under Title 17, U.S.Code. All Other Rights Reserved.
## but.md but Combined from primary sources listed below. # [In Operators](#___top "go to top of document")[§](#(Operators)_infix_but "direct link") See primary documentation [in context](/language/operators#infix_but) for **infix but**. ```raku multi infix:<but>(Mu $obj1, Mu $role) is assoc<non> multi infix:<but>(Mu $obj1, Mu:D $obj2) is assoc<non> ``` Creates a copy of `$obj` with `$role` mixed in. Since `$obj` is not modified, `but` can be used to create immutable values with mixins. If `$role` supplies exactly one attribute, an initializer can be passed in parentheses: ```raku role Answerable { has $.answer; } my $ultimate-question = 'Life, the Universe and Everything' but Answerable(42); say $ultimate-question; # OUTPUT: «Life, the Universe and Everything␤» say $ultimate-question.^name; # OUTPUT: «Str+{Answerable}␤» say $ultimate-question.answer; # OUTPUT: «42␤» ``` Instead of a role, you can provide an instantiated object. In this case, the operator will create a role for you automatically. The role will contain a single method named the same as `$obj.^name` and that returns `$obj`: ```raku my $forty-two = 42 but 'forty two'; say $forty-two+33; # OUTPUT: «75␤» say $forty-two.^name; # OUTPUT: «Int+{<anon|1>}␤» say $forty-two.Str; # OUTPUT: «forty two␤» ``` Calling `^name` shows that the variable is an [`Int`](/type/Int) with an anonymous object mixed in. However, that object is of type [`Str`](/type/Str), so the variable, through the mixin, is endowed with a method with that name, which is what we use in the last sentence. We can also mixin classes, even created on the fly. ```raku my $s = 12 but class Warbles { method hi { 'hello' } }.new; say $s.Warbles.hi; # OUTPUT: «hello␤» say $s + 42; # OUTPUT: «54␤» ``` To access the mixed-in class, as above, we use the class name as is shown in the second sentence. If methods of the same name are present already, the last mixed in role takes precedence. A list of methods can be provided in parentheses separated by comma. In this case conflicts will be reported at runtime.
## dist_zef-l10n-L10N-NL.md # NAME L10N::NL - Dutch localization of Raku # SYNOPSIS ``` use L10N::NL; zeg "Hello World"; ``` # DESCRIPTION L10N::NL contains the logic to provide a Dutch localization of the Raku Programming Language. # AUTHORS Elizabeth Mattijsen [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2023 Raku Localization Team This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## allomorph.md class Allomorph Dual value number and string ```raku class Allomorph is Str { } ``` The `Allomorph` class is a common parent class for Raku's dual value types: [`ComplexStr`](/type/ComplexStr), [`IntStr`](/type/IntStr), [`NumStr`](/type/NumStr), [`RatStr`](/type/RatStr). The dual value types (often referred to as [allomorphs](/language/glossary#Allomorph)) allow for the representation of a value as both a string and a numeric type. Typically they will be created for you when the context is "stringy" but they can be determined to be numbers, such as in some [quoting constructs](/language/quoting): ```raku my $c = <42+0i>; say $c.^name; # OUTPUT: «ComplexStr␤» my $i = <42>; say $i.^name; # OUTPUT: «IntStr␤» my $n = <42.1e0>; say $n.^name; # OUTPUT: «NumStr␤» my $r = <42.1>; say $r.^name; # OUTPUT: «RatStr␤» ``` As a subclass of both a [`Numeric`](/type/Numeric) class and [`Str`](/type/Str), via the `Allomorph` class, an allomorph will be accepted where either is expected. However, an allomorph does not share object identity with its [`Numeric`](/type/Numeric) parent class- or [`Str`](/type/Str)-only variants: ```raku my ($complex-str, $int-str, $num-str, $rat-str) = < 42+0i 42 42e10 42.1 >; my (Complex $complex, Int $int, Num $num, Rat $rat) = $complex-str, $int-str, $num-str, $rat-str; # OK! my Str @strings = $complex-str, $int-str, $num-str, $rat-str; # OK! # ∈ operator cares about object identity say 42+0i ∈ < 42+0i 42 42e10 42.1 >; # OUTPUT: «False␤» say 42 ∈ < 42+0i 42 42e10 42.1 >; # OUTPUT: «False␤» say 42e10 ∈ < 42+0i 42 42e10 42.1 >; # OUTPUT: «False␤» say 42.1 ∈ < 42+0i 42 42e10 42.1 >; # OUTPUT: «False␤» ``` Please see [the Numerics page](/language/numerics#Allomorphs) for a more complete description on how to work with these allomorphs. # [Methods](#class_Allomorph "go to top of document")[§](#Methods "direct link") ## [method ACCEPTS](#class_Allomorph "go to top of document")[§](#method_ACCEPTS "direct link") ```raku multi method ACCEPTS(Allomorph:D: Any:D \a) ``` If the `a` parameter is [`Numeric`](/type/Numeric) (including another [allomorph](/language/glossary#Allomorph)), checks if invocant's [`Numeric`](/type/Numeric) value [ACCEPTS](/type/Numeric#method_ACCEPTS) `a`. If the `a` parameter is [`Str`](/type/Str), checks if invocant's [`Str`](/type/Str) value [ACCEPTS](/type/Str#method_ACCEPTS) `a`. If the `a` parameter is anything else, checks if both [`Numeric`](/type/Numeric) and [`Str`](/type/Str) values of the invocant `ACCEPTS` `a`. ```raku say "5.0" ~~ <5>; # OUTPUT: «False␤» say 5.0 ~~ <5>; # OUTPUT: «True␤» say <5.0> ~~ <5>; # OUTPUT: «True␤» ``` ## [method Bool](#class_Allomorph "go to top of document")[§](#method_Bool "direct link") ```raku multi method Bool(::?CLASS:D:) ``` Returns `False` if the invocant is numerically `0`, otherwise returns `True`. The [`Str`](/type/Str) value of the invocant is not considered. **Note**: For the `Allomorph` subclass [`RatStr`](/type/RatStr) also see [`Rational.Bool`](/type/Rational#method_Bool). ## [method chomp](#class_Allomorph "go to top of document")[§](#method_chomp "direct link") ```raku method chomp(Allomorph:D:) ``` Calls [`Str.chomp`](/type/Str#routine_chomp) on the invocant's [`Str`](/type/Str) value. ## [method chop](#class_Allomorph "go to top of document")[§](#method_chop "direct link") ```raku method chop(Allomorph:D: |c) ``` Calls [`Str.chop`](/type/Str#routine_chop) on the invocant's [`Str`](/type/Str) value. ## [method comb](#class_Allomorph "go to top of document")[§](#method_comb "direct link") ```raku method comb(Allomorph:D: |c) ``` Calls [`Str.comb`](/type/Str#routine_comb) on the invocant's [`Str`](/type/Str) value. ## [method fc](#class_Allomorph "go to top of document")[§](#method_fc "direct link") ```raku method fc(Allomorph:D:) ``` Calls [`Str.fc`](/type/Str#routine_fc) on the invocant's [`Str`](/type/Str) value. ## [method flip](#class_Allomorph "go to top of document")[§](#method_flip "direct link") ```raku method flip(Allomorph:D:) ``` Calls [`Str.flip`](/type/Str#routine_flip) on the invocant's [`Str`](/type/Str) value. ## [method lc](#class_Allomorph "go to top of document")[§](#method_lc "direct link") ```raku method lc(Allomorph:D:) ``` Calls [`Str.lc`](/type/Str#routine_lc) on the invocant's [`Str`](/type/Str) value. ## [method pred](#class_Allomorph "go to top of document")[§](#method_pred "direct link") ```raku method pred(Allomorph:D:) ``` Calls [`Numeric.pred`](/type/Numeric#method_pred) on the invocant's numeric value. ## [method raku](#class_Allomorph "go to top of document")[§](#method_raku "direct link") ```raku multi method raku(Allomorph:D:) ``` Return a representation of the object that can be used via [`EVAL`](/routine/EVAL) to reconstruct the value of the object. ## [method samecase](#class_Allomorph "go to top of document")[§](#method_samecase "direct link") ```raku method samecase(Allomorph:D: |c) ``` Calls [`Str.samecase`](/type/Str#method_samecase) on the invocant's [`Str`](/type/Str) value. ## [method samemark](#class_Allomorph "go to top of document")[§](#method_samemark "direct link") ```raku method samemark(Allomorph:D: |c) ``` Calls [`Str.samemark`](/type/Str#routine_samemark) on the invocant's [`Str`](/type/Str) value. ## [method split](#class_Allomorph "go to top of document")[§](#method_split "direct link") ```raku method split(Allomorph:D: |c) ``` Calls [`Str.split`](/type/Str#routine_split) on the invocant's [`Str`](/type/Str) value. ## [method Str](#class_Allomorph "go to top of document")[§](#method_Str "direct link") ```raku method Str(Allomorph:D:) ``` Returns the [`Str`](/type/Str) value of the invocant. ## [method subst](#class_Allomorph "go to top of document")[§](#method_subst "direct link") ```raku method subst(Allomorph:D: |c) ``` Calls [`Str.subst`](/type/Str#method_subst) on the invocant's [`Str`](/type/Str) value. ## [method subst-mutate](#class_Allomorph "go to top of document")[§](#method_subst-mutate "direct link") ```raku method subst-mutate(Allomorph:D \SELF: |c) ``` Calls [`Str.subst-mutate`](/type/Str#method_subst-mutate) on the invocant's [`Str`](/type/Str) value. ## [method substr](#class_Allomorph "go to top of document")[§](#method_substr "direct link") ```raku method substr(Allomorph:D: |c) ``` Calls [`Str.substr`](/type/Str#routine_substr) on the invocant's [`Str`](/type/Str) value. ## [method substr-rw](#class_Allomorph "go to top of document")[§](#method_substr-rw "direct link") ```raku method substr-rw(Allomorph:D \SELF: $start = 0, $want = Whatever) ``` Calls [`Str.substr-rw`](/type/Str#method_substr-rw) on the invocant's [`Str`](/type/Str) value. ## [method succ](#class_Allomorph "go to top of document")[§](#method_succ "direct link") ```raku method succ(Allomorph:D:) ``` Calls [`Numeric.succ`](/type/Numeric#method_succ) on the invocant's numeric value. ## [method tc](#class_Allomorph "go to top of document")[§](#method_tc "direct link") ```raku method tc(Allomorph:D:) ``` Calls [`Str.tc`](/type/Str#routine_tc) on the invocant's [`Str`](/type/Str) value. ## [method tclc](#class_Allomorph "go to top of document")[§](#method_tclc "direct link") ```raku method tclc(Allomorph:D:) ``` Calls [`Str.tclc`](/type/Str#routine_tclc) on the invocant's [`Str`](/type/Str) value. ## [method trim](#class_Allomorph "go to top of document")[§](#method_trim "direct link") ```raku method trim(Allomorph:D:) ``` Calls [`Str.trim`](/type/Str#method_trim) on the invocant's [`Str`](/type/Str) value. ## [method trim-leading](#class_Allomorph "go to top of document")[§](#method_trim-leading "direct link") ```raku method trim-leading(Allomorph:D:) ``` Calls [`Str.trim-leading`](/type/Str#method_trim-leading) on the invocant's [`Str`](/type/Str) value. ## [method trim-trailing](#class_Allomorph "go to top of document")[§](#method_trim-trailing "direct link") ```raku method trim-trailing(Allomorph:D:) ``` Calls [`Str.trim-trailing`](/type/Str#method_trim-trailing) on the invocant's [`Str`](/type/Str) value. ## [method uc](#class_Allomorph "go to top of document")[§](#method_uc "direct link") ```raku method uc(Allomorph:D:) ``` Calls [`Str.uc`](/type/Str#routine_uc) on the invocant's [`Str`](/type/Str) value. ## [method WHICH](#class_Allomorph "go to top of document")[§](#method_WHICH "direct link") ```raku multi method WHICH(Allomorph:D:) ``` Returns an object of type [`ValueObjAt`](/type/ValueObjAt) which uniquely identifies the object. ```raku my $f = <42.1e0>; say $f.WHICH; # OUTPUT: «NumStr|Num|42.1|Str|42.1e0␤» ``` # [Operators](#class_Allomorph "go to top of document")[§](#Operators "direct link") ## [infix cmp](#class_Allomorph "go to top of document")[§](#infix_cmp "direct link") ```raku multi infix:<cmp>(Allomorph:D $a, Allomorph:D $b) ``` Compare two `Allomorph` objects. The comparison is done on the [`Numeric`](/type/Numeric) value first and then on the [`Str`](/type/Str) value. If you want to compare in a different order then you would coerce to a [`Numeric`](/type/Numeric) or [`Str`](/type/Str) value first: ```raku my $f = IntStr.new(42, "smaller"); my $g = IntStr.new(43, "larger"); say $f cmp $g; # OUTPUT: «Less␤» say $f.Str cmp $g.Str; # OUTPUT: «More␤» ``` ## [infix eqv](#class_Allomorph "go to top of document")[§](#infix_eqv "direct link") ```raku multi infix:<eqv>(Allomorph:D $a, Allomorph:D $b --> Bool:D) ``` Returns `True` if the two `Allomorph` `$a` and `$b` are of the same type, their [`Numeric`](/type/Numeric) values are [equivalent](/routine/eqv) and their [`Str`](/type/Str) values are also [equivalent](/routine/eqv). Returns `False` otherwise. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Allomorph` raku-type-graph Allomorph Allomorph Str Str Allomorph->Str Mu Mu Any Any Any->Mu Cool Cool Cool->Any Stringy Stringy Str->Cool Str->Stringy Numeric Numeric Real Real Real->Numeric Int Int Int->Cool Int->Real IntStr IntStr IntStr->Allomorph IntStr->Int Num Num Num->Cool Num->Real NumStr NumStr NumStr->Allomorph NumStr->Num Complex Complex Complex->Cool Complex->Numeric ComplexStr ComplexStr ComplexStr->Allomorph ComplexStr->Complex Rational Rational Rational->Real Rat Rat Rat->Cool Rat->Rational RatStr RatStr RatStr->Allomorph RatStr->Rat [Expand chart above](/assets/typegraphs/Allomorph.svg)
## dist_zef-raku-community-modules-MQTT-Client.md [![Actions Status](https://github.com/raku-community-modules/MQTT-Client/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/MQTT-Client/actions) [![Actions Status](https://github.com/raku-community-modules/MQTT-Client/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/MQTT-Client/actions) [![Actions Status](https://github.com/raku-community-modules/MQTT-Client/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/MQTT-Client/actions) # NAME MQTT::Client - Minimal MQTT v3 client interface for Perl 6 # SYNOPSIS ``` use MQTT::Client; my $m = MQTT::Client.new('test.mosquitto.org'); await $m.connect; $m.publish("hello-world", "$*PID is still here!"); react { whenever $m.subscribe("typing-speed-test.aoeu.eu") { say "Typing test completed at { .<message>.decode("utf8-c8") }"; } whenever Supply.interval(10) { $m.publish("hello-world", "$*PID is still here!"); } } ``` # METHODS ## new($server, $port) Returns a new `MQTT::Client` object. Note: it does not automatically connect. Before doing anything, `.connect` should be called! ## connect Attempts to connect to the MQTT broker, and returns a `Promise` that will be kept after connection confirmation from the broker. ## connection Returns a `Promise` that isn't kept until the connection ends. ## publish(Str $topic, Buf|Str $message) ## retain(Str $topic, Buf|Str $message) Publish a message to the MQTT broker. If the $message is a Str, it will be UTF-8 encoded. Topics are always UTF-8 encoded in MQTT. ## subscribe($topic) Subscribes to the topic, returning a `Supply` of messages that match the topic. Note that messages that are matched by multiple subscriptions will be passed to all of the supplies that match. Tap the supply to receive, for each message, a hash with the keys `topic`, `message`, and a boolean `retain`. Note that `message` is a `Buf` (binary buffer), which in most cases you will need to `.decode` before you can use it. # FUNCTIONS ## MQTT::Client::filter\_as\_regex(topic\_filter) Given a valid MQTT topic filter, returns the corresponding regular expression. # NOT YET IMPLEMENTED The following features that are present in Net::MQTT::Simple for Perl, have not yet been implemented in `MQTT::Client` for Raku: * dropping the connection when a large message is received * unsubscribe * automatic reconnecting * SSL * connection timeouts * simple functional interface # NOT SUPPORTED * QoS (Quality of Service) Every message is published at QoS level 0, that is, "at most once", also known as "fire and forget". * DUP (Duplicate message) Since QoS is not supported, no retransmissions are done, and no message will indicate that it has already been sent before. * Authentication No username and password are sent to the server. * Last will The server won't publish a "last will" message on behalf of us when our connection's gone. * Large data Because everything is handled in memory and there's no way to indicate to the server that large messages are not desired, the connection is dropped as soon as the server announces a packet larger than 2 megabytes. * Validation of server-to-client communication The MQTT spec prescribes mandatory validation of all incoming data, and disconnecting if anything (really, anything) is wrong with it. However, this minimal implementation silently ignores anything it doesn't specifically handle, which may result in weird behaviour if the server sends out bad data. Most clients do not adhere to this part of the specifications. # AUTHOR Juerd Waalboer # COPYRIGHT AND LICENSE Copyright 2015 - 2019 Juerd Waalboer Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. # SEE ALSO [Net::MQTT::Simple](https://metacpan.org/pod/Net::MQTT::Simple) inr Perl
## dist_cpan-KJPYE-Geo-Coordinates-UTM.md # NAME Geo::Coordinates::UTM - Perl extension for Latitude Longitude conversions. # SYNOPSIS use Geo::Coordinates::UTM; my ($zone,$easting,$northing)=|latlon-to-utm($ellipsoid,$latitude,$longitude); my ($latitude,$longitude)=|utm-to-latlon($ellipsoid,$zone,$easting,$northing); my ($zone,$easting,$northing)=|mgrs-to-utm($mgrs); my ($latitude,$longitude)=|mgrs-to-latlon($ellipsoid,$mgrs); my ($mgrs)=|utm-to-mgrs($zone,$easting,$northing); my ($mgrs)=|latlon-to-mgrs($ellipsoid,$latitude,$longitude); my @ellipsoids=ellipsoid-names; my($name, $r, $sqecc) = |ellipsoid-info 'WGS-84'; # DESCRIPTION This module will translate latitude longitude coordinates to Universal Transverse Mercator(UTM) coordinates and vice versa. ## Mercator Projection The Mercator projection was first invented to help mariners. They needed to be able to draw a straight line on a map and follow that bearing to arrive at a destination. In order to do this, Mercator invented a projection which preserved angle, by projecting the earth's surface onto a cylinder, sharing the same axis as the earth itself. This caused all Latitude and Longitude lines to be straight and to intersect at a 90 degree angle, but the downside was that the scale of the map increased as you moved away from the equator so that the lines of longitude were parallel. Because the scale varies, areas near the poles appear much larger on the map than a similar sized object near the equator. The Mercator Projection is useless near the poles since the scale becomes infinite. ## Transverse Mercator Projection A Transverse Mercator projection takes the cylinder and turns it on its side. Now the cylinder's axis passes through the equator, and it can be rotated to line up with the area of interest. Many countries use Transverse Mercator for their grid systems. The disadvantage is that now neither the lines of latitude or longitude (apart from the central meridian) are straight. ## Universal Transverse Mercator The Universal Transverse Mercator(UTM) system sets up a universal world wide system for mapping. The Transverse Mercator projection is used, with the cylinder in 60 positions. This creates 60 zones around the world. Positions are measured using Eastings and Northings, measured in meters, instead of Latitude and Longitude. Eastings start at 500,000 on the centre line of each zone. In the Northern Hemisphere, Northings are zero at the equator and increase northward. In the Southern Hemisphere, Northings start at 10 million at the equator, and decrease southward. You must know which hemisphere and zone you are in to interpret your location globally. Distortion of scale, distance and area increase away from the central meridian. UTM projection is used to define horizontal positions world-wide by dividing the surface of the Earth into 6 degree zones, each mapped by the Transverse Mercator projection with a central meridian in the center of the zone. UTM zone numbers designate 6 degree longitudinal strips extending from 80 degrees South latitude to 84 degrees North latitude. UTM zone characters designate 8 degree zones extending north and south from the equator. Eastings are measured from the central meridian (with a 500 km false easting to insure positive coordinates). Northings are measured from the equator (with a 10,000 km false northing for positions south of the equator). UTM is applied separately to the Northern and Southern Hemisphere, thus within a single UTM zone, a single X / Y pair of values will occur in both the Northern and Southern Hemisphere. To eliminate this confusion, and to speed location of points, a UTM zone is sometimes subdivided into 20 zones of Latitude. These grids can be further subdivided into 100,000 meter grid squares with double-letter designations. This subdivision by Latitude and further division into grid squares is generally referred to as the Military Grid Reference System (MGRS). The unit of measurement of UTM is always meters and the zones are numbered from 1 to 60 eastward, beginning at the 180th meridian. The scale distortion in a north-south direction parallel to the central meridian (CM) is constant However, the scale distortion increases either direction away from the CM. To equalize the distortion of the map across the UTM zone, a scale factor of 0.9996 is applied to all distance measurements within the zone. The distortion at the zone boundary, 3 degrees away from the CM is approximately 1%. ## Datums and Ellipsoids Unlike local surveys, which treat the Earth as a plane, the precise determination of the latitude and longitude of points over a broad area must take into account the actual shape of the Earth. To achieve the precision necessary for accurate location, the Earth cannot be assumed to be a sphere. Rather, the Earth's shape more closely approximates an ellipsoid (oblate spheroid): flattened at the poles and bulging at the Equator. Thus the Earth's shape, when cut through its polar axis, approximates an ellipse. A "Datum" is a standard representation of shape and offset for coordinates, which includes an ellipsoid and an origin. You must consider the Datum when working with geospatial data, since data with two different Datum will not line up. The difference can be as much as a kilometer! # EXAMPLES A description of the available ellipsoids and sample usage of the conversion routines follows ## Ellipsoids The Ellipsoids available are as follows: # over 6 * 1 Airy * 2 Australian National * 3 Bessel 1841 * 4 Bessel 1841 (Nambia) * 5 Clarke 1866 * 6 Clarke 1880 * 7 Everest 1830 (India) * 8 Fischer 1960 (Mercury) * 9 Fischer 1968 * 10 GRS 1967 * 11 GRS 1980 * 12 Helmert 1906 * 13 Hough * 14 International * 15 Krassovsky * 16 Modified Airy * 17 Modified Everest * 18 Modified Fischer 1960 * 19 South American 1969 * 20 WGS 60 * 21 WGS 66 * 22 WGS-72 * 23 WGS-84 * 24 Everest 1830 (Malaysia) * 25 Everest 1956 (India) * 26 Everest 1964 (Malaysia and Singapore) * 27 Everest 1969 (Malaysia) * 28 Everest (Pakistan) * 29 Indonesian 1974 * 30 Arc 1950 * 31 NAD 27 * 32 NAD 83 # back ## ellipsoid-names The ellipsoids can be accessed using ellipsoid-names. To store thes into an array you could use ``` my @names = ellipsoid-names; ``` ## ellipsoid-info Ellipsoids may be called either by name, or number. To return the ellipsoid information, ( "official" name, equator radius and square eccentricity) you can use ellipsoid-info and specify a name. The specified name can be numeric (for compatibility reasons) or a more-or-less exact name. Any text between parentheses will be ignored. ``` my($name, $r, $sqecc) = |ellipsoid-info 'wgs84'; my($name, $r, $sqecc) = |ellipsoid-info 'WGS 84'; my($name, $r, $sqecc) = |ellipsoid-info 'WGS-84'; my($name, $r, $sqecc) = |ellipsoid-info 'WGS-84 (new specs)'; my($name, $r, $sqecc) = |ellipsoid-info 23; ``` ## latlon-to-utm Latitude values in the southern hemisphere should be supplied as negative values (e.g. 30 deg South will be -30). Similarly Longitude values West of the meridian should also be supplied as negative values. Both latitude and longitude should not be entered as deg,min,sec but as their decimal equivalent, e.g. 30 deg 12 min 22.432 sec should be entered as 30.2062311 The ellipsoid value should correspond to one of the numbers above, e.g. to use WGS-84, the ellipsoid value should be 23 For latitude 57deg 49min 59.000sec North longitude 02deg 47min 20.226sec West using Clarke 1866 (Ellipsoid 5) ``` ($zone,$east,$north)=|latlon-to-utm('clarke 1866',57.803055556,-2.788951667) ``` returns ``` $zone = 30V $east = 512543.777159849 $north = 6406592.20049111 ``` On occasions, it is necessary to map a pair of (latitude, longitude) coordinates to a predefined zone. This is done by p[roviding a value for the optional named parameter zone as follows: ``` ($zone, $east, $north)=|latlon-to-utm('international', :zone($zone_number), $latitude, $longitude) ``` For instance, Spain territory goes over zones 29, 30 and 31 but sometimes it is convenient to use the projection corresponding to zone 30 for all the country. Santiago de Compostela is at 42deg 52min 57.06sec North, 8deg 32min 28.70sec West ``` ($zone, $east, $norh)=|latlon-to-utm('international', 42.882517, -8.541306) ``` returns ``` $zone = 29T $east = 537460.331 $north = 4747955.991 ``` but forcing the conversion to zone 30: ``` ($zone, $east, $norh)=|latlon-to-utm('international', :zone(30), 42.882517, -8.541306) ``` returns ``` $zone = 30T $east = 47404.442 $north = 4762771.704 ``` ## utm-to-latlon Reversing the above example, ``` ($latitude,$longitude)=|utm-to-latlon(5,'30V',512543.777159849,6406592.20049111) ``` returns ``` $latitude = 57.8030555601332 $longitude = -2.7889516669741 which equates to latitude 57deg 49min 59.000sec North longitude 02deg 47min 20.226sec West ``` ## latlon-to-mgrs Latitude values in the southern hemisphere should be supplied as negative values (e.g. 30 deg South will be -30). Similarly Longitude values West of the meridian should also be supplied as negative values. Both latitude and longitude should not be entered as deg,min,sec but as their decimal equivalent, e.g. 30 deg 12 min 22.432 sec should be entered as 30.2062311 The ellipsoid value should correspond to one of the numbers above, e.g. to use WGS-84, the ellipsoid value should be 23 For latitude 57deg 49min 59.000sec North longitude 02deg 47min 20.226sec West using WGS84 (Ellipsoid 23) ``` ($mgrs)=|latlon-to-mgrs(23,57.8030590197684,-2.788956799) ``` returns ``` $mgrs = 30VWK1254306804 ``` ## mgrs-to-latlon Reversing the above example, ``` ($latitude,$longitude)=|mgrs-to-latlon(23,'30VWK1254306804') ``` returns ``` $latitude = 57.8030590197684 $longitude = -2.788956799645 ``` ## mgrs-to-utm ``` Similarly it is possible to convert MGRS directly to UTM ($zone,$easting,$northing)=|mgrs-to-utm('30VWK1254306804') returns $zone = 30V $easting = 512543 $northing = 6406804 ``` ## utm-to-mgrs ``` and the inverse converting from UTM yo MGRS is done as follows ($mgrs)=|utm-to-mgrs('30V',512543,6406804); returns $mgrs = 30VWK1254306804 ``` # AUTHOR Graham Crookham, [[email protected]](mailto:[email protected]) # THANKS Thanks go to the following: Felipe Mendonca Pimenta for helping out with the Southern hemisphere testing. Michael Slater for discovering the Escape \Q bug. Mark Overmeer for the ellipsoid\_info routines and code review. Lok Yan for the >72deg. N bug. Salvador Fandino for the forced zone UTM and additional tests Matthias Lendholt for modifications to MGRS calculations Peder Stray for the short MGRS patch # COPYRIGHT Copyright (c) 2000,2002,2004,2007,2010,2013 by Graham Crookham. All rights reserved. copyright (c) 2017 by Kevin Pye. This package is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
## cache.md cache Combined from primary sources listed below. # [In Any](#___top "go to top of document")[§](#(Any)_method_cache "direct link") See primary documentation [in context](/type/Any#method_cache) for **method cache**. ```raku method cache() ``` Provides a [`List`](/type/List) representation of the object itself, calling the method `list` on the instance. # [In role PositionalBindFailover](#___top "go to top of document")[§](#(role_PositionalBindFailover)_method_cache "direct link") See primary documentation [in context](/type/PositionalBindFailover#method_cache) for **method cache**. ```raku method cache(PositionalBindFailover:D: --> List:D) ``` Returns a [`List`](/type/List) based on the `iterator` method, and caches it. Subsequent calls to `cache` always return the same [`List`](/type/List) object.
## dist_zef-lizmat-Method-Protected.md [![Actions Status](https://github.com/lizmat/Method-Protected/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Method-Protected/actions) [![Actions Status](https://github.com/lizmat/Method-Protected/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Method-Protected/actions) [![Actions Status](https://github.com/lizmat/Method-Protected/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/Method-Protected/actions) # NAME Method::Protected - add "is protected" trait to methods # SYNOPSIS ``` use Method::Protected; my @words = "/usr/share/dict/words".IO.lines; class Frobnicate { has %!hash; method pick() is protected { %!hash{@words.pick}++ } method hash() is protected { %!hash.clone } } # Set up 2 threads massively updating a single hash my $frobnicator = Frobnicate.new; start { loop { $frobnicator.pick } start { loop { $frobnicator.pick } # Start reporter until $frobnicator.hash.elems == @words.elems { say $frobnicator.hash.elems; sleep .1; } ``` # DESCRIPTION The `Method::Protected` distribution provides an `is protected` trait to methods in a class. If applied to a method, all calls to that method will be protected by a [Lock](https://docs.raku.org/type/Lock), making sure that any other method call to this method (or any other method protected by the trait) from another thread, will block until the call is finished. Functionally this is similar to what the [OO::Monitor](https://raku.land/cpan:JNTHN/OO::Monitors) does, except that with this module this logic is only applied to methods that actuall have the `is protected` trait applied. # THEORY OF OPERATION When the trait is applied on a method, the class of the method id checked whether it already has a `$!LOCK` attribute. If not, then that attribute is added, and the associated accessor method `LOCK` is also added. Then the method will be [wrapped](https://docs.raku.org/routine/wrap) with code that will protect the execution of the original body of the method. # A NOTE OF CAUTION If the method being protected has an `is raw` or `is rw` trait set, then the protected version will also have that set. However, this is usually used to return a container, which can potentially cause a race-condition **outside** of the protected method because the container **may** contain logic that would execute code in a non-threadsafe manner (e.g. in the autovivification of keys in a hash). So only use `is raw` or `is rw` on protected methods if you **really** know what you're doing. Generally spoken: don't do that! If you think you need to do this, first find another way to structure your code, e.g. by using [`hyper`](https://docs.raku.org/type/Iterable#method_hyper). # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Method-Protected> . 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, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## abs.md abs Combined from primary sources listed below. # [In Complex](#___top "go to top of document")[§](#(Complex)_routine_abs "direct link") See primary documentation [in context](/type/Complex#routine_abs) for **routine abs**. ```raku method abs(Complex:D: --> Num:D) multi abs(Complex:D $z --> Num:D) ``` Returns the absolute value of the invocant (or the argument in sub form). For a given complex number `$z` the absolute value `|$z|` is defined as `sqrt($z.re * $z.re + $z.im * $z.im)`. ```raku say (3+4i).abs; # OUTPUT: «5␤» # sqrt(3*3 + 4*4) == 5 ``` # [In role Numeric](#___top "go to top of document")[§](#(role_Numeric)_routine_abs "direct link") See primary documentation [in context](/type/Numeric#routine_abs) for **routine abs**. ```raku multi abs(Numeric:D --> Real:D) multi method abs(Numeric:D: --> Real:D) ``` Returns the absolute value of the number. # [In Cool](#___top "go to top of document")[§](#(Cool)_routine_abs "direct link") See primary documentation [in context](/type/Cool#routine_abs) for **routine abs**. ```raku sub abs(Numeric() $x) method abs() ``` Coerces the invocant (or in the sub form, the argument) to [`Numeric`](/type/Numeric) and returns the absolute value (that is, a non-negative number). ```raku say (-2).abs; # OUTPUT: «2␤» say abs "6+8i"; # OUTPUT: «10␤» ```
## dist_cpan-UFOBAT-IoC.md [![Build Status](https://travis-ci.org/ufobat/perl6-ioc.svg?branch=master)](https://travis-ci.org/ufobat/perl6-ioc) # NAME IoC - Wire your application components together using inversion of control # SYNOPSIS ``` use IoC; my $c = container 'myapp' => contains { service 'logfile' => 'logfile.txt'; service 'logger' => { 'class' => 'MyLogger', 'lifecycle' => 'Singleton', 'dependencies' => {'logfile' => 'logfile'}, }; service 'storage' => { 'lifecycle' => 'Singleton', 'block' => sub { ... return MyStorage.new(); }, }; service 'app' => { 'class' => 'MyApp', 'lifecycle' => 'Signleton', 'dependencies' => { 'logger' => 'logger', 'storage' => 'storage', }, }; }; my $app = $c.resolve(service => 'app'); $app.run(); ``` # DESCRIPTION IoC is a port of stevan++'s Perl 5 module Bread::Board. # INVERSION OF CONTROL Inversion of control is a way of keeping all your component creation logic in one place. Instead of creating an object and explicitly pass it around everywhere, one could just make a *container* of all these components and allow the components to cleanly interact with each other as *services*. # EXPORTED FUNCTIONS * **container** Creates a new IoC::Container object. In the block you create your services. * **service** Adds services to your container, bringing your components together. See `IoC::Service` for more information on this. # BUGS All complex software has bugs lurking in it, and this module is no exception. If you find a bug please either email me, or post an issue to <http://github.com/jasonmay/perl6-ioc/> # REFERENCE * IoC::Container - Container of all your application components * IoC::Service - Service representing a component in your application # ACKNOWLEDGEMENTS * Thanks to Stevan Little who is the original author of Perl 5's Bread::Board # AUTHOR Jason May, [[email protected]](mailto:[email protected]) # LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
## dist_zef-coke-Slang-Date_1.md # Slang::Date A Slang for Raku that adds support for literal dates in ISO-8601 style. ## Examples Replaces the ISO String with a QAST node that generates a call to Date.new...; ``` my $a = 2023-01-13; say "Happy Friday the 13th" if $a.day-of-week == 5; ``` Invalid dates will error out as expected: ``` my $b = 2023-01-99; ``` ``` Day out of range. Is: 99, should be in 1..31 in block <unit> at -e line 1 ``` ## Notes Requires a 4 digit year, 2 digit month, and 2 digit day.
## dist_zef-librasteve-Contact.md [![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) [![test](https://github.com/librasteve/raku-Contact/actions/workflows/test.yml/badge.svg)](https://github.com/librasteve/raku-Contact/actions/workflows/test.yml) # Contact ## Synopsis ``` #!/usr/bin/env raku use v6.d; use lib '../lib'; use Data::Dump::Tree; use Contact; my ( $country, $text ); #[ $country = 'USA'; $text = q:to/END/; John Doe, 123, Main St., Springfield, IL 62704 END #] #[ $country = 'UK'; $text = q:to/END/; Dr. Jane Doe, Sleepy Cottage, 123, Badgemore Lane, Henley-on-Thames, Oxon, RG9 2XX END #] my Contact $contact .= new: :$country, :$text; ddt $contact; say ~$contact; say $contact.to-json; ``` *you are welcome to view / raise issues / make PRs if you would like to contribute...* ### TODOs * add Email::Address (dependency) * add more countries (GE, FR ...) ### Copyright copyright(c) 2023 Henley Cloud Consulting Ltd.
## dist_zef-grizzlysmit-Display-Listings.md ## Chunk 1 of 2 # Display::Listings ## Table of Contents * [NAME](#name) * [AUTHOR](#author) * [VERSION](#version) * [TITLE](#title) * [SUBTITLE](#subtitle) * [COPYRIGHT](#copyright) * [Introduction](#introduction) * [list-by(…)](#list-by) * [Examples:](#examples) * [A more complete example:](#a-more-complete-example) * [Another example:](#another-example) * [An Example of the above code **`list-editors-backups(…)`** at work:](#An-Example-of-the-above-code-list-editors-backups-at-work) * [The default callbacks](#the-default-callbacks) * [The hash of hashes stuff](#the-hash-of-hashes-stuff) * [The array of hashes stuff](#the-array-of-hashes-stuff) # NAME Display::Listings # AUTHOR Francis Grizzly Smit ([[email protected]](mailto:[email protected])) # VERSION 0.1.9 # TITLE Display::Listings # SUBTITLE A Raku module for displaying lines in a listing. # COPYRIGHT LGPL V3.0+ [LICENSE](https://github.com/grizzlysmit/Display-Listings/blob/main/LICENSE) [Top of Document](#table-of-contents) # Introduction A **Raku** module for managing the users GUI Editor preferences in a variety of programs. ### list-by(…) This is a multi sub it has two signatures. ``` multi sub list-by(Str:D $prefix, Bool:D $colour is copy, Bool:D $syntax, Int:D $page-length, Regex:D $pattern, Str:D $key-name, Str:D @fields, %defaults, %rows, Int:D :$start-cnt = -3, Bool:D :$starts-with-blank = True, Str:D :$overline-header = '', Bool:D :$underline-header = True, Str:D :$underline = '=', Bool:D :$put-line-at-bottom = True, Str:D :$line-at-bottom = '=', Bool:D :$sort = True, Str:D :%flags = default-zip-flags($key-name, @fields), Str:D :%between-flags = default-zip-flags($key-name, @fields), Str:D :%head-flags = default-zip-flags($key-name, @fields), Str:D :%between-head-flags = default-zip-flags($key-name, @fields), :&include-row:(Str:D $pref, Regex $pat, Str:D $k, Str:D @f, %r --> Bool:D) = &default-include-row, :&head-value:(Int:D $idx, Str:D $fld, Bool:D $c, Bool:D $syn, Str:D @flds --> Str:D) = &default-head-value, :&head-between:(Int:D $idx, Str:D $fld, Bool:D $c, Bool:D $syn, Str:D @flds --> Str:D) = &default-head-between, :&field-value:(Int:D $idx, Str:D $fld, $val, Bool:D $c, Bool:D $syn, Str:D @flds, %r --> Str:D) = &default-field-value, :&between:(Int:D $idx, Str:D $fld, Bool:D $c, Bool:D $syn, Str:D @flds, %r --> Str:D) = &default-between, :&row-formatting:(Int:D $cnt, Bool:D $c, Bool:D $syn --> Str:D) = &default-row-formatting --> Bool:D) is export { ``` [Top of Document](#table-of-contents) And ``` multi sub list-by(Str:D $prefix, Bool:D $colour is copy, Bool:D $syntax, Int:D $page-length, Regex:D $pattern, Str:D @fields, %defaults, @rows, Int:D :$start-cnt = -3, Bool:D :$starts-with-blank = True, Str:D :$overline-header = '', Bool:D :$underline-header = True, Str:D :$underline = '=', Bool:D :$put-line-at-bottom = True, Str:D :$line-at-bottom = '=', Bool:D :$sort = True, Str:D :%flags = default-zip-flags(@fields), Str:D :%between-flags = default-zip-flags(@fields), Str:D :%head-flags = default-zip-flags(@fields), Str:D :%between-head-flags = default-zip-flags(@fields), :&include-row:(Str:D $pref, Regex:D $pat, Int:D $i, Str:D @f, %r --> Bool:D) = &default-include-row-array, :&head-value:(Int:D $idx, Str:D $fld, Bool:D $c, Bool:D $syn, Str:D @flds --> Str:D) = &default-head-value-array, :&head-between:(Int:D $idx, Str:D $fld, Bool:D $c, Bool:D $syn, Str:D @flds --> Str:D) = &default-head-between-array, :&field-value:(Int:D $idx, Str:D $fld, $val, Bool:D $c, Bool:D $syn, Str:D @flds, %r --> Str:D) = &default-field-value-array, :&between:(Int:D $idx, Str:D $fld, Bool:D $c, Bool:D $syn, Str:D @flds, %r --> Str:D) = &default-between-array, :&row-formatting:(Int:D $cnt, Bool:D $c, Bool:D $syn --> Str:D) = &default-row-formatting-array --> Bool:D) is export { ``` **Note: you have to be careful writing your own callbacks like `:&include-row` you need to get the signature of said callback exactly right or you will run into difficult to debug errors, with no version of the `list-by` multi sub matching etc.** [Top of Document](#table-of-contents) ### Examples: ``` use Display::Listings; my Str:D $prefix = ''; my Str:D $key-name = 'key'; my Str:D @fields = 'host', 'port', 'comment'; my %defaults = port => 22; my %rows = one => { host => 'example.com', type => 'host', port => 22 }, two => { type => 'alias', host => 'one', comment => 'An alias' }, three => { port => 345, host => 'www.smit.id.au', type => 'host', comment => 'mine all mine' }; my Bool:D $colour = False; my Bool:D $syntax = True; my Int:D $page-length = 20; my Regex:D $pattern = rx:i/ ^ .* 'smit' .* $/; my @rows = {key => 'one', host => 'example.com', type => 'host', port => 22 }, { type => 'alias', host => 'one', comment => 'An alias', key => 'two', }, { port => 345, host => 'www.smit.id.au', type => 'host', comment => 'mine all mine', key => 'three' }; list-by($prefix, $colour, $syntax, $page-length, $pattern, $key-name, @fields, %defaults, %rows); list-by($prefix, $colour, $syntax, $page-length, $pattern, @fields, %defaults, @rows); $pattern = rx/ ^ .* $/; list-by($prefix, $colour, $syntax, $page-length, $pattern, $key-name, @fields, %defaults, %rows); list-by($prefix, $colour, $syntax, $page-length, $pattern, @fields, %defaults, @rows); ``` [Top of Document](#table-of-contents) #### A more complete example: ``` use Terminal::ANSI::OO :t; use Display::Listings; sub list-by-all(Str:D $prefix, Bool:D $colour, Bool:D $syntax, Int:D $page-length, Regex:D $pattern --> Bool:D) is export { my Str:D $key-name = 'key'; my Str:D @fields = 'host', 'port', 'comment'; my %defaults = port => 22; sub include-row(Str:D $prefix, Regex:D $pattern, Str:D $key, Str:D @fields, %row --> Bool:D) { return True if $key.starts-with($prefix, :ignorecase) && $key ~~ $pattern; for @fields -> $field { my Str:D $value = ''; with %row{$field} { #`««« if %row{$field} does not exist then a Any will be returned, and if some cases, you may return undefined values so use some sort of guard this is one way to do that, you could use %row{$field}:exists or :!exists or // perhaps. TIMTOWTDI rules as always. »»» $value = ~%row{$field}; } return True if $value.starts-with($prefix, :ignorecase) && $value ~~ $pattern; } return False; } # sub include-row(Str:D $prefix, Regex:D $pattern, Str:D $key, @fields, %row --> Bool:D) # sub head-value(Int:D $indx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields --> Str:D) { if $syntax { t.color(0, 255, 255) ~ $field; } elsif $colour { t.color(0, 255, 255) ~ $field; } else { return $field; } } #`««« sub head-value(Int:D $indx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields --> Str:D) »»» sub head-between(Int:D $idx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields --> Str:D) { if $colour { if $syntax { given $field { when 'key' { return t.color(0, 255, 255) ~ ' sep '; } when 'host' { return t.color(0, 255, 255) ~ ' : '; } when 'port' { return t.color(0, 255, 255) ~ ' # '; } when 'comment' { return t.color(0, 0, 255) ~ ' '; } default { return ''; } } } else { given $field { when 'key' { return t.color(0, 255, 255) ~ ' sep '; } when 'host' { return t.color(0, 255, 255) ~ ' : '; } when 'port' { return t.color(0, 255, 255) ~ ' # '; } when 'comment' { return t.color(0, 255, 255) ~ ' '; } default { return ''; } } } } else { given $field { when 'key' { return ' sep '; } when 'host' { return ' : '; } when 'port' { return ' # '; } when 'comment' { return ' '; } default { return ''; } } } } #`««« sub head-between(Int:D $idx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields --> Str:D) »»» sub field-value(Int:D $idx, Str:D $field, $value, Bool:D $colour, Bool:D $syntax, Str:D @fields, %row --> Str:D) { if $syntax { given $field { when 'key' { return t.color(0, 255, 255) ~ ~$value; } when 'host' { my Str:D $type = %row«type»; if $type eq 'host' { return t.color(255, 0, 255) ~ ~$value; } else { return t.color(0, 255, 255) ~ ~$value; } } when 'port' { my Str:D $type = %row«type»; if $type eq 'host' { return t.color(255, 0, 255) ~ ~$value; } else { return t.color(255, 0, 255) ~ ''; } } when 'comment' { return t.color(0, 0, 255) ~ ~$value; } default { return t.color(255, 0, 0) ~ ''; } } # given $field # } elsif $colour { given $field { when 'key' { return t.color(0, 0, 255) ~ ~$value; } when 'host' { return t.color(0, 0, 255) ~ ~$value; } when 'port' { my Str:D $type = %row«type»; if $type eq 'host' { return t.color(0, 0, 255) ~ ~$value; } else { return t.color(0, 0, 255) ~ ''; } } when 'comment' { return t.color(0, 0, 255) ~ ~$value; } default { return t.color(255, 0, 0) ~ ''; } } } else { given $field { when 'key' { return ~$value; } when 'host' { return ~$value; } when 'port' { my Str:D $type = %row«type»; if $type eq 'host' { return ~$value; } else { return ''; } } when 'comment' { return ~$value; } default { return ''; } } } } #`««« sub field-value(Int:D $idx, Str:D $field, $value, Bool:D $colour, Bool:D $syntax, Str:D @fields, %row --> Str:D) »»» sub between(Int:D $idx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields, %row --> Str:D) { if $syntax { given $field { when 'key' { my Str:D $type = %row«type»; if $type eq 'host' { return t.color(255, 0, 0) ~ ' => '; } else { return t.color(255, 0, 0) ~ ' --> '; } } when 'host' { my Str:D $type = %row«type»; if $type eq 'host' { return t.color(255, 0, 0) ~ ' : '; } else { return t.color(255, 0, 0) ~ ' '; } } when 'port' { return t.color(0, 0, 255) ~ ' # '; } when 'comment' { return t.color(0, 0, 255) ~ ' '; } default { return t.color(255, 0, 0) ~ ''; } } } elsif $colour { given $field { when 'key' { my Str:D $type = %row«type»; if $type eq 'host' { return t.color(0, 0, 255) ~ ' => '; } else { return t.color(0, 0, 255) ~ ' --> '; } } when 'host' { my Str:D $type = %row«type»; if $type eq 'host' { return t.color(0, 0, 255) ~ ' : '; } else { return t.color(0, 0, 255) ~ ' '; } } when 'port' { return t.color(0, 0, 255) ~ ' # '; } when 'comment' { return t.color(0, 0, 255) ~ ' '; } default { return t.color(255, 0, 0) ~ ''; } } } else { given $field { when 'key' { my Str:D $type = %row«type»; if $type eq 'host' { return ' => '; } else { return ' --> '; } } when 'host' { my Str:D $type = %row«type»; if $type eq 'host' { return ' : '; } else { return ' '; } } when 'port' { return ' # '; } when 'comment' { return ' '; } default { return ''; } } } } #`««« sub between(Int:D $idx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields, %row --> Str:D) »»» sub row-formatting(Int:D $cnt, Bool:D $colour, Bool:D $syntax --> Str:D) { if $colour { if $syntax { return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -3; # three heading lines. # return t.bg-color(0, 0, 127) ~ t.bold ~ t.bright-blue if $cnt == -2; return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -1; return (($cnt % 2 == 0) ?? t.bg-yellow !! t.bg-color(0,255,0)) ~ t.bold ~ t.bright-blue; } else { return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -3; return t.bg-color(0, 0, 127) ~ t.bold ~ t.bright-blue if $cnt == -2; return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -1; return (($cnt % 2 == 0) ?? t.bg-yellow !! t.bg-color(0,255,0)) ~ t.bold ~ t.bright-blue; } } else { return ''; } } #`««« sub row-formatting(Int:D $cnt, Bool:D $colour, Bool:D $syntax --> Str:D) »»» return list-by($prefix, $colour, $syntax, $page-length, $pattern, $key-name, @fields, %defaults, %the-lot, :&include-row, :&head-value, :&head-between, :&field-value, :&between, :&row-formatting); } #`««« sub list-by-all(Str:D $prefix, Bool:D $colour is copy, Bool:D $syntax, Int:D $page-length, Regex:D $pattern --> Bool:D) is export »»» ``` [Top of Document](#table-of-contents) #### Another example ``` use Terminal::ANSI::OO :t; use Display::Listings; use File::Utils; sub list-editors-backups(Str:D $prefix, Bool:D $colour is copy, Bool:D $syntax, Regex:D $pattern, Int:D $page-length --> Bool:D) is export { $colour = True if $syntax; my IO::Path @backups = $editor-config.IO.dir(:test(rx/ ^ 'editors.' \d ** 4 '-' \d ** 2 '-' \d ** 2 [ 'T' \d **2 [ [ '.' || ':' ] \d ** 2 ] ** {0..2} [ [ '.' || '·' ] \d+ [ [ '+' || '-' ] \d ** 2 [ '.' || ':' ] \d ** 2 || 'z' ]? ]? ]? $ / ) ); my $actions = EditorsActions; @backups .=grep: -> IO::Path $fl { my @file = $fl.slurp.split("\n"); Editors.parse(@file.join("\x0A"), :enc('UTF-8'), :$actions).made; }; @backups .=sort; my @_backups = @backups.map: -> IO::Path $f { my %elt = backup => $f.basename, perms => symbolic-perms($f, :$colour, :$syntax), user => $f.user, group => $f.group, size => $f.s, modified => $f.modified; %elt; }; my Str:D @fields = 'perms', 'size', 'user', 'group', 'modified', 'backup'; my %defaults; my Str:D %fancynames = perms => 'Permissions', size => 'Size', user => 'User', group => 'Group', modified => 'Date Modified', backup => 'Backup'; sub include-row(Str:D $prefix, Regex:D $pattern, Int:D $idx, Str:D @fields, %row --> Bool:D) { my Str:D $value = ~(%row«backup» // ''); return True if $value.starts-with($prefix, :ignorecase) && $value ~~ $pattern; return False; } # sub include-row(Str:D $prefix, Regex:D $pattern, Int:D $idx, Str:D @fields, %row --> Bool:D) # sub head-value(Int:D $indx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields --> Str:D) { #dd $indx, $field, $colour, $syntax, @fields; if $colour { if $syntax { return t.color(0, 255, 255) ~ %fancynames{$field}; } else { return t.color(0, 255, 255) ~ %fancynames{$field}; } } else { return %fancynames{$field}; } } # sub head-value(Int:D $indx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields --> Str:D) # sub head-between(Int:D $indx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields --> Str:D) { return ' '; } # sub head-between(Int:D $indx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields --> Str:D) # sub field-value(Int:D $idx, Str:D $field, $value, Bool:D $colour, Bool:D $syntax, Str:D @fields, %row --> Str:D) { my Str:D $val = ~($value // ''); #`««« assumming $value is a Str:D »»» #dd $val, $value, $field; if $syntax { given $field { when 'perms' { return $val; } when 'size' { my Int:D $size = +$value; return t.color(255, 0, 0) ~ format-bytes($size); } when 'user' { return t.color(255, 255, 0) ~ uid2username(+$value); } when 'group' { return t.color(255, 255, 0) ~ gid2groupname(+$value); } when 'modified' { my Instant:D $m = +$value; my DateTime:D $dt = $m.DateTime.local; return t.color(0, 0, 235) ~ $dt.Str; } when 'backup' { return t.color(255, 0, 255) ~ $val; } default { return t.color(255, 0, 0) ~ $val; } } # given $field # } elsif $colour { given $field { when 'perms' { return $val; } when 'size' { my Int:D $size = +$value; return t.color(0, 0, 255) ~ format-bytes($size); } when 'user' { return t.color(0, 0, 255) ~ uid2username(+$value); } when 'group' { return t.color(0, 0, 255) ~ gid2groupname(+$value); } when 'modified' { my Instant:D $m = +$value; my DateTime:D $dt = $m.DateTime.local; return t.color(0, 0, 255) ~ $dt.Str; } when 'backup' { return t.color(0, 0, 255) ~ $val; } default { return t.color(255, 0, 0) ~ $val; } } # given $field # } else { given $field { when 'perms' { return $val; } when 'size' { my Int:D $size = +$value; return format-bytes($size); } when 'user' { return uid2username(+$value); } when 'group' { return gid2groupname(+$value); } when 'modified' { my Instant:D $m = +$value; my DateTime:D $dt = $m.DateTime.local; return $dt.Str; } when 'backup' { return $val; } default { return $val; } } # given $field # } } # sub field-value(Int:D $idx, Str:D $field, $value, Bool:D $colour, Bool:D $syntax, Str:D @fields, %row --> Str:D) # sub between(Int:D $idx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields, %row --> Str:D) { return ' '; } # sub between(Int:D $idx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields, %row --> Str:D) # sub row-formatting(Int:D $cnt, Bool:D $colour, Bool:D $syntax --> Str:D) { if $colour { if $syntax { return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -3; # three heading lines. # return t.bg-color(0, 0, 127) ~ t.bold ~ t.bright-blue if $cnt == -2; return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -1; return (($cnt % 2 == 0) ?? t.bg-yellow !! t.bg-color(0,195,0)) ~ t.bold ~ t.bright-blue; } else { return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -3; return t.bg-color(0, 0, 127) ~ t.bold ~ t.bright-blue if $cnt == -2; return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -1; return (($cnt % 2 == 0) ?? t.bg-yellow !! t.bg-color(0,195,0)) ~ t.bold ~ t.bright-blue; } } else { return ''; } } # sub row-formatting(Int:D $cnt, Bool:D $colour, Bool:D $syntax --> Str:D) # return list-by($prefix, $colour, $syntax, $page-length, $pattern, @fields, %defaults, @_backups, :!sort, :&include-row, :&head-value, :&head-between, :&field-value, :&between, :&row-formatting); } #`««« sub list-editors-backups(Str:D $prefix, Bool:D $colour is copy, Bool:D $syntax, Regex:D $pattern, Int:D $page-length --> Bool:D) is export »»» ``` [Top of Document](#table-of-contents) #### An Example of the above code **`list-editors-backups(…)`** at work: ![image not available here go to the github page](/docs/images/sc-list-editors-backups.png) [Top of Document](#table-of-contents) ## The default callbacks ### The hash of hashes stuff ``` sub default-include-row(Str:D $prefix, Regex:D $pattern, Str:D $key, Str:D @fields, %row --> Bool:D) is export { return True if $key.starts-with($prefix, :ignorecase) && $key ~~ $pattern; for @fields -> $field { my Str:D $value = ''; with %row{$field} { #`««« if %row{$field} does not exist then a Any will be retured, and if some cases, you may return undefined values so use some sort of guard this is one way to do that, you could use %row{$field}:exists or :!exists or // perhaps. TIMTOWTDI rules as always. »»» $value = ~%row{$field}; } return True if $value.starts-with($prefix, :ignorecase) && $value ~~ $pattern; } return False; } sub default-head-value(Int:D $indx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields --> Str:D) { if $colour { if $syntax { #`««« no real syntax Highlighting here this is a generic function write your own. »»» return t.color(0, 255, 255) ~ $field; } else { return t.color(0, 255, 255) ~ $field; } } else { return $field; } } sub default-field-value(Int:D $idx, Str:D $field, $value, Bool:D $colour, Bool:D $syntax, Str:D @fields, %row --> Str:D) { my Str:D $val = ~($value // ''); #`««« assumming $value is a Str:D; if this asumption is false you will need to wrte your own function to pass to list-by(…) »»» if $colour { if $syntax { #`««« no real syntax Highlighting here this is a generic function write your own. »»» return t.color(0, 0, 255) ~ $val; } else { return t.color(0, 0, 255) ~ $val; } } else { return $val; } } sub default-head-between(Int:D $idx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields --> Str:D) is export { if $idx < @fields.elems { return ' '; } else { return ''; } } sub default-between(Int:D $idx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields, %row --> Str:D) is export { if $idx < @fields.elems { return ' '; } else { return ''; } } sub default-row-formatting(Int:D $cnt, Bool:D $colour, Bool:D $syntax --> Str:D) is export { if $colour { if $syntax { #`««« no real syntax Highlighting here this is a generic function write your own. »»» return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -3; # three heading lines. # return t.bg-color(0, 255, 255) ~ t.bold ~ t.bright-blue if $cnt == -2; return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -1; return (($cnt % 2 == 0) ?? t.bg-yellow !! t.bg-color(0,255,0)) ~ t.bold ~ t.bright-blue; } else { return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -3; return t.bg-color(0, 255, 255) ~ t.bold ~ t.bright-blue if $cnt == -2; return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -1; return (($cnt % 2 == 0) ?? t.bg-yellow !! t.bg-color(0,255,0)) ~ t.bold ~ t.bright-blue; } } else { return ''; } } multi sub default-zip-flags(Str:D $key-name, Str:D @fields --> Hash[Str:D] ) is export { my Str:D %hash = @fields Z=> @fields.map: { '-' }; %hash{$key-name} = '-'; return %hash; } ``` ### The array of hashes stuff ``` sub default-include-row-array(Str:D $prefix, Regex:D $pattern, Int:D $indx, Str:D @fields, %row --> Bool:D) is export { for @fields -> $field { my Str:D $value = ~(%row{$field} // ''); return True if $value.starts-with($prefix, :ignorecase) && $value ~~ $pattern; } return False; } sub default-head-value-array(Int:D $indx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields --> Str:D) { if $colour { if $syntax { #`««« no real syntax Highlighting here this is a generic function write your own. »»» return t.color(0, 255, 255) ~ $field; } else { return t.color(0, 255, 255) ~ $field; } } else { return $field; } } sub default-field-value-array(Int:D $idx, Str:D $field, $value, Bool:D $colour, Bool:D $syntax, Str:D @fields, %row --> Str:D) { my Str:D $val = ~($value // ''); #`««« assumming $value is a Str:D; if this asumption is false you will need to wrte your own function to pass to list-by(…) »»» if $colour { if $syntax { #`««« no real syntax Highlighting here this is a generic function write your own. »»» return t.color(0, 0, 255) ~ $val; } else { return t.color(0, 0, 255) ~ $val; } } else { return $val; } } sub default-head-between-array(Int:D $idx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields --> Str:D)
## dist_zef-grizzlysmit-Display-Listings.md ## Chunk 2 of 2 is export { if $idx < @fields.elems { return ' '; } else { return ''; } } sub default-between-array(Int:D $idx, Str:D $field, Bool:D $colour, Bool:D $syntax, Str:D @fields, %row --> Str:D) is export { if $idx < @fields.elems { return ' '; } else { return ''; } } sub default-row-formatting-array(Int:D $cnt, Bool:D $colour, Bool:D $syntax --> Str:D) is export { if $colour { if $syntax { #`««« no real syntax Highlighting here this is a generic function write your own. »»» return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -3; # three heading lines. # return t.bg-color(0, 255, 255) ~ t.bold ~ t.bright-blue if $cnt == -2; return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -1; return (($cnt % 2 == 0) ?? t.bg-yellow !! t.bg-color(0,255,0)) ~ t.bold ~ t.bright-blue; } else { return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -3; return t.bg-color(0, 255, 255) ~ t.bold ~ t.bright-blue if $cnt == -2; return t.bg-color(255, 0, 255) ~ t.bold ~ t.bright-blue if $cnt == -1; return (($cnt % 2 == 0) ?? t.bg-yellow !! t.bg-color(0,255,0)) ~ t.bold ~ t.bright-blue; } } else { return ''; } } multi sub default-zip-flags(Str:D @fields --> Hash[Str:D] ) is export { my Str:D %hash = @fields Z=> @fields.map: { '-' }; return %hash; } ```
## dist_zef-khalidelborai-Resend.md [![Actions Status](https://github.com/khalidelborai/raku-Resend/actions/workflows/test.yml/badge.svg)](https://github.com/khalidelborai/raku-Resend/actions) # NAME Resend - Raku SDK for Resend # SYNOPSIS ``` use Resend; my $resend = Resend.new("YOUR_API_KEY"); say $resend.domains.list; ``` # DESCRIPTION Raku SDK for Resend # AUTHOR khalidelborai [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2023 khalidelborai This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## para.md class Pod::Block::Para Paragraph in a Pod document ```raku class Pod::Block::Para is Pod::Block { } ``` Class for a Pod paragraph.
## dist_github-FCO-Math-PascalTriangle.md [![Build Status](https://travis-ci.org/FCO/Math-PascalTriangle.svg?branch=master)](https://travis-ci.org/FCO/Math-PascalTriangle) # Math-PascalTriangle Simple Pascal's Triangle module
## os.md role X::OS Error reported by the operating system ```raku role X::OS { has $.os-error } ``` Common role for all exceptions that are triggered by some error reported by the operating system (failed IO, system calls, fork, memory allocation). # [Methods](#role_X::OS "go to top of document")[§](#Methods "direct link") ## [method os-error](#role_X::OS "go to top of document")[§](#method_os-error "direct link") ```raku method os-error(--> Str:D) ``` Returns the error as reported by the operating system.
## dist_zef-lizmat-DateTime-strftime.md [![Actions Status](https://github.com/lizmat/DateTime-strftime/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/DateTime-strftime/actions) [![Actions Status](https://github.com/lizmat/DateTime-strftime/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/DateTime-strftime/actions) [![Actions Status](https://github.com/lizmat/DateTime-strftime/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/DateTime-strftime/actions) # NAME DateTime::strftime - provide strftime() formatting for DateTime objects # SYNOPSIS ``` use DateTime::strftime; say strftime(DateTime.now, '%c'); # default": EN # Sun Jan 19 13:19:02 +0100 2025 say strftime(DateTime.now, '%c', "NL"); # zon 19 jan 13:19:02 +0100 2025 ``` # DESCRIPTION The `DateTime::strftime` distribution provides a `strftime` subroutine that takes a `DateTime` object, a [`strftime`](https://linux.die.net/man/3/strftime) format string (or its `:text:` equivalent), and an optional locale indicator (which defaults to the dynamic variable `$*LOCALE-DATES` or `"EN"`). It returns the representation of the `DateTime` object according to that format and locale. # FORMAT SPECIFICATION The supported formats are a (large) subset of `strftime`. The `E` and `O` modifiers are **not** supported. Since the `strftime` format codes are rather cryptic (although very widely in use), one can also use an alternate `:text:` format. So instead of the rather cryptic `"%c"`, one can also use `":datetime:"`. | Code | :text: | Value | | --- | --- | --- | | %a | wkdname | abbreviated weekday name | | %A | weekdayname | full weekday name | | %b | mnthname | abbreviated month name | | %B | monthname | full month name | | %c | datetime | preferred date/time representation | | %C | century | century number (year div 100) | | %d | 0day | day of month ("01" .. "31") | | %D | usadate | short for: %m/%d/%y | | %e | day | day of month (" 1" .. "31") | | %f | | same as %M | | %F | isodate | short for: %Y/%m/%d | | %g | weekYY | YY of this week ("00" .. "99") | | %G | weekYYYY | full year of this week | | %h | | same as %b | | %H | 0hour | 24-hour hour ("00" .. "23") | | %I | 0amhour | 12-hour hour ("01" .. "12") | | %j | yearday | day of the year ("001" .. "366") | | %k | hour | 24-hour hour (" 1" .. "23") | | %l | amhour | 12-hour hour (" 1" .. "12") | | %L | | same as %Y | | %m | month | month ("01" .. "12") | | %M | minute | minute ("00" .. "59") | | %n | newline | "\n" | | %p | AMPM | "AM" | "PM" | | %P | ampm | "am" | "pm" | | %r | amtime | short for: %I:%M:%S %p | | %R | HHMM | short for: %H:%M | | %s | epoch | seconds since epoch (midnight 1970-01-01 UTC) | | %S | second | second ("00" .. "59") | | %t | tab | "\t" | | %T | HHMMSS | short for: %H:%M:%S | | %u | weekday | weekday (1 .. 7) | | %U | weekSun | week number (first Sunday) ("00" .. "53") | | %v | DD-MON-YYYY | short for: %e-%b-%Y | | %V | weekISO | week number (ISO 8601) ("00" .. "53") | | %w | 0weekday | weekday (0 .. 6) | | %W | weekMon | week number (first Monday) ("00" .. "53") | | %x | date | preferred date representation | | %X | time | preferred time representation | | %y | YY | year without century ("00" .. "99") | | %Y | year | year (yyyy) | | %z | tzoffset | numeric timezone (±HHMM) | | %Z | timezone | timezone (no name: %z) | | %+ | unixdate | short for: %a %b %e %T %Z %Y | | %% | percent | "%" | Please note that one probably shouldn't use the `%g` and `%y` formats for anything that is persistent. Data and programs stay around longer then anybody expects, and we don't want another [Y2K](https://en.wikipedia.org/wiki/Year_2000_problem) problem, especially in a 100-year programming language! # DEFAULT LOCALIZATION ``` my $*LOCALE-DATES = "NL"; say strftime($dt, ':weekdayname:'); # zondag say strftime($dt, ':weekdayname:', "EN"); # Sunday ``` The `$*LOCALE-DATES` dynamic variable can be set with the string of the desired localization, or with an instantiated `Locale::Dates` object. It will then affect any call to `strftime` that does **not** have an explicit localization specified. # LEXICAL REFINEMENT ``` use DateTime::strftime :refine; say DateTime.now.strftime('%c'); # default": EN # Sun Jan 19 13:19:02 +0100 2025 say DateTime.now.strftime(':datetime:', "NL"); # zon 19 jan 13:19:02 +0100 2025 ``` You can also use `DateTime::strftime` with the `:refine` parameter. This will add a `strftime` method to the `DateTime` class in the lexical scope in which the `use` statement is located. This allows one to not to have to change existing code using the `DateTime` class, while still having the added functionality of a `DateTime.strftime` method. # OTHER SOFTWARE See also Jean Forget's [`Date::Calendar::Strftime`](https://raku.land/zef:jforget/Date::Calendar::Strftime) and [`Date::Calendar::Gregorian`](https://raku.land/zef:jforget/Date::Calendar::Gregorian). # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/DateTime-strftime> . Comments and Pull Requests are welcome. If you like this module, or what I'm doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-ppentchev-Test-Deeply-Relaxed.md # NAME Test::Deeply::Relaxed - Compare two complex data structures loosely # SYNOPSIS ``` use Test; use Test::Deeply::Relaxed; is-deeply-relaxed 'foo', 'foo'; isnt-deeply-relaxed 'foo', 'bar'; is-deeply-relaxed 5, 5; isnt-deeply-relaxed 5, '5'; is-deeply-relaxed [1, 2, 3], Array[Int:D].new(1, 2, 3); is-deeply-relaxed {:a("foo"), :b("bar")}, Hash[Str:D].new({ :a("foo"), :b("bar") }); # And now for the one that made me write this... my Array[Str:D] %opts; %opts<v> = Array[Str:D].new("v", "v"); %opts<i> = Array[Str:D].new("foo.txt", "bar.txt"); is-deeply-relaxed %opts, {:v([<v v>]), :i([<foo.txt bar.txt>]) }; # It works with weirder types, too is-deeply-relaxed bag(<a b a a>), { a => 3, b => 1 }.Mix; isnt-deeply-relaxed bag(<a b a a>), { a => 2, b => 1 }.Mix; isnt-deeply-relaxed bag(<a b a a>), { a => 3, b => 1.5 }.Mix; ``` # DESCRIPTION The `Test:::Deeply::Relaxed` module provides the `is-deeply-relaxed()` and `isnt-deeply-relaxed()` functions that do not check the state of mind of the passed objects, but instead compare their structure in depth similarly to `is-deeply()`, but a bit more loosely. In particular, they ignore the differences between typed and untyped collections, e.g. they will consider an array and an explicit `Array[Str:D]` to be the same if the strings contained within are indeed the same. # FUNCTIONS * sub is-deeply-relaxed ``` sub is-deeply-relaxed($got, $expected, $name = Str, Bool:D :$cache = False) ``` Compare the two data structures in depth similarly to `is-deeply()`, but a bit more loosely. If the `:cache` flag is specified, the cache of values will be used for any iterable objects that support it. This allows the caller to later examine the sequences further. Current API available since version 0.1.0. * sub isnt-deeply-relaxed ``` sub isnt-deeply-relaxed($got, $expected, $name = Str, Bool:D :$cache = False) ``` The opposite of `is-deeply-relaxed()` - fail if the two structures are loosely the same. Current API available since version 0.1.0. # AUTHOR Peter Pentchev <[[email protected]](mailto:[email protected])> # COPYRIGHT Copyright (C) 2016, 2017 Peter Pentchev # LICENSE The Test::Deeply::Relaxed module is distributed under the terms of the Artistic License 2.0. For more details, see the full text of the license in the file LICENSE in the source distribution.
## dist_zef-rawleyfowler-Humming-Bird-Core.md # Humming-Bird ![Zef Badge](https://raku.land/zef:rawleyfowler/Humming-Bird/badges/version?) [![SparrowCI](https://ci.sparrowhub.io/project/gh-rawleyfowler-Humming-Bird/badge)](https://ci.sparrowhub.io) **Here be dragons**: Humming-Bird is still young, you may run into bugs, creatures, and daemons, if you run into any issues, please make an [issue](https://github.com/rawleyfowler/Humming-Bird/issues)! Humming-Bird is a simple, composable, and performant, all in one HTTP web-framework for Raku. Humming-Bird was inspired mainly by [Opium](https://github.com/rgrinberg/opium), [Sinatra](https://sinatrarb.com), and [Express](https://expressjs.com), and tries to keep things minimal, allowing the user to pull in things like templating engines, and ORM's on their own terms. Humming-Bird comes with what you need to quickly, and efficiently spin up REST API's, and with a few of the users favorite libraries, dynamic MVC style web-apps. Humming-Bird is not meant to face the internet directly. Please use a reverse proxy such as httpd or NGiNX. ## Examples #### Simple example: ``` use v6.d; use Humming-Bird::Core; get('/', -> $request, $response { $response.html('<h1>Hello World</h1>'); }); listen(8080); # Navigate to localhost:8080! ``` #### Simple JSON example: ``` use v6; use Humming-Bird::Core; my %users = Map.new('bob', '{ "name": "bob" }', 'joe', '{ "name": "joe" }'); get('/users/:user', -> $request, $response { my $user = $request.param('user'); if %users{$user}:exists { $response.json(%users{$user}); } else { $response.status(404); } }); listen(8080); ``` #### Middleware ``` use v6.d; use Humming-Bird::Core; use Humming-Bird::Middleware; get('/logged', -> $request, $response { $response.html('This request has been logged!'); }, [ &middleware-logger ]); # &middleware-logger is provided by Humming-Bird::Middleware # Custom middleware sub block-firefox($request, $response, &next) { return $response.status(400) if $request.header('User-Agent').starts-with('Mozilla'); $response.status(200); } get('/no-firefox', -> $request, $response { $response.html('You are not using Firefox!'); }, [ &middleware-logger, &block-firefox ]); # Scoped middleware # Both of these routes will now share the middleware specified in the last parameter of the group. group([ &get.assuming('/', -> $request, $response { $response.write('Index'); }), &post.assuming('/users', -> $request, $response { $response.write($request.body).status(204); }) ], [ &middleware-logger, &block-firefox ]); ``` More examples can be found in the [examples](https://github.com/rawleyfowler/Humming-Bird/tree/main/examples) directory. ## Design * Humming-Bird should be easy to pickup, and simple for developers new to Raku and/or web development. * Humming-Bird is not designed to be exposed to the internet directly. You should hide Humming-Bird behind a reverse-proxy like NGiNX or httpd. * Simple and composable via middlewares. ## Things to keep in mind * This project is in active development, things will break. * You may run into bugs. * **Not** production ready, yet. ## How to install Make sure you have [zef](https://github.com/ugexe/zef) installed. #### Install latest ``` zef -v install https://github.com/rawleyfowler/Humming-Bird.git ``` #### Install stable ``` zef install Humming-Bird ``` ## Contributing All contributions are encouraged! I know the Raku community is amazing, so I hope to see some people get involved :D Please make sure you squash your branch, and name it accordingly before it gets merged! ## License Humming-Bird is available under the MIT, you can view the license in the `LICENSE` file at the root of the project. For more information about the MIT, please click [here](https://mit-license.org/).
## dist_zef-finanalyst-Collection-Raku-Documentation.md # Collection-based Raku Documentation > **Description** Distribution to set up Raku Documentation website. > **Author** Richard Hainsworth, aka finanalyst --- ## Table of Contents [Installation](#installation) [Raku-Doc](#raku-doc) [Raku-Doc as a wrapper for Collection::collect](#raku-doc-as-a-wrapper-for-collectioncollect) [More contemporary web site.](#more-contemporary-web-site) [In the future (not now)](#in-the-future-not-now) [Enabling Cro App](#enabling-cro-app) [Highlighting](#highlighting) [Problems](#problems) [Copyright and License](#copyright-and-license) --- This Module creates a local website of the Raku documentation. It pulls together information held in several other distributions. The main content of this distribution is the `Raku-Doc` utility. It is intended to be as simple as possible. But the documentation system is large. The following contain other requirements. * The documentation files are held in a github repository that is maintained and updated by the Raku community. `Raku-Doc` needs to have a local clone of the repository. It can be used to refresh the documents automatically. * `Raku-Doc` uses Collection and Raku::Pod::Render to link all the Rakudoc (aka Pod6) files together. So `Collection` needs to be installed, which will install `Raku::Pod::Render`. By installing `Raku-Pod-Render` a user can then use `Pod::To::HTML2` to render individual `.rakudoc / .pod6` files into HTML, or `Pod::To::MarkDown2` to render them into `.md` files. * `Collection` requires over a dozen plugins, which are automatically refreshed from a github repository by `Raku-Doc`. * The Raku documentation system can currently be visualised in two ways: * using the original web design started by Moritz Lenz (using the mode Website) - currently the default. * using a new design by OgdenWebb (using the mode OgdenWebb). * The website is intended to be served locally with a Cro app. Since making Cro a dependency can cause problems in a testing environment, the META6.json does not have Cro as a dependency. If Cro::HTTP is not installed, the completion plugin will exit with a note. * A website contains templates and structure documents, which describe the website into which the Raku documentation fit. This content is also held in a separate repository. This is intended to keep the development of plugins separate from the structure documents and templates, and separate from the Raku documentation content. # Installation ``` zef install Collection-Raku-Documentation ``` This installs the `Collection` (and other) dependencies and the `Raku-Doc` executable. These in turn install the the other main distributions and `Raku::Pod::Render`. By default `Raku::Pod::Render` does not install the highlighter automatically because `node.js` and `npm` are required. See [Highlighting](Highlighting.md) for installation of highlighter. # Raku-Doc On a Linux based distributions, `Raku-Doc` depends on `git` and `unzip`, which typically are installed by default, to get and unpack other files. Under Linux, in a terminal, the following will lead to the installation of a local copy of Raku docs and start a Cro app that will make the HTML documentation available in a browser at `localhost:30000`, and produce a progress status bar for the longer stages. ``` mkdir ~/raku-collection cd raku-collection Raku-Doc Init ``` This sets up a Collection directory by downloading the Website mode from github, then installs the Collection plugins. By default the `Raku/doc` repository (containing all the Raku documentation files) will be created in the next step as **local\_raku\_docs**. If a user wants to clone the Raku docs repository elsewhere or has an existing clone of the Raku repository, then the non-default path needs to be put into the config.raku file in the `sources-obtain` and `sources-refresh` keys. See the documentation for the `Collection` distribution for more information. At the next invocation of **Raku-Doc**, the documentation source will be cloned, cached, and rendered. For example, to render the full Raku Docs, the following would work, where `raku-local` is a local directory. ``` - raku-collection - local_raku_docs # this is generated by the git clone command - Website # this is generated by runnng 'Raku-Doc Init' in raku-collection config.raku # as Website ``` After the `Init` stage, calling `Raku-Doc` without any other options implies the mode **Website** with default options. The Raku Documentation source files are regularly updated. The **Website** mode is configured to pull the latest versions of the source files into the Collection whenever `Raku-Doc` is run, which then updates the cache for any sources that have changed, and then re-render all the html files that are affected. These stages are automatically called by running Raku-Doc with the config defaults given. The Website mode files and plugins are being actively developed, so newer versions may be available. New versions of the plugins are automatically called on each invocation of Raku-Doc. To get new versions of the Website mode files (sources and additional plugins), use ``` Raku-Doc Update ``` `Raku-Doc` can be called with other options, which are described in the `Collection` documentation. **Collection-Raku-Documentation** is set up with the default `mode` called **Website**. The more contemporary web design by Ogden Webb is in a mode call **OgdenWebb**. It is generated thus: ``` Raku-Doc OgdenWebb ``` It can be made the default by changing the `mode` key in the top-level `config.raku` file. # Raku-Doc as a wrapper for Collection::collect With the exception of 'Init' and 'Update', `Raku-Doc` can be called with all the options listed for `Collection::collect`. More information about these options is given in the Documentation for `Collection`. ## More contemporary web site. A more contemporary web design by Ogden Webb is now included. It is generated by running ``` Raku-Doc OgdenWebb ``` ## In the future (not now) If `Raku-Doc` is called with a string other than 'Init' or 'Website', then the string is interpreted as another **Mode**, with its own sub-directory and [Configuration](Configuration.md) for the collection. For example, ``` Raku-Doc Book ``` would create the collection output defined by the configuration in the sub-directory `Book/config/`. This design is to allow for the creation of different Collection outputs to be defined for the same content files. # Enabling Cro App A Cro App is included that will run the website automatically by running `Raku-Doc`. The Cro App is called using a plugin that runs after the html files have been refreshed. The Cro App is called at completion (see Collection documentation). It contains a test to see if Cro::HTTP is installed. Since installing Cro can cause testing problems, this distribution does not have Cro::HTTP as a dependency. Cro in installed using zef as ``` zef install Cro::HTTP ``` Running `Raku-Doc` without options will now serve the documentation files locally on port 3000. So point your browser at `localhost:3000` # Highlighting The default highlighter at present is a Node based toolstack called **atom-perl-highlighter**. In order to install it automatically, `Raku::Pod::Render` requires an uptodate version of npm. The builder is known not to work with `node.js` > \*\*\*\*v13.0> and `npm` > **v14.15**. For someone who has not installed `node` or `npm` before, or for whom they are only needed for the highlighter, the installation is ... confusing. It would seem at the time of writing that the easiest method is: ``` # Using Ubuntu curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash - sudo apt-get install -y nodejs ``` Then, **after the default installation of Raku::Pod::Render**, highlighting can be enabled by running the following in a terminal: ``` raku-render-install-highlighter ``` # Problems Collection is still being actively developed. * When running `Raku-Doc` with a `sources-refresh` key set to a git pull stanza, Raku-Doc teminates after a git pull. Workaround: run `Raku-Doc` again. # Copyright and License (c) Richard N Hainsworth, 2021-2022 **LICENSE** Artistic-2.0 --- Rendered from README at 2023-01-14T10:19:05Z
## dist_zef-khalidelborai-SOD.md # TITLE SOD # SUBTITLE Raku bindings for the SOD image processing library # DESCRIPTION SOD is an embedded, modern cross-platform computer vision and machine learning software library that exposes a set of APIs for deep-learning, advanced media analysis & processing including real-time, multi-class object detection and model training on embedded systems with limited computational resource and IoT devices. # CLASSES ## Image An `Image` class representing an image that can be manipulated. ### Attributes * * CImage $.cimage - underlying CImage structure ### Class Methods * *load* `load(Str $filename, Int :$channels = 3 --> Image)` Load an image from file with a specified number of channels * *load\_gray* `load_gray(Str $filename --> Image)` Load an image from file in grayscale (single channel) * *empty* `empty(:w($width), :h($height), :c($channels) = 3 --> Image)` Create an empty image with given dimensions and number of channels * *zeros* `zeros(:w($width), :h($height), :c($channels) = 3 --> Image)` Create an image filled with zeros with given dimensions and number of channels * *random* `random(:w($width), :h($height), :c($channels) = 3 --> Image)` Create a random image with given dimensions and number of channels ### Instance Methods * *copy* `copy(--> Image)` Copy the current image * *clone* `clone(--> Image)` Clone the current image (alias for copy) * *save\_png* `save_png(Str $filename --> uint8)` Save the current image as a PNG file * *save\_jpeg* `save_jpeg(Str $filename, Int() $quality --> uint8)` Save the current image as a JPEG file with specified quality * *save\_bmp* `save_bmp(Str $filename --> uint8)` Save the current image as a BMP file * *set\_pixel* `set_pixel($x, $y, $c, Num() $v)` Set the pixel value at the specified coordinates and channel * *get\_pixel* `get_pixel($x, $y, $c)` Get the pixel value at the specified coordinates and channel * *resize* `resize(Int() $w, Int() $h --> Image)` Resize the current image to the specified dimensions * *resize\_max* `resize_max(Int() $max --> Image)` Resize the current image such that the maximum dimension is equal to $max * *resize\_min* `resize_min(Int() $min --> Image)` Resize the current image such that the minimum dimension is equal to $min * *rotate\_crop* `rotate_crop(Num() :a($angle), Scale() :s($scale), Int() :w($width), Int() :h($height), Int() :x($dx), Int() :y($dy), Num() :as($aspect) --> Image)` Rotate and crop the current image * *translate* `translate(Scale() $scale --> Image)` Translate the current image by the specified scale * *scale* `scale(Scale() $scale --> Image)` Scale the current image by the specified scale * *normalize* `normalize(--> Image)` Normalize the current image * *transpose* `transpose(--> Image)` Transpose the current image * *rotate* `rotate(Num() $angle --> Image)` Rotate the current image by the specified angle * *box* `box(Int() $x1, Int() $y1, Int() $x2, Int() $y2, Num() $r, Num() $g, Num() $b --> Image)` Draw a box on the current image with specified coordinates and color * *bbox* `bbox(Box $box, Num() $r, Num() $g, Num() $b --> Image)` `bbox(Box $box, Num() $r, Num() $g, Num() $b, Int() $width --> Image)` Draw a bounding box on the current image with specified box, color, and optional width * *box\_grayscale* `box_grayscale(Int() $x1, Int() $y1, Int() $x2, Int() $y2, Num() $v --> Image)` Draw a box on the current image with specified coordinates and grayscale value * *circle* `circle(Int() $x, Int() $y, Int() $r, Num() $red, Num() $green, Num() $blue --> Image)` `circle(Int() $x, Int() $y, Int() $radius,Int() $thickness, Num() $r, Num() $g,Num() $b, --> Image)` Draw a circle on the current image with specified coordinates, radius, color, and optional thickness. * *crop* `crop(Int() $x, Int() $y, Int() $w, Int() $h --> Image)` Crop the current image with specified coordinates and dimensions * *random\_crop* `random_crop(Int() $w, Int() $h --> Image)` Randomly crop the current image with specified dimensions * *random\_augment* `random_augment(Num() $angel, Num() $aspect, Int() $low, Int() $high, Int() $size --> Image)` Randomly augment the current image with specified parameters. * *add\_pixel* `add_pixel(Int() $x, Int() $y, Int() $c, Num() $v --> Image)` Add a constant value to a pixel at the given location. This value must be set between 0..1 such as 0.7. * *rgb\_to\_bgr* `rgb_to_bgr(--> Image)` Change the RGB colorspace of a given image to the BGR colorspace. * *bgr\_to\_rgb* `bgr_to_rgb(--> Image)` Change the BGR colorspace of a given image to the RGB colorspace. * *rgb\_to\_hsv* `rgb_to_hsv(--> Image)` Change the RGB colorspace of a given image to the HSV colorspace. * *hsv\_to\_rgb* `hsv_to_rgb(--> Image)` Change the HSV colorspace of a given image to the RGB colorspace. * *yuv\_to\_rgb* `yuv_to_rgb(--> Image)` Change the YUV colorspace of a given image to the RGB colorspace. * *rgb\_to\_yuv* `rgb_to_yuv(--> Image)` Change the RGB colorspace of a given image to the YUV colorspace. # AUTHOR Khalid Elborai [[email protected]](mailto:[email protected])
## dist_github-cosimo-Cache-Memcached.md # Cache::Memcached [Build Status](https://travis-ci.org/cosimo/perl6-cache-memcached) Perl6 client for [memcached](http://www.danga.com/memcached/) a distributed caching daemon. ## Synopsis ``` use Cache::Memcached; my $memd = Cache::Memcached.new; $memd.set("my_key", "Some value"); $memd.incr("key"); $memd.decr("key"); $memd.incr("key", 2); ``` Or you can use it as an Associative type: ``` use Cache::Memcached; my $memd = Cache::Memcached.new; $memd<my_key> = "Some value"; say $memd<my_key>; $memd<my_key>:delete; ``` ## Description This provides an interface to the [memcached](http://www.danga.com/memcached/) daemon. You will need to have access to a memcached server to be able to use it. Currently there is no support for compression or the serialization of structured objects (though both could be provided by the agency of external modules.) ## Installation Assuming you have a working Rakudo Perl 6 installation you should be able to install this with *zef* : ``` # From the source directory zef install . # Remote installation zef install Cache::Memcached ``` There should be no reason that it won't work with any new installer that may come along in the future. ## Support Suggestions/patches are welcomed via github at <https://github.com/cosimo/perl6-cache-memcached/issues>
## dist_github-jaffa4-Path-Util.md # pathutil Path::Util Break up a file path into its components. Usage: use Path::Util; my $p = Path::Util.new("d:\docs\usage.txt"); It can break-up Unix like or Dos like file paths. say $p.getdrive; or say $p.drive; # it gets the drive letter, for Windwos only. Otherwise, it returns "". say $p.getdir; or say $p.directory; or say $p.dir say $p.getext; or say $p.extension say $p.getbasename; # returns the filename without directory say $p.getjustname; # returns the filename without directory and extension Above also work without get. say $p.print; # prints all components say $p.separator; # returns the separator found in the path, it can be "" or "/" or "". say $p.fsseparator; # returns Windows or Unix-like file separator depending where you run your script say $p.getnumberofdirlevel; # number of levels in the directory say $p.getdirlevel(2); # returns directory up to the second level say $p.tocygwin(); # returns the cygwin format of a Windows path, nothing happens if it is of other kind. e.g. /cygdrive/d/music/after.mp4 say $p.tomsys(); # returns the msysformat of a Windows path, nothing happens if it is of other kind. e.g. /d/music/after.mp4 Also, it is possible to use them non-object oriented way. say Path::Util.getbasename("d:\docs\usage.txt"); Extension is returned without dot. Directories are returned without ending separator.
## dist_zef-FCO-Acme-Overreact.md [![Actions Status](https://github.com/FCO/Acme-Overreact/actions/workflows/test.yml/badge.svg)](https://github.com/FCO/Acme-Overreact/actions) # NAME Acme::Overreact - Make your code overreact # SYNOPSIS ``` use Acme::Overreact; CHECK overreact; say 42; # prints '42!!!' ``` # DESCRIPTION Acme::Overreact is just a joke, please do not use that in production code # AUTHOR Fernando Corrêa de Oliveira [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2024 Fernando Corrêa de Oliveira This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-elcaro-Exportable.md # NAME Exportable - Simple function exporting # SYNOPSIS Import in module code, and apply trait to exportable subs. Tags work normally ``` use Exportable; module Foo { our sub foo is exportable { ... } our sub bar is exportable(:b) { ... } our sub baz is exportable(:b) { ... } our sub qux { ... } } ``` Module users can now import subs by name... ``` use Foo <foo bar baz>; ``` or with tags... ``` use Foo :b; # 'foo' not imported ``` # DESCRIPTION `Exportable` makes it simple to explicitly declare exportable functions from your module. There's already an `export` sub trait, but it pollute the users namespace. The `exportable` trait is almost identical, except it does not export by default. There's no need to write the function name a second time, and/or write your own complicated `EXPORT` sub. This module is fairly sparse in what it does on purpose, but if you think there is a glaring omission, raise an issue. # CAVEATS Due to how this module works, it must be imported outside the module scope. Typically this is done either above a `Module` block (as shown in the SYNOPSIS), or above a unit scoped module. ``` use Exportable; unit module Foo; our sub foo is exportable { ... } our sub bar is exportable(:b) { ... } ``` On a side note, declaring public facing subs as `our` scoped is a courtesy to users who may not wish to import any functions, and instead use the fully-qualified name, eg. `Foo::bar()`. # ADDENDUM This module was written after a wrote a [blog post](https://0racle.info/articles/exportation_exploration) talking about the function exporting in Raku. Special thanks goes to [FCO](https://github.com/FCO), who helped by figuring out most the core in this module.
## dist_github-Skarsnik-Linux-Proc-Statm.md # Name Linux::Proc::Statm # Usage ``` use Linux::Proc::Statm; my %meminfo = get-statm(42); #get info for the pid 42 say %meminfo<data>; # data + stack size say get-statm.perl; #use $*PID say get-statm-human<data>; # 54.552 kB ``` Values are given in Kb by default. You can change this behavior by passing a `:unit` named parameter with etheir b, k or m according to the unit you want. ``` say get-statm-human(:unit<m>)<data>; # 53 mB ``` # Author Sylvain "Skarsnik" Colinet [[email protected]](mailto:[email protected])
## dist_zef-jjmerelo-Algorithm-Evolutionary-Simple.md [![Test-install and cache deps](https://github.com/JJ/p6-algorithm-evolutionary-simple/actions/workflows/test.yaml/badge.svg)](https://github.com/JJ/p6-algorithm-evolutionary-simple/actions/workflows/test.yaml) # NAME Algorithm::Evolutionary::Simple - A simple evolutionary algorithm # SYNOPSIS ``` use Algorithm::Evolutionary::Simple; # From resources/examples/max-ones.p6 my UInt :$length = 64; my UInt :$population-size = 256; my @initial-population = initialize( size => $population-size, genome-length => $length ); my %fitness-of; my $population = evaluate( population => @initial-population, fitness-of => %fitness-of, evaluator => &max-ones ); my $result = 0; while $population.sort(*.value).reverse.[0].value < $length { $population = generation( population => $population, fitness-of => %fitness-of, evaluator => &max-ones, population-size => $population-size) ; $result += $population-size; info(to-json( { best => best-fitness($population) } )); } say $result ``` # DESCRIPTION `Algorithm::Evolutionary::Simple` is a module for writing simple and quasi -canonical evolutionary algorithms in Raku. It uses binary representation, integer fitness (which is needed for the kind of data structure we are using) and a single fitness function. It is intended mainly for demo purposes, although it's been actually used in research. In the future, more versions will be available. It uses a fitness cache for storing and not reevaluating already seen chromosomes, so be mindful of memory bloat. # EXAMPLES Go to [`resources/examples`](resources/examples) for examples. For instance , run `max-ones.p6` or `p-peaks.p6` there. You'll need to run ``` zef install --deps-only . ``` To install needed modules in that directory. # METHODS ## initialize( UInt :$size, UInt :$genome-length --> Array ) is export Creates the initial population of binary chromosomes with the indicated length; returns an array. ## random-chromosome( UInt $length --> List ) Generates a random chromosome of indicated length. Returns a `Seq` of `Bool`s ## max-ones( @chromosome --> Int ) Returns the number of trues (or ones) in the chromosome. ## leading-ones( @chromosome --> Int ) Returns the number of ones from the beginning of the chromosome. ## royal-road( @chromosome ) That's a bumpy road, returns 1 for each block of 4 which has the same true or false value. ## multi evaluate( :@population, :%fitness-of, :$evaluator, :$auto-t = False --> Mix ) is export Evaluates the chromosomes, storing values in the fitness cache. If `auto-t` is set to 'True', uses autothreading for faster operation (if needed). In absence of that parameter, defaults to sequential. ## sub evaluate-nocache( :@population, :$evaluator --> Mix ) Evaluates the population, returning a Mix, but does not use a cache. Intended mainly for concurrent operation. ## get-pool-roulette-wheel( Mix $population, UInt $need = $population.elems ) is export Returns `$need` elements with probability proportional to its *weight*, which is fitness in this case. ## mutation( @chromosome is copy --> Array ) Returns the chromosome with a random bit flipped. ## crossover ( @chromosome1 is copy, @chromosome2 is copy ) returns List Returns two chromosomes, with parts of it crossed over. Generally you will want to do crossover first, then mutation. ## produce-offspring( @pool, $size = @pool.elems --> Seq ) is export Produces offspring from an array that contains the reproductive pool; it returns a `Seq`. ## produce-offspring-no-mutation( @pool, $size = @pool.elems --> Seq ) is export Produces offspring from an array that contains the reproductive pool without using mutation; it returns a `Seq`. ## best-fitness( $population ) Returns the fitness of the first element. Mainly useful to check if the algorithm is finished. ## multi sub generation( :@population, :%fitness-of, :$evaluator, :$population-size = $population.elems, Bool :$auto-t --> Mix ) Single generation of an evolutionary algorithm. The initial `Mix` has to be evaluated before entering here using the `evaluate` function. Will use auto-threading if `$auto-t` is `True`. ## multi sub generation( :@population, :%fitness-of, :$evaluator, :$population-size = $population.elems, Bool :$no-mutation --> Mix ) Single generation of an evolutionary algorithm. The initial `Mix` has to be evaluated before entering here using the `evaluate` function. Will not use mutation if that variable is set to `True` ## sub generations-without-change( $generations, $population ) Returns `False` if the number of generations in `$generations` has not been reached without changing; it returns `True` otherwise. ## mix( $population1, $population2, $size --> Mix ) is export Mixes the two populations, returning a single one of the indicated size and with type Mix. ## sub pack-individual( @individual --> Int ) Packs the individual in a single `Int`. The invidual must be binary, and the maximum length is 64. ## sub unpack-individual( Int $packed, UInt $bits --> Array(Seq)) Unpacks the individual that has been packed previously using `pack-individual` ## sub pack-population( @population --> Buf) Packs a population, producing a buffer which can be sent to a channel or stored in a compact form. ## sub unpack-population( Buf $buffer, UInt $bits --> Array ) Unpacks the population that has been packed using `pack-population` ## multi sub frequencies( $population) `$population` can be an array or a Mix, in which case the keys are extracted. This returns the per-bit (or gene) frequency of one (or True) for the population. ## multi sub frequencies-best( $population, $proportion = 2) `$population` is a Mix, in which case the keys are extracted. This returns the per-bit (or gene) frequency of one (or True) for the population of the best part of the population; the size of the population will be divided by the $proportion variable. ## sub generate-by-frequencies( $population-size, @frequencies ) Generates a population of that size with every gene according to the indicated frequency. ## sub crossover-frequencies( @frequencies, @frequencies-prime --> Array ) Generates a new array with random elements of the two arrays that are used as arguments. # SEE ALSO There is a very interesting implementation of an evolutionary algorithm in [Algorithm::Genetic](https://github.com/samgwise/p6-algorithm-genetic). Check it out. This is also kind of a port of [Algorithm::Evolutionary::Simple to Perl6](https ://metacpan.org/release/Algorithm-Evolutionary-Simple), which has a few more goodies, but it's not simply a port, since most of the code is completely different. # AUTHOR JJ Merelo [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2022 JJ Merelo This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-ramiroencinas-FileSystem-Capacity.md # FileSystem::Capacity [![Build Status](https://travis-ci.org/ramiroencinas/perl6-FileSystem-Capacity.svg?branch=master)](https://travis-ci.org/ramiroencinas/perl6-FileSystem-Capacity) Provides filesystem capacity information. Currently implements: ## Filesystem volumes size and free space: * GNU/Linux by df command. * Win32 by wmic command. * OS X by df command. ## Size of given Directory: * GNU/Linux by du command. * Win32. ## Installing the module ``` zef update zef install FileSystem::Capacity ``` ## Example Usage: ``` use v6; use FileSystem::Capacity::VolumesInfo; use FileSystem::Capacity::DirSize; say "Volumes Capacity Info:"; say "----------------------\n"; say "Byte version:\n"; my %vols = volumes-info(); for %vols.sort(*.key)>>.kv -> ($location, $data) { say "Location: $location"; say "Size: $data<size> bytes"; say "Used: $data<used> bytes"; say "Used%: $data<used%>"; say "Free: $data<free> bytes"; say "---"; } say "----"; say "Human version:\n"; my %vols-human = volumes-info(:human); for %vols-human.sort(*.key)>>.kv -> ($location, $data) { say "Location: $location"; say "Size: $data<size>"; say "Used: $data<used>"; say "Used%: $data<used%>"; say "Free: $data<free>"; say "---"; } my $dir; given $*KERNEL { when /linux/ { $dir = '/bin' } when /win32/ { $dir = 'c:\windows' } } say "\n\nDirectory Size of $dir:"; say "-----------------\n"; say " Byte version: " ~ dirsize($dir) ~ " bytes"; say "Human version: " ~ dirsize($dir, :human) ~ "\n"; ```
## argfiles.md class IO::ArgFiles Iterate over contents of files specified on command line ```raku class IO::ArgFiles is IO::CatHandle { } ``` This class exists for backwards compatibility reasons and provides no additional methods to [`IO::CatHandle`](/type/IO/CatHandle), so it can be used in the same way as it, for instance, in this way: ```raku my $argfiles = IO::ArgFiles.new(@*ARGS); .say for $argfiles.lines; ``` If invoked with `raku io-argfiles.raku *.raku` it will print the contents of all the files with that extension in the directory. However, that is totally equivalent to: ```raku my $argfiles = IO::CatHandle.new(@*ARGS); .say for $argfiles.lines; ``` # [Variables](#class_IO::ArgFiles "go to top of document")[§](#Variables "direct link") ## [`$*ARGFILES`](#class_IO::ArgFiles "go to top of document")[§](#$*ARGFILES "direct link") This class is the magic behind the `$*ARGFILES` variable, which provides a way to iterate over files passed in to the program on the command line (i.e. elements of [`@*ARGS`](/language/variables#index-entry-%40%2AARGS)). Thus the examples above can be simplified like so: ```raku .say for $*ARGFILES.lines; # or while ! $*ARGFILES.eof { say $*ARGFILES.get; } # or say $*ARGFILES.slurp; ``` Save one of the variations above in a file, say `argfiles.raku`. Then create another file (named, say `sonnet18.txt` with the contents: 「text」 without highlighting ``` ``` Shall I compare thee to a summer's day? ``` ``` Running the command 「text」 without highlighting ``` ``` $ raku argfiles.raku sonnet18.txt ``` ``` will then give the output 「text」 without highlighting ``` ``` Shall I compare thee to a summer's day? ``` ``` As of 6.d language, `$*ARGFILES` *inside* [`sub MAIN`](/language/functions#sub_MAIN) is always set to `$*IN`, even when `@*ARGS` is not empty. That means that ```raku sub MAIN () { .say for $*ARGFILES.lines; } ``` which can be used as `cat *.raku | raku argfiles-main.raku`, for instance, is totally equivalent to: ```raku sub MAIN () { .say for $*IN.lines; } ``` and, in fact, can't be used to process the arguments in the command line, since, in this case, it would result in a usage error. Bear in mind that the object `$*ARGFILES` is going to contain a handle for every argument in a command line, even if that argument is not a valid file. You can retrieve them via the `.handles` method. ```raku for $*ARGFILES.handles -> $fh { say $fh; } ``` That code will fail if any of the arguments is not the valid name of a file. You will have to deal with that case at another level, checking that [`@*ARGS`](/language/variables#index-entry-%40*ARGS) contains valid file names, for instance.
## dist_zef-jonathanstowe-JSON-Infer.md # JSON::Infer Create Raku classes to represent JSON data by some dodgy inference. ![Build Status](https://github.com/jonathanstowe/JSON-Infer/workflows/CI/badge.svg) ## Synopsis Use the script to do it simply: ``` # Create the module in the directory "foo" raku-json-infer --uri=http://api.mixcloud.com/spartacus/party-time/ --out-dir=foo --class-name=Mixcloud::Show ``` Or do it in your own code: ``` use JSON::Infer; my $obj = JSON::Infer.new(); my $ret = $obj.infer(uri => 'http://api.mixcloud.com/spartacus/party-time/', class-name => 'Mixcloud::Show'); say $ret.make-class; # Print the class definition ``` ## Description JSON is nearly ubiquitous on the internet, developers love it for making APIs. However the webservices that use it for transfer of data rarely have a machine readable specification that can be turned into code so developers who want to consume these services usually have to make the client definition themselves. This module aims to provide a way to generate Raku classes that can represent the data from a JSON source. The structure and the types of the data is inferred from a single data item so the accuracy may depend on the consistency of the data. ## Installation Assuming you have a working Rakudo installation you should be able to install this with *zef* : ``` # From the source directory zef install . # Remote installation zef install JSON::Infer ``` Other install mechanisms may be become available in the future. ## Support Suggestions/patches are welcomed via github at <https://github.com/jonathanstowe/JSON-Infer/issues> ## Licence This is free software. Please see the <LICENCE> file in the distribution for details. © Jonathan Stowe 2015, 2016, 2017, 2019, 2020, 2021
## eq.md eq Combined from primary sources listed below. # [In Operators](#___top "go to top of document")[§](#(Operators)_infix_eq "direct link") See primary documentation [in context](/language/operators#infix_eq) for **infix eq**. ```raku multi infix:<eq>(Any, Any) multi infix:<eq>(Str:D, Str:D) ``` String equality operator. Coerces both arguments to [`Str`](/type/Str) (if necessary); returns `True` if both are equal. Mnemonic: *equal*
## dist_zef-lizmat-Object-Trampoline.md [![Actions Status](https://github.com/lizmat/Object-Trampoline/workflows/test/badge.svg)](https://github.com/lizmat/Object-Trampoline/actions) # NAME Raku port of Perl's Object::Trampoline module 1.50.4 # SYNOPSIS ``` # direct object creation my $dbh = DBIish.connect( ... ); my $sth = $dbh.prepare( 'select foo from bar' ); if $need-to-execute { $sth.execute; # execute } else { say "database handle and statement executed without need"; } # with delayed object creation use Object::Trampoline; my $dbh = Object::Trampoline.connect( DBIish, ... ); my $sth = Object::Trampoline.prepare( $dbh, 'select foo from bar' ); if $need-to-execute { $sth.execute; # create $dbh, then $sth, then execute } else { say "no database handle opened or statement executed"; } LEAVE .disconnect with $dbh; # only disconnects if connection was made # alternate setup way, more idiomatic Raku my $dbh = trampoline { DBIish.connect: ... } my $sth = trampoline { $dbh.prepare: 'select foo from bar' } # lazy default values for attributes in objects class Foo { has $.bar = trampoline { say "delayed init"; "bar" } } my $foo = Foo.new; say $foo.bar; # delayed init; bar ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `Object::Trampolinee` module as closely as possible in the Raku Programming Language. There are times when constructing an object is expensive but you are not sure yet you are going to need it. In that case it can be handy to delay the creation of the object. But then your code may become much more complicated. This module allows you to transparently create an intermediate object that will perform the delayed creation of the original object when **any** method is called on it. The original Perl was is to call **any** method on the `Object::Trampoline` class, with as the first parameter the object to call that method on when it needs to be created, and the other parameters the parameters to give to that method then. The alternate, more idiomatic Raku way, is to call the `trampoline` subroutine with a code block that contains the code to be executed to create the final object. This can also be used to serve as a lazy default value for a class attribute. To make it easier to check whether the actual object has been created, you can check for `.defined` or booleaness of the object without actually creating the object. This can e.g. be used when wanting to disconnect a database handle upon exiting a scope, but only if an actual connection has been made (to prevent it from making the connection only to be able to disconnect it). # PORTING CAVEATS Due to the lexical scope of `use` in Raku, it is not really possible to mimic the behaviour of `Object::Trampoline::Use`. Due to the nature of the implementation, it is not possible to use smartmatch (aka `~~`) on a trampolined object. This is because smartmatching a trampolined object does not call any methods on it. Fixing that by using a `Proxy` would break the `.defined` and `.Bool` functionality. You can also not call `.WHAT` on a trampolined object. This is because `.WHAT` is internally generated as a call to `nqp::what`, and it is as yet impossible to provide candidates for nqp:: ops. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Object-Trampoline> . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2020, 2021, 2023 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. Re-imagined from the Perl version as part of the CPAN Butterfly Plan. Perl version originally developed by Steven Lembark.
## dist_github-japhb-RPG-Base.md [![Actions Status](https://github.com/japhb/RPG-Base/workflows/test/badge.svg)](https://github.com/japhb/RPG-Base/actions) # NAME `RPG::Base` - Common base components for RPGs # SYNOPSIS ``` use RPG::Base::Container; use RPG::Base::Creature; use RPG::Base::Location; use RPG::Base::Thing; # Using the base classes directly my $bob = RPG::Base::Creature.new(:name('Bob the Magnificent')); my $backpack = RPG::Base::Container.new(:name('Cloth Backpack')); my $flint = RPG::Base::Thing.new(:name('Flint and Steel')); my $wand = RPG::Base::Thing.new(:name('Ironwood Wand')); my $clearing = RPG::Base::Location.new(:name('Grassy Clearing')); my $grove = RPG::Base::Location.new(:name('Oak Grove')); my $cliff = RPG::Base::Location.new(:name('Sheer Cliff')); $backpack.add-thing($flint); $bob.add-thing($_) for $backpack, $wand; $grove .add-exit('north' => $clearing); $cliff .add-exit('down' => $clearing); $clearing.add-exit('south' => $grove); $clearing.add-exit('up' => $cliff); $clearing.add-thing($bob); $clearing.say; # "Grassy Clearing (exits: 2, things: 1)" $bob.say; # "Bob the Magnificent (RPG::Base::Creature in # RPG::Base::Location 'Grassy Clearing' carrying # Cloth Backpack (contents: Flint and Steel), # Ironwood Wand)" $clearing.move-thing('south' => $bob); $clearing.say; # "Grassy Clearing (exits: 2, things: 0)" $bob.container.say; # "Oak Grove (exits: 1, things: 1)" ``` # DESCRIPTION `RPG::Base` is a set of common base concepts and components on which more complex RPG rulesets can be based. It limits itself to those concepts that are near universal across RPGs (though some games use different terminology, `RPG::Base` simply chooses common terms knowing that game-specific subclasses can be named using that game's particular terminology). The entire point of `RPG::Base` is to be subclassable, extensible, and generic. If it turns out that one of the design choices is making that difficult, **please let me know**. ## STABILITY `RPG::Base` is not entirely stable, as befits the low version number (though already in use as the base of considerably more complete rulesystems). A first approximation of stability can be seen by looking at the tests for each module. Modules with lots of tests but specific `XXXX` markers still have a few slushy behaviors and might change a bit; those with very few tests or even just a `plan :skip-all` at the top of the test file represent conjectured designs and are probably very much still in flux. # CONTRIBUTING Pull requests are very welcome! It will take the implementation of many rulesets based on `RPG::Base` to find all the common code and concepts that should be factored out, and I'm certainly not going to be implementing them all myself. That said, please be aware that if I believe the new code wouldn't work well with one of the other rulesets or will block off a useful direction for extension, I may alter the PR before merging, or ask you to consider a different approach to make sure it fits well into the ecosystem. Please be *very* careful with copyrights and trademarks. Some of the companies that own game system intellectual property are famously litigious and it's important that any such questions stay well away from `RPG::Base` so that the "blast radius" of an IP disagreement won't include all modules depending on this one. Stylistically, I generally keep with Larry Wall's classic formatting rules (4 space indents, uncuddled elses, opening brace on same line as the control structure it goes with, and so on). I prefer to use the Unicode forms of operators such as `»` and `∈` rather than the pure ASCII forms. Due to quirks of my brain, I will tend to favor aligning similar parts of consecutive lines when I can get it. This tends to manifest most often in variable and class attribute definitions, where I align the type names, attribute names, and default values in columns. Finally, I treat overall readability as more important than strict adherence to 80 column width, which I see as a good default because it happens to be fairly readable and guides one towards limiting the complexity of each line, not a hard limit that should be enforced with an iron will. # AUTHOR Geoffrey Broadwell [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2016-2021 Geoffrey Broadwell This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-FRITH-Math-FFT-Libfftw3.md ## Math::FFT::Libfftw3 Math::FFT::Libfftw3 - An interface to libfftw3. ## Build Status | Operating System | Build Status | CI Provider | | --- | --- | --- | | Linux | [Build Status](https://travis-ci.org/frithnanth/perl6-Math-FFT-Libfftw3) | Travis CI | ## Example ``` use v6; use Math::FFT::Libfftw3::C2C; use Math::FFT::Libfftw3::Constants; # needed for the FFTW_BACKWARD constant my @in = (0, π/100 … 2*π)».sin; put @in».Complex».round(10⁻¹²); # print the original array as complex values rounded to 10⁻¹² my Math::FFT::Libfftw3::C2C $fft .= new: data => @in; my @out = $fft.execute; put @out; # print the direct transform output my Math::FFT::Libfftw3::C2C $fftr .= new: data => @out, direction => FFTW_BACKWARD; my @outr = $fftr.execute; put @outr».round(10⁻¹²); # print the backward transform output rounded to 10⁻¹² ``` ``` use v6; use Math::FFT::Libfftw3::C2C; use Math::FFT::Libfftw3::Constants; # needed for the FFTW_BACKWARD constant # direct 2D transform my Math::FFT::Libfftw3::C2C $fft .= new: data => 1..18, dims => (6, 3); my @out = $fft.execute; put @out; # reverse 2D transform my Math::FFT::Libfftw3::C2C $fftr .= new: data => @out, dims => (6,3), direction => FFTW_BACKWARD; my @outr = $fftr.execute; put @outr».round(10⁻¹²); ``` For more examples see the `example` directory. ## Description Math::FFT::Libfftw3 provides an interface to libfftw3 and allows you to perform Fast Fourier Transforms. ## Documentation ### Math::FFT::Libfftw3::C2C Complex-to-Complex transform #### new(:@data!, :@dims?, Int :$direction? = FFTW\_FORWARD, Int :$flag? = FFTW\_ESTIMATE, Int :$dim?, Int :$thread? = NONE, Int :$nthreads? = 1) #### new(:$data!, Int :$direction? = FFTW\_FORWARD, Int :$flag? = FFTW\_ESTIMATE, Int :$dim?, Int :$thread? = NONE, Int :$nthreads? = 1) The first constructor accepts any Positional of type Int, Rat, Num, Complex (and IntStr, RatStr, NumStr, ComplexStr); it allows List of Ints, Array of Complex, Seq of Rat, shaped arrays of any base type, etc. The only mandatory argument is **@data**. Multidimensional data are expressed in row-major order (see the [C Library Documentation](#c-library-documentation)) and the array **@dims** must be passed to the constructor, or the data will be interpreted as a 1D array. If one uses a shaped array, there's no need to pass the **@dims** array, because the dimensions will be read from the array itself. The **$direction** parameter is used to specify a direct or backward transform; it defaults to `FFTW_FORWARD`. The **$flag** parameter specifies the way the underlying library has to analyze the data in order to create a plan for the transform; it defaults to `FFTW_ESTIMATE` (see the [C Library Documentation](#c-library-documentation)). The **$dim** parameter asks for an optimization for a specific matrix rank. The parameter is optional and if present must be in the range 1..3. The **$thread** parameter specifies the kind of threaded operation one wants to get; this argument is optional and if not specified is assumed as **NONE**. There are three possibile values: * NONE * THREAD * OPENMP **THREAD** will use specific POSIX thread library while **OPENMP** will select an OpenMP library. The **$nthreads** specifies the number of threads to use; it defaults to 1. The second constructor accepts a scalar: an object of type **Math::Matrix** (if that module is installed, otherwise it returns a **Failure**); the meaning of all the other parameters is the same as in the other constructor. #### execute(Int :$output? = OUT-COMPLEX --> Positional) Executes the transform and returns the output array of values as a normalized row-major array. The parameter **$output** can be optionally used to specify how the array is to be returned: * OUT-COMPLEX * OUT-REIM * OUT-NUM The default (**OUT-COMPLEX**) is to return an array of Complex. **OUT-REIM** makes the `execute` method return the native representation of the data: an array of couples of real/imaginary values. **OUT-NUM** makes the `execute` method return just the real part of the complex values. #### Attributes Some of this class' attributes are readable: * @.out * $.rank * @.dims * $.direction * @.kind (available only in the R2R transform) * $.dim (used when a specialized tranform has been requested) * $.flag (how to compute a plan) * $.adv (normal or advanced interface) * $.howmany (only for the advanced interface) * $.istride (only for the advanced interface) * $.ostride (only for the advanced interface) * $.idist (only for the advanced interface) * $.odist (only for the advanced interface) * @.inembed (only for the advanced interface) * @.onembed (only for the advanced interface) * $.thread (only for the threaded model) #### Wisdom interface This interface allows to save and load a plan associated to a transform (There are some caveats. See [C Library Documentation](#c-library-documentation)). ##### plan-save(Str $filename --> True) Saves the plan into a file. Returns **True** if successful and a **Failure** object otherwise. ##### plan-load(Str $filename --> True) Loads the plan From a file. Returns **True** if successful and a **Failure** object otherwise. #### Advanced interface This interface allows to compose several transformations in one pass. See [C Library Documentation](#c-library-documentation). ##### advanced(Int $rank!, @dims!, Int $howmany!, @inembed!, Int $istride!, Int $idist!, @onembed!, Int $ostride!, Int $odist!) This method activates the advanced interface. The meaning of the arguments are detailed in the [C Library Documentation](#c-library-documentation). This method returns `self`, so it can be concatenated to the `.new()` method: ``` my $fft = Math::FFT::Libfftw3::C2C.new(data => (1..30).flat) .advanced: $rank, @dims, $howmany, @inembed, $istride, $idist, @onembed, $ostride, $odist; ``` ### Math::FFT::Libfftw3::R2C Real-to-Complex transform The interface for the R2C transform is slightly different. In particular: * in the `execute` method, when performing the reverse transform, the output array has only real values, so the `:$output` parameter is ignored. See the `pod` documentation inside the module for further details. ### Math::FFT::Libfftw3::R2R Real-to-Real transform This module implements several R2R transforms. The major difference is that the constructor has a new `$kind` argument, which specifies the kind of trasform that will be performed on the input data. See the `pod` documentation inside the module for further details. ## C Library documentation For more details on libfftw see [the FFTW home](http://www.fftw.org/). The manual is available [here](http://www.fftw.org/fftw3.pdf). ## Prerequisites This module requires the libfftw3 library to be installed. Please follow the instructions below based on your platform: ### Debian Linux ``` sudo apt-get install libfftw3-double3 ``` The module looks for a library called libfftw3.so. ## Installation To install it using zef (a module management tool): ``` $ zef update $ zef install Math::FFT::Libfftw3 ``` ## Testing To run the tests: ``` $ prove -e "perl6 -Ilib" ``` ## Notes Math::FFT::Libfftw3 relies on a C library which might not be present in one's installation, so it's not a substitute for a pure Perl 6 module. If you need a pure Perl 6 module, Math::FourierTransform works just fine. This module needs Perl 6 ≥ 2018.09 only if one wants to use shaped arrays as input data. An attempt to feed a shaped array to the `new` method using `$*PERL.compiler.version < v2018.09` results in an exception. ## TODO There are some alternative interfaces to implement: * The *guru* interface to apply the same plan to different data. * The *distributed-memory* interface, for parallel systems supporting the MPI message-passing interface. ## Author Fernando Santagata ## Copyright and license The Artistic License 2.0
## dist_zef-FCO-Red.md [![Build Status](https://github.com/FCO/Red/workflows/test/badge.svg)](https://github.com/FCO/Red/actions) [![Build Status](https://github.com/FCO/Red/workflows/ecosystem/badge.svg)](https://github.com/FCO/Red/actions) [![SparrowCI](https://ci.sparrowhub.io/project/gh-FCO-Red/badge)](https://ci.sparrowhub.io) # Red Take a look at our Documentation: <https://fco.github.io/Red/> ## Red - A **WiP** ORM for Raku ## INSTALL Install with (you need **rakudo 2018.12-94-g495ac7c00** or **newer**): ``` zef install Red ``` ## SYNOPSIS ``` use Red:api<2>; model Person {...} model Post is rw { has Int $.id is serial; has Int $!author-id is referencing( *.id, :model(Person) ); has Str $.title is column{ :unique }; has Str $.body is column; has Person $.author is relationship{ .author-id }; has Bool $.deleted is column = False; has DateTime $.created is column .= now; has Set $.tags is column{ :type<string>, :deflate{ .keys.join: "," }, :inflate{ set(.split: ",") } } = set(); method delete { $!deleted = True; self.^save } } model Person is rw { has Int $.id is serial; has Str $.name is column; has Post @.posts is relationship{ .author-id }; method active-posts { @!posts.grep: not *.deleted } } my $*RED-DB = database "SQLite"; Person.^create-table; ``` ``` -- Equivalent to the following query: CREATE TABLE person( id integer NOT NULL primary key AUTOINCREMENT, name varchar(255) NOT NULL ) ``` ``` Post.^create-table; ``` ``` -- Equivalent to the following query: CREATE TABLE post( id integer NOT NULL primary key AUTOINCREMENT, author_id integer NULL references person(id), title varchar(255) NOT NULL, body varchar(255) NOT NULL, deleted integer NOT NULL, created varchar(32) NOT NULL, tags varchar(255) NOT NULL, UNIQUE (title) ) ``` ``` my Post $post1 = Post.^load: :42id; ``` ``` -- Equivalent to the following query: SELECT post.id, post.author_id as "author-id", post.title, post.body, post.deleted, post.created, post.tags FROM post WHERE post.id = 42 ``` ``` my Post $post1 = Post.^load: 42; ``` ``` -- Equivalent to the following query: SELECT post.id, post.author_id as "author-id", post.title, post.body, post.deleted, post.created, post.tags FROM post WHERE post.id = 42 ``` ``` my Post $post1 = Post.^load: :title("my title"); ``` ``` -- Equivalent to the following query: SELECT post.id, post.author_id as "author-id", post.title, post.body, post.deleted, post.created, post.tags FROM post WHERE post.title = ‘my title’ ``` ``` my $person = Person.^create: :name<Fernando>; ``` ``` -- Equivalent to the following query: INSERT INTO person( name ) VALUES( $1 ) RETURNING * -- BIND: ["Fernando"] ``` ``` RETURNS: Person.new(name => "Fernando") ``` ``` say $person.posts; ``` ``` -- Equivalent to the following query: SELECT post.id, post.author_id as "author-id", post.title, post.body, post.deleted, post.created, post.tags FROM post WHERE post.author_id = ? -- BIND: [1] ``` ``` say Person.new(:2id) .active-posts .grep: { .created > now } ``` ``` -- Equivalent to the following query: SELECT post.id, post.author_id as "author-id", post.title, post.body, post.deleted, post.created, post.tags FROM post WHERE ( post.author_id = ? AND ( post.deleted == 0 OR post.deleted IS NULL ) ) AND post.created > 1554246698.448671 -- BIND: [2] ``` ``` my $now = now; say Person.new(:3id) .active-posts .grep: { .created > $now } ``` ``` -- Equivalent to the following query: SELECT post.id, post.author_id as "author-id", post.title, post.body, post.deleted, post.created, post.tags FROM post WHERE ( post.author_id = ? AND ( post.deleted == 0 OR post.deleted IS NULL ) ) AND post.created > ? -- BIND: [ -- 3, -- Instant.from-posix( -- <399441421363/257>, -- Bool::False -- ) -- ] ``` ``` Person.^create: :name<Fernando>, :posts[ { :title("My new post"), :body("A long post") }, ] ; ``` ``` -- Equivalent to the following query: INSERT INTO person( name ) VALUES( ? ) RETURNING * -- BIND: ["Fernando"] INSERT INTO post( created, title, author_id, tags, deleted, body ) VALUES( ?, ?, ?, ?, ?, ? ) RETURNING * -- BIND: [ -- "2019-04-02T22:55:13.658596+01:00", -- "My new post", -- 1, -- "", -- Bool::False, -- "A long post" -- ] ``` ``` my $post = Post.^load: :title("My new post"); ``` ``` -- Equivalent to the following query: SELECT post.id, post.author_id as "author-id", post.title, post.body, post.deleted, post.created, post.tags FROM post WHERE post.title = ‘My new post’ -- BIND: [] ``` ``` RETURNS: Post.new( title => "My new post", body => "A long post", deleted => 0, created => DateTime.new( 2019, 4, 2, 23, 7, 46.677388, :timezone(3600) ), tags => Set.new("") ) ``` ``` say $post.body; ``` ``` PRINTS: A long post ``` ``` my $author = $post.author; ``` ``` RETURNS: Person.new(name => "Fernando") ``` ``` $author.name = "John Doe"; $author.^save; ``` ``` -- Equivalent to the following query: UPDATE person SET name = ‘John Doe’ WHERE id = 1 ``` ``` $author.posts.create: :title("Second post"), :body("Another long post"); ``` ``` -- Equivalent to the following query: INSERT INTO post( title, body, created, tags, deleted, author_id ) VALUES( ?, ?, ?, ?, ?, ? ) RETURNING * -- BIND: [ -- "Second post", -- "Another long post", -- "2019-04-02T23:28:09.346442+01:00", -- "", -- Bool::False, -- 1 -- ] ``` ``` $author.posts.elems; ``` ``` -- Equivalent to the following query: SELECT count(*) as "data_1" FROM post WHERE post.author_id = ? -- BIND: [1] ``` ``` RETURNS: 2 ``` ## DESCRIPTION Red is a *WiP* ORM for Raku. ### traits * `is column` * `is column{}` * `is id` * `is id{}` * `is serial` * `is referencing{}` * `is relationship{}` * `is table<>` * `is nullable` ### features: #### relationships Red will infer relationship data if you use type constraints on your properties. ``` # Single file e.g. Schema.pm6 model Related { ... } # belongs to model MyModel { has Int $!related-id is referencing( *.id, :model<Related> ); has Related $.related is relationship{ .id }; } # has one/has many model Related { has Int $.id is serial; has MyModel @.my-models is relationship{ .related-id }; } ``` If you want to put your schema into multiple files, you can create an "indirect" relationship, and Red will look up the related models as necessary. ``` # MyModel.pm6 model MyModel { has Int $!related-id is referencing{ :model<Related>, :column<id> }; has $.related is relationship({ .id }, :model<Related>); } # Related.pm6 model Related { has Int $.id is serial; has @.my-models is relationship({ .related-id }, :model<MyModel>); } ``` If Red can’t find where your `model` is defined you can override where it looks with `require`: ``` has Int $!related-id is referencing{ :model<Related>, :column<id>, :require<MyApp::Schema::Related> }; ``` #### custom table name ``` model MyModel is table<custom_table_name> {} ``` #### not nullable columns by default Red, by default, has not nullable columns, to change it: ``` #| This makes this model’s columns nullable by default model MyModel is nullable { has Int $.col1 is column; #= this column is nullable has Int $.col2 is column{ :!nullable }; #= this one is not nullable } ``` #### load object from database ``` MyModel.^load: 42; MyModel.^load: id => 42; ``` #### save object on the database ``` $object.^save; ``` #### search for a list of object ``` Question.^all.grep: { .answer == 42 }; # returns a result seq ``` #### phasers * `before-create` * `after-create` * `before-update` * `after-update` * `before-delete` * `after-delete` #### Temporary table ``` model Bla is temp { ... } ``` #### Create table ``` Question.^create-table; Question.^create-table: :if-not-exists; Question.^create-table: :unless-exists; ``` #### IN ``` Question.^all.grep: *.answer ⊂ (3.14, 13, 42) ``` #### create ``` Post.^create: :body("bla ble bli blo blu"), :title("qwer"); model Tree { has UInt $!id is id; has Str $.value is column; has UInt $!parent-id is referencing{ Tree.id }; has Tree $.parent is relationship{ .parent-id }; has Tree @.kids is relationship{ .parent-id }; } Tree.^create-table: :if-not-exists; Tree.^create: :value<Bla>, :parent{:value<Ble>}, :kids[ {:value<Bli>}, {:value<Blo>}, {:value<Blu>} ] ; ``` ## AUTHOR Fernando Correa de Oliveira [[email protected]](mailto:[email protected]) ## COPYRIGHT AND LICENSE Copyright 2018 Fernando Correa de Oliveira This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-CTILMES-DB-SQLite.md # DB::SQLite - SQLite access for Raku [![Build Status](https://travis-ci.org/CurtTilmes/raku-dbsqlite.svg)](https://travis-ci.org/CurtTilmes/raku-dbsqlite) This is a reimplementation of Raku bindings for SQLite. ## Basic usage ``` my $s = DB::SQLite.new(); # You can pass in various connection options ``` Execute a query, and get a single value: ``` say $s.query('select 42').value; # 42 ``` Create a table: ``` $s.execute('create table foo (x int, y text)'); ``` Insert some values using placeholders: ``` $s.query('insert into foo (x,y) values (?,?)', 1, 'this'); ``` Or even fancy placeholders: ``` $s.query('insert into foo (x,y) values ($x,$y)', x => 2, y => 'that'); ``` Execute a query returning a row as an array or hash; ``` say $s.query('select * from foo where x = $x', :x(1)).array; say $s.query('select * from foo where x = $x', :2x).hash; ``` Execute a query returning a bunch of rows as arrays or hashes: ``` .say for $s.query('select * from foo').arrays; .say for $s.query('select * from foo').hashes; ``` ## Connection Information When you create a **DB::SQLite** object, you can specify a `filename` option to `.new` for the database to open. If it isn't specified, it will default to an empty string which causes a private, temporary on-disk database to be created. This will be useless if you use more than one connection, since each will get its own database, but maybe you want that.. If you specify `filename => ':memory'` you will get a private, temporary, in-memory database. Again, this will not be shared across connections. You can also use a `busy-timeout` option to specify in milliseconds, the amount of sleeping to wait for a locked table to become available. This defaults to 10000 (10 seconds). Setting to zero will turn off busy handling. ``` use DB::SQLite; my $s = DB::SQLite.new(filename => 'this.db', busy-timeout => 50000); ``` You can also pass in additional extended open flags, such as 'readonly': ``` my $s = DB::SQLite.new(filename => 'this.db', :readonly); ``` Depending on your sqlite version, Flags may include: readonly, readwrite, create, deleteonclose, exclusive, autoproxy, uri, memory, main\_db, temp\_db, transient\_db, main\_journal, temp\_journal, subjournal, super\_journal, nomutex, fullmutex, sharedcache, privatecache, wal, nofollow. Refer to the SQLite docs for more information on them. ## DB::SQLite::Connection The main **DB::SQLite** object acts as a factory for connections, maintaining a cache of connections already created. A new connection can be requested with the `.db` method, but often this isn't needed. When you are finished with a connection, you can explicitly return it to the cache with `.finish`. You can call `.query()` or `.execute()` on the main **DB::SQLite** object, but all they really do is allocate a **DB::SQLite::Connection** (either from the cache, or create a new one) and call those methods on it, then return the connection to the cache. These are equivalent: ``` .say for $s.query('select * from foo').arrays; ``` ``` my $db = $s.db; .say for $db.query('select * from foo').arrays; $db.finish; ``` The connection object also has some extra methods for separately preparing and executing the query: ``` my $db = $s.db; my $sth = $db.prepare('insert into foo (x,y) values (?,?)'); $sth.execute(1, 'this'); $sth.execute(2, 'that'); $db.finish; ``` You can also call `.finish()` on the statement: ``` my $sth = $s.db.prepare('insert into foo (x,y) values (?,?)'); $sth.execute(1, 'this'); $sth.execute(2, 'that'); $sth.finish; ``` The statement will finish the associated connection, returning it to the cache. Yet another way to do it is to pass `:finish` in to the execute. ``` my $sth = $s.db.prepare('insert into foo (x,y) values (?,?)'); $sth.execute(1, 'this'); $sth.execute(2, 'that', :finish); ``` And finally, a cool Perl 6ish way is the `will` trait to install a Phaser directly on the variable: ``` { my $sth will leave { .finish } = $s.db.prepare('insert into foo (x,y) values (?,?)'); $sth.execute(1, 'this'); $sth.execute(2, 'that'); } ``` Calling `.prepare()` on the **DB::SQLite::Connection** prepares and returns a **DB::SQLite::Statement** that can then be `.execute()`ed. The prepared statement is also retained in a cache with the connection. If the same statement is prepared again on the same connection, the cached object will be returned instead of re-preparing. If you don't want it to be cached, you can pass in the `:nocache` option. ``` my $sth = $s.db.prepare('insert into foo (x,y) values (?,?)', :nocache); $sth.execute(1, 'this'); $sth.execute(2, 'that', :finish); ``` You must still take care to call `.finish()` to return the connection to the connection cache so it will get reused. (Or take care NOT to call `.finish()` if you don't want the connection to be reused, possibly in another thread.) For the main object, or the connection object, `.execute()` is used instead of `.query()` under two conditions: 1. You don't need placeholders/arguments. 2. You don't want the results. As a special added bonus you can execute multiple statements separated by semi-colons in one shot: ``` $s.execute(q:to/END/); create table foo ( x int, y text ); insert into foo (x,y) values (1, 'this'); insert into foo (x,y) values (2, 'that'); END ``` ## Transactions The database connection object can also manage transactions with the `.begin`, `.commit`, and `.rollback` methods: ``` my $db = $s.db; my $sth = $db.prepare('insert into foo (x,y) values (?,?)'); $db.begin; $sth.execute(1, 'this'); $sth.execute(2, 'that'); $db.commit; $db.finish; ``` The `begin`/`commit` ensure that the statements between them happen atomically, either all or none. Transactions can also dramatically improve performance for some actions, such as performing thousands of inserts/deletes/updates since the indexes for the affected table can be updated in bulk once for the entire transaction. If you `.finish` the database prior to a `.commit`, an uncommitted transaction will automatically be rolled back. As a convenience, `.commit` also returns the database object, so you can just `$db.commit.finish`. ## Placeholders and Binding SQLite parameters can take several different forms: * ? * ?*NNN* * :*AAA* * $*AAA* * @*AAA* Where *NNN* is an integer value, and *AAA* is an identifier. When calling execute, the numbered binds are bound starting with 1 from the arguments to `.execute` (or `.query`): ``` my $sth = $s.db.prepare('select ?1, ?2, ?3'); say $sth.execute(1,2,3).array; $sth.finish; ``` The named binds with $*AAA* placeholders are bound with named parameter pairs: ``` my $sth = $s.db.prepare('select $x, $y, $z'); say $sth.execute(:x(1), :y(2), :z(3)).array; say $sth.execute(x => 1, y => 2, z => 3).array; # same thing $sth.finish; ``` Binding the other placeholders is a little more complicated. They must be bound explicitly prior to calling `.execute()` (This will work with numbered placeholders too.): ``` my $sth = $s.db.prepare('select :x, $y, @z'); $sth.bind(':x', 1) $sth.bind('$y', 2) $sth.bind('@z', 3) $sth.execute(); $sth.finish; ``` You don't have to bind every placeholder. If you leave one out, it just gets a `NULL`. If you `.execute` multiple times with the same statement, it will use whatever bindings are in place from previous executions. Since by default, statements get cached and re-used, the safest approach is always to bind every placeholder, even ones you want to be `NULL`. (Bind with an undefined type, such as `Any` for `NULL`). You can even mix and match numbered and named placeholders if you want to (and are careful). ## Results Calling `.query()` on a **DB::SQLite** or **DB::SQLite::Connection**, or calling `.execute()` on a **DB::SQLite::Statement** with an SQL SELECT or something that returns data, a `DB::SQLite::Result` object will be returned. The query results can be consumed from that object with the following methods: * `.value` - a single scalar result * `.array` - a single array of results from one row * `.hash` - a single hash of results from one row * `.arrays` - a sequence of arrays of results from all rows * `.hashes` - a sequence of hashes of results from all rows If the query isn't a select or otherwise doesn't return data, such as an INSERT, UPDATE, or DELETE, it will return the number of rows affected. ## Exceptions All database errors, including broken SQL queries, are thrown as exceptions. ## Acknowledgements Inspiration taken from the existing Raku [DBIish](https://github.com/raku-community-modules/DBIish) module as well as the Perl 5 [Mojo::Pg](http://mojolicious.org/perldoc/Mojo/Pg) from the Mojolicious project. Thanks to hythm7 for contributing to the open flags capability. ## License Portions thanks to DBIish: Copyright © 2009-2016, the DBIish contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## dist_cpan-KAIEPI-Net-LibIDN2.md [![Build Status](https://travis-ci.org/Kaiepi/p6-Net-LibIDN2.svg?branch=master)](https://travis-ci.org/Kaiepi/p6-Net-LibIDN2) # NAME Net::LibIDN2 - Perl 6 bindings for GNU LibIDN2 # SYNOPSIS ``` use Net::LibIDN2; my $idn = Net::LibIDN2.new; my Int $code; my $ulabel = "m\xFC\xDFli"; my $alabel = $idn.lookup_u8($ulabel, IDN2_NFC_INPUT, $code); say "$alabel $code"; # xn--mli-5ka8l 0 my $result = $idn.register_u8($ulabel, $alabel, IDN2_NFC_INPUT, $code); say "$result $code"; # xn--mli-5ka8l 0 say $idn.strerror($code); # success say $idn.strerror_name($code); # IDN2_OK ``` # DESCRIPTION Net::LibIDN2 is a Perl 6 wrapper for the GNU LibIDN2 library. # METHODS * **Net::LibIDN2.check\_version**(--> Version) * **Net::LibIDN2.check\_version**(Str *$version* --> Version) * **Net::LibIDN2.check\_version**(Version *$version* --> Version) Compares `$version` against the version of LibIDN2 installed and returns either an empty string if `$version` is greater than the version installed, or `IDN2_VERSION` otherwise. * **Net::LibIDN2.strerror**(Int *$errno* --> Str) Returns the error represented by `$errno` in human readable form. * **Net::LibIDN2.strerror\_name**(Int *$errno* --> Str) Returns the internal error name of `$errno`. * **Net::LibIDN2.to\_ascii\_8z**(Str *$input* --> Str) * **Net::LibIDN2.to\_ascii\_8z**(Str *$input*, Int *$flags* --> Str) * **Net::LibIDN2.to\_ascii\_8z**(Str *$input*, Int *$flags*, Int *$code* is rw --> Str) Converts a UTF8 encoded string `$input` to ASCII and returns the output. `$code`, if provided, is assigned to `IDN2_OK` on success, or another error code otherwise. Requires LibIDN2 v2.0.0 or greater. * **Net::LibIDN2.to\_unicode\_8z8z**(Str *$input* --> Str) * **Net::LibIDN2.to\_unicode\_8z8z**(Str *$input*, Int *$flags* --> Str) * **Net::LibIDN2.to\_unicode\_8z8z**(Str *$input*, Int *$flags*, Int *$code* is rw --> Str) Converts an ACE encoded domain name `$input` to UTF8 and returns the output. `$code`, if provided, is assigned to `IDN2_OK` on success, or another error code otherwise. Requires LibIDN v2.0.0 or greater. * **Net::LibIDN2.lookup\_u8**(Str *$input* --> Str) * **Net::LibIDN2.lookup\_u8**(Str *$input*, Int *$flags* --> Str) * **Net::LibIDN2.lookup\_u8**(Str *$input*, Int *$flags*, Int *$code* is rw --> Str) Performs an IDNA2008 lookup string conversion on `$input`. See RFC 5891, section 5. `$input` must be a UTF8 encoded string in NFC form if no `IDN2_NFC_INPUT` flag is passed. * **Net::LibIDN2.register\_u8**(Str *$uinput*, Str *$ainput* --> Str) * **Net::LibIDN2.register\_u8**(Str *$uinput*, Str *$ainput*, Int *$flags* --> Str) * **Net::LibIDN2.register\_u8**(Str *$uinput*, Str *$ainput*, Int *$flags*, Int *$code* is rw --> Str) Performs an IDNA2008 register string conversion on `$uinput` and `$ainput`. See RFC 5891, section 4. `$uinput` must be a UTF8 encoded string in NFC form if no `IDN2_NFC_INPUT` flag is passed. `$ainput` must be an ACE encoded string. # CONSTANTS * Int **IDN2\_LABEL\_MAX\_LENGTH** The maximum label length. * Int **IDN2\_DOMAIN\_MAX\_LENGTH** The maximum domain name length. ## VERSIONING * Str **IDN2\_VERSION** The version of LibIDN2 installed. * Int **IDN2\_VERSION\_NUMBER** The version of LibIDN2 installed represented as a 32 bit integer. The first pair of bits represents the major version, the second represents the minor version, and the last 4 represent the patch version. * Int **IDN2\_VERSION\_MAJOR** The major version of LibIDN2 installed. * Int **IDN2\_VERSION\_MINOR** The minor version of LidIDN2 installed. * Int **IDN2\_VERSION\_PATCH** The patch version of LibIDN2 installed. ## FLAGS * Int **IDN2\_NFC\_INPUT** Normalize the input string using the NFC format. * Int **IDN2\_ALABEL\_ROUNDTRIP** Perform optional IDNA2008 lookup roundtrip check. * Int **IDN2\_TRANSITIONAL** Perform Unicode TR46 transitional processing. * Int **IDN2\_NONTRANSITIONAL** Perform Unicode TR46 non-transitional processing. ## ERRORS * Int **IDN2\_OK** Success. * Int **IDN2\_MALLOC** Memory allocation failure. * Int **IDN2\_NO\_CODESET** Failed to determine a string's encoding. * Int **IDN2\_ICONV\_FAIL** Failed to transcode a string to UTF8. * Int **IDN2\_ENCODING\_ERROR** Unicode data encoding error. * Int **IDN2\_NFC** Failed to normalize a string. * Int **IDN2\_PUNYCODE\_BAD\_INPUT** Invalid input to Punycode. * Int **IDN2\_PUNYCODE\_BIG\_OUTPUT** Punycode output buffer is too small. * Int **IDN2\_PUNYCODE\_OVERFLOW** Punycode conversion would overflow. * Int **IDN2\_TOO\_BIG\_DOMAIN** Domain is larger than `IDN2_DOMAIN_MAX_LENGTH`. * Int **IDN2\_TOO\_BIG\_LABEL** Label is larger than `IDN2_LABEL_MAX_LENGTH`. * Int **IDN2\_INVALID\_ALABEL** Invalid A-label. * Int **IDN2\_UALABEL\_MISMATCH** Given U-label and A-label do not match. * Int **IDN2\_INVALID\_FLAGS** Invalid combination of flags. * Int **IDN2\_NOT\_NFC** String is not normalized in NFC format. * Int **IDN2\_2HYPHEN** String has forbidden two hyphens. * Int **IDN2\_HYPHEN\_STARTEND** String has forbidden start/end hyphen. * Int **IDN2\_LEADING\_COMBINING** String has forbidden leading combining character. * Int **IDN2\_DISALLOWED** String has disallowed character. * Int **IDN2\_CONTEXTJ** String has forbidden context-j character. * Int **IDN2\_CONTEXTJ\_NO\_RULE** String has context-j character without any rull. * Int **IDN2\_CONTEXTO** String has forbidden context-o character. * Int **IDN2\_CONTEXTO\_NO\_RULE** String has context-o character without any rull. * Int **IDN2\_UNASSIGNED** String has forbidden unassigned character. * Int **IDN2\_BIDI** String has forbidden bi-directional properties. * Int **IDN2\_DOT\_IN\_LABEL** Label has forbidden dot (TR46). * Int **IDN2\_INVALID\_TRANSITIONAL** Label has a character forbidden in transitional mode (TR46). * Int **IDN2\_INVALID\_NONTRANSITIONAL** Label has a character forbidden in non-transitional mode (TR46). # AUTHOR Ben Davies (kaiepi) # COPYRIGHT AND LICENSE Copyright 2017 Ben Davies This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-FRITH-Math-Libgsl-Wavelet.md [![Actions Status](https://github.com/frithnanth/raku-Math-Libgsl-Wavelet/actions/workflows/test.yml/badge.svg)](https://github.com/frithnanth/raku-Math-Libgsl-Wavelet/actions) ![Original data](examples/ecg.png) ![Filtered data](examples/ecg.processed.png) # NAME Math::Libgsl::Wavelet - An interface to libgsl, the Gnu Scientific Library - Wavelet Transform # SYNOPSIS ``` use Math::Libgsl::Wavelet; use Math::Libgsl::Constants; constant \N = 256; constant \kind = 4; my @data; for ^N X ^N -> ($i, $j) { @data[$i * N + $j] = ($i * N + $j).Num / (N * N); } my Math::Libgsl::Wavelet $w .= new: DAUBECHIES, kind; my @fdata = $w.forward2d(@data); ``` # DESCRIPTION Math::Libgsl::Wavelet is an interface to the Wavelet Transform functions of libgsl, the Gnu Scientific Library. ### new(UInt:D $type!, UInt:D $variant!) ### new(UInt:D :$type!, UInt:D :$variant!) The constructor accepts two simple or named arguments: the type of wavelet function and the specific member of the wavelet family. The available wavelet functions are: * **DAUBECHIES** * **DAUBECHIES\_CENTERED** * **HAAR** * **HAAR\_CENTERED** * **BSPLINE** * **BSPLINE\_CENTERED** There are two methods for dealing with 1D transforms (direct and inverse): ### forward1d(@data, UInt:D $stride where { $\_ < @data.elems / 2 } = 1, UInt:D $size where { is-powerof2($\_) } = @data.elems --> List) Forward 1D transform. The **@data** array is the only mandatory argument. The array may be larger than the set of values that one wants to transform; in that case the **$stride** and **$size** arguments define the set of values that will be transformed. ### inverse1d(@data, UInt:D $stride where { $\_ < @data.elems / 2 } = 1, UInt:D $size where { is-powerof2($\_) } = @data.elems --> List) Inverse 1D transform. The **@data** array is the only mandatory argument. The array may be larger than the set of values that one wants to transform; in that case the **$stride** and **$size** arguments define the set of values that will be transformed. ### forward2d(@data!, UInt:D $dim? where { is-powerof2($dim) } = sqrt(@data.elems).UInt, UInt:D $tda? where { $\_ ≥ $dim } = $dim, :$nonstandard --> List) ### forward2d(Math::Libgsl::Matrix $data! where { $data.matrix.size1 == $data.matrix.size2 && is-powerof2($data.matrix.size1) }, :$nonstandard --> Math::Libgsl::Matrix) Forward 2D transform. There are two forms of this method: one accepts an array as its first argument, the other works on a Math::Libgsl::Matrix object. The first form takes an array **@data** which represents a square matrix that must have a number of elements which is a power of 2. The @data array may contain more values than those one wants to transform; in this case the **$size** argument is the dimension of the (square) matrix to be processed and **$tda** is the physical row length. The second form accepts a square Math::Libgsl::Matrix object whose sizes are powers of 2. Both forms allow for a named argument **:$nonstandard**, which selects the non-standard form of the computation as detailed in the C library documentation. ### inverse2d(@data!, UInt:D $dim? where { is-powerof2($dim) } = sqrt(@data.elems).UInt, UInt:D $tda? where { $\_ ≥ $dim } = $dim, :$nonstandard --> List) ### inverse2d(Math::Libgsl::Matrix $data! where { $data.matrix.size1 == $data.matrix.size2 && is-powerof2($data.matrix.size1) }, :$nonstandard --> Math::Libgsl::Matrix) Inverse 2D transform. There are two forms of this method: one accepts an array as its first argument, the other works on a Math::Libgsl::Matrix object. The first form takes an array **@data** which represents a square matrix that must have a number of elements which is a power of 2. The @data array may contain more values than those one wants to transform; in this case the **$size** argument is the dimension of the (square) matrix to be processed and **$tda** is the physical row length. The second form accepts a square Math::Libgsl::Matrix object whose sizes are powers of 2. Both forms allow for a named argument **:$nonstandard**, which selects the non-standard form of the computation as detailed in the C library documentation. # 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::Wavelet ``` # AUTHOR Fernando Santagata [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2022 Fernando Santagata This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-melezhik-Tomty.md # Tomty Tomty - Raku Test Framework. # Install ``` zef install Tomty ``` # Build Status ![SparkyCI](https://sparky.sparrowhub.io/badge/gh-melezhik-Tomty?foo=bar) # Quick start ``` tomty --edit test-01 bash "echo Hello World" tomty --edit test-02 bash "echo Upps && exit 1"; tomty --edit test-03 bash "echo Hello Again!"; tomty --all # Run all tests and make reports [1/3] / [test-01] ....... 2 sec. OK [2/3] / [test-02] ....... 3 sec. FAIL [3/3] / [test-03] ....... 3 sec. OK ========================================= )=: (2) tests passed / (1) failed # save tests to Git echo ".tomty/.cache" >> .gitignore git add .tomty ``` # Guide ## Writing tests Tomty test is just a Raku scenario: ``` tomty --edit test-meta6-file-exist #!raku bash "test -f META6.json" ``` You can write more advanced tests, for example: ``` # Check if raku.org is accessible tomty --edit test-raku-org-alive #!raku http-ok("https://raku.org"); # Check if META6.json file is a valid json tomty --edit test-meta6-is-valid-json #!raku task-run "meta6 is a valid json", "json-lint"; ``` Check out [Sparrow6 DSL](https://github.com/melezhik/Sparrow6#sparrow6-dsl) on what you can use writing your tests. ## Running tests * To run all test just say `tomty --all` It will find all the tests and run them in sequence. * To run single test just say `tomty $test` For example: ``` tomty test-meta6-is-valid-json ``` ## Examining tests To list all the tests just say `tomty --list` This command will list all tests. ## Managing tests ### Removing test To remove test use `--remove` option: ``` tomty --remove $test ``` ### Edit test source code Use `--edit` to create test from the scratch or to edit existed test source code: ``` tomty --edit $test ``` ### Getting test source code Use `--cat` command to print out test source code: ``` tomtit --cat $test ``` Use `--lines` flag to print out test source code with line numbers. # Environments * Tomty environments are configuration files, written on Raku and technically speaking are plain Raku Hashes * Environment configuration files should be placed at `.tomty/conf` directory: `.tomty/env/config.raku`: ``` { dbname => "products", dbhost => "localhost" } ``` When tomty runs it picks the `.tomty/env/config.raku` and read configuration from it variables will be accessible as `config` Hash, inside Tomty scenarios: ``` my $dbname = config<dbname>; my $dbhost = config<dbhost>; ``` To define *named* configuration ( environment ), simply create `.tomty/env/config{$env}.raku` file and refer to it through `--env=$env` parameter: ``` nano .tomty/env/config.prod.raku tomty --env=prod ... other parameters here # will run with production configuration ``` You can run editor for environment configuration by using --edit option: ``` tomty --env-edit test # edit test environment configuration tomty --env-edit default # edit default configuration ``` You can activate environment by using `--env-set` parameter: ``` tomty --env-set prod # set prod environment as default tomty --env-set # to list active (current) environment tomty --env-set default # to set current environment to default ``` To view environment configuration use `--env-cat` command: ``` tomty --env-cat $env ``` Use `--lines` flag to print out environment source code with line numbers. You print out the list of all environments by using `--env-list` parameters: ``` tomty --env-list ``` ## Macros Tomty macros allow to pre-process test scenarios. To embed macros use `=begin tomty` .. `=end tomty` syntax: ``` =begin tomty %( tag => "slow" ) =end tomty ``` Macros could be any Raku code, returning `Hash`. The example above set tag=`slow` for slow running tests, you can skip test execution by using `--skip` option: ``` tomty --skip=slow ``` See also `tags filtering`. Tags could be multiple as well: ``` =begin tomty %( tag => [ "flaky", "slow" ] ) =end tomty ``` ## Tags filtering Tags filtering allows to run subsets of scenarios using tags as criteria. ### Logical OR By default logical OR is implied when using comma: Examples: ``` tomty --skip=slow,windows # skip slow OR windows tests tomty --only=frontend,backend # only frontend OR backend test ``` ### Logical AND Use `+` to mimic logical AND: ``` tomty --only=database+mysql # execute only mysql database tests ``` `--skip` and `--only` could be combined to get more sophisticated scenarios: ``` tomty --only=database+mysql,skip=window # execute only mysql database tests BUT not for windows OS system ``` ## List tags One can list available tags by: ``` tomty --list --tags ``` You can combine `--tags` with `--only` or `--skip` options to *list* tagged tests. Examples: ``` tomty --tags --only=foo # list tests tagged by `foo` tomty --tags --only=foo+bar # list tests tagged by `foo` AND `bar` tomty --tags --only=foo,bar # list tests tagged by `foo` OR `bar` ``` ## Filter untagged scenarios Use special `untagged` keyword to filter untagged scenarios: ``` tomty --tags --only=untagged # list all untagged tests tomty --only=untagged # run all untagged tests tomty --skip=untagged # run all but untagged tests ``` ## Profiles Tomty profile sets command line arguments for a named profile: ``` cat .tomty/profile ``` ``` %( default => %( skip => "broken" ) ) ``` One can override following command line arguments through a profile: * `skip` * `only` * `env` * `no-index-update` In the future more arguments will be supported. A `default` profile sets default command line arguments when `tomty` cli run. To add more profiles just add more Hash keys and define proper settings: ``` %( default => %( skip => "broken" ), development => %( only => "new-bugs" ) ) ``` To chose profile use `--profile` option: ``` tomty --profile development ``` ## Bash completion Tomty comes with nice Bash completion to easy cli usage, use `--completion` option to install completion: ``` tomty --completion ``` And then `source ~/.tomty_completion.sh` to activate one. # Tomty cli ## Options * `--all|-a` Run all tests * `--show-failed` Show failed tests * `--verbose` Runs tests in verbose mode, print more details about every test * `--no-index-update` Don't update Sparrow repository index * `--dump-task` Dump task code before execution, see SP6\_DUMP\_TASK\_CODE Sparrow documentation * `--color` Run in color mode * `--list` List tests/tags To list test only: ``` tomty --list ``` To lists tags only: ``` tomty --list --tags ``` * `--noheader` Omit header when list tests. Allow to edit tests one by one: ``` for i in $(tomty --noheader); do tomty --edit $i; done ``` * `--edit|--cat|--remove` Edit, dump, remove test * `--env-edit|--env-list|--env-set` Edit, list, set environment * `--completion` Install Tomty Bash completion * `--log` Get log for given test run, useful when running in all tests mode: ``` tomty -all tomty --log test-01 ``` * `--skip` | `--only` Set tags filters. Skip tests tagged as `slow` ``` tomty --skip=slow ``` Only run tests tagged as `linux` ``` tomty --only=linux ``` See also `tags filtering` for more details on tag filtering. * `--tags` Show available tags: ``` tomty --list --tags # list all tags ``` You can combine `--tags` with `--only` or `--skip` options: ``` tomty --tags --only=foo+bar # list tests tagged by `foo` AND `bar` ``` # Environment variables * `TOMTY_DEBUG` Use it when debugging Tomty itself: ``` TOMTY_DEBUG=1 tomty --all ``` # See also * [Sparrow6](https://github.com/melezhik/Sparrow6) * [Tomtit](https://github.com/melezhik/Tomtit) # Author Alexey Melezhik # Thanks to God, as my inspiration
## dist_cpan-SOFTMOTH-Text-ShellWords.md # NAME Text::ShellWords - Split a string into words like a command-line shell # SYNOPSIS ``` use Text::ShellWords; my $input = Q{printf "%s\n" 1 "2 hello" '3 world' 4\ .}; my @output = run(:out, shell-words $input).out.lines(:close); .put for @output; # OUTPUT: «1␤2 hello␤3 world␤4 .␤» ``` # DESCRIPTION Text::ShellWords provides routines to split a string into words, respecting the Unix Bourne Shell (`/bin/sh`) quoting rules. From the `bash` manual page: * There are three quoting mechanisms: the escape character, single quotes, and double quotes. A non-quoted backslash (`\`) is the escape character. It preserves the literal value of the next character that follows, with the exception of *newline*. If a `\`*newline* pair appears, and the backslash is not itself quoted, the `\`*newline* is treated as a line continuation (that is, it is removed from the input stream and effectively ignored). Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of `\`. The backslash retains its special meaning only when followed by one of the following characters: `"`, `\`, or *newline*. A double quote may be quoted within double quotes by preceding it with a backslash. * Unlike the Bourne Shell, the characters `$`, ```, and `!` have no special meaning to this module. ## class Text::ShellWords::Grammar Parsing grammar for a shell-input string ## class Text::ShellWords::WordFailure Error indicator for an incomplete parse ### Incomplete parsing When the input string is malformed, or intended to continue on another line, the last word is made a `WordFailure` object, rather than a `Str`. This object behaves just like any `Failure`, but it stringifies to the final piece of input text if it has been `handled` (by testing if it is `True` or `defined`). ``` my @words = shell-words 'hello, "world'; put @words[0]; # OUTPUT «hello,␤» try put @words[1]; # OUTPUT «» put $!.message; # OUTPUT «Input is malformed or incomplete, ends with '"world'␤» # Now that it's been handled, it can used as a Str put @words[1]; # OUTPUT «"world␤» # But it is still a Failure say @words[1].^name if not @words[1]; # OUTPUT: «Text::ShellWords::WordFailure␤» ``` ## class Text::ShellWords::Actions Actions class for C<.parse>. Use C<.new(:keep)> to keep quoting characters in the made words ## shell-words ### sub shell-words ``` sub shell-words( Cool:D $input, Bool :$keep = Bool::False ) returns Mu ``` Split a string into its shell-quoted words. If C is True, the quote characters are preserved in the returned words. By default they are removed. # SEE ALSO This module is inspired by, but has different behavior than, Perl's [Text::ParseWords](https://metacpan.org/pod/Text::ParseWords) and [Text::Shellwords](https://metacpan.org/pod/Text::Shellwords). The [Bash manual page](https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Quoting) describes the three quoting mechanisms copied by this module. # AUTHOR Tim Siegel [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2020 Tim Siegel This library is free software; you can redistribute and modify it under the [Artistic License 2.0](http://www.perlfoundation.org/artistic_license_2_0).
## dist_zef-thundergnat-Smooth-Numbers.md [![Actions Status](https://github.com/thundergnat/smooth-numbers/actions/workflows/test.yml/badge.svg)](https://github.com/thundergnat/smooth-numbers/actions) # NAME Smooth::Numbers Given a list of prime factors, return an iterator which will produce numbers that are "smooth" to those factors. # SYNOPSIS ``` use Smooth::Numbers; my $Hammings = smooth-numbers(2,3,5); put $Hammings[^20]; # 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36 ``` # DESCRIPTION Smooth numbers are defined as "numbers that are products of small prime factors." Hamming numbers, which are the numbers that are products of 2, 3, 5, is the classic example. The first ten Hamming numbers ( 2,3,5 smooth numbers ) are: ``` 1 ( 2⁰ * 3⁰ * 5⁰ ) 2 ( 2¹ * 3⁰ * 5⁰ ) 3 ( 2⁰ * 3¹ * 5⁰ ) 4 ( 2² * 3⁰ * 5⁰ ) 5 ( 2⁰ * 3⁰ * 5¹ ) 6 ( 2¹ * 3¹ * 5⁰ ) 8 ( 2³ * 3⁰ * 5⁰ ) 9 ( 2⁰ * 3² * 5⁰ ) 10 ( 2¹ * 3⁰ * 5¹ ) 12 ( 2² * 3¹ * 5⁰ ) ``` Smooth numbers are easy to conceptualize but can be challenging to generate in order. This module provides a simple routine to overcome that. Exports a single subroutine: ``` sub smooth-numbers(*@factors) ``` Takes a list or array of factors and returns an iterator that generates an ordered sequence of numbers that are smooth to those factors. The factors need not be in any order, and need not be prime. Smooth numbers traditionally are thought of as products of only prime factors, but if you want, for instance, the products of powers of 4 and 9, this module will oblige. ``` put smooth-numbers(4,9)[^15]; # 1 4 9 16 36 64 81 144 256 324 576 729 1024 1296 2304 ``` For that matter, there is no constraint that the "factors" need even be integers. ``` put smooth-numbers(1.5,2.5)[^10]; # 1 1.5 2.25 2.5 3.375 3.75 5.0625 5.625 6.25 7.59375 ``` There *are* a few constraints: * there must be at least one passed factor. * the passed parameters must all be numeric. (Can't exponentiate strings). * the factors must all be greater than or equal to 1 (or the sequence would be non-ascending). Note that if *any* of the factors is equal to 1, the sequence will return an infinite series of 1s. Should be obvious why if you think about it. # AUTHOR 2019 Steve Schulze aka thundergnat This package is free software and is provided "as is" without express or implied warranty. You can redistribute it and/or modify it under the same terms as Perl itself. # LICENSE Licensed under The Artistic 2.0; see LICENSE.
## dist_github-yowcow-Digest-MurmurHash3.md [![Build Status](https://travis-ci.org/yowcow/p6-Digest-MurmurHash3.svg?branch=master)](https://travis-ci.org/yowcow/p6-Digest-MurmurHash3) # NAME Digest::MurmurHash3 - MurmurHash3 implementation for Perl 6 # SYNOPSIS ``` use Digest::MurmurHash3; my Int $uint32 = murmurhash3_32($key, $seed); my Buf $hex8 = murmurhash3_32_hex($key, $seed); my Int @uint32 = murmurhash3_128($key, $seed); my Buf $hex32 = murmurhash3_128_hex($key, $seed); ``` # DESCRIPTION Digest::MurmurHash3 is a [MurmurHash3](https://github.com/aappleby/smhasher) hashing algorithm implementation. # METHODS ## murmurhash3\_32(Str $key, uint32 $seed) returns Int Calculates 32-bit hash, and returns as Int. ## murmurhash3\_32\_hex(Str $key, uint32 $seed) returns Buf Calculates 32-bit hash, and returns as Buf. A hex string can be obtained with `.unpack("H4")`. ## murmurhash3\_128(Str $key, uint32 $seed) returns Array[Int] Calculates 128-bit hash, and returns as Array[Int] with length of 4. ## murmurhash3\_128\_hex(Str $key, uint32 $seed) returns Buf Calculates 128-bit hash, and returns as Buf. A hex string can be obtained with `.unpack("H16")`. # INSTALL For installation from source, [zef](https://github.com/ugexe/zef) is required. ``` zef build . zef test . zef install . ``` # AUTHOR yowcow [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE MurmurHash3 was written by [Austin Appleby](https://github.com/aappleby), and is released under MIT license. Copyright 2016 yowcow This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-jonathanstowe-RPi-Device-DS18B20.md # RPi::Device::DS18B20 Interface to the DS18B20 digital thermometer from Maxim Integrated [![CI](https://github.com/jonathanstowe/RPi-Device-DS18B20/actions/workflows/main.yml/badge.svg)](https://github.com/jonathanstowe/RPi-Device-DS18B20/actions/workflows/main.yml) ## Synopsis ``` use RPi::Device::DS18B20; my $t = RPi::Device::DS18B20.new; for $t.thermometers -> $thermometer { say $thermometer.name, ":\t", $thermometer.temperature; } ``` Or asynchronously: ``` use RPi::Device::DS18B20; my $t = RPi::Device::DS18B20.new; react { whenever $t -> $reading { say $reading.when, "\t", $reading.name, "\t", $reading.temperature; } } ``` The source is in the <examples> directory of the distribution. ## Description The [DS18B20](https://www.maximintegrated.com/en/products/sensors/DS18B20.html) is a handy and inexpensive digital thermometer that uses the [Dallas 1-Wire bus](https://en.wikipedia.org/wiki/1-Wire). The Linux kernel has support for 1-Wire which can be enabled with `raspi-config` (via `Interface Options -> 1-Wire`,) which by default enables the 1-Wire interface on GPIO 4 as per: ![Raspberry Pi GPIO pins](https://www.raspberrypi.com/documentation/computers/images/GPIO-Pinout-Diagram-2.png) The minimum viable circuit will be something like: [![Minimal Circuit](examples/hardware/ds18b20.png)](examples/hardware/ds18b20.png) The 4.7K resistor is required as a pull up on the data wire, only one appears to be needed for multiple sensors on the same bus. It can be configured on another pin (or pins,) as described [here](https://blog.oddbit.com/post/2018-03-27-multiple-1-wire-buses-on-the/) Each thermometer has a unique identifer (in common with all 1-Wire sensors,) which means that multiple thermometers can be used on the same bus at once, however there is no way of distinguishing the devices without querying them, so a programme may need to provide its own mapping of identifier to thermometer (location etc,) this can be achieved by either wiring them in one by one, running something like the synopsis code and noting the identifier (and presumably labelling the sensor,) or by applying some heat source to each one in turn (if you have one of the encapsulated "waterproof" sensors a cup of hot water is ideal, but holding the sensor in your hand should work if the ambient temperature is lower than body temparature,) and similarly noting the identifier. The module provides for the enumeration of the thermometers detected on the 1-Wire bus providing a list of `Thermometer` objects, having a name attribute and a `temperature` method that returns the degrees Celcius with a precision of a thousandth of a degree (though the device is commonly stated as having ±0.5⁰ accuracy so this precision may or may not be useful to you.) The default "conversion time" for the device is 750 milliseconds so requesting the temperature more frequently than that is likely to be fruitless. Alternatively the `RPi::Device::DS18B20` object provides a `Supply` "coercion" method which allows it be used anywhere a `Supply` can be used (such as a `whenever` in a `react` block,) this will emit a `Reading` object with a `name` attribute of the sensor id, a `temperature` attribute with the measured temperature and a `when` attribute, for every sensor detected at minimum frequency determined by the `supply-interval` attribute as supplied to the constructor (the default is 30 seconds.) The readings may not be emitted in a predictable order at each interval as each sensor may take a different length of time to produce a reading, plus the bus protocol will, by necessity, serialise the readings. ## Install Assuming you have a working copy of Rakudo you can install with *zef* : ``` zef install RPi::Device::DS18B20 ``` It is unlikely to work on anything else than a Raspberry Pi. ## Support This is difficult to test in a completely automated fashion without the actual device attached and knowing what the temparature should be so there may be bugs which I haven't noticed. Please send any patches/suggestions/issues via [Github](https://github.com/jonathanstowe/RPi-Device-DS18B20/issues). Ideally any reports should include the Raspberry Pi and OS versions and some indication of how the device was wired up. This may work with other 1-Wire thermometer sensors [supported by the Linux kernel](https://www.kernel.org/doc/html/latest/w1/slaves/w1_therm.html) by adjusting the `device-class` passed to the constructor, but as I don't have any to test with right now I can't make any guarantees, it also appears that DS18B20 is by far and away the most commonly used. ## Copyright & Licence This is free software, please see the <LICENCE> in the distribution. © Jonathan Stowe 2022
## dist_zef-lizmat-P5substr.md [![Actions Status](https://github.com/lizmat/P5substr/workflows/test/badge.svg)](https://github.com/lizmat/P5substr/actions) # NAME Raku port of Perl's substr() built-in # SYNOPSIS ``` use P5substr; # exports substr() say substr("foobar",3); # bar say substr("foobar",1,4); # ooba my $a = "foobar"; substr($a,1,2) = "OO"; say $a; # fOObar ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `substr` built-in as closely as possible in the Raku Programming Language. # ORIGINAL PERL DOCUMENTATION ``` substr EXPR,OFFSET,LENGTH,REPLACEMENT substr EXPR,OFFSET,LENGTH substr EXPR,OFFSET Extracts a substring out of EXPR and returns it. First character is at offset zero. If OFFSET is negative, starts that far back from the end of the string. If LENGTH is omitted, returns everything through the end of the string. If LENGTH is negative, leaves that many characters off the end of the string. my $s = "The black cat climbed the green tree"; my $color = substr $s, 4, 5; # black my $middle = substr $s, 4, -11; # black cat climbed the my $end = substr $s, 14; # climbed the green tree my $tail = substr $s, -4; # tree my $z = substr $s, -4, 2; # tr You can use the substr() function as an lvalue, in which case EXPR must itself be an lvalue. If you assign something shorter than LENGTH, the string will shrink, and if you assign something longer than LENGTH, the string will grow to accommodate it. To keep the string the same length, you may need to pad or chop your value using "sprintf". If OFFSET and LENGTH specify a substring that is partly outside the string, only the part within the string is returned. If the substring is beyond either end of the string, substr() returns the undefined value and produces a warning. When used as an lvalue, specifying a substring that is entirely outside the string raises an exception. Here's an example showing the behavior for boundary cases: my $name = 'fred'; substr($name, 4) = 'dy'; # $name is now 'freddy' my $null = substr $name, 6, 2; # returns "" (no warning) my $oops = substr $name, 7; # returns undef, with warning substr($name, 7) = 'gap'; # raises an exception An alternative to using substr() as an lvalue is to specify the replacement string as the 4th argument. This allows you to replace parts of the EXPR and return what was there before in one operation, just as you can with splice(). my $s = "The black cat climbed the green tree"; my $z = substr $s, 14, 7, "jumped from"; # climbed # $s is now "The black cat jumped from the green tree" Note that the lvalue returned by the three-argument version of substr() acts as a 'magic bullet'; each time it is assigned to, it remembers which part of the original string is being modified; for example: $x = '1234'; for (substr($x,1,2)) { $_ = 'a'; print $x,"\n"; # prints 1a4 $_ = 'xyz'; print $x,"\n"; # prints 1xyz4 $x = '56789'; $_ = 'pq'; print $x,"\n"; # prints 5pq9 } With negative offsets, it remembers its position from the end of the string when the target string is modified: $x = '1234'; for (substr($x, -3, 2)) { $_ = 'a'; print $x,"\n"; # prints 1a4, as above $x = 'abcdefg'; print $_,"\n"; # prints f } Prior to Perl version 5.10, the result of using an lvalue multiple times was unspecified. Prior to 5.16, the result with negative offsets was unspecified. ``` # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/P5substr> . 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-JJMERELO-Text-Chart.md # Text::Chart [Test](https://github.com/JJ/p6-text-chart/actions/workflows/test.yaml) A simple Text Chart for Raku ## Running an example `raku-text-chart` should have been installed in your binary directory, you can run it directly this way: ``` raku-text-chart 3 2 1 4 ``` Obtaining a result such as this one: ``` ▮ ▮ ▮ ▮ ▮ ▮ ▮ ▮ ▮▮ ▮ ▮▮ ▮ ▮▮▮▮ ▮▮▮▮ ``` Or you can use ``` raku-text-chart --max=4 --chart-chars=▐░▓█ 3 2 1 4 ``` Which will give us: ``` █ ▐ █ ▐░ █ ▐░▓█ ``` ## License This is distributed under the GNU GPL v3
## dist_zef-dwarring-LibXML.md [![Actions Status](https://github.com/libxml-raku/LibXML-raku/workflows/test/badge.svg)](https://github.com/libxml-raku/LibXML-raku/actions) [![SparrowCI](https://ci.sparrowhub.io/project/git-dwarring-LibXML-raku/badge)](https://ci.sparrowhub.io) [[Raku LibXML Project]](https://libxml-raku.github.io) / [[LibXML Module]](https://libxml-raku.github.io/LibXML-raku) / # NAME LibXML - Raku bindings to the libxml2 native library # SYNOPSIS ``` use LibXML; use LibXML::Document; my LibXML::Document $doc .= parse: :string('<Hello/>'); $doc.root.nodeValue = 'World!'; say $doc.Str; # <?xml version="1.0" encoding="UTF-8"?> # <Hello>World!</Hello> say $doc<Hello>; # <Hello>World!</Hello> my Version $library-version = LibXML.version; my Version $module-version = LibXML.^ver; ``` # DESCRIPTION This module is an interface to libxml2, providing XML and HTML parsers with DOM, SAX and XMLReader interfaces, a large subset of DOM Layer 3 interface and a XML::XPath-like interface to XPath API of libxml2. For further information, please check the following documentation: ## DOM Objects The nodes in the Document Object Model (DOM) are represented by the following classes (most of which "inherit" from [LibXML::Node](https://libxml-raku.github.io/LibXML-raku/Node)): * [LibXML::Document](https://libxml-raku.github.io/LibXML-raku/Document) - LibXML DOM document class * [LibXML::Attr](https://libxml-raku.github.io/LibXML-raku/Attr) - LibXML attribute class * [LibXML::CDATA](https://libxml-raku.github.io/LibXML-raku/CDATA) - LibXML class for DOM CDATA sections * [LibXML::Comment](https://libxml-raku.github.io/LibXML-raku/Comment) - LibXML class for comment DOM nodes * [LibXML::DocumentFragment](https://libxml-raku.github.io/LibXML-raku/DocumentFragment) - LibXML's DOM L2 Document Fragment implementation * [LibXML::Dtd](https://libxml-raku.github.io/LibXML-raku/Dtd) - LibXML front-end for DTD validation * [LibXML::Element](https://libxml-raku.github.io/LibXML-raku/Element) - LibXML class for element nodes * [LibXML::EntityRef](https://libxml-raku.github.io/LibXML-raku/EntityRef) - LibXML class for entity references * [LibXML::Namespace](https://libxml-raku.github.io/LibXML-raku/Namespace) - LibXML namespaces (Inherits from [LibXML::Item](https://libxml-raku.github.io/LibXML-raku/Item)) * [LibXML::Node](https://libxml-raku.github.io/LibXML-raku/Node) - LibXML DOM abstract base node class * [LibXML::Text](https://libxml-raku.github.io/LibXML-raku/Text) - LibXML text node class * [LibXML::PI](https://libxml-raku.github.io/LibXML-raku/PI) - LibXML DOM processing instruction nodes See also [LibXML::DOM](https://libxml-raku.github.io/LibXML-raku/DOM), which summarizes DOM classes and methods. ## Container/Mapping classes * [LibXML::Attr::Map](https://libxml-raku.github.io/LibXML-raku/Attr/Map) - LibXML DOM attribute map class * [LibXML::Node::List](https://libxml-raku.github.io/LibXML-raku/Node/List) - Sibling Node Lists * [LibXML::Node::Set](https://libxml-raku.github.io/LibXML-raku/Node/Set) - XPath Node Sets * [LibXML::HashMap](https://libxml-raku.github.io/LibXML-raku/HashMap) - LibXML Hash Bindings ## Parsing * [LibXML::Parser](https://libxml-raku.github.io/LibXML-raku/Parser) - LibXML Parser bindings * [LibXML::PushParser](https://libxml-raku.github.io/LibXML-raku/PushParser) - LibXML Push Parser bindings * [LibXML::Reader](https://libxml-raku.github.io/LibXML-raku/Reader) - LibXML Reader (pull parser) bindings ### SAX Parser * [LibXML::SAX::Builder](https://libxml-raku.github.io/LibXML-raku/SAX/Builder) - Builds SAX callback sets * [LibXML::SAX::Handler::SAX2](https://libxml-raku.github.io/LibXML-raku/SAX/Handler/SAX2) - SAX handler base class * [LibXML::SAX::Handler::XML](https://libxml-raku.github.io/LibXML-raku/SAX/Handler/XML) - SAX Handler for XML ## XPath and Searching * [LibXML::XPath::Expression](https://libxml-raku.github.io/LibXML-raku/XPath/Expression) - XPath Compiled Expressions * [LibXML::XPath::Context](https://libxml-raku.github.io/LibXML-raku/XPath/Context) - XPath Evaluation Contexts * [LibXML::Pattern](https://libxml-raku.github.io/LibXML-raku/Pattern) - LibXML Patterns * [LibXML::RegExp](https://libxml-raku.github.io/LibXML-raku/RegExp) - LibXML Regular Expression bindings ## Validation * [LibXML::Dtd](https://libxml-raku.github.io/LibXML-raku/Dtd) - LibXML DTD validation class * [LibXML::Schema](https://libxml-raku.github.io/LibXML-raku/Schema) - LibXML schema validation class * [LibXML::RelaxNG](https://libxml-raku.github.io/LibXML-raku/RelaxNG) - LibXML RelaxNG validation class ## Other * [LibXML::Config](https://libxml-raku.github.io/LibXML-raku/Config) - LibXML global and local configuration * [LibXML::Enums](https://libxml-raku.github.io/LibXML-raku/Enums) - XML\_\* enumerated constants * [LibXML::Raw](https://libxml-raku.github.io/LibXML-raku/Raw) - LibXML native interface * [LibXML::ErrorHandling](https://libxml-raku.github.io/LibXML-raku/ErrorHandling) - LibXML class for Error handling * [LibXML::InputCallback](https://libxml-raku.github.io/LibXML-raku/InputCallback) - LibXML class for Input callback handling * See also [LibXML::Threads](https://libxml-raku.github.io/LibXML-raku/Threads), for notes on threading and concurrency # PREREQUISITES This module may requires the libxml2 library to be installed. Please follow the instructions below based on your platform: ## Debian/Ubuntu Linux ``` sudo apt-get install libxml2-dev ``` Additional packages (such as build-essential) may be required to enable make, C compilation and linking. ## Mac OS X ``` brew update brew install libxml2 ``` The Xcode package also needs to be installed to enable compilation. ## Windows This module uses prebuilt DLLs on Windows. There are currently some configuration (`LibXML::Config`) restrictions: * `parser-locking` is set `True` to to disable concurrent parsing. This is due to known threading issues and unresolved failures in `t/90threads.t` * `iconv` is `False`. The library is built without full Unicode support, which restricts the ability to read and write various encoding schemes. * `compression` is `False`. The library is built without full compression, and is unable to read and write compressed XML directly. # ACKNOWLEDGEMENTS This Raku module: * is based on the Perl XML::LibXML module; in particular, the test suite, selected XS and C code and documentation. * derives SelectorQuery() and SelectorQueryAll() methods from the Perl XML::LibXML::QuerySelector module. * also draws on an earlier attempt at a Perl 6 (nee Raku) port (XML::LibXML). With thanks to: Christian Glahn, Ilya Martynov, Matt Sergeant, Petr Pajas, Shlomi Fish, Toby Inkster, Tobias Leich, Xliff, and others. # COPYRIGHT 2001-2007, AxKit.com Ltd. 2002-2006, Christian Glahn. 2006-2009, Petr Pajas. # LICENSE This program is free software; you can redistribute it and/or modify it under the terms of the Artistic License 2.0 <http://www.perlfoundation.org/artistic_license_2_0>.
## dist_zef-raku-community-modules-IDNA-Punycode.md [![Actions Status](https://github.com/raku-community-modules/IDNA-Punycode/workflows/test/badge.svg)](https://github.com/raku-community-modules/IDNA-Punycode/actions) # NAME IDNA::Punycode - Punycode implementation according to RFC3492 # SYNOPSIS ``` use IDNA::Punycode; say encode_punycode 'nice' # nice say encode_punycode 'schön' # xn--schn-7qa say decode_punycode 'nice' # nice say decode_punycode 'xn--schn-7qa' # schön ``` # DESCRIPTION The `IDNA::Punycode` provides an easy way to encode / decode strings according to [RFC3492](https://www.rfc-editor.org/info/rfc3492). # AUTHOR Tobias Leich (FROGGS) Source can be located at: <https://github.com/raku-community-modules/IDNA-Punycode> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2015, 2016, 2017 Tobias Leich, 2023 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-lizmat-Rakudo-CORE-META.md [![Actions Status](https://github.com/lizmat/Rakudo-CORE-META/workflows/test/badge.svg)](https://github.com/lizmat/Rakudo-CORE-META/actions) # NAME Rakudo::CORE::META - Provide zef compatible meta-data for Rakudo # SYNOPSIS ``` use Rakudo::CORE::META; say "Rakudo core provides these additional modules:"; .say for %Rakudo::CORE::META<provides>.keys.sort(*.fc); ``` # DESCRIPTION Rakudo::CORE::META provides zef compatible meta-data of the modules that are provided by the Rakudo core, by exporting `%Rakudo::CORE::META` hash. This hash contains information that could be introspected at installation time of the module, or after any Rakudo core update. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Rakudo-CORE-META> . 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 2021, 2022 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-azawawi-Parse-Selenese.md # Parse::Selenese [Build Status](https://travis-ci.org/azawawi/perl6-parse-selenese) This is a simple utility to parse Selenese test cases and suites that are usually generated from the Selenium IDE. ## Example ``` use Parse::Selenese; my $selenese = qq{<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head profile="http://selenium-ide.openqa.org/profiles/test-case"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="selenium.base" href="http://some-server:3000/" /> <title>Login</title> </head> <body> <table cellpadding="1" cellspacing="1" border="1"> <thead> <tr><td rowspan="1" colspan="3">Login</td></tr> </thead><tbody> <tr> <td>open</td> <td>/login</td> <td></td> </tr> <tr> <td>type</td> <td>name=username</td> <td>admin</td> </tr> <tr> <td>type</td> <td>name=password</td> <td>123</td> </tr> <tr> <td>clickAndWait</td> <td>//button[@type='submit']</td> <td></td> </tr> <tr> <td>verifyTitle</td> <td>regex:Home</td> <td></td> </tr> </tbody></table> </body> </html> }; my $parser = Parse::Selenese.new; my $result = $parser.parse($selenese); if $result { say "Matches with the following results: " ~ $result.ast.perl; } else { say "Fails"; } ``` ## Installation To install it using Panda (a module management tool bundled with Rakudo Star): ``` $ panda update $ panda install Parse::Selenese ``` ## Testing To run tests: ``` $ prove -e "perl6 -Ilib" ``` ## Author Ahmad M. Zawawi, azawawi on #perl6, <https://github.com/azawawi/> ## License Artistic License 2.0
## dist_zef-kjpye-Geo-Geometry.md [![Actions Status](https://github.com/kjpye/Raku-Geo-Geometry/actions/workflows/test.yml/badge.svg)](https://github.com/kjpye/Raku-Geo-Geometry/actions) # TITLE Geo::Geometry `Geo::Geometry` is a module containing a series of classes defining objects descibing geographic objects. The module is based on chapters 8 and 9 of the Open Geospatial Consortium's *OpenGISⓇ Implemantation Standard for Geographic Information - Simple Feature Access - part 1: Common architecture*. This can be obtained from <https://www.ogc.org/standards/sfa>. # Geo::Geometry A series of classes for storing geographic data. ## Generic Methods The following methods are available for most classes. Classes for which they are not available are documented below. ### type The `type` method returns a member of the `WKBGeometryType` enum corresponding to the geometry type. ### Str The `Str` method returns a string representing the object. Note that this is **not** the WKT representation, which can be obtained using the `wkt` method described below. ### wkb The `wkb` method will produce a `Buf` object with the well-known-binary representation of the object. An optional named argument `byteorder` parameter is available. The value of the argument is one of the values of the `WKBByteOrder` enum. The default value is `wkbXDR` (little endian) with the alternative being `wkbNDR` (big endian). ### wkt The `wkt` method returns a string containing the well-known text representation of the geometry. ### tobuf The `tobuf` method is used internally; This interface may change without warning. ## Subroutines The subroutines `from-wkb` and `from-wkt` previously available in this module are now avialable from `Geo::WellKnownBinary` and `Geo::WellKnownText` respectively. ## Enums Two enums are defined which represent values used in the WKB representation of a geometry. ### WKBByteOrder The `WKBByteOrder` enum gives the values used in the byte order field of a WKB representation. It contains two values `wkbXDR` (0, little-endian) and `wkbBDR` (1, big-endian). ### WKBGeometryType The `WKBGeometryType` enum contains the values used in the geometry type filed of a WKB representation. It allows for the following values: | | | | --- | --- | | 1 | wkbPoint | | 2 | wkbLineString | | 3 | wkbPolygon | | 4 | wkbMultiPoint | | 5 | wkbMultiLineString | | 6 | wkbMultiPolygon | | 7 | wkbGeometryCollection | | 15 | wkbPolyhedralSurface | | 16 | wkbTIN | | 17 | wkbTriangle | | 1001 | wkbPointZ | | 1002 | wkbLineStringZ | | 1003 | wkbPolygonZ | | 1004 | wkbMultiPointZ | | 1005 | wkbMultiLineStringZ | | 1006 | wkbMultiPolygonZ | | 1007 | wkbGeometryCollectionZ | | 1015 | wkbPolyhedralSurfaceZ | | 1016 | wkbTINZ | | 1017 | wkbTriangleZ | | 2001 | wkbPointM | | 2002 | wkbLineStringM | | 2003 | wkbPolygonM | | 2004 | wkbMultiPointM | | 2005 | wkbMultiLineStringM | | 2006 | wkbMultiPolygonM | | 2007 | wkbGeometryCollectionM | | 2015 | wkbPolyhedralSurfaceM | | 2016 | wkbTINM | | 2017 | wkbTriangleM | | 3001 | wkbPointZM | | 3002 | wkbLineStringZM | | 3003 | wkbPolygonZM | | 3004 | wkbMultiPointZM | | 3005 | wkbMultiLineStringZM | | 3006 | wkbMultiPolygonZM | | 3007 | wkbGeometryCollectionZM | | 3015 | wkbPolyhedralSurfaceZM | | 3016 | wkbTINZM | | 3017 | wkbTriangleZM | ## Object types (classes) ### Geometry `Geometry` is a role which all the other objects inherit. It contains no methods, and is simply a marker that another class is a Geometry type. If you want to check whether a variable contains any of the geometry classes, then code like ``` if $variable ~~ Geometry { ... } ``` can be useful. ### Point ### PointZ ### PointM ### PointZM The `Point` class represents a single point geometry. It has two attributes, `x` and `y`, each of which is constrained to be a 64-bit floating point number (`num`). The `PointZ` class also contains a third attribute `z` to represent a third dimension. The `PointM` class, in addition to the `X` and `y` attributes contains an `m` attribute which can contain an arbitrary "measure" in addition to the two-dimensionallocation. The `PointMZ` class combines the `z` attribute of `PointZ` and the `m` attribute of `PointM`. An object of each class may be constructed either by using named parameters (`Point.new(x => 10, y => 12)`, or by using positional parameters (`PointZ.new(1,2,3)`). When positional parameters are used, the ordering of the parameters is `x`, `y`, `z`, `m`; omitting those parameters which are not appropriate for the object type. All the parameters of a point geometry are required. `NaN` might be used if an `m` parameter for example were not required. Accessor methodes are available for the `x`, `y`, `z` and `m`. ## LineString ## LineStringZ ## LineStringM ## LineStringZM The `LineString` class represents a single line, a sequence of `Point`s, not necessarily closed. Similarly, `LineStringZ`, `LineStringM` and `LineStringZM` are lines consisting of sequences of `PointZ`s, `PointM`sand `PointZM`s respectively. An object in the LineString family is created by passing an array of the appropriate point type geometries, to the named argument `points`. At the moment there is no way of accessing the contents of a LineString geometry other than using the standard methods. An accessor method `points` will give the constituent points. ### LinearRing ### LinearRingZ ### LinearRingM ### LinearRingZM Objects in the LinearRing classes are not normally intended for end users, apart from their use in creating more complex objects. None of the usual methods apply to these types of object. A linear ring is similar to a line string, but is closed; i.e. the last point should be identical to the first point. This is not currently enforced, but may be in the future. Creation of a linear ring is the same as that of a line string. The ring should be simple; the path should not cross itself. This is also not enforced. Each of these classes has a `winding` method. This determines whether the linear ring is clockwise (a positive number is returned) or anti-clockwise (a negative number is returned). This method will be unreliable unless the linear ring actually is a simple closed loop. The winding method ignores everything except the `x` and `y` attributes. An accessor method `points` will give the constituent points. ### Polygon ### PolygonZ ### PolygonM ### PolygonZM A `Polygon` consists of one or more `LinearRings`. In general, the first linear ring should be clockwise (with a positive winding number). The other linear rings should be fully enclosed within the first and be disjoint from each other. They should have a negative winding number. These rings represent a polygon (the first ring) and holes within that polygon, represented by the other rings. Having only a single ring specified is acceptable (and normal under most circumstances), representing a polygon without holes. A `Polygon` is created using an array of rings, such as `Polygon.new(rings => @rings)`. An accessor method `rings` will give the constituent rings. `PolygonZ`, `PolygonM` and `PolygonZM` behave similarly. ### Triangle ### TriangleZ ### TriangleM ### TriangleZM A triangle is a polygon where the outer ring has exactly four points, the fourth being the same as the first and otherwise having no oints in common. The points must not be in a straight line. No internal rings are permitted. An accessor method `rings` gives the constituent rings. ### PolyhedralSurface ### PolyhedralSurfaceZ ### PolyhedralSurfaceM ### PolyhedralSurfaceZM A polyhedral surface is a set of contiguous non-overlapping polygons. (There are further restrictions.) ### TIN ### TINZ ### TINM ### TINZM A triangular irregular network is a polyhedral surface consisting only of triangles. ### MultiPoint ### MultiPointZ ### MultiPointM ### MultiPointZM The MultiPoint classes behave just like LineStrings, including their definition. The difference is the intent of the object. A LineString, as the name implies, forms a line. A MultiPoint object is just a collection of points. ### MultiLineString ### MultiLineStringZ ### MultiLineStringM ### MultiLineStringZM A `MultiLineString` object contains an array of `LineString`s. It is created with that array: ``` MultiLineString.new(linestrings => @array-of-linestrings) ``` ### MultiPolygon ### MultiPolygonZ ### MultiPolygonM ### MultiPolygonZM Just as a `MultiPoint` is a collections of `Point`s, and a `MultiLineString` is a collection of `LineString`s, a `MultiPolygon` is a collection of `Polygon`s. ### GeometryCollection ### GeometryCollectionZ ### GeometryCollectionM ### GeometryCollectionZM A GeometryCollection is an arbitrary collection of geometry objects. Unlike a PointCollection, a LineStringCollection or a PolygonCollection, the objects do not need to be of the same geometry type.
## dist_zef-CIAvash-APISports-Football.md # NAME APISports::Football - An interface to [API-Football](https://www.api-football.com/). # DESCRIPTION APISports::Football is a [Raku](https://www.raku-lang.ir/en) module for interfacing with [API Sports Football](https://v3.football.api-sports.io). An API key is required to use the API. # SYNOPSIS ``` use APISports::Football:auth<zef:CIAvash>; my $f = APISports::Football.new: :api_key<1234>; my @competitions = $f.competitions: name => 'premier league', :current, type => LeagueType::League, :country<england>; ``` # INSTALLATION You need to have [Raku](https://www.raku-lang.ir/en) and [zef](https://github.com/ugexe/zef), then run: ``` zef install "APISports::Football:auth<zef:CIAvash>" ``` or if you have cloned the repo: ``` zef install . ``` # TESTING ``` prove -ve 'raku -I.' --ext rakutest ``` or ``` prove6 -I. -v ``` # ATTRIBUTES ## has Str $.api\_key API key required by api-football.com ## has APISports::Football::HTTPClient $.http\_client An object for making requests to api-football.com # METHODS ## method timezones ``` method timezones( Bool :h(:$http_body) ) returns Mu ``` Get the respone object containing list of available timezones. ## Bool :h(:$http\_body) Get the HTTP response body ## method countries ``` method countries( Bool :h(:$http_body), *%params (Str :$name, Str :$code where { ... }, Str :$search where { ... }) ) returns Mu ``` Get the respone object containing list of available countries. ### Bool :h(:$http\_body) Get the HTTP response body ### Str :$name Name of the country ### TwoChars :$code Code of the country ### SearchTerm :$search Name of the country ## method seasons ``` method seasons( Bool :h(:$http_body) ) returns Mu ``` Get the respone object containing list of available seasons for competitions. ### Bool :h(:$http\_body) Get the HTTP response body ## method competitions ``` method competitions( Bool :h(:$http_body), *%params (Int :$id where { ... }, Str :$name, Str :$country, Str :$code where { ... }, Int :$season where { ... }, Int :$team where { ... }, LeagueType(Str) :$type, Bool :$current, Str :$search where { ... }, Int :$last where { ... }) ) returns Mu ``` Get the respone object containing list of available competitions. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$id ID of the league ### Str :$name Name of the league ### Str :$country Country name of the league ### TwoChars :$code Code of the country ### Year :$season Season of the league ### ID :$team ID of the team ### LeagueType(Str) :$type Type of the league ### Bool :$current State of the league ### SearchTerm :$search Name or country name of the league ### AtMost2Digits :$last The X last leagues added to the API ## method clubs ``` method clubs( Bool :h(:$http_body), *%params (Int :$id where { ... }, Str :$name, Int :$league where { ... }, Str :$country, Int :$season where { ... }, Str :$search where { ... }) ) returns Mu ``` Get the respone object containing list of available clubs. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$id ID of the team ### Str :$name Name of the team ### ID :$league ID of the league ### Str :$country Country name of the team ### Year :$season Season of the league ### SearchTerm :$search Name or country name of the team ## method team\_stats ``` method team_stats( Bool :h(:$http_body), *%params (Int :$team! where { ... }, Int :$league! where { ... }, Int :$season! where { ... }, Date(Any) :$date) ) returns Mu ``` Get the respone object containing team's statistics. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$team! ID of the team ### ID :$league! ID of the league ### Year :$season! Season of the league ### Date() :$date The limit date ## method team\_seasons ``` method team_seasons( Bool :h(:$http_body), *%params (Int :$team! where { ... }) ) returns Mu ``` Get the respone object containing list of available seasons for a team. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$team! ID of the team ## method venues ``` method venues( Bool :h(:$http_body), *%params (Int :$id where { ... }, Str :$name, Str :$country, Str :$search where { ... }) ) returns Mu ``` Get the respone object containing list of available venues. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$id ID of the venue ### Str :$name Name of the venue ### Str :$country Country name of the venue ### SearchTerm :$search Name, city or the country of the venue ## method tables ``` method tables( Bool :h(:$http_body), *%params (Int :$team where { ... }, Int :$league where { ... }, Int :$season! where { ... }) ) returns Mu ``` Get the respone object containing standings of a league or team. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$team ID of the team ### ID :$league ID of the league ### Year :$season! Season of the league ## method rounds ``` method rounds( Bool :h(:$http_body), *%params (Int :$league! where { ... }, Int :$season! where { ... }, Bool :$current) ) returns Mu ``` Get the respone object containing list of rounds for a league or cup. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$league! ID of the league ### Year :$season! Season of the league ### Bool :$current Current round only ## method matches ``` method matches( Bool :h(:$http_body), *%params (Int :$id where { ... }, Str :$live where { ... }, Date(Any) :$date, Int :$league where { ... }, Int :$season where { ... }, Int :$team where { ... }, Int :$last where { ... }, Int :$next where { ... }, Date(Any) :$from, Date(Any) :$to, Str :$round, MatchStatus(Str) :$status, Str :$timezone where { ... }) ) returns Mu ``` Get the respone object containing list of available matches. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$id ID of the fixture ### AllOrIDs :$live all or IDs of two teams ### Date() :$date A valid date ### ID :$league ID of the league ### Year :$season Season of the league ### ID :$team ID of the team ### AtMost2Digits :$last For the X last fixtures ### AtMost2Digits :$next For the X next fixtures ### Date() :$from Fixtures from date ### Date() :$to Fixtures to date ### Str :$round Round of the fixture ### MatchStatus(Str) :$status Status of the fixture ### Timezone :$timezone A valid timezone ## method head\_to\_head ``` method head_to_head( Bool :h(:$http_body), *%params (Str :$h2h! where { ... }, Date(Any) :$date, Int :$league where { ... }, Int :$season where { ... }, Int :$last where { ... }, Int :$next where { ... }, Date(Any) :$from, Date(Any) :$to, MatchStatus(Str) :$status, Str :$timezone where { ... }) ) returns Mu ``` Get the respone object containing list of head to heads between two teams. ### Bool :h(:$http\_body) Get the HTTP response body ### IDs :$h2h! IDs of two teams ### Date() :$date Date of the fixtures ### ID :$league ID of the league ### Year :$season Season of the league ### AtMost2Digits :$last For the X last fixtures ### AtMost2Digits :$next For the X next fixtures ### Date() :$from Fixtures from date ### Date() :$to Fixtures to date ### MatchStatus(Str) :$status Status of the fixture ### Timezone :$timezone A valid timezone ## method match\_stats ``` method match_stats( Bool :h(:$http_body), *%params (Int :$fixture! where { ... }, Int :$team where { ... }, MatchStats(Str) :$type) ) returns Mu ``` Get the respone object containing statistics of a match. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$fixture! ID of the fixture ### ID :$team ID of the team ### MatchStats(Str) :$type Type of statistics ## method fixture\_events ``` method fixture_events( Bool :h(:$http_body), *%params (Int :$fixture! where { ... }, Int :$team where { ... }, Int :$player where { ... }, FixtureEvent(Str) :$type) ) returns Mu ``` Get the respone object containing events for a fixture. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$fixture! ID of the fixture ### ID :$team ID of the team ### ID :$player ID of the player ### FixtureEvent(Str) :$type Type of events ## method fixture\_lineups ``` method fixture_lineups( Bool :h(:$http_body), *%params (Int :$fixture! where { ... }, Int :$team where { ... }, Int :$player where { ... }, FixtureLineup(Str) :$type) ) returns Mu ``` Get the respone object containing lineups for a fixture. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$fixture! ID of the fixture ### ID :$team ID of the team ### ID :$player ID of the player ### FixtureEvent(Str) :$type Type of lineups ## method fixture\_players ``` method fixture_players( Bool :h(:$http_body), *%params (Int :$fixture! where { ... }, Int :$team where { ... }) ) returns Mu ``` Get the respone object containing statistics for players from a fixture. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$fixture! ID of the fixture ### ID :$team ID of the team ## method injuries ``` method injuries( Bool :h(:$http_body), *%params (Int :$league where { ... }, Int :$fixture where { ... }, Int :$team where { ... }, Int :$player where { ... }, Date(Any) :$date, Int :$season where { ... }, Str :$timezone where { ... }) ) returns Mu ``` Get the respone object containing list of players not participating in matches. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$league ID of the league ### ID :$fixture ID of the fixture ### ID :$team ID of the team ### ID :$player ID of the player ### Date() :$date Date of the injury ### Year :$season Season of the league, required with league, team and player parameters ### Timezone :$timezone A valid timezone ## method predictions ``` method predictions( Bool :h(:$http_body), *%params (Int :$fixture! where { ... }) ) returns Mu ``` Get the respone object containing predictions for a fixture. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$fixture! ID of the fixture ## method coachs ``` method coachs( Bool :h(:$http_body), *%params (Int :$id where { ... }, Int :$team where { ... }, Str :$search where { ... }) ) returns Mu ``` Get the respone object containing information about coachs and their careers. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$id ID of the coach ### ID :$team ID of the team ### SearchTerm :$search Name of the coach ## method players ``` method players( Bool :h(:$http_body), *%params (Int :$id where { ... }, Int :$team where { ... }, Int :$league where { ... }, Int :$season where { ... }, Str :$search where { ... }, Int :$page) ) returns Mu ``` Get the respone object containing information and statistics about players. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$id ID of the player ### ID :$team ID of the team ### ID :$league ID of the league ### Year :$season Season of the league ### SearchTerm :$search Name of the player ### Int :$page Use for pagination ## method player\_seasons ``` method player_seasons( Bool :h(:$http_body), *%params (Int :$player where { ... }) ) returns Mu ``` Get the respone object containing list of available seasons for players statistics. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$player ID of the player ## method squads ``` method squads( Bool :h(:$http_body), *%params (Int :$player where { ... }, Int :$team where { ... }) ) returns Mu ``` Get the respone object containing squad of a team or squads of a player. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$player ID of the player ### ID :$team ID of the team ## method top\_scorers ``` method top_scorers( Bool :h(:$http_body), *%params (Int :$league! where { ... }, Int :$season! where { ... }) ) returns Mu ``` Get the respone object containing best players for a league or cup. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$league! ID of the league ### Year :$season! Season of the league ## method top\_assists ``` method top_assists( Bool :h(:$http_body), *%params (Int :$league! where { ... }, Int :$season! where { ... }) ) returns Mu ``` Get the respone object containing best assists for a league or cup. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$league! ID of the league ### Year :$season! Season of the league ## method top\_yellow\_cards ``` method top_yellow_cards( Bool :h(:$http_body), *%params (Int :$league! where { ... }, Int :$season! where { ... }) ) returns Mu ``` Get the respone object containing players with the most yellow cards for a league or cup. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$league! ID of the league ### Year :$season! Season of the league ## method top\_red\_cards ``` method top_red_cards( Bool :h(:$http_body), *%params (Int :$league! where { ... }, Int :$season! where { ... }) ) returns Mu ``` Get the respone object containing players with the most red cards for a league or cup. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$league! ID of the league ### Year :$season! Season of the league ## method transfers ``` method transfers( Bool :h(:$http_body), *%params (Int :$player where { ... }, Int :$team where { ... }) ) returns Mu ``` Get the respone object containing all available transfers for players and teams. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$player ID of the player ### ID :$team --- ID of the team ## method trophies ``` method trophies( Bool :h(:$http_body), *%params (Int :$player where { ... }, Int :$coach where { ... }) ) returns Mu ``` Get the respone object containing all available trophies for a player or coach. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$player ID of the player ### ID :$coach ID of the coach ## method sidelined ``` method sidelined( Bool :h(:$http_body), *%params (Int :$player where { ... }, Int :$coach where { ... }) ) returns Mu ``` Get the respone object containing all available sidelined information for a player or coach. ### Bool :h(:$http\_body) Get the HTTP response body ### ID :$player ID of the player ### ID :$coach ID of the coach # ERRORS * If a response contains errors, a `Failure` of type `X::APISports::Football::APIError` is returned. * If HTTP errors occur, `Failure` of type `X::APISports::Football::HTTPError` is returned. # REPOSITORY <https://codeberg.org/CIAvash/APISports-Football> # BUGS <https://codeberg.org/CIAvash/APISports-Football/issues> # AUTHOR Siavash Askari Nasr <https://siavash.askari-nasr.com> # COPYRIGHT Copyright © 2022 Siavash Askari Nasr # LICENSE APISports::Football is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. APISports::Football is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with APISports::Football. If not, see <http://www.gnu.org/licenses/>.
## dist_zef-raku-community-modules-Image-PNG-Portable.md [![Actions Status](https://github.com/raku-community-modules/Image-PNG-Portable/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Image-PNG-Portable/actions) [![Actions Status](https://github.com/raku-community-modules/Image-PNG-Portable/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Image-PNG-Portable/actions) [![Actions Status](https://github.com/raku-community-modules/Image-PNG-Portable/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Image-PNG-Portable/actions) # NAME Image::PNG::Portable - portable PNG output for Raku # SYNOPSIS ``` use Image::PNG::Portable; my $o = Image::PNG::Portable.new: :width(16), :height(16); $o.set: 8,8, 255,255,255; $o.write: 'image.png'; ``` ## STATUS This module is currently useful for outputting 8-bit-per-channel truecolor images. Reading, precompression filters, palettes, grayscale, non-8-bit channels, and ancillary features like gamma correction, color profiles, and textual metadata are all NYI. # DESCRIPTION This is an almost-pure Raku PNG module. # USAGE The following types are used internally and in this documentation. They are here for brevity, not exported in the public API. ``` subset UInt8 of Int where 0 <= * <= 255; # unsigned 8-bit subset PInt of Int where * > 0; # positive ``` # METHODS ## .new(PInt :$width!, PInt :$height!, Bool $alpha = True) Creates a new `Image::PNG::Portable` object, initialized to black. If the alpha channel is enabled, it is initialized to transparent. ## .set(UInt $x, UInt $y, UInt8 $red, UInt8 $green, UInt8 $blue, UInt8 $alpha = 255) Sets the color of a pixel in the image. ## .set-all(UInt8 $red, UInt8 $green, UInt8 $blue, UInt8 $alpha = 255) Sets the color of all pixels in the image. ## .get(UInt $x, UInt $y) Gets the color of a pixel in the image as an array of channel values. ## .write($file) Writes the contents of the image to the specified file. # AUTHOR raydiak # COPYRIGHT AND LICENSE Copyright 2015 - 2021 raydiak Copyright 2025 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-nige123-WAT.md # wat.nigelhamilton.com wat - does this code do? LLM-powered utility for quickly understanding code. Usage: ``` wat <filename> -- summarise what the program does wat "$some-code.here();" -- explain what some code does ``` ![](images/demo.gif?raw=true)
## code.md code Combined from primary sources listed below. # [In CallFrame](#___top "go to top of document")[§](#(CallFrame)_method_code "direct link") See primary documentation [in context](/type/CallFrame#method_code) for **method code**. ```raku method code() ``` Return the callable code for the current block. When called on the object returned by `callframe(0)`, this will be the same value found in [`&?BLOCK`](/language/variables#Compile-time_variables). ```raku my $frame; for ^3 { FIRST $frame = callframe; say $_ * 3 }; say $frame.code() ``` The `$frame` variable will hold the [`Code`](/type/Code) for the block inside the loop in this case. # [In Backtrace::Frame](#___top "go to top of document")[§](#(Backtrace::Frame)_method_code "direct link") See primary documentation [in context](/type/Backtrace/Frame#method_code) for **method code**. ```raku method code(Backtrace::Frame:D) ``` Returns the code object into which `.file` and `.line` point, if available. ```raku my $bt = Backtrace.new; my $btf = $bt[0]; say $btf.code; ```
## dist_zef-Scimon-Test-HTTP-Server.md [![Build Status](https://travis-ci.org/Scimon/p6-Test-HTTP-Server.svg?branch=master)](https://travis-ci.org/Scimon/p6-Test-HTTP-Server) # NAME Test::HTTP::Server - Simple to use wrapper around HTTP::Server::Async designed for tests # SYNOPSIS ``` use Test::HTTP::Server; # Simple usage # $path is a folder with a selection of test files including index.html my $test-server = Test::HTTP::Server.new( :dir($path) ); # method-to-test expects a web host and will make a GET request to host/index.html ok method-to-test( :host( "http://localhost:{$test-server.port}" ) ), "This is a test"; # Other tests on the results here. my @events = $test-server.events; is @events.elems, 1, "One request made"; is @events[0].path, '/index.html', "Expected path called"; is @events[0].method, 'GET', "Expected method used"; is @events[0].code, 200, "Expected response code"; $test-server.clear-events; ``` # DESCRIPTION Test::HTTP::Server is a wrapper around HTTP::Server::Async designed to allow for simple Mock testing of web services. The constructor accepts a 'dir' and an optional 'port' parameter. The server will server up any files that exist in 'dir' on the given port (if not port is given then one will be assigned, the '.port' method can be accessed to find what port is being used). All requests are logged in a basic even log allowing for testing. If you make multiple async requests to the server the ordering of the events list cannot be assured and tests should be written based on this. If a file doesn't exist then the server will return a 404. Currently the server returns all files as 'text/plain' except files with the following extensions : * `html` => `text/html` * `png` => `image/png` * `jpg` => `image/jpeg` * `jpeg` => `image/jpeg` * `gif` => `image/gif` * `js` => `application/javascript` * `json` => `application/json` * `css` => `text/css` * `xml` => `application/xml` ## CONFIG You can include a file called `config.yml` in the file which allows for additional control over the responses. The following keys are available : ### mime Hash representation of extension and mime type header allows adding additional less common mime types. ### paths Hash where keys are paths to match (including leading `/`), values are hashes with the currently allowed keys : #### returns A list of commands to specify the return result, currently valid values. * Any 3 digit code => returns that HTTP status. * "file" => returns the file at the given path. * "loop" => goes to the top of the list and processes that Each time a request is made to the given path the next response in the list will be given. If the end of the list is reached then this result will be returned from then on. ## METHODS ### events Returns the list of event objects giving the events registered to the server. Note if async requests are being made the order of events cannot be assured. Events objects have the following attributes : * `path` Path of the request * `method` Method of the request * `code` HTTP code of the response ### clear-events Clear the event list allowing the server to be reused in further tests. Calling this method will also reset all the indexes on 'returns' in the config files. Further requests will start from the first registered response. ### mime-types Returns a hash of mime-types registered with the server including any added in `config.yml` file. ## TODO This is a very basic version of the server in order to allow other development to be worked on. Planned is to allow a config.yml file to exist in the top level directory. If the file exists it will allow you control different paths and their responses. This is intended to allow the system to replicate errors to allow for error testing. # AUTHOR Simon Proctor [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2018 Simon Proctor This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-TYIL-I18n-Simple.md # NAME I18n::Simple # AUTHOR Patrick Spek [[email protected]](mailto:[email protected]) # VERSION 0.0.0 # Description A simple internationalisation module. # Installation Install this module through [zef](https://github.com/ugexe/zef): ``` zef install Text::I18n ``` # Using the module # Examples Take the following YAML file, and save it in your module's `resources` directory. These examples assume the file being saved at `resources/i18n/en.yml`. ``` --- foo: This is a template! bar: This template is for you, $(user). ``` Then use the module as follows: ``` use I18n::Simple; # Load the templates. You can make the `en` part a variable to easily switch # between different languages in your program. i18n-init(%?RESOURCES<i18n/en.yml>); # Call a template without placeholders dd i18n("foo"); # "This is a template!" # Call a template with placeholders dd i18n("bar", user => "Bob"); # "This template is for you, Bob." ``` # License This module is distributed under the terms of the AGPL-3.0.
## dist_github-wollmers-LCS-BV.md # NAME LCS::BV - Bit Vector (BV) implementation of the Longest Common Subsequence (LCS) Algorithm # html [![P6-LCS-BV](https://travis-ci.org/wollmers/P6-LCS-BV.png)](https://travis-ci.org/wollmers/P6-LCS-BV) # SYNOPSIS ``` use LCS::BV; $lcs = LCS::BV::LCS($a,$b); ``` # ABSTRACT LCS::BV implements the Longest Common Subsequence (LCS) Algorithm and is more than double as fast (Jan 2016) than Algorithm::Diff::LCSidx(). # DESCRIPTION This module is a port from the Perl5 module with the same name. The algorithm used is based on ``` H. Hyyroe. A Note on Bit-Parallel Alignment Computation. In M. Simanek and J. Holub, editors, Stringology, pages 79-87. Department of Computer Science and Engineering, Faculty of Electrical Engineering, Czech Technical University, 2004. ``` ## METHODS * LCS($a,$b) Finds a Longest Common Subsequence, taking two arrayrefs as method arguments. It returns an array reference of corresponding indices, which are represented by 2-element array refs. # SEE ALSO Algorithm::Diff # AUTHOR Helmut Wollmersdorfer [[email protected]](mailto:[email protected])
## dist_zef-lizmat-Ecosystem.md [![Actions Status](https://github.com/lizmat/Ecosystem/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Ecosystem/actions) [![Actions Status](https://github.com/lizmat/Ecosystem/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Ecosystem/actions) [![Actions Status](https://github.com/lizmat/Ecosystem/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/Ecosystem/actions) # NAME Ecosystem - Accessing a Raku Ecosystem Storage # SYNOPSIS ``` use Ecosystem; my $eco = Ecosystem.new; # access the REA ecosystem say "Ecosystem has $eco.identities.elems() identities:"; .say for $eco.identities.keys.sort; ``` # DESCRIPTION Ecosystem provides the basic logic to accessing a Raku Ecosystem, defaulting to the Raku Ecosystem Archive, a place where (almost) every distribution ever available in the Raku Ecosystem, can be obtained even after it has been removed (specifically in the case of the old ecosystem master list and the distributions kept on CPAN). # COMMAND LINE INTERFACE An `ecosystems` interactive interface is provided by the [App::Ecosystems](https://raku.land/zef:lizmat/App::Ecosystems) distribution. # CONSTRUCTOR ARGUMENTS ## ecosystem ``` my $eco = Ecosystem.new(:ecosystem<fez>); ``` The `ecosystem` named argument is string that indicates which ecosystem (content-storage) should be used: it basically is a preset for the `meta-url` and `IO` arguments. The following names are recognized: * p6c the original content storage / ecosystem * cpan the content storage that uses CPAN * fez the zef (fez) ecosystem * rea the Raku Ecosystem Archive (default) If this argument is not specified, then at least the `IO` named argument must be specified. ## IO ``` my $eco = Ecosystem.new(IO => "path".IO); ``` The `IO` named argument specifies the path of the file that contains / will contain the META information. If not specified, will default to whatever can be determined from the other arguments. ## meta-url ``` my $eco = Ecosystem.new(meta-url => "https://foo.bar/META.json"); ``` The `meta-url` named argument specifies the URL that should be used to obtain the META information if it is not available locally yet, or if it has been determined to be stale. Will default to whatever can be determined from the other arguments. If specified, then the `IO` arguments **must** also be specified to store the meta information in. ## stale-period ``` my $eco = Ecosystem.new(stale-period => 3600); ``` The `stale-period` named argument specifies the number of seconds after which the meta information is considered to be stale and needs updating using the `meta-url`. Defaults to `86400`, aka 1 day. ## longname ``` my $eco = Ecosystem.new(longname => 'My very own ecosystem storage'; ``` The long name with which the ecosystem is to be known. Defaults to sensible name for the 4 original ecosystems: p6c cpan fez rea. # CLASS METHODS ## dependencies-from-meta ``` my $eco = Ecosystem.new; .say for $eco.dependencies-from-meta(from-json $io.slurp); ``` The `dependencies-from-meta` class method returns the list of `use-targets` as specified in the `depends` field of the given hash with meta information. ## sort-identities ``` .say for Ecosystem.sort-identities(@identities); ``` The `sort-identities` class method sorts the given identities with the highest version first, and then by the `short-name` of the identity. # INSTANCE METHODS ## authors ``` my $eco = Ecosystem.new; .say for $eco.authors{ / eigenstates / } ``` The `authors` instance method returns a [Map::Match](https://raku.land/zef:lizmat/Map::Match) with the authors found in each distribution as the keys, and all of the identities each author was found in as the value. ## dependencies ``` my $eco = Ecosystem.new; .say for $eco.dependencies("Ecosystem"); ``` The `dependencies` instance method returns a sorted list of all `use-target`s (either directly or recursively) for an `identity`, `use-target` or `distro-name`. ## distro-names ``` my $eco = Ecosystem.new; say "Found $eco.distro-names.elems() differently named distributions"; ``` The `distro-names` instance method returns a `Map` keyed on distribution name, with a sorted list of the identities that have that distribution name (sorted by short-name, latest version first). ## distros-of-use-target ``` my $eco = Ecosystem.new; .say for $eco.distros-of-use-target($target); ``` The `distro-of-use-target` instance method the names of the distributions that provide the given use target. ## ecosystem ``` my $eco = Ecosystem.new; say "The ecosystem is $_" with $eco.ecosystem; ``` The `ecosystem` instance method returns the value (implicitely) specified with the `:ecosystem` named argument. ## find-distro-names ``` my $eco = Ecosystem.new; .say for $eco.find-distro-names: / JSON /; .say for $eco.find-distro-names: :auth<zef:lizmat>; ``` The `find-distro-names` instance method returns the distribution names that match the optional given string or regular expression, potentially filtered by a `:ver`, `:auth`, `:api` and/or `:from` value. ## find-identities ``` my $eco = Ecosystem.new; .say for $eco.find-identities: / Utils /, :ver<0.0.3+>, :auth<zef:lizmat>; .say for $eco.find-identities: :auth<zef:lizmat>, :all; .say for $eco.find-identities: :latest; ``` The `find-identities` method returns identities (sorted by short-name, latest version first) that match the optional given string or regular expression, potentially filtered by `:ver`, `:auth`, `:api` and/or `:from` value. The specified string is looked up / regular expression is matched in the distribution names, the use-targets and the descriptions of the distributions. By default, only the identity with the highest `:ver` value will be returned: a `:all` flag can be specified to return **all** possible identities. The `:latest` flag can be specified to apply heuristics on the identities so that only the most recent version of a distribution across ecosystems and authorities will be returned. This will e.g. return only `AccountableBagHash:ver<0.0.6>:auth<zef:lizmat>` from a list with: ``` AccountableBagHash:ver<0.0.3>:auth<cpan:ELIZABETH> AccountableBagHash:ver<0.0.6>:auth<zef:lizmat> ``` ## find-no-tags ``` my $eco = Ecosystem.new; .say for $eco.find-no-tags; .say for $eco.find-no-tags: / zef /; .say for $eco.find-no-tags: / zef / :all; ``` The `find-no-tags` method returns identities (sorted by short-name, latest version first) that match the optional given string or regular expression (potentially filtered by `:ver`, `:auth`, `:api` and/or `:from` value) that do **not** have any tags specified. The specified string is looked up / regular expression is matched in the distribution names, the use-targets and the descriptions of the distributions. By default, only the identity with the highest `:ver` value will be returned: a `:all` flag can be specified to return **all** possible identities that do **not** have tags. ## find-use-targets ``` my $eco = Ecosystem.new; .say for $eco.find-use-targets: / JSON /; .say for $eco.find-use-targets: :auth<zef:lizmat>; ``` The `find-use-targets` instance method returns the strings that can be used in a `use` command that match the optional given string or regular expression, potentially filtered by a `:ver`, `:auth`, `:api` and/or `:from` value. ## identities ``` my $eco = Ecosystem.new; my %identities := $eco.identities; say "Found %identities.elems() identities"; ``` The `identities` instance method returns a `Map` keyed on identity string, with a `Map` of the META information of that identity as the value. ## identity-dependencies ``` my $eco = Ecosystem.new; .say for $eco.identity-dependencies($identity); .say for $eco.identity-dependencies($identity, :all); ``` The `identity-dependencies` instance method returns a sorted list of the dependencies of the given **identity** string, if any. Takes an optional `:all` named to also return any dependencies of the initial dependencies, recursively. ## identity-release-Date ``` my $eco = Ecosystem.new; say $eco.identity-release-Date($identity); ``` The `identity-release-Date` instance method returns the `Date` when the the distribution of the given identity string was released, or `Nil` if either the identity could not be found, or if there is no release date information available. ## identity-release-yyyy-mm-dd ``` my $eco = Ecosystem.new; say $eco.identity-release-yyyy-mm-dd($identity); ``` The `identity-release-yyyy-mm-dd` instance method returns a `Str` in YYYY-MM-DD format of when the the distribution of the given identity string was released, or `Nil` if either the identity could not be found, or if there is no release date information available. ## identity-url ``` my $eco = Ecosystem.new; say $eco.identity-url($identity); ``` The `identity-url` instance method returns the `URL` of the distribution file associated with the given identity string, or `Nil`. ## IO ``` my $eco = Ecosystem.new(:IO("foobar.json").IO); say $eco.IO; # "foobar.json".IO ``` The `IO` instance method returns the `IO::Path` object of the file where the local copy of the META data lives. ## least-recent-release ``` my $eco = Ecosystem.new; say $eco.least-recent-release; ``` The `least-recent-release` instancemethod returns the `Date` of the least recent release in the ecosystem, if any. ## longname ``` my $eco = Ecosystem.new; say $eco.longname; # Raku Ecosystem Archive ``` Return the long name of the ecosystem. ## matches ``` my $eco = Ecosystem.new; .say for $eco.matches{ / Utils / } ``` The `matches` instance method returns a [Map::Match](https://raku.land/zef:lizmat/Map::Match) with the string that caused addition of an identity as the key, and a sorted list of the identities that either matched the distribution name or the description (sorted by short-name, latest version first). It is basically the workhorse of the [find-identities](#find-identities) method. ## meta ``` my $eco = Ecosystem.new; say $eco.meta; # ... ``` The `meta` instance method returns the JSON representation of the META data. ## meta-url ``` my $eco = Ecosystem.new(:ecosystem<fez>); say $eco.meta-url; # https://360.zef.pm/ ``` The `meta-url` instance method returns the URL that is used to fetch the META data, if any. ## most-recent-release ``` my $eco = Ecosystem.new; say $eco.most-recent-release; ``` The `most-recent-release` instance method returns the `Date` of the most recent release in the ecosystem, if any. ## resolve ``` my $eco = Ecosystem.new; say $eco.resolve("eigenstates"); # eigenstates:ver<0.0.9>:auth<zef:lizmat> ``` The `resolve` instance method attempts to resolve the given string and the given `:ver`, `:auth`, `:api` and `:from` named arguments to the identity that would be assumed when specified with e.g. `dependencies`. ## reverse-dependencies ``` my $eco = Ecosystem.new; my %reverse-dependencies := $eco.reverse-dependencies; say "Found %reverse-dependencies.elems() reverse dependencies"; ``` The `reverse-dependencies` instance method returns a `Map` keyed on resolved dependencies, with a list of identities that depend on it. ## reverse-dependencies-for-short-name ``` my $eco = Ecosystem.new; .say for $eco.reverse-dependencies-for-short-name("File::Temp"); ``` The `reverse-dependencies-for-short-name` instance method returns a unique list of short-names of identities that depend on any version of the given short-name. ## river ``` my $eco = Ecosystem.new; say "Top five modules on the Raku Ecosystem River:"; .say for $eco.river.sort(-*.value.elems).map(*.key).head(5); ``` The `river` instance method returns a `Map` keyed on short-name of an identity, with as value a list of short-names of identities that depend on it **without** having pinned `:ver` and `:auth` in their dependency specification. ## stale-period ``` my $eco = Ecosystem.new; say $eco.stale-period; # 86400 ``` The `stale-period` instance method returns the number of seconds after which any locally stored META information is considered to be stale. ## release-dates ``` my $eco = Ecosystem.new; .say for $eco.release-dates{ / ^2024 / } ``` The `release-dates` instance method returns a [Map::Match](https://raku.land/zef:lizmat/Map::Match) with the release-dates (YYYY-MM-DD) found in each distribution as the keys, and all of the identities that were released on that date as the value. ## tags ``` my $eco = Ecosystem.new; .say for $eco.tags{ / eigenstates / } ``` The `tags` instance method returns a [Map::Match](https://raku.land/zef:lizmat/Map::Match) with the tags found in each distribution as the keys, and all of the identities each tag was found in as the value. ## update ``` my $eco = Ecosystem.new; $eco.update; ``` The `update` instance method re-fetches the META information from the `meta-url` and updates it internal state in a thread-safe manner. ## unresolvable-dependencies ``` my $eco = Ecosystem.new; say "Found $eco.unresolvable-dependencies.elems() unresolvable dependencies"; ``` The `unresolvable-dependencies` instance method returns a `Map` keyed on an unresolved dependency, and a `List` of identities that have this unresolvable dependency as the value. By default, only current (as in the most recent version) identities will be in the list. You can specify the named `:all` argument to have also have the non-current identities listed. ## unversioned-distros ``` my $eco = Ecosystem.new; say "Found $eco.unversioned-distro-names.elems() unversioned distributions"; ``` The `unversioned-distro-names` instance method returns a sorted list of distribution names (identity without `:ver`) that do not have any release with a valid `:ver` value (typically **:ver<\*>**). ## use-targets ``` my $eco = Ecosystem.new; say "Found $eco.use-targets.elems() different 'use' targets"; ``` The `use-targets` instance method returns a `Map` keyed on 'use' target, with a sorted list of the identities that provide that 'use' target (sorted by short-name, latest version first). # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Ecosystem> . 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, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-TYIL-File-XML-DMARC-Google.md # NAME File::XML::DMARC::Google # AUTHOR Patrick Spek [[email protected]](mailto:[email protected]) # VERSION 0.1.1 # Description Parser for XML-formatted DMARC reports from Google # Installation Install this module through [zef](https://github.com/ugexe/zef): ``` zef install File::XML::DMARC::Google ``` # License This module is distributed under the terms of the AGPL-3.0.
## dist_zef-tony-o-fez.md # zef ecosystem - cli To install: ``` $ zef install fez ``` ***NOTE: you must have zlib installed if you are not on windows!*** ## fez fez is the command line tool used to manage your ecosystem user/pass. * [installation](#installation) * [current functionality](#current-functionality) * [module management](#module-management) * [plugins](#plugins) * [faq](#faq) * [articles-about-fez](#articles-about-fez) * [license](#license) * [authors](#authors) ### installation as easy as: `zef install fez` ### current functionality: * login * register * upload * reset-password * meta * plugin management * command extensions via plugins if you have features or edge cases that would make your migration to fez easier, please open a bug here in github or message me in #raku on freenode (tonyo). ### register ``` λ local:~$ fez register >>= Email: [email protected] >>= Username: tony-o >>= Password: >>= registration successful, requesting auth key >>= login successful, you can now upload dists >>= what would you like your display name to show? tony o >>= what's your website? DEATHBYPERL6.com >>= public email address? xxxx =<< your meta info has been updated ``` ### login This is not necessary if you've just registered but you will eventually have to request a new key. ``` λ local:~$ fez login >>= Username: tony-o >>= Password: >>= login successful, you can now upload dists ``` ### meta Update your meta info - this information is public. ``` λ local:~$ fez meta >>= what would you like your display name to show? tony o >>= what's your website? DEATHBYPERL6.com >>= public email address? xxxx =<< your meta info has been updated ``` ### upload If you're not logged in for this bit then it will prompt you to do so. ``` λ local:~/projects/perl6-slang-sql-master$ fez upload >>= Slang::SQL:ver<0.1.2>:auth<zef:tony-o> looks OK >>= Hey! You did it! Your dist will be indexed shortly. ``` or, if there are errors: ``` λ local:~/Downloads/perl6-slang-sql-master$ fez upload =<< "tonyo" does not match the username you last logged in with (tony-o), =<< you will need to login before uploading your dist ``` ### reset password If you've forgotten your password, use this little guy. ``` λ local:~$ fez reset-password >>= Username: tony-o >>= A reset key was successfully requested, please check your email >>= New Password: >>= What is the key in your email? abcdef... >>= password reset successful, you now have a new key and can upload dists ``` ### review This is the check fez runs when you run `fez upload`. NOTE: the depends, build depends, and provides checks are disabled until RakuAST becomes available. ``` $ fez review >= Bundle manifest: <..list of files fez will bundle for upload..> >>= Build depends ok >>= Depends ok >>= Provides ok >>= Resources ok >>= Test depends ok ``` -or if you have errors- ``` $ fez review >= Bundle manifest: <..list of files fez will bundle for upload..> >>= Build depends ok >>= Depends not ok >>= in meta but unexpected: raku-mailgun >>= Provides ok >>= Resources not ok >>= not in meta: usage/license >>= Test depends ok ``` If you're rolling your own tarballs then you can specify the file to checkout with `--file=`, please keep in mind that checkbuild requires access to a tar that can work with compression for *some* of these checks. ## module management ### listing your modules `fez list <filter?>` ``` $ fez list csv >>= CSV::Parser:ver<0.1.2>:auth<zef:tony-o> >>= Text::CSV::LibCSV:ver<0.0.1>:auth<zef:tony-o> ``` ``` $ fez list >>= Bench:ver<0.2.0>:auth<zef:tony-o> >>= Bench:ver<0.2.1>:auth<zef:tony-o> >>= CSV::Parser:ver<0.1.2>:auth<zef:tony-o> >>= Data::Dump:ver<0.0.12>:auth<zef:tony-o> ...etc ``` ### removing a module This is highly unrecommended but a feature nonetheless. This requires you use the full dist name as shown in `list` and is only available within 24 hours of upload. If an error occurs while removing the dist, you'll receive an email. ``` $ fez remove 'Data::Dump:ver<0.0.12>:auth<zef:tony-o>' >>= Request received ``` ## plugins ### plugin `fez plugin` lists the current plugins in your config file(s). `fez plugin <key> 'remove'|'append'|'prepend' <value>` does the requested action to in your user config. #### extensions fez can now load extensions to `MAIN`. this happens as a catchall at the bottom of fez and uses the first available extensions that it can and exits afterwards. eg if two extensions provide a command `fez test` then the first one that successfully completes (doesn't die or exit) will be run and then fez will exit. ## faq * [do I need to remove modules from cpan](#do-i-need-to-remove-modules-from-cpan) * [which version will zef choose if my module is also on cpan](#which-version-will-zef-choose-if-my-module-is-also-on-cpan) * [what's this sdist directory](#whats-this-sdist-directory) ### do i need to remove modules from cpan? No. If you want your fez modules to be prioritized then simply bump the version. Note that you can upload older versions of your modules using a tar.gz and specifing `fez upload --file <path to tar.gz>`. ### which version will zef choose if my module is also on cpan? zef will prioritize whichever gives the highest version and then the rest depends on which ecosystem is checked first which can vary system to system. ### what's this sdist directory? when fez bundles your source it outputs to `sdist/<name>.tar.gz` and then uploads that package to the ecosystem. there are two ways that fez might try to bundle your package. as of `fez:ver<26+>` fez will attempt to remove the sdist/ directory *if no `--file` is manually specified* #### using pax pax is the bundler included with v38 onward to avoid compatibility issues with certain BSDs. git archive is no longer used as it caused a lot of confusion - this means that what's on disk is what is getting bundled rather than what is in main/master! #### using git archive (deprecated with v38) fez will attempt to run `git archive` which will obey your `.gitignore` files. it is a good idea to put sdist/ in your root gitignore to prevent previously uploaded modules. #### using tar (deprecated with v38) if there is a `tar` in path then fez will try to bundle everything not in hidden directories/files (anything starting with a `.`) and ignore the `sdist/` directory. ## articles about fez if you'd like to see your article featured here, please send a pr. * [faq: zef ecosystem](https://deathbyperl6.com/faq-zef-ecosystem/) * [fez|zef - a raku ecosystem and auth](https://deathbyperl6.com/fez-zef-a-raku-ecosystem-and-auth/) ## license [![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) ## authors @[tony-o](https://github.com/tony-o) @[patrickbr](https://github.com/patrickbkr) @[JJ](https://github.com/JJ) @[melezhik](https://github.com/melezhik)
## dist_cpan-SAMGWISE-Lazy-Static.md [![Build Status](https://travis-ci.org/samgwise/Lazy-Static.svg?branch=master)](https://travis-ci.org/samgwise/Lazy-Static) # NAME Lazy::Static - Lazy calculation of static values # SYNOPSIS ``` use Lazy::Static; # Something for our lazy static closure to pick from my @options = <foo bar baz>; my &result = lazy-static -> { sleep 2; # Some long running calculation; @options.pick } # It's thread safe my @threads = start { say result; # This will be the same value, since the generator will only be called once. } for 1..16; say "Awaiting execution of lazy-static generator..."; await Promise.allof: @threads; say '-' x 78; # We can call it without the wait now, since now the result has been calculated say result; ``` # DESCRIPTION Lazy::Static is a thread-safe alternative to the the `state` keyword for working with static values. # AUTHOR Sam Gillespie [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2019 (c) Sam Gillespie This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. ### sub lazy-static ``` sub lazy-static( &generator ) returns Mu ``` Creates a closure which lazily returns the result of the generator provided. The generator Callable is executed the first time the closure is called and all calls afterwards will receive the the value from the first call. If the result of the generator is never required it will never be generated. A value generated in a lazy-static closure will persist until it is garbage collected, like a normal scalar.
## dist_github-CurtTilmes-DBI-Async.md # NAME DBI::Async - Tiny async wrapper around DBIish # SYNOPSIS ``` use DBI::Async; # Pass any DBIish.connect() options # connections defaults to 5 my $db = DBI::Async.new('Pg', connections => 5); # Make blocking requests: my $result = $db.query("select version()"); say $result.row[0]; $result.finish; # Use array() instead of row() to auto-finish the results: say $db.query("select version()").array[0]; # array() auto-finishes # Use :async to immediately get a Promise: my $promise = $db.query("select version()", :async); await $promise.then(-> $p { say $p.result.array[0]; }); # Or even start a bunch of background queries in parallel, # then check the results await do for 1..10 { start { say "starting $_"; say "Done #", $db.query("select pg_sleep(1)::text, ?::int as val", $_).array[1]; } } # same await do for 1..10 { say "starting $_"; $db.query("select pg_sleep(1)::text, ?::int as val", $_, :async).then( -> $p { say "Done #", $p.result.array[1] }); } $db.dispose; # Drop all queued handles ``` # DESCRIPTION This is deprecated in favor of DB::Pg. `DBI::Async` is an experimental wrapper around DBIish that does all the heavy lifting. It manages a pool of connections and as queries are issued, it queues them and allocates them to a connection, gets the results and returns them asynchronously. You can issue queries from multiple threads without worrying about managing connections. It also wraps some of the mechanics of dealing with results. Passes all arguments to DBI::Async.new() through to DBIish.connect() except connections. ``` my $db = DBI::Async.new('Pg', connections => 5); ``` Connections constrains the object from creating more than $connections database handles. Each call to query() queues the database query for the query scheduler. To process each query, it will use a free database handle from the handle pool. It will create up to $connections new handles. If no handles are available, it wait until another query completes and returns a handle. query() returns a DBI::Async::Results object. It supports the basic methods from DBIish statement handles: ``` .column-names() # Array of column names .column-types() # Array of column types .rows() # Count of rows returns .row() # Get a single row, call repeatedly to get all .allrows() # Lazy list of all rows suitable for iteration ``` It has a special version of .finish() that returns the database handle to the pool to be reused by other queries. If you access your results with the methods above, you must explicitly call .finish() to return the handle. (Otherwise they will leak and not be available for use until the garbage collector gets around to reaping them.) ``` my $result = $db.query("select version()"); say $result.row[0]; $result.finish; ``` To make this a little easier for common cases, the Results object has some extra methods that automatically grab the results and finish() for you. ``` .array() # Return a single row as an array .hash() # Return a single row as a hash .arrays() # Eagerly get all rows and return as an array of arrays .flatarray() # Flatten all elements of all rows into a single array .hashes() # Eagerly get all rows and return as an array of hashes ``` If and only if you use those methods to get results, the finish() will be automatically called. ``` say $db.query("select version()").array[0]; ``` If you do want to use, e.g. .allrows() to process your results, the LEAVE phaser or corresponding 'will leave' trait, can help assure that the .finish() gets called, even if the processing code throws an exception. These are identical: ``` { my $res = $db.query(blah blah); LEAVE $res.finish; while $res.allrows -> $r { ...do something... } } ``` or ``` { my $res will leave { .finish } = $db.query(blah blah); while $res.allrows -> $r { ...do something... } } ``` ## PROMISES If you include the :async adverb in a call to query(), instead of waiting for the result, a Promise will be returned that will be kept when the results of the database query are available. ``` my $promise = $db.query("select version()", :async); await $promise.then(-> $p { say $p.result.array[0]; }); ``` You can have more outstanding queries than you have database connections available. The additional queries will queue up and get executed once previous queries complete and their results are processed. ``` my $db = DBI::Async.new('Pg', connections => 10); await do for 1..100 { say "starting $_"; $db.query("select pg_sleep(1)::text, ?::int as val", $_, :async).then( -> $p { say "Done #", $p.result.array[1] }); } ``` This allocates 10 database handles, then processes the 100 queries in parallel, 10 at a time. Since the results are processed with array(), the handles are returned to the pool immediately when the result is returned. Make sure you don't take up too many waiting threads without leaving enough open threads to get work done and return handles for the rest of the waiting queries. You may be able to get around this by increasing $RAKUDO\_MAX\_THREADS. Also see: <https://github.com/rakudo/rakudo/pull/1004> ## RETRIES DBI::Async aggressively tries to open a database connection. If the connection can't be made immediately, it will sleep a while and try again, 1 second, then 2 seconds, then 3 seconds... up to 60 seconds, finally trying to open the database connection every 60 seconds. This happens both on inital database handle creation, or on subsequent reuse of an existing handle where the connection is dropped. # COPYRIGHT Copyright © 2017 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. No copyright is claimed in the United States under Title 17, U.S.Code. All Other Rights Reserved.
## dist_zef-lizmat-Ecosystem-Archive-Update.md [![Actions Status](https://github.com/lizmat/Ecosystem-Archive-Update/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Ecosystem-Archive-Update/actions) [![Actions Status](https://github.com/lizmat/Ecosystem-Archive-Update/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Ecosystem-Archive-Update/actions) # NAME Ecosystem::Archive::Update - Updating the Raku Ecosystem Archive # SYNOPSIS ``` use Ecosystem::Archive::Update; my $ea = Ecosystem::Archive::Update.new( shelves => 'archive', jsons => 'meta', ); say "Archive has $ea.meta.elems() identities:"; .say for $ea.meta.keys.sort; ``` # DESCRIPTION Ecosystem::Archive::Update provides the basic logic to updating the Raku Ecosystem Archive, a place where (almost) every distribution ever available in the Raku Ecosystem, can be obtained even after it has been removed (specifically in the case of the old ecosystem master list and the distributions kept on CPAN). ## ARGUMENTS * shelves The name (or an `IO` object) of a directory in which to place distributions. This is usually a symlink to the "archive" directory of the actual [Raku Ecosystem Archive repository](https://github.com/lizmat/REA). The default is 'archive', aka the 'archive' subdirectory from the current directory. * jsons The name (or an `IO` object) of a directory in which to store `META6.json` files as downloaded. This is usually a symlink to the "meta" directory of the actual [Raku Ecosystem Archive repository](https://github.com/lizmat/REA). The default is 'meta', aka the 'meta' subdirectory from the current directory. * degree The number of CPU cores that may be used for parallel processing. Defaults to the **half** number of `Kernel.cpu-cores`. * batch The number of objects to be processed in parallel per batch. Defaults to **64**. # METHODS ## batch ``` say "Processing with batches of $ea.batch() objects in parallel"; ``` The number of objects per batch that will be used in parallel processing. ## clear-notes ``` my @cleared = $ea.clear-notes; say "All notes have been cleared"; ``` Returns the `notes` of the object as a `List`, and removes them from the object. ## degree ``` say "Using $ea.degree() CPUs"; ``` The number of CPU cores that will be used in parallel processing. ## investigate-repo ``` my @found = $ea.investigate-repo($url, "lizmat"); ``` Performs a `git clone` on the given URL, scans the repo for changes in the `META6.json` file that would change the version, and downloads and saves a tar-file of the repository (and the associated META information in `git-meta`) at that state of the repository. The second positional parameter indicates the default `auth` value to be applied to any JSON information, if no `auth` value is found or it is invalid. Only `Github` and `Gitlab` URLs are currently supported. Returns a list of `Pair`s of the distributions that were added, with the identity as the key, and the META information hash as the value. Updates the `.meta` information in a thread-safe manner. ## jsons ``` indir $ea.jsons, { my $jsons = (shell 'ls */*', :out).out.lines.elems; say "$jsons different distributions"; } ``` The `IO` object of the directory in which the JSON meta files are being stored. For instance the `IRC::Client` distribution: ``` meta |- ... |- I |- ... |- IRC::Client |- IRC::Client:ver<1.001001>:auth<github:zoffixznet>.json |- IRC::Client:ver<1.002001>:auth<github:zoffixznet>.json |- ... |- IRC::Client:ver<3.007010>:auth<github:zoffixznet>.json |- IRC::Client:ver<3.007011>:auth<cpan:ELIZABETH>.json |- IRC::Client:ver<3.009990>:auth<cpan:ELIZABETH>.json |- ... |- ... ``` ## identities ``` say "Archive has $ea.identities.elems() identities, they are:"; .say for $ea.identities.keys.sort; ``` Returns a hash of all of the META information of all distributions, keyed by identity (for example "Module::Name:ver<0.1>:authfoo:bar:api<1>"). The value is a hash obtained from the distribution's meta data. ## meta-as-json ``` say $ea.meta-as-json; # at least 3MB of text ``` Returns the JSON of all the currently known meta-information. The JSON is ordered by identity in the top level array. ## note ``` $ea.note("something's wrong"); ``` Add a note to the `notes` of the object. ## notes ``` say "Found $ea.notes.elems() notes:"; .say for $ea.notes; ``` Returns the `notes` of the object as a `List`. ## shelves ``` indir $ea.shelves, { my $distro-names = (shell 'ls */*/*', :out).out.lines.elems; say "$distro-names different distributions in archive"; } ``` The `IO` object of the directory where distributions are being stored in a subdirectory by the name of the module in the distribution. For instance the `silently` distribution: ``` archive |- ... |- S |- ... |- silently |- silently:ver<0.0.1>:auth<cpan:ELIZABETH>.tar.gz |- silently:ver<0.0.2>:auth<cpan:ELIZABETH>.tar.gz |- silently:ver<0.0.3>:auth<cpan:ELIZABETH>.tar.gz |- silently:ver<0.0.4>:auth<zef:lizmat>.tar.gz |- ... |- ... ``` Note that a subdirectory will contain **all** distributions of the name, regardless of version, authority or API value. ## update ``` my %updated = $ea.update; ``` Updates all the meta-information and downloads any new distributions. Returns a hash with the identities and the meta info of any distributions that were not seen before. Also updates the `.identities` information in a thread-safe manner. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Ecosystem-Archive-Update> . 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 2021, 2022, 2023, 2024 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-dwarring-PDF-Content.md [[Raku PDF Project]](https://pdf-raku.github.io) / [PDF::Content](https://pdf-raku.github.io/PDF-Content-raku) [![Actions Status](https://github.com/pdf-raku/PDF-Content-raku/workflows/test/badge.svg)](https://github.com/pdf-raku/PDF-Content-raku/actions) # PDF::Content This Raku module is a library of roles, modules and classes for basic PDF content creation and rendering, including text, images, basic colors, core fonts, marked content and general graphics. It is centered around implementing a graphics state machine and provding support for the operators and graphics variables as listed in the [PDF::API6 Graphics Documentation](https://pdf-raku.github.io/PDF-API6#appendix-i-graphics). ## Key classes and modules: * [PDF::Content](https://pdf-raku.github.io/PDF-Content-raku/PDF/Content) manages content stream graphics and related resources * [PDF::Content::Canvas](https://pdf-raku.github.io/PDF-Content-raku/PDF/Content/Canvas) manages a canvas that contains a content stream * [PDF::Content::Ops](https://pdf-raku.github.io/PDF-Content-raku/PDF/Content/Ops) implements a content stream as a graphics state machine * [PDF::Content::Image](https://pdf-raku.github.io/PDF-Content-raku/PDF/Content/Image) loading and manipulation of PDF images * [PDF::Content::Font::CoreFont](https://pdf-raku.github.io/PDF-Content-raku/PDF/Content/Font/CoreFont) provides simple support for core fonts * [PDF::Content::Text::Box](https://pdf-raku.github.io/PDF-Content-raku/PDF/Content/Text/Box) a utility class for creating boxed text content for output by `print()` or `say()` * [PDF::Content::Text::Style](https://pdf-raku.github.io/PDF-Content-raku/PDF/Content/Text/Style) text styling class for text boxes. * [PDF::Content::Text::Line](https://pdf-raku.github.io/PDF-Content-raku/PDF/Content/Text/Line) an individual text box line. * [PDF::Content::Color](https://pdf-raku.github.io/PDF-Content-raku/PDF/Content/Color) A module of color construction functions * [PDF::Content::Tag](https://pdf-raku.github.io/PDF-Content-raku/PDF/Content/Tag) Tagged content detection and construction * [PDF::Content::PageTree](https://pdf-raku.github.io/PDF-Content-raku/PDF/Content/PageTree) PDF Page-tree related methods ## See Also * [PDF::Font::Loader](https://pdf-raku.github.io/PDF-Font-Loader-raku) provides the ability to load and embed Type-1, True-Type and Open-Type fonts. * [PDF::Lite](https://pdf-raku.github.io/PDF-Lite-raku) minimal creation and manipulation of PDF documents. Built directly from PDF and this module. * [PDF::API6](https://pdf-raku.github.io/PDF-API6) PDF manipulation library. Uses this module. Adds handling of outlines, options annotations, separations and device-n colors * [PDF::Tags](https://pdf-raku.github.io/PDF-Tags-raku) DOM-like creation and reading of tagged PDF structure (under construction)
## dist_zef-lizmat-OneSeq.md [![Actions Status](https://github.com/lizmat/OneSeq/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/OneSeq/actions) [![Actions Status](https://github.com/lizmat/OneSeq/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/OneSeq/actions) [![Actions Status](https://github.com/lizmat/OneSeq/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/OneSeq/actions) # NAME OneSeq - turn two or more Iterables into a single Seq # SYNOPSIS ``` use OneSeq; my @a = ^5; my @b = <a b c d e>; my @c = @a >>> @b; say @c; # [0 1 2 3 4 a b c d e] my @d = @a <<< @b; say @d; # [e d c b a 4 3 2 1 0] # as a meta-op my %h = a => [0,1,2], b => [3,4,5], c => [6,7,8,9]; my @e; @e[$_] = $_ + 1 for [>>>] %h.values; say @e; # [1 2 3 4 5 6 7 8 9 10] ``` # DESCRIPTION The `OneSeq` distribution provides two infix operators: `>>>` and `<<<`, each of which produces a single `Seq` object from the given arguments. Their functionality is similar to the [`flat`](https://docs.raku.org/routine/flat) method, but with the important distinction that it does **NOT** look at the containerization of the arguments. So any iterable such as a `Array` or `List` inside a `Hash` or an `Array`, **will** produce all of its values. And it also does **NOT** recurse into any `Iterable` values that it encounters, so in that aspect it is **NOT** like `flat` at all. ## infix >>> The infix `>>>` operator takes any number of arguments (usually `Iterable` objects), takes the **first** argument and calls the `.iterator` method on it, then then produces the values for that iterator until exhausted, and then switches to the next argument. Until there are no arguments left. ## infix <<< The infix `<<<` operator takes any number of arguments (usually `Iterable` objects), takes the **last** argument and calls the `.iterator` method on it, then then produces the values for that iterator until exhausted **in reverse order**, and then switches to the previous argument. Until there are no arguments left. ## PERFORMANCE Depending on the situation, the use of these infix operators can be anywhere to 1.5x to 3x as fast as the equivalent code using `.flat`. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/OneSeq> . 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, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-tbrowder-PDF-Document.md [![Actions Status](https://github.com/tbrowder/PDF-Document/actions/workflows/linux.yml/badge.svg)](https://github.com/tbrowder/PDF-Document/actions) [![Actions Status](https://github.com/tbrowder/PDF-Document/actions/workflows/macos.yml/badge.svg)](https://github.com/tbrowder/PDF-Document/actions) [![Actions Status](https://github.com/tbrowder/PDF-Document/actions/workflows/windows.yml/badge.svg)](https://github.com/tbrowder/PDF-Document/actions) # WARNING - A WORK IN PROGRESS - EXPECT CHANGES # NAME **PDF::Document** - Provides high-level classes and routines to create original documents in Portable Document Format (PDF) This module is currently functioning as a laboratory to create routines and classes to support other PDF modules. As such, its API is subject to change until version 1.0.0+. In the meantime, users are encouraged to use it, report issues, and submit feature requests. See the `dev` directory in the source repository for examples of use. The example in the **SYNOPSIS** is program `./dev/make-example-doc.raku`. # SYNOPSIS ``` #!/usr/bin/env raku use PDF::Document; # We change only three of the many defaults for this # example: (1) output file name, (2) force option to # allow overwriting that file if it exists, and (3) # turn page numbering on: my \d = Doc.new: :pdf-name<example-letter>, :force, :page-numbering, :$debug; #=========== THE LETTER ================= # starts with a new page, current position top baseline, left margin # put the date at the top-right corner d.print: "2021-03-04", :tr, :align<right>, :valign<top>; d.nl; # adds the newline, resets x to left margin, moves y down one line d.say: "Dear Mom,"; # SHOULD automatically add a newline d.nl: 1; # moves y down one line, resets x=0 (left margin) d.say: "I am fine."; d.nl: 1; d.say: "How are you?"; # simple graphics: circle, etc. d.nl: 30; d.say: "circle: radius = 36 pts, linewidth = 4 points"; d.save; # save the current position and graphics state d.setlinewidth: 4; # points d.circle: :x<5in>, :y<3in>, :radius(36); # default points (or in, cm) d.restore; # don't forget to go back to normal! d.np; # new page, current position top baseline, left margin d.say: q:to/PARA/; Pretend this is a VERY long para that extends at least more than one line length in the current font so we can observe the effect of paragraph wrapping. Isn't this swell! PARA d.nl: 3; d.say: "Thats all, folks, but see following pages for other bells and whistles!"; d.nl: 2; d.say: "Love,"; d.nl: 2; d.say: "Isaiah"; d.np; # for some graphics examples d.say: "ellipse: a = 1 in, b = 0.5 in", :y<8in>; d.ellipse: :x<5in>, :y<8in>, :a<1in>, :b<.5in>; d.say: "ellipse: a = 0.3 in, b = 2 cm", :y<6in>; d.ellipse: :x<5in>, :y<6in>, :a<.3in>, :b<2cm>; d.say: "circle: radius = 24 mm", :y<4in>; d.circle: :x<5in>, :y<4in>, :radius<24mm>; d.say: "rectangle: width = 2 in, height = 2 cm", :y<2in>; d.rectangle: :llx<5in>, :lly<2in>, :width<2in>, :height<2cm>; d.np; # for some more graphics examples d.say: "polyline:", :y<7.5in>; my @pts = 1*i2p, 7*i2p, 4*i2p, 6.5*i2p, 3*i2p, 5*i2p; d.polyline: @pts; d.say: "blue polygon:", :y<4.5in>; @pts = 1*i2p, 4*i2p, 4*i2p, 3.5*i2p, 3*i2p, 2*i2p; d.polygon: @pts, :fill, :color[0,0,1]; # rgb, 0-1 values d.end-doc; # renders the pdf and saves the output # also numbers the pages if you requested it #=========== END THE LETTER ================= ``` # DESCRIPTION Module `PDF::Document` leverages the power of lower-level modules `PDF::Lite`, `FontFactory`, and `FontFactory::Type1` and encapsulates some of its classes, routines, and variables into higher-level contructs to ease PDF document creation. ## PDF document generation process This module is designed around the document generation process used by those who use PostScript (PS) code to create PS documents which are then transformed into PDF by the GNU program `ps2pdf`. That process is described in great detail in the classic PS books by Adobe (see REFERENCES). The same sequence is also followed in the PDF document creation process: * Define the `PDF::Lite` class instance (a heavy-weight instantiation, only one per document) ``` my $pdf = PDF::Lite; ``` * Select the fonts (with size) to be used with either (1) the `FontFactory` or (2) the `FontFactory::Type1` or both. The advantage of (1) is the fonts are usually TrueType or OpenType with large numbers of Unicode glyphs. Any Type 1 fonts ('.t1') available may have more glyphs available than the fonts in (2). (There are 72 PS points per inch.) ``` my $ff = FontFactory.new; my $fft = FontFactory::Type1.new: # uses PDF::Lite to access standard fonts my $t12d1 = $fft.get-font: 't12d1' # Times-Roman at 12.1 points my $c10 = $fft.get-font: 'c10'; # Courier at 10 points my $ft1 = $ff.get-font: :name(), :size(); my $ft2 = $ff.get-font: :index(), :size(); ``` * Define each page ``` my $page = $pdf.add-page; #...add text and graphics... #...add a new page... my $page = $pdf.add-page; #...add text and graphics... ``` * Create the document and exit ``` $pdf.save-as<MyDoc.pdf>; ``` ## Summary As you can see the document steps are equivalent, but the steps in PDF page creation are much easier because common low-level code required in PS creation is available under the covers in `PDF::Lite` and accessed more easily by this module. # CURRENT CAPABILITY Currently the the module provides routines and constants as used in the example program shown in the **SYNOPSIS**. In addition, other graphics and text examples are shown in the `/dev` directory including showing phases of the Moon, creating grids, using landscape orientation, and using A4 paper. There is also a font factory which eases selection and use of multiple fonts. Fonts included are all the standard PostScript fonts plus a font used to create bank checks: **MICREncoding**. The PS fonts are free for any use, but the MICR font is only free for non-commercial use. See its **license.txt** file in the `/dev/fonts/micr/unzipped` directory. More work is planned including: * font underlining * font strikethrough # FUTURE CAPABILITY This module is being used during the development of the author's other PDF modules: * `PDF::Writer`\* * `PDF::Labelmaker`\*\* * `PDF::Calendar` * `PDF::ReWriter` * `PDF::Forms` * `CheckWriter` This module will be updated with more items as the user modules are updated and published. NOTE: The asterisk (`*`) indicates the module has been published, albeit of minimal use. Two asterisks means the published module is not even minimally useful, but it is exposed to issues or feature requests from interested parties. # CREDITS The author is indebted to the tremendous amount of work done by his Raku friend, David Warring. David's voluminous project, hosted at <https://github.com/PDF-Raku>, provides all the tools needed to manipulate PDF files using our wonderful Raku language. Thank you David! # REFERENCES ##### 1. *PostScript Language Reference Manual* (the "Red Book"), 2nd Edition, Adobe Systems Inc., 1990 ##### 2. *PostScript Language Tutorial and Cookbook* (the "Blue Book"), Adobe Systems Inc., 1986 # AUTHOR Tom Browder [[email protected]](mailto:[email protected]) # COPYRIGHT and LICENSE Copyright © 2021-2023 Tom Browder This library is free software; you may redistribute it or modify it under the Artistic License 2.0.
## dist_zef-guifa-Intl-Format-DateTime.md # IntlFormatDateTime > Hoy es siempre todavía, toda la vida es ahora. Y ahora, ahora es el momento de cumplir las promesas que nos hicimos. Porque ayer no lo hicimos, porque mañana es tarde. Ahora. > — *Proverbios y cantares* (Antonio Machado) A module for formatting dates and times in a variety of languages and styles. To use, simple include the module: ``` use Intl::Format::DateTime my $dt = DateTime.new: now; format-date $dt; # Format the date only format-time $dt; # Format the time only format-datetime $dt; # Format the date and time together ``` The command options are * **`:length`** The main option, sets the length. Acceptable values are either *full*, *long*, *medium* (default), *short*. For the most verbose, choose *wide*. Defaults to *medium* which should be optimal in most cases. * **`:skeleton`** (alias **`:like`**) Accepts a string representing various formatting options documented in [TR 35.4.8](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table). The optimal pattern is chosen based on the given skeleton, deferring to the skeleton for minor differences (e.g. number of digits). If used, **length** option is ignored. * **`:language`** Sets the language to be used in formatting. Acceptable values are a `LanguageTag` or a `Str` representation thereof. Defaults to whatever `User::Language` provides, which itself defaults to `en` (English). * **`:relative-to`** **NYI**. This option will create a relative time offset based on the the interval. Generally `:relative-to(now)` is what you will want to use, but you can use anything that can coerce to a DateTime. If you will be constantly reusing a formatter, you can also obtain a `Callable` form which will reduce some of the overhead and be more performant: ``` my &formatter = local-datetime-formatter :$language, :$length, :$skeleton; # or local-date-formatter # or local-time-formatter formatter DateTime.now ``` Current performance is about an order of magnitude slower than `DateTime.Str` and is about as fast as vanilla Raku can get. The performance gap can be narrowed if alternate `nqp` versions of formatters are written, but that is not a priority at the moment. ## To do * Finish skeleton patterns support (allowing selection of more specific formats). * Respect capitalization rules per CLDR casing data. * Handle non-Gregorian calendars (once a `DateTime::Calendars` module or similar is available) * Handle relative time formats (though this may ultimately go into a separate module). ## Dependencies * `Intl::LanguageTag` Used for introspection of language tags. * `Intl::UserLanguage` Determines the default language for formatting). * `Intl::CLDR` Contains formatting information. * `DateTime::Timezones` Ensures that `DateTime` objects are timezone aware. These modules are designed to work together, and as of 2023, are maintained by the same person so should not have issues if fully updated. ## Version history * **v0.3.0** * All code now runs with RakuAST for improved performance * Added `local-datetime-formatter` calls for enhanced performance in some situations * Proper week-of-year/weekyear support * Non-Latin digit support * Restructured file hierarchy for better long term maintenance * **v0.2.0** * Skeleton formats supported for `format-datetime` (NYI: missing fields and C/j/J formatters NYI) * **v0.1** * Initial release ## Copyright and License © 2021–2023 Matthew Stephen Stuckwisch. All files licensed under the Artistic License 2.0 except for `resources/metaZones.xml` which is owned by Unicode, Inc. and licensed under the Unicode License Agreement (found at `resources/unicode-license.txt`)
## excludes-max.md excludes-max Combined from primary sources listed below. # [In Range](#___top "go to top of document")[§](#(Range)_method_excludes-max "direct link") See primary documentation [in context](/type/Range#method_excludes-max) for **method excludes-max**. ```raku method excludes-max(Range:D: --> Bool:D) ``` Returns `True` if the end point is excluded from the range, and `False` otherwise. ```raku say (1..5).excludes-max; # OUTPUT: «False␤» say (1^..^5).excludes-max; # OUTPUT: «True␤» ```
## dist_zef-Kaiepi-Data-Record.md ![Build Status](https://github.com/Kaiepi/ra-Data-Record/actions/workflows/test.yml/badge.svg) # NAME Data::Record - Record types! # SYNOPSIS ``` use Data::Record; # Data::Record introduces record types for maps, lists, and tuples: my constant Schema = {@ name => Str:D, items => [@ <@ Int:D, Str:D @> @] @} :name('Schema'); # With the type we just made, we can typecheck data structures to ensure they # match it: my %valid = name => 'Kaiepi', items => [(1, 'Item 1'), (2, 'Item 2')]; my %invalid = name => 'Mrofnet', items => [], constructor => 'Thanks, JavaScript.'; say %valid ~~ Schema; # OUTPUT: True say %invalid ~~ Schema; # OUTPUT: False # ...but typechecking this way is inefficient, and is always done eagerly! # Using the (<<), (>>), (<>), and (><) operators provided, data can be coerced # to our record type by various means: %valid := %valid (><) Schema; %invalid := %invalid (<<) Schema; say %invalid; # OUTPUT: {items => [], name => Mrofnet} # For the most part, coerced data can be used the same way as the original # data, with the bonus of extra typechecking: { CATCH { default { say .^name } } %invalid<items>.push: (3, 'Item 3'); # OK! %invalid<items>.push: "OOPSIE WOOPSIE OwO"; # OUTPUT: X::Data::Record::TypeCheck } # Finally, to restore the data's original typing, simply call the unrecord # method on it: my %now-valid := %invalid.unrecord; say %now-valid.^name; # OUTPUT: Hash say %now-valid<items>.^name; # OUTPUT: Array say %now-valid<items>[0].^name; # OUTPUT: List ``` # DESCRIPTION `Data::Record` is a library that adds support for record types to Raku. Operators for creating record types for maps, lists, and tuples are included. Data structures can then be coerced to these record types using the coercion operators provided, some of which will sanitize them, all of which allow for efficient typechecking for common operations you can do with them. For documentation on how this library can be used, refer to the [wiki](https://github.com/Kaiepi/p6-Data-Record/wiki/). # AUTHOR Ben Davies (Kaiepi) # COPYRIGHT AND LICENSE Copyright 2022 Ben Davies This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-bbkr-HomoGlypher.md # Homoglyph toolset for [Raku](https://www.raku.org) language [![.github/workflows/test.yml](https://github.com/bbkr/HomoGlypher/actions/workflows/test.yml/badge.svg)](https://github.com/bbkr/HomoGlypher/actions/workflows/test.yml) [Homoglyph](https://en.wikipedia.org/wiki/Homoglyph) is set of one or more graphemes that has identical or very similar look to some other set of graphemes. For example: * `6` (DIGIT SIX) and `б` (CYRILLIC SMALL LETTER BE) * `w` (LATIN SMALL LETTER W) and `ω` (GREEK SMALL LETTER OMEGA) * `oo` (2 x LATIN SMALL LETTER O) and `က` (MYANMAR LETTER KA) * `E` (LATIN CAPITAL LETTER E) and `Ε` (GREEK CAPITAL LETTER EPSILON) and `Е` (CYRILLIC CAPITAL LETTER IE) * `V` (LATIN CAPITAL LETTER V) and `\/` (REVERSE SOLIDUS + SOLIDUS) Homoglyphs are: * Font dependent - two homoglyphs may be 100% identical in one font but have visual differences when rendered in other. Even cursive matters, for example `т` in cursive in some fonts looks like `m`. * Subjective - similarity level cannot be measured and there is no fixed point where two sets of graphemes stops being homoglyphs. Are `a` and `а` homoglyphs? Sure! How about `ź` and `ž`? Probably yes. What will you say about `R` and `Я`? Er.... You see the point? * Funny - replace `;` (SEMICOLON) with `;` (GREEK QUESTION MARK) in someone's code and watch them trying to debug code that looks perfectly fine :) * Dangerous - someone can register [IDN domain](https://en.wikipedia.org/wiki/Internationalized_domain_name) that looks very similar to your business domain to swindle money out of your clients. # TABLE OF CONTENTS * [SYNOPSIS](#synopsis) * [HINT](#hint) * [METHODS](#methods) * [add-mapping](#add-mapping) * [unwind](#unwind) * [collapse](#collapse) * [tokenize](#tokenize) * [randomize](#randomize) * [CONTACT](#contact) # SYNOPSIS ``` use HomoGlypher; my %cyrillic = ( '6' => [ 'б' ], 'a' => [ 'а' ], 'b' => [ 'б', 'ь' ], 'r' => [ 'г' ] ); my %greek = ( 'a' => [ 'α' ], 'o' => [ 'ο' ] ); my %myanmar = ( 'oo' => [ 'က' ] ); my $hg = HomoGlypher.new; $hg.add-mapping( %cyrillic ); $hg.add-mapping( %greek ); $hg.add-mapping( %myanmar ); my @unwinded = $hg.unwind( 'foo' ); # [ 'foο', 'fοo', 'fοο', 'fက' ] my @collapsed = $hg.collapse( 'бαг' ); # [ 'bar', '6ar' ] my $randomized = $hg.randomize( 'bar', level => 80 ); # for example 'bαr' my &tokenized = $hg.tokenize( ); say so 'bαг' ~~ / <&tokenized: 'bar'> /; # True ``` # HINT When dealing with homoglyphs the easiest method to debug them is to use uniname(s) method: ``` $ raku -e '.say for "fοο".uninames' LATIN SMALL LETTER F GREEK SMALL LETTER OMICRON GREEK SMALL LETTER OMICRON ``` # METHODS ## add-mapping Merge given mapping (given as Hash of Arrays) with existed mappings. Typically keys are composed from ASCII characters. Duplicates are filtered out automatically. Multi character glyphs can be used both in keys and values: ``` my %mapping = ( 'IO' => [ 'Ю' ], 'P' => [ '|Ͻ'] ); ``` You can inspect megred mappings under `$hg.mappings`, just ***do not modify it directly***. If you want to fine tune it then fetch merged result, tweak it and add to new `HomoGlypher` object. Few ready to use mappings are provided in [HomoGlypher::Mappings](https://github.com/bbkr/HomoGlypher/blob/master/lib/HomoGlypher/Mappings.rakumod): * `@basic` - ASCII letters and digits that are faked by completely different characters: `ΤꜦꜪ QՍΙᴄк вᚱՕꓪɴ ꓝᏅХ` `jսოр𐑈 օ𐐷еᎱ tᏥе ιαzႸ Ժօց` `ОᛐշʒᏎƼỼ7ꝸᏭ`. Consists of: * `%armenian` * `%cherokee` * `%cyrillic` * `%deseret` * `%greek` * `%greek-mathematical-typeface` * `%georgian` * `%latin` * `%lisu` * `%myanmar` * `%roman-numerals` * `%runic` * `%math-symbols` * `@typeface` - ASCII letters and digits that have typeface styles applied, base characters are not changed: `𝗧𝕳𝓔 𝒬𝕌𝕀𝙲𝔎 𝔹𝗥OW𝓝 𝘍𝕆𝗫` `𝒿𝓾𝗺𝚙𝕤 𝔬𝘃𝘦𝓇 𝔱𝘩𝘦 𝖑𝖆𝕫𝔂 𝗱𝓸𝔤` `𝟘𝟙2𝟹4𝟻𝟼𝟽𝟠𝟡`. Consists of: * `%ballot` * `%ballot-bold-script` * `%ballot-script` * `%bold` * `%bold-fraktur` * `%bold-italic` * `%bold-script` * `%doublestruck` * `%doublestruck-italic` * `%fraktur` * `%fullwidth` * `%heavy-ballot` * `%italic` * `%monospace` * `%sansserif` * `%sansserif-bold` * `%sansserif-bold-italic` * `%sansserif-italic` * `%script` * `%accented` - ASCII letters that have accents applied, base characters are not changed: `ȚȞȆ ꝖṲÏÇꝂ ḂŔǾⱲṆ ḞṌẌ` `ĵữṁꝕṩ ǭⱱëȑ ʈẖḕ ļǟʐȳ ɗȫǵ`. Try to read it loud... Correctly :) * `%control` - ASCII printable representations of non printable characters: `P␆ ␎ME ␖THE␏SE␞`. Have perfect similarity but letters are very crammed and those acronyms are unlikely to be found in regular language. * `%flipped` - ASCII letters, digits and symbols that are faked by some completely different characters in various rotations and mirroring: `ꓕH⧢ Ꝺ⋂I𐐣ꓘ ꓭꓤOW𐐥 ꓞOX` `jᴝᴟpƨ ᴑ⋏ǝɹ ʇɥɘ ꞁɐzʎ dᴑᵷ` `0ᛚ2Ƹ4567∞9` ``` use HomoGlypher; use HomoGlypher::Mappings; my $hg = HomoGlypher.new; $hg.add-mapping( $_ ) for @HomoGlypher::Mappings::basic; # load all basic mappings $hg.add-mapping( %HomoGlypher::Mappings::accented ); # load single, specific mapping ``` I won't tell you where to get perfect, complete, ultimate mapping because homoglyphs are font-dependent and similarity is subjective. Good start point for creating your own mappings are [\*\_alphabet](https://en.wikipedia.org/wiki/List_of_writing_systems) and [\*\_numeral](https://en.wikipedia.org/wiki/List_of_numeral_systems) pages on Wikipedia. Or you can borrow mappings from some other projects like [Codebox homoglyphs](https://github.com/codebox/homoglyph), [IronGeek Homoglyph Attack Generator](https://www.irongeek.com/homoglyph-attack-generator.php) and many others. ## unwind Generates every possible mapping combination for your ASCII text. Beware, ***this works only for short inputs*** and ***list grows really, really fast***. ``` my %cyrillic = ( '6' => [ 'б' ], 'a' => [ 'а' ], 'b' => [ 'б', 'ь' ], 'e' => [ 'е', 'ё' ], 'm' => [ 'м' ], 'p' => [ 'р' ], 'r' => [ 'г' ], 'x' => [ 'х' ] ); my $hg = HomoGlypher.new; $hg.add-mapping( %cyrillic ); .say for $hg.unwind( 'example' ); ``` ``` examplё examрle examрlе examрlё exaмple exaмplе exaмplё exaмрle ... ``` (total 143 combinations) Output list: * Is lazy - so you can iterate over it without worrying about memory consumption. * Has preserverd mappings order - so if you sort your mappings from most to less similar your result will have the same characteristics. Main purpose of homoglyph unwinding is to check if someone is spoofing your domain. See ready to use [IDN Checker](https://github.com/bbkr/HomoGlypher/blob/master/example/IDN-checker.raku) script. ## collapse Opposite of [unwind](#unwind). If you have suspicious, homoglyphed text you can check which ASCII texts it might be derived from. Beware, ***this works only for short inputs***. ``` my %ascii-art = ( 'O' => [ '()' ], 'V' => [ '\/' ], 'W' => [ '\/\/' ] ); my $hg = HomoGlypher.new; $hg.add-mapping( %ascii-art ); .print for $hg.collapse( '\/()\/\/EL' ); ``` ``` VOVVEL VOWEL ``` (as you can see sometimes it may return more than one possible ASCII text) Main purpose of homoglyph collapsing is to check if someone is using your forums, hostings, or other services for phishing or false advertising. Check also [tokenize](#tokenize) method. [Unicode::Security](https://github.com/JJ/perl6-unicode-security) module does similar thing. ## tokenize Construct token that can be used to match homoglyphed text in grammars. ``` my %greek = ( 'a' => [ 'α' ], 'r' => [ 'Γ' ], ); my $hg = HomoGlypher.new; $hg.add-mapping( %greek ); my &homoglyphy = $hg.tokenize( ); 'foobαΓbaz' ~~ / $<result>=<&homoglyphy: 'bar'> /; say $/{ 'result' }; ``` ``` 「bαΓ」 ``` Beware, ***token uses mappings present at match time***. You can create token without any mappings added, define grammar that uses this token and then add mappings before text is actually matched against grammar. If you need tokens with different set of mapping in one grammar you can create and tokenize many `HomoGlypher` instances. [Regex::FuzzyToken](https://github.com/alabamenhu/RegexFuzzyToken) module can be used to catch misspelled phrases. Homoglypher and FuzzyToken can coexist in single grammar: ``` say 'Suspicious!' if $email-text ~~ / [ <fuzzy: 'paypal'> | <&homoglyphy: 'paypal'> ] /; ``` Will catch both `papyal` (misspelled) and `pαypαl` (homoglyphed). And yes, you can throw nuke on phishers and catch misspells and homoglyphs at the same time: ``` say 'Suspicious!' if $email-text ~~ / <fuzzy: $hg.unwind('paypal')> /; ``` Will catch such sneaky phrases as `pαpyαl`. ## randomize Replace characters in text with homoglyphs with given probability. ``` my $hg = HomoGlypher.new; $hg.add-mapping( %HomoGlypher::Mappings::flipped ); say $hg.randomize( 'DIRECTIONS & CAKE ARE A LIE', level => 100 ); ``` ``` ⫏Iя∃C⟘IOИƧ ⅋ C∀K⧢ ∀Я∃ ∀ LI∃ ``` Level can be given as percentage value from 1 to 100 (default 50). It decides if ***possible*** mapping should be used at given position. Do not confuse that with amount of replaced characters. For example you have mapping `'a' => [ 'α' ]` and level set to 50%. Transforming `barrrr` will result with unmodified `barrrr` with 50% probability (at second position transformation was possible but not used) and modified `bαrrrr` with 50% probability (at second position transformation was possible and used). Each position is rolled individually against level. Each possible replacement glyph has equal chance to be picked. [Text::Homoglyph](https://github.com/MattOates/Text--Homoglyph) module does similar thing.
## dist_zef-grizzlysmit-File-Utils.md # File::Utils ## Table of Contents * [NAME](#name) * [AUTHOR](#author) * [VERSION](#version) * [TITLE](#title) * [SUBTITLE](#subtitle) * [COPYRIGHT](#copyright) * [Introduction](#introduction) * [CorruptFile](#corruptfile) * [symbolic-perms(…)](#symbolic-perms) * [format-bytes(…)](#format-bytes) * [uid2username(…)](#uid2username) * [gid2groupname(…)](#gid2groupname) # NAME File::Utils # AUTHOR Francis Grizzly Smit ([[email protected]](mailto:[email protected])) # VERSION 0.1.2 # TITLE File::Utils # SUBTITLE A Raku module for converting various File system properties to symbolic form. # COPYRIGHT LGPL V3.0+ [LICENSE](https://github.com/grizzlysmit/File-Utils/blob/main/LICENSE) [Top of Document](#table-of-contents) # Introduction A **Raku** module for converting various File system properties to symbolic form. For instance **`symbolic-perms(…)`** will give you the **.rwxr-xr-x** type representation of the file type and permissions like used by **`ls`** and **`exa`**. And **`format-bytes(…)`** will convert the file size from bytes **B** to **TiB**, **GiB** etc. [Top of Document](#table-of-contents) ### CorruptFile **`CorruptFile`** is an exception class to be used if a corrupt file is encountered. ``` class CorruptFile is Exception is export { has Str:D $.msg = 'Error: File is Corrupt'; method message( --> Str:D) { $!msg; } } ``` [Top of Document](#table-of-contents) ### symbolic-perms(…) A function for producing the **.rwxrwxrwx** form of a files type and permissions like that used by **ls** and **exa**. It also supports colourising and syntax highlighting of the perms. ``` sub symbolic-perms(IO::Path $path, Bool:D :$colour is copy = False, Bool:D :$syntax = False, Bool:D :$highlighted = False, Bool:D :$cond = False, Str:D :$highlight-fg-colour = t.color(255, 0, 0), Str:D :$fg-colour0 = t.color(255, 0, 0), Str:D :$fg-colour1 = t.color(255, 0, 0) --> Str:D) is export { ``` * Where * **`$path`** Is the path of the file/directory to describe the perms for. * **`$colour`** If True colour the perms. * **`$syntax`** If true syntax highlight the perms. * **`$highlighted`** If true set the text colour to **`$highlight-fg-colour`**. * **`$cond`** If not highlighted and True set the text colour to **`$fg-color0`** else set text to **`$fg-color1`**. * **`$highlight-fg-colour`** Colour to set the text to if **`$highlighted`**. * **`$fg-colour0`** Colour to set the text to if not **`$highlighted`** and **`$cond`**. * **`$fg-colour1`** Colour to set the text to if not **`$highlighted`** and not **`$cond`**. **NB: Only recognises directory, link and regular file just now.** ### format-bytes(…) Format a number in bytes into **KiB**, **MiB**, **GiB**, **TiB**, …… also appends the **GiB**, **TiB** designator. ``` sub format-bytes(Int:D $bytes, Int:D :$width = 5, Int:D :$precision = 1 --> Str:D) is export ``` ### uid2username(…) A function to convert a numeric **uid** into a **username**, will only work on a typical \***nix** file system requires **/etc/passwd** to exist, and be readable. Will fail if these conditions are not true. ``` sub uid2username(UInt:D $uid --> Str:D) is export ``` ### gid2groupname(…) A function to convert a numeric **gid** into a **groupname**, will only work on a typical \***nix** file system requires **/etc/group** to exist, and be readable. Will fail if these conditions are not true. ``` sub gid2groupname(UInt:D $gid --> Str:D) is export ```
## dist_zef-thundergnat-Math-Handy.md [![Actions Status](https://github.com/thundergnat/Math-Handy/actions/workflows/test.yml/badge.svg)](https://github.com/thundergnat/Math-Handy/actions) # NAME Math::Handy - Handy math routines and operators that aren't in CORE Raku. # SYNOPSIS ``` use Math::Handy; say 25!; # 15511210043330985984000000 say Γ 1/2; # 1.7724538509055163 say binomial(9, 5); # 126 say Σ (^1e2).grep: &is-prime; # 1060 say Π (^1e2).grep: &is-prime; # 2305567963945518424753102147331756070 say 33 divmod 5; # (6 3) say 33 divmod 5.1; # (6 3) say 33 /% 5.1; # (6 2.5) say adr 16781; # (5 2) say mdr 16781; # (0 4) say 180°; # 3.141592653589793 say 200ᵍ; # 3.141592653589793 ``` # DESCRIPTION Math::Handy provides several handy functions and operators. ### Factorial operators `factorial (Int)` - the product of the integers from one to $n. Also available as `postfix:<!> (Int)`. Factorial is a discrete operation, only valid at integer values. For a continuous function, you want `gamma (Real $n)`. `gamma (Real)` is a continuous factorial function. `Γ($n) =~= ($n - 1)!`. Also available as `Γ (Real $n)` (Greek uppercase gamma). Calculated using Lanczos approximation. (Only valid for positive arguments at this point.) Also related to `factorial()` is `binomial()`. `binomial(Int $n, Int $p)`, very commonly appears in combinatorics. Is equivalently expressed as: `n! / (p! × (n - p)!)`. ### Arithematic operators Raku has the very convenient `sum` function. Traditional mathematics spells it `Σ`. This module provides a `Σ (*@list)` operator to remedy that. Another common mathematical operator that Raku left out is `product()`. Raku has the `[*]` meta reduce operator, but that is difficult to chain with other operations. This module provides both a `product (*@list)` routine, and the more traditionally spelled: `Π (*@list)` (Greek uppercase pi) Raku has `div`, Raku has `mod`, Raku has `polymod()`, but sometimes you may want a plain old `divmod`. `infix:<divmod> (Real, Real)` coerces arguments to Int and returns the whole divisions and the remainder. Also available as `infix:</%> (Real, Real)`: `Real %/ Real` which doesn't coerce. ### Digital roots The `additive digital root` of an Integer in a particular base, is the recursive sum of the digits until only a single digit remains. The `persistance` is the number of times the function needs to recurse to reach a single digit. Provides `digital-root (Int $n, :$base = 10)`. Calculates and returns the additive digital root and the persistance, by default in base 10. Pass in a named base (2 = 36) if a different base is desired. Also available as the abbreviated `adr (Int $n, :$base = 10)` Similar to the additive `digital-root()` is the `multiplicative-digital-root()`. The `multiplicative-digital-root (Int $n, :$base = 10)` is the recursive product of the digits until only one digit remains. Returns the multiplicative digital root and the persistance. Also available as the abbreviated `mdr (Int $n, :$base = 10)` ### Radian conversions Raku provides a multitude of trigonometric functions, but they all work with radian angle measurements by default. To make it easy to work with degrees (360° in 2π radians), or gradians (400ᵍ in 2π radians), provides two postfix conversion routines. `postfix:<°> (Real $degrees)` converts degree measurments to radians. `postfix:<ᵍ> (Real $gradians)` converts gradian measurments to radians. # AUTHOR Most of these were code snippets I or someone else wrote as helper functions for solving RosettaCode tasks. If there is a routine you think should be added, or if I bungled one of the existing, please let me know. Stephen Schulze (aka thundergnat [[email protected]](mailto:[email protected])) # COPYRIGHT AND LICENSE Copyright 2023 thundergnat This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-CTILMES-LibGit2.md # LibGit2 -- Direct access to Git via libgit2 library Note: This is a WORK IN PROGRESS. The tests are under construction and many of them probably won't work on your computer.. This module provides Raku access to [libgit2](https://libgit2.github.com/). That library must be installed, and this module will be subject to the features enabled during the build/install of that library. This module is **EXPERIMENTAL**. In particular, I'm still trying to refine the Raku API to be as friendly as possible, and also as Raku-ish as possible. I've converted some callbacks into Channels, and some options into :pairs, etc. If you see anything that could be done better, PLEASE raise an issue. There are also still some unimplemented corners, so if you see anything you can't do, raise an issue and we can try to add more libgit2 bindings. Also some functionality that looks like it should work doesn't seem to... Debugging, test improvements, etc. are all appreciated -- feel free to ask questions or offer patches! For now, there are also some 64-bit assumptions. If there is demand for a 32-bit version, there are ways to adapt it I can work with someone who wants to tackle that. It also doesn't currently support Windows, but could probably do so if someone wants to port it. Patches welcome! ## Global Initialization Always start with `use LibGit2` rather than using individual `Git::*` modules. That pulls in the rest of the modules, and also initializes the library as a whole. Query some global information about the library: ``` use LibGit2; say LibGit2.version; say LibGit2.features; 0.26.0 (GIT_FEATURE_NSEC GIT_FEATURE_SSH GIT_FEATURE_HTTPS GIT_FEATURE_THREADS) ``` ## Tracing If libgit2 is compiled with tracing support, you can enable that tracing from Raku. ``` LibGit2.trace('debug'); # none,fatal,error,warn,info,debug,trace ``` The default trace callback just prints the message and its level to STDOUT. You can also supply a callback: ``` use NativeCall; sub my-trace($level, $message) { say "$level $message" } LibGit2.trace('info', &my-trace); ``` ## Init ``` my $repo = Git::Repository.init('/my/dir'); my $repo = Git::Repository.init('/my/dir', :bare); my $repo = Git::Repository.init('/my/dir', :mkpath, description => 'my description', ...); ``` See Git::Repository::InitOptions for the complete init option list. ## Clone ``` my $repo = Git::Repository.clone('https://github.com/...', '/my/dir'); my $repo = Git::Repository.clone('https://github.com/...', '/my/dir', :bare); ``` See Git::Clone::Options for the complete clone option list. ## Open This will open an existing Git repo or throw an exception. ``` try my $repo = Git::Repository.open('/my/dir'); if not $repo { say "FATAL: '/my/dir' is not a Git repo."; exit; } my $repo = Git::Repository.open('/my/dir', :bare); my $repo = Git::Repository.open('/my/dir/some/subdir', :search); ``` See Git::Repository::OpenOptions for the complete open options list. ## Config From a `Git::Repository`, you can use the `.config` method to access configuration information. ``` my $config = $repo.config; ``` ## Status Get status for a specific file/path: ``` my $status = $repo.status-file('afile'); say $status.status; say $status.path; say "new in workdir" if $status.is-workdir-new; ``` Other queries on status: is-current is-index-new is-index-modified is-index-deleted is-index-renamed is-index-typechange is-workdir-new is-workdir-modified is-workdir-deleted is-workdir-typechange is-workdir-renamed is-workdir-unreadable is-ignored is-conflicted Query for status of everything, or specific pathes/globs: ``` for $repo.status-each { say 'new' if .is-workdir-new; } say .path for $repo.status-each('*.p6', :include-untracked); ``` See `Git::Status::Options` for more information on status options. ## Index Retrieve an object representing the repository's index with `.index`, then you can add files to the index, either a specific file `.add-bypath` or a group of files or all files with `.add-all`, or just update with `.update-all`. ``` my $repo.index; $index.add-bypath('afile.p6'); # Even works on ignored files $index.add-all('*.p6'); # Add any new files or update any changes $index.update-all('*.t'); # Just update, don't add new files ``` Remove from index with `.remove-bypath` or `.remove-all`. The index is maintained in memory. To persist the changes to disk, always `$index.write` after completeing changes. Use `.read(:force)` to discard any changes and re-read index from disk. See Git::Index for more information on options. After adding new or changed files to the index, create a `Git::Tree` representing the changes with `.write-tree` which returns a `Git::Oid` for the new tree. ``` my $tree-id = $index.write-tree; ``` ## Tree ``` my $tree = $repo.tree-lookup($tree-id); ``` ## Signature ``` my $sig = $repo.signature-default; # Fails if user.name, user.email not set my $sig = Git::Signature('Full Name <[email protected]'); my $sig = Git::Signature('Full Name', '[email protected]'); my $sig = Git::Signature('Full Name', '[email protected]', DateTime.new('...')); ``` ## Commit A commit requires several components: * **:update-ref** - Defaults to 'HEAD', the name of the reference that will be updated to point to this commit. If the reference is not direct, it will be resolved to a direct reference. Use "HEAD" to update the HEAD of the current branch and make it point to this commit. If the reference doesn't exist yet, it will be created. If it does exist, the first parent must be the tip of this branch. * **:author** - Git::Signature of the commit author, defaults to $repo.signature-default. * **:committer** - Git::Signature of the committer, defaults to the same as the author. * **:messsage** - Commit message. Add **:prettify** option to prettify it. * **:tree** -- Git::Tree of the changes to add to the commit. If not specified, $repo.tree-lookup($repo.index.write-tree) will be used, the tree of all changes to the index. * **Git::Commit** - parents for this commit. Specify **:root** for a root commit with no parents. If no parents are specified, and **:root** is not included, the commit pointed to by 'HEAD' will be used as the only parent. $repo.commit(message => "This is my new commit."); See ... for more information about commits. ## References Look up references by name with: ``` my $ref = $repo.reference-lookup('/refs/heads/master'); ``` or by 'short name' (by git precedence rules) with: ``` my $ref = $repo.ref('master'); ``` They return Git::Reference. You can get list of names references: ``` .say for $repo.reference-list; ``` or a list of full references: ``` .name.say for $repo.references; # Say each full name refs/heads/master refs/remotes/origin/master refs/tags/0.1 .short.say for $repo.references; # Say each short name master origin/master 0.1 ``` or limit with a glob: ``` .name.say for $repo.references('refs/tags/*') ``` You can also get the Oid from a reference name: ``` my $oid = $repo.name-to-id('HEAD'); ``` ## Tags ## Branches ## Remotes ## Fetch ## Checkout ## Push ## Worktree ## Diff
## dist_zef-raku-community-modules-HTTP-HPACK.md [![Actions Status](https://github.com/raku-community-modules/HTTP-HPACK/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/HTTP-HPACK/actions) [![Actions Status](https://github.com/raku-community-modules/HTTP-HPACK/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/HTTP-HPACK/actions) [![Actions Status](https://github.com/raku-community-modules/HTTP-HPACK/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/HTTP-HPACK/actions) # NAME HTTP::HPACK - Implementation of RFC 7541 HPACK: Header Compression for HTTP/2 # SYNOPSIS ``` use HTTP::HPACK; # Decoding: my $decoder = HTTP::HPACK::Decoder.new; my @headers = $decoder.decode-headers($buf); say "{.name}: {.value} ({.indexing})" for @headers; # Encoding: my @headers = HTTP::HPACK::Header.new( name => ':method', value => 'GET' ), HTTP::HPACK::Header.new( name => 'password', value => 'correcthorsebatterystaple', indexing => HTTP::HPACK::Indexing::NeverIndexed ); my $encoder = HTTP::HPACK::Encoder.new; my $buf = $encoder.encode-headers(@headers); ``` # DESCRIPTION HPACK is the HTTP/2 header compression algorithm. This module implements encoding (compression) and decoding (decompression) of the HPACK format, as specified in RFC 7541. A HTTP/2 connection will typically have an instance of the decoder (to decompress incoming headers) and an instance of the encoder (to compress outgoing headers). # Notes on specific features ## Huffman compression Decoding of headers compressed using the Huffman codes (set out in the RFC) takes place automatically. By default, the encoder will not apply Huffman compression. To enable this, construct it with the `huffman` named argument set to `True`: ``` my $encoder = HTTP::HPACK::Encoder.new(:huffman); ``` ## Dynamic table management The dynamic table size can be limited by passing the `dynamic-table-limit` named argument when constructing either the encoder or decoder: ``` my $decoder = HTTP::HPACK::Decoder.new(dynamic-table-limit => 256); ``` It is also possible to introspect the current dynamic table size: ``` say $decoder.dynamic-table-size; ``` The size is computed according to the algorithm in RFC 7541 Section 4.1. # Thread safety Instances of HTTP::HPACK::Header are immutable and so safe to share and access concurrently. Instances of `HTTP::HPACK::Decoder` and `HTTP::HPACK::Encoder` are stateful (as a result of the dynamic table), and so a given instance may not be used concurrently. This is not a practical problem, since headers may only be processed in the order they are being received or transmitted anyway. # Known issues * The Huffman code termination handling has not been validated to be completely up to specification, and so may fail to signal errors in some cases where the Huffman code is terminated in a bogus way. # AUTHOR Jonathan Worthington # COPYRIGHT AND LICENSE Copyright 2016 - 2023 Jonathan Worthington Copyright 2024 - 2025 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## maxpairs.md maxpairs Combined from primary sources listed below. # [In Any](#___top "go to top of document")[§](#(Any)_method_maxpairs "direct link") See primary documentation [in context](/type/Any#method_maxpairs) for **method maxpairs**. ```raku multi method maxpairs(Any:D:) ``` Calls [`.pairs`](/routine/pairs) and returns a [`Seq`](/type/Seq) with all of the Pairs with maximum values, as judged by the [`cmp` operator](/routine/cmp): ```raku <a b c a b c>.maxpairs.raku.put; # OUTPUT: «(2 => "c", 5 => "c").Seq␤» %(:42a, :75b).maxpairs.raku.put; # OUTPUT: «(:b(75),).Seq␤» ``` # [In role Setty](#___top "go to top of document")[§](#(role_Setty)_method_maxpairs "direct link") See primary documentation [in context](/type/Setty#method_maxpairs) for **method maxpairs**. ```raku multi method maxpairs(Setty:D: --> Seq:D) ``` Returns the value of [`self.pairs`](/routine/pairs) (as all Pairs have maximum values). See also [`Any.maxpairs`](/routine/maxpairs)
## bridge.md Bridge Combined from primary sources listed below. # [In role Rational](#___top "go to top of document")[§](#(role_Rational)_method_Bridge "direct link") See primary documentation [in context](/type/Rational#method_Bridge) for **method Bridge**. ```raku method Bridge() ``` Returns the number, converted to [`Num`](/type/Num). # [In Num](#___top "go to top of document")[§](#(Num)_method_Bridge "direct link") See primary documentation [in context](/type/Num#method_Bridge) for **method Bridge**. ```raku method Bridge(Num:D:) ``` Returns the number. # [In Int](#___top "go to top of document")[§](#(Int)_method_Bridge "direct link") See primary documentation [in context](/type/Int#method_Bridge) for **method Bridge**. ```raku method Bridge(Int:D: --> Num:D) ``` Returns the integer converted to [`Num`](/type/Num). # [In role Real](#___top "go to top of document")[§](#(role_Real)_method_Bridge "direct link") See primary documentation [in context](/type/Real#method_Bridge) for **method Bridge**. ```raku method Bridge(Real:D:) ``` Default implementation coerces the invocant to [`Num`](/type/Num) and that's the behavior of this method in core `Real` types. This method primarily exist to make it easy to implement custom `Real` types by users, with the `Bridge` method returning *one of* the core `Real` types (*NOT* necessarily a [`Num`](/type/Num)) that best represent the custom `Real` type. In turn, this lets all the core operators and methods obtain a usable value they can work with. As an example, we can implement a custom `Temperature` type. It has a unit of measure and the value, which are given during instantiation. We can implement custom operators or conversion methods that work with this type. When it comes to regular mathematical operators, however, we can simply use the `.Bridge` method to convert the `Temperature` to Kelvin expressed in one of the core numeric types: ```raku class Temperature is Real { has Str:D $.unit is required where any <K F C>; has Real:D $.value is required; method new ($value, :$unit = 'K') { self.bless :$value :$unit } # Note: implementing .new() that handles $value of type Temperature is left as an exercise method Bridge { when $!unit eq 'F' { ($!value + 459.67) × 5/9 } when $!unit eq 'C' { $!value + 273.15 } $!value } method gist { self.Str } method Str { "$!value degrees $!unit" } } sub postfix:<℃> { Temperature.new: $^value, :unit<C> } sub postfix:<℉> { Temperature.new: $^value, :unit<F> } sub postfix:<K> { Temperature.new: $^value, :unit<K> } my $human := 36.6℃; my $book := 451℉; my $sun := 5778K; say $human; # OUTPUT: «36.6 degrees C␤» say $human + $book + $sun; # OUTPUT: «6593.677777777778␤» say 123K + 456K; # OUTPUT: «579␤» ``` As we can see from the last two lines of the output, the type of the bridged result is not forced to be any *particular* core type. It is a [`Rat`](/type/Rat), when we instantiated `Temperature` with a [`Rat`](/type/Rat) or when conversion was involved, and it is an [`Int`](/type/Int) when we instantiated `Temperature` with an [`Int`](/type/Int).
## dist_cpan-GARLANDG-LibUSB.md [![Build Status](https://travis-ci.org/travis/Raku-LibUSB.svg?branch=master)](https://travis-ci.org/travis/Raku-LibUSB) # NAME LibUSB - OO binding to libusb # SYNOPSIS ``` constant VID = <vid> constant PID = <pid> use LibUSB; my LibUSB $dev .= new; $dev.init; $dev.get-device(VID, PID); $dev.open() # Will require elevated privileges # Do things with the device $dev.close(); $dev.exit() ``` # DESCRIPTION LibUSB is an OO Raku binding to the libusb library, allowing for access to USB devices from Raku. This interface is experimental and incomplete. ## Methods ### init Initialize the libusb library for this device object. ### get-device (multi) Find the first device that matches the parameters and select it. #### Params ##### Int $vid The VID of the device. ##### Int $pid The PID of the device. ### get-device (multi) Find the first device with a user-defined check. #### Params ##### &check($desc) Find the first device for which &check returns true. $desc is a libusb\_device\_descriptor as found in the libusb documentation. ### open() Open the selected device. ### close() Close the device. ### exit() Close down the libusb library for this device object. ### vid() Returns the VID of the device. ### pid() Returns the PID of the device. ### bus-number() Returns the bus number of the device. ### address() Returns the address of the device. ### speed() Returns the speed of the device. ### control-transfer Perform a control transfer to the device. It supports named parameters in any order, or positional parameters in the order below. #### Params ##### uint8 $request-type The USB control transfer request type. ##### uint8 $request The USB control transfer request. ##### uint16 $value The USB control transfer value. ##### uint16 $index The USB control transfer index. ##### blob8 $data A buffer containing data to send, or containing space to receive data. ##### uint16 $elems The number of elems in $data. ##### uint32 $timeout How long to wait before timing out. Defaults to 0 (never time out). ### bulk-transfer Perform a bulk transfer to the device. It supports named parameters in any order, or positional parameters in the order below. #### Params ##### uint8 $endpoint The target endpoint ##### blob8 $data A buffer containing data to send, or containing space to receive data. ##### uint16 $elems The number of elems in $data. ##### Int $transferred is rw The amount of data transferred (output) ##### uint32 $timeout How long to wait before timing out. Defaults to 0 (never time out). ### interrupt-transfer Perform a interrupt transfer to the device. It supports named parameters in any order, or positional parameters in the order below. #### Params ##### uint8 $endpoint The target endpoint ##### blob8 $data A buffer containing data to send, or containing space to receive data. ##### uint16 $elems The number of elems in $data. ##### Int $transferred is rw The amount of data transferred (output) ##### uint32 $timeout How long to wait before timing out. Defaults to 0 (never time out). # AUTHOR Travis Gibson [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2020 Travis Gibson This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-lizmat-Net-servent.md [![Actions Status](https://github.com/lizmat/Net-servent/workflows/test/badge.svg)](https://github.com/lizmat/Net-servent/actions) # NAME Raku port of Perl's Net::servent module # SYNOPSIS ``` use Net::servent; $s = getservbyname('ftp') || die "no service"; printf "port for %s is %s, aliases are %s\n", $s.name, $s.port, "@_aliases[]"; use Net::servent qw(:FIELDS); getservbyname('ftp') || die "no service"; print "port for $s_name is $s_port, aliases are @s_aliases[]\n"; ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `Net::servent` module as closely as possible in the Raku Programming Language. This module's exports `getservbyname`, `getservbyportd`, and `getservent` functions that return `Net::servent` objects. This object has methods that return the similarly named structure field name from the C's servent structure from servdb.h, stripped of their leading "s\_" parts, namely name, aliases, port and proto. You may also import all the structure fields directly into your namespace as regular variables using the :FIELDS import tag. Access these fields as variables named with a preceding s\_ in front their method names. Thus, $serv\_obj.name corresponds to $s\_name if you import the fields. The `getserv` function is a simple front-end that forwards a numeric argument to `getservbyport` and the rest to `getservbyname`. # PORTING CAVEATS This module depends on the availability of POSIX semantics. This is generally not available on Windows, so this module will probably not work on Windows. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/serv-servent> . 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_cpan-SOFTMOTH-Template-Mustache.md [![Build Status](https://travis-ci.org/softmoth/raku-Template-Mustache.svg?branch=master)](https://travis-ci.org/softmoth/raku-Template-Mustache) [![Windows Status](https://ci.appveyor.com/api/projects/status/github/softmoth/raku-Template-Mustache?branch=master&passingText=Windows%20-%20OK&failingText=Windows%20-%20FAIL&pendingText=Windows%20-%20pending&svg=true)](https://ci.appveyor.com/project/softmoth/raku-Template-Mustache/branch/master) Raku implementation of Mustache templates, <http://mustache.github.io/>. # Synopsis ``` use Template::Mustache; # Call .render as a class method Template::Mustache.render('Hello, {{planet}}!', { planet => 'world' }).say; # Or instantiate an instance my $stache = Template::Mustache.new: :from<./views>; # Subroutines are called say $stache.render('The time is {{time}}', { time => { ~DateTime.new(now).local } }); my @people = { :name('James T. Kirk'), :title<Captain> }, { :name('Wesley'), :title('Dread Pirate'), :emcee }, { :name('Dana Scully'), :title('Special Agent') }, ; # See this template in ./t/views/roster.mustache $stache.render('roster', { :@people }).say; my %context = event => 'Masters of the Universe Convention', :@people, ; my %partials = welcome => qq:b{Welcome to the {{event}}! We’re pleased to have you here.\n\n}, ; # See this result in ./t/50-readme.t Template::Mustache.render(q:to/EOF/, {{> welcome}} {{> roster}} Dinner at 7PM in the Grand Ballroom. Bring a chair! EOF %context, :from([%partials, './views']) ).say; ``` # Description ## Logging ### Log levels Messages are logged with varying severity levels (from most to least severe): `Fatal`, `Error`, `Warn`, `Info`, `Verbose`, `Audit`, `Debug`, `Trace`, `Trace2` By default, only messages of `Error` or worse are logged. That default can be changed with the `TEMPLATE_MUSTACHE_LOGLEVEL` environment variable. ``` TEMPLATE_MUSTACHE_LOGLEVEL=Debug ``` The default is overridden with the `:log-level` option to `Template::Mustache.new`, or a `Template::Mustache::Logger` object can be passed via the `:logger` option. ``` my $stache = Template::Mustache.new: :log-level<Trace>; my $logger = Template::Mustache::Logger.new: :level<Debug>; my $stache = Template::Mustache.new: :$logger; ``` Either method can be used with the `.render` method, as well. ``` my %data = hello => 'world'; Template::Mustache.render: 'Hello, {{hello}}!', %data, :log-level<Trace>; my $logger = Template::Mustache::Logger.new: :level<Debug>; Template::Mustache.render: 'Hello, {{hello}}!', %data, :$logger; ``` ### Log routine By default, any messages at level `Warn` or worse are logged with the `warn` routine. A `CONTROL` block can handle such warnings if needed; see [Language/phasers](https://docs.raku.org/language/phasers#CONTROL) for details. Less severe messages (`Info` and up) are logged with the `note` routine. The routine can be set per log level, in the `Template::Mustache::Logger.routines` hash. ``` # Use say instead of note for Info and up; the more severe # levels (C<Warn> down to C<Fatal>) still use the warn routine my $stache = Template::Mustache.new: :log-routine(&say); # But even those can be set explicitly $stache.logger.routines{$_} = &die for <Warn Error Fatal>; $stache.render: '{{missing}}', {}; # dies ``` ### method log * `multi method log(Exception $exception, LogLevel :$level)` * `multi method log(LogLevel :$level, *@msgs)` Emit a message at `$level` (`Info` by default). # Extra features ## Template inheritence Support for `hogan.js`-style [template inheritence](https://github.com/groue/GRMustache/blob/master/Guides/template_inheritance.md) is available. ## Pragma: KEEP-UNUSED-VARIABLES Specify `:pragma<KEEP-UNUSED-VARIABLES>` to either `Template::Mustache.new` or `.render`, and any variables which are not defined in the data context will be kept in the rendered text. See `t/13-pragmas.t` for examples. # More Examples and Tests The Mustache spec provides a wealth of examples to demonstrate exactly how the format behaves. <https://github.com/mustache/spec/tree/master/specs/> All of the official Mustache spec tests pass. An updated copy of the tests is distributed in `t/specs`. To check against the official specs repository, clone it into `../mustache-spec`: ``` git clone https://github.com/mustache/spec.git ../mustache-spec prove -v -e 'raku -Ilib' t/ ``` ## Extra Specifications The test file `t/specs/inheritable_partials.json` is taken from [groue/GRMustache](https:/github.com/groue/GRMustache). # Other Mustache Implementations There are many, many Mustache implementations in various languages. Some of note are: * The original Ruby version <https://github.com/defunkt/mustache> * Twitter's hogan.js <https://github.com/twitter/hogan.js> * mustache.java <https://github.com/spullara/mustache.java> * GRMustache (Objective C) <https://github.com/groue/GRMustache> * mustache.php <https://github.com/bobthecow/mustache.php> # TODO * full object support (with method calls; currently the object is just stringified) * global helpers (context items that float at the top of the stack) * database loader * pragmas (FILTERS?) # License [Artistic License 2.0](http://www.perlfoundation.org/artistic_license_2_0)
## dist_cpan-JMASLAK-Sys-Domainname.md [![Build Status](https://travis-ci.org/jmaslak/Raku-Sys-Domainname.svg?branch=master)](https://travis-ci.org/jmaslak/Raku-Sys-Domainname) # NAME Sys::Domainname - Determine System Domain Name # SYNOPSIS ``` use Sys::Domainname; say "My domain name: {domainname}"; ``` # DESCRIPTION This module uses the `hostname -f` command (where it works) to determine the system's domain name. If a domain name is not present, it returns an empty string. Should the `hostname -f` command fail, it returns a `Str` type object. # WARNING This module currently only works on Linux, OSX, and similar environments where the domain name is able to be determined with `hostname -f`. In particular, this will always return `Str` on Windows. # AUTHOR Joelle Maslak [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright © 2020 Joelle Maslak This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## catpath.md catpath Combined from primary sources listed below. # [In IO::Spec::Cygwin](#___top "go to top of document")[§](#(IO::Spec::Cygwin)_method_catpath "direct link") See primary documentation [in context](/type/IO/Spec/Cygwin#method_catpath) for **method catpath**. ```raku method catpath (Str:D $volume, Str:D $dir, Str:D $file --> Str:D) ``` Same as [`IO::Spec::Win32.catpath`](/type/IO/Spec/Win32#method_catpath), except will also change all backslashes to slashes at the end: ```raku IO::Spec::Cygwin.catpath('C:', '/some/dir', 'foo.txt').say; # OUTPUT: «C:/some/dir/foo.txt␤» IO::Spec::Cygwin.catpath('C:', '/some/dir', '').say; # OUTPUT: «C:/some/dir␤» IO::Spec::Cygwin.catpath('', '/some/dir', 'foo.txt').say; # OUTPUT: «/some/dir/foo.txt␤» IO::Spec::Cygwin.catpath('E:', '', 'foo.txt').say; # OUTPUT: «E:foo.txt␤» ``` # [In IO::Spec::Unix](#___top "go to top of document")[§](#(IO::Spec::Unix)_method_catpath "direct link") See primary documentation [in context](/type/IO/Spec/Unix#method_catpath) for **method catpath**. ```raku method catpath ($, Str:D $part1, Str:D $part2 --> Str:D) ``` Takes two path fragments and concatenates them, adding or removing a path separator, if necessary. The first argument is ignored (it exists to maintain consistent interface with other [`IO::Spec`](/type/IO/Spec) types for systems that have volumes). ```raku IO::Spec::Unix.catpath($, 'some/dir', 'and/more').say; # OUTPUT: «some/dir/and/more␤» ``` # [In IO::Spec::Win32](#___top "go to top of document")[§](#(IO::Spec::Win32)_method_catpath "direct link") See primary documentation [in context](/type/IO/Spec/Win32#method_catpath) for **method catpath**. ```raku method catpath (Str:D $volume, Str:D $dir, Str:D $file --> Str:D) ``` Concatenates a path from given volume, a chain of directories, and file. An empty string can be given for any of the three arguments. No attempt to make the path canonical is made. Use [`canonpath`](/routine/canonpath) for that purpose. ```raku IO::Spec::Win32.catpath('C:', '/some/dir', 'foo.txt').say; # OUTPUT: «C:/some/dir\foo.txt␤» IO::Spec::Win32.catpath('C:', '/some/dir', '').say; # OUTPUT: «C:/some/dir␤» IO::Spec::Win32.catpath('', '/some/dir', 'foo.txt').say; # OUTPUT: «/some/dir\foo.txt␤» IO::Spec::Win32.catpath('E:', '', 'foo.txt').say; # OUTPUT: «E:foo.txt␤» ```
## dist_cpan-JJATRIA-Timer-Stopwatch.md ## NAME Timer::Stopwatch - Schedule and reset repeated time measurements ## SYNOPSIS ``` use Timer::Stopwatch; my $irregular-supply = Supply.interval(1).grep: { Bool.pick } my $timer = Timer::Stopwatch.new; react { whenever $irregular-supply { note "{ now.DateTime.hh-mm-ss }: Received an irregular event"; # Wait up to 2 seconds for the next event $timer.reset: 2; } whenever $timer { note "It's been { .round } seconds since the last event"; $timer.stop; } whenever Promise.in: 20 { note 'Stopping after 20 seconds'; $timer.stop; } whenever $timer.Promise { note "Timer was stopped. We're done"; done; } } # OUTPUT: # 20:33:39: Received an irregular event # 20:33:40: Received an irregular event # 20:33:42: Received an irregular event # It's been 2 seconds since the last event # Timer was stopped. We're done ``` ## DESCRIPTION Timer::Stopwatch is a resettable, stoppable wrapper around a Supply that can be used to mark multiple moments in time. ## METHODS ### in ``` method in( Numeric $in ) returns Timer::Stopwatch ``` Creates a new Stopwatch with a timer that will trigger in the given amount of seconds, unless it is reset or stopped before that. ### tick ``` method tick() returns Duration ``` Emits the duration since creation time (or the last `reset`) to the Supply. Returns the emitted Duration. ### reset ``` method reset( Numeric $in? ) returns Bool ``` Reset sets the start time for the stopwatch to the current time. If called with a numeric argument, it also sets a timer to expire after the given duration. It returns True if the call interrupted a pending timer, and False if no timer had been set, or if it had already expired, or if the stopwatch had already been stopped. ### stop ``` method stop() returns Bool ``` Stop marks this stopwatch as done. Once a stopwatch has been stopped, most of its actions are finished, and new stopwatch should be created. Internally, it stops any pending timers and closes the supply. It returns True if the call interrupted a pending timer, and False if no timer had been set, or if it had already expired, or if the stopwatch had already been stopped. ### Duration ``` method Duration() returns Duration ``` Returns the amount of time elapsed since the start (or the last reset) as a Duration. ### Promise ``` method Promise() returns Promise ``` Returns a Promise that will be kept when the Stopwatch is stopped. When kept, it will hold the Duration elapsed since the time the Stopwatch was created, or since the last call to `reset`. ### Supply ``` method Supply() returns Supply ``` Returns a live Supply that will receive timer events ## AUTHOR José Joaquín Atria [[email protected]](mailto:[email protected]) ## COPYRIGHT AND LICENSE Copyright 2020 José Joaquín Atria This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-SAMGWISE-Slang-Predicate.md # NAME Slang::Predicate - Predicates in perl6 # SYNOPSIS ``` use Slang::Predicate; my (\α, \β) = (T, F); say ((α → β) ∧ α) → β; ``` # DESCRIPTION Slang::Predicate adds operators common to predicate logic directly to perl6. Exported terms and operators are: | | | | | --- | --- | --- | | Terms | Term | Example | | True | T | T ~~ True | | False | F | F ~~ False | | | | | | --- | --- | --- | | Infix | operator | Example | | True | T | T ~~ True | | False | F | F ~~ False | | Disjunction | ∨ | T ∨ F ~~ True | | Conjunction | ∧ | T ∧ F ~~ False | | Exclusive disjunction | ⊻ or ⊕ | T ⊻ F ~~ True | | Conditional | → or ⇒ or ⊃ | T → F ~~ False | | Biconditional | ↔ or ⇔ or ≡ | T ↔ F ~~ False | | | | | | --- | --- | --- | | Prefix | operator | Example | | Negation | ¬ | ¬T ~~ False | | Verum | ⊤ | ⊤F ~~ True | | Falsum | ⊥ | ⊥T ~~ False | # AUTHOR Sam Gillespie [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2017 Sam Gillespie This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-wayland-Class-Loader-Dynamic.md # Class::Loader::Dynamic Will dynamically create classes with the same name as the modules. Modules can be specified with the glob language. # Primary use: .load-module-pattern() ``` use Class::Loader::Dynamic; class Foo does Class::Loader::Dynamic {} my $loader = Foo.new(); my ($passes, $fails) = $loader.load-module-pattern( :paths(['lib', 't']), :globs(["Lo?derTest*"]), ); $passing-class = $passes<LoaderTestPassing> $passing-class.the-method() ``` The above code will try to load eg. `LoaderTestPassing` and `LoaderTestFailing`, and even `LoZderTestZZZZZ`, but will ignore `IgnoreLoaderTest`. It will also call `.the-method` on the new object that's a `LoaderTestPassing`. .load-module-pattern can also take a `:regexes` key that contains an array of regexes. If a module matches any of the regexes or globs, then this will try to load the class. See `.available-modules` for info on the `:paths` option. # .available-modules(@lib-paths) Returns a list of all modules that could be loaded. The @lib-paths are the library paths to search (eg. anything you declare with `use lib 'path'` will need to be repeated here). # .load-library(Str :$type, \*%parameters) Loads the class specified in the `$type` string from the module of the same name. %parameters are passed to the .new() method on the class.
## dist_zef-japhb-MUGS-Core.md [![Actions Status](https://github.com/Raku-MUGS/MUGS-Core/workflows/test/badge.svg)](https://github.com/Raku-MUGS/MUGS-Core/actions) # NAME MUGS-Core - Core modules for MUGS (Multi-User Gaming Services) # SYNOPSIS ``` # Setting up a simple MUGS-Core development environment mkdir MUGS cd MUGS git clone [email protected]:Raku-MUGS/MUGS-Core.git cd MUGS-Core zef install --deps-only --exclude="pq:ver<5>:from<native>" . raku -Ilib bin/mugs-admin create-universe ``` # DESCRIPTION **NOTE: See the [top-level MUGS repo](https://github.com/Raku-MUGS/MUGS) for more info.** MUGS-Core is the core of MUGS (Multi-User Gaming Services), a Raku-based platform for game service development. In other words, it is a set of basic services written in the Raku language for creating client-server and multi-user games. It abstracts away the boilerplate of managing player identities, tracking active games and sessions, sending and receiving messages and actions, and so forth. This Proof-of-Concept release includes a WebSocket-based game server, simple admin and developer tools, and simple "games" intended primarily for testing. The game server can store data using either an internal ephemeral/test storage driver, or in SQLite databases on disk using a storage driver based on the Red ORM. # ROADMAP MUGS is still in its infancy, at the beginning of a long and hopefully very enjoyable journey. There is a [draft roadmap for the first few major releases](https://github.com/Raku-MUGS/MUGS/tree/main/docs/todo/release-roadmap.md) but I don't plan to do it all myself -- I'm looking for contributions of all sorts to help make it a reality. # CONTRIBUTING Please do! :-) In all seriousness, check out [the CONTRIBUTING doc](docs/CONTRIBUTING.md) (identical in each repo) for details on how to contribute, as well as [the Coding Standards doc](https://github.com/Raku-MUGS/MUGS/tree/main/docs/design/coding-standards.md) for guidelines/standards/rules that apply to code contributions in particular. The MUGS project has a matching GitHub org, [Raku-MUGS](https://github.com/Raku-MUGS), where you will find all related repositories and issue trackers, as well as formal meta-discussion. More informal discussion can be found on IRC in Libera.Chat #mugs. # AUTHOR Geoffrey Broadwell [[email protected]](mailto:[email protected]) (japhb on GitHub and Libera.Chat) # COPYRIGHT AND LICENSE Copyright 2021-2024 Geoffrey Broadwell MUGS is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-lizmat-Tie-Array.md [![Actions Status](https://github.com/lizmat/Tie-Array/workflows/test/badge.svg)](https://github.com/lizmat/Tie-Array/actions) # NAME Raku port of Perl's Tie::Array module # SYNOPSIS ``` use P5tie; use Tie::Array; ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `Tie::Array` module as closely as possible in the Raku Programming Language. Tie::Array is a module intended to be subclassed by classes using the </P5tie|tie()> interface. It depends on the implementation of methods `FETCH`, `STORE`, `FETCHSIZE` and `STORESIZE`. The `EXISTS` method should be implemented if `exists` functionality is needed. The `DELETE` method should be implemented if `delete` functionality is needed. Apart from these, all other interfaces methods are provided in terms of `FETCH`, `STORE`, `FETCHSIZE` and `STORESIZE`. # SEE ALSO <P5tie>, Tie::StdArray # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Tie-Array> . 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-HTTP-Roles.md [![Actions Status](https://github.com/raku-community-modules/HTTP-Roles/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/HTTP-Roles/actions) # NAME HTTP::Roles - Roles for an HTTP::Server with interchangeable backends # SYNOPSIS ``` use HTTP::Roles; my class HTTP::Server::MyWay does HTTP::Server::Role { ... } my class HTTP::Request::MyWay does HTTP::Request::Role { ... } my class HTTP::Response::MyWay does HTTP::Response::Role { ... } ``` # DESCRIPTION HTTP::Roles provides a set of roles to define the functionality of an HTTP server, and handling requests and responses. # ROLES ## HTTP::Server::Role All of the methods defined by the `HTTP::Server::Role` take a `Callable` as the argument, which should provide the necessary functionality. ### listen Calling the `listen` method is telling the server to start up and start accepting connections. ### middleware The `middleware` method should be called with a `Callable` during server setup: the specified `Callable` is to be executed whenever the reception of the request headers of a request is complete. ### handler The `handler` method should be called with a `Callable` during server setup: the specified `Callable` is to be executed whenever the reception of the request headers **and** the body of a request is complete. ### after The `after` method should be called with a `Callable` during server setup: the specified `Callable` is to be executed whenever the response is complete and sent. ## HTTP::Request::Role The `HTTP::Request::Role` provides some generic attributes for the class that *should* be present in any decent `HTTP::Request` class. These are: ``` has Str $.method; has Str $.uri; has Str $.version; has Buf $.data is rw; has %.params; has %.headers; ``` ### header A generic `header` method to retrieve headers in a case insensitive way from the `%.headers` attribute. ## HTTP::Response::Role The `HTTP::Response::Role` provides some generic attributes for the class that *should* be present in any decent `HTTP::Response` class. ``` has Int:D $.status is rw = 200; has %.headers is rw; has $.connection; has %.statuscodes = HTTP::Status.Map; ``` ### write The `write` method is expected to write the given data of the response. ### close The `close` method is expected to close the connection to the client, taking any optional data to be sent, and a named argument `:force` to forcefully close the connection (which defaults to `False`). # AUTHOR Tony O'Dell # COPYRIGHT AND LICENSE Copyright 2015 - 2019 Tony O'Dell Copyright 2020 - 2022 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## rolepunning.md role Metamodel::RolePunning Metaobject that supports *punning* of roles. ```raku role Perl6::Metamodel::RolePunning {} ``` *Warning*: this role is part of the Rakudo implementation, and is not a part of the language specification. Implements the ability to create objects from `Role`s without the intermediate need to use a class. Not intended to be used directly (will in fact error if it's `use`d), but via punning of roles, as below. This is also Rakudo specific and not part of the spec. ```raku role A { method b { return "punned" } }; my $a = A.new; say $a.b; # OUTPUT: «punned␤» ```
## dist_zef-vrurg-Cro-RPC-JSON.md # NAME `Cro::RPC::JSON` - server side JSON-RPC 2.0 in minutes # SYNOPSIS ``` use Cro::HTTP::Server; use Cro::HTTP::Router; use Cro::RPC::JSON:api<2>; class JRPC-Actor is export { method foo ( Int :$a, Str :$b ) is json-rpc("FOO") { return "$b and $a"; } proto method bar (|) is json-rpc { * } multi method bar ( Str :$a! ) { "single named Str param" } multi method bar ( Int $i, Num $n, Str $s ) { "Int, Num, Str positionals" } multi method bar ( *%options ) { [ "slurpy hash:", %options ] } method non-json (|) { "I won't be called!" } } sub routes is export { my $actor = JRPC-Actor.new; route { # Use an object implementation of API post -> "api" { json-rpc $actor; } # Use a code-based implementation of API post -> "api2" { json-rpc -> Cro::RPC::JSON::Request $jrpc-req { { to-user => "a string", num => pi } } } } } ``` # DESCRIPTION The initial and primary purpose of this module is to provide a fast path to make your class-based API implementation available to serve [JSON-RPC 2.0](https://www.jsonrpc.org/specification) requests over both HTTP/POST and WebSocket protocols with as little pain as possible. In many cases it is feasible to use the same method to serve both your Raku code and JSON-RPC calls without any special case code paths in the method implementation. Alongside with supporting class-based API implementation the module also supports code-based scenarios where JSON-RPC requests are handled by a single user-provided code object like a pointy block or a `sub`. This case has two modes of operation: synchronous and asynchronous. These will be discussed later. ## Modes Of Operation `Cro::RPC::JSON` supports the following modes of operation in mutually exclusive pairs: * code or object * HTTP or WebSocket * synchronous or asynchronous ### Code vs. Object The [SYNOPSIS](#SYNOPSIS) provides examples for both of the modes. For any relatively complex API object mode would be preferred over code for its higher abstraction level and, correspondingly, for better maintainabilty. Declaring a class for serving a JSON-RPC requests is as simple as adding `is json-rpc` trait to some of its methods. If we consider `JRPC-Actor` class from [SYNOPSIS](#SYNOPSIS) then calling its method `bar` from a remote client would be done with the following JSON structure: ``` { jsonrpc: "2.0", id: 314, method: "bar", params: { a: "string" } } ``` Which will result in invoking the first `bar` multi-candidate with named parameter `:a<string>`. But if we pass an array together with `params` key: `[42, 3.1415926, "anything"]` – then the second multi-candidate will be called with three positional arguments. This is the basic rule of translation used by `Cro::RPC::JSON`: a top-level JSON object is translated into named parameters; a top-level array represents positional parameters. See more information about handling of method arguments and return values in the [Method Call Convention](#Method Call Convention) section below. More information about exporting methods for JSON-RPC is provided in `json-rpc` trait section below. Handling a JSON-RPC request by a code object is considered more low-level approach. Particular format of the code is determined by wether it operates in synchronous or asynchronous mode (see below), general principle is: the code is provided with a [`Cro::RPC::JSON::Request`](JSON/Request.md) object and must produce JSONifiable return value which is then returned to the client. The [SYNOPSIS](#SYNOPSIS) provides the most simple case of a synchronous code object. Any call to JSON-RPC to any method in the example will return: ``` { jsonrpc: "2.0", id: <user-request-id>, result: { "to-user": "a string", num: 3.141592653589793 } } ``` ### HTTP And WebSocket The difference between these two modes is in the nature of the protocols: where HTTP supports single request/response, WebSocket supports continuous flow of requests/responses and bidirectional communication between client and server. Because handling of an HTTP request is rather easy to understand we're not going to focus much on it. Instead, let's focus in WebSocket specifics of implemeting JSON-RPC by `Cro::RPC::JSON`. First of all, it has to be mentioned that there is no single specification of how JSON-RPC over WebSocket is to be implemented. `Cro::RPC::JSON` targetting at supporting [rpc-websockets](https://github.com/elpheria/rpc-websockets) implementation for JavaScript. To handle JSON-RPC request/response protocol a WebSocket stream is considered a bidirectional sequence of JSON objects or arrays of JSON-RPC batch requests/responses. Any server-side notification pushed toward the client must be a JSON object and must not contain `jsonrpc` key. From the server implementation side of things the above said means that for object mode of operation there is nothing to be changed in method implementations. Everything is handled automatically and makes no difference with HTTP requests. For code objects in synchronous mode there is no change either. But for asynchronous ones it is recommended to use `jrpc-notify` sub to simplify producing of a valid JSON return. The exact meaning of this statement will be clear later. To get your server support WebSocket transport all is needed is two changes in router code: `get` to be used in place of `post`; and `:web-socket` named argument to be added to call to `json-rpc`: ``` route { my $actor = JRPC-Actor.new; get -> "api" { json-rpc :web-socket, $actor; } } ``` Same applies to a synchronous code mode: ``` route { get -> "api2" { json-rpc :web-socket, -> Cro::RPC::JSON::Request $jrpc-req { { to-user => "a string", num => pi } } } } ``` The asynchronous mode wil be considered in the corresponding section later. It is still possible though for both object and synchronous code mode cases to provide async notifications. See `:async` in sections dedicated to `json-rpc` routine and `json-rpc` trait. ### Synchronous And Asynchronous Hopefully, by this moment it is clear that in synchronous mode of operation user code receives a request in either raw, as [`Cro::RPC::JSON::Request`](JSON/Request.md) instance, or in a "prepared" form as method arguments. One way or another, a JSONifiable response is produced and that's the end of the cycle for server-side user code. In asynchronous mode things are pretty much different. First of all, it's not supported for objects; though they still can provide asynchronous notifications using `json-rpc` trait `:async` argument. Second, a code in asynchronous mode receives a [`Supply`](https://docs.raku.org/type/Supply) of incoming requests as an argument and must return a supply emitting [`Cro::RPC::JSON::MethodResponse`](JSON/MethodResponse.md) objects. This is the lowest mode of operation as in this case the code is plugged almost directly into a [`Cro`](https://cro.services) pipeline. See `respond` helper method in [`Cro::RPC::JSON::Request`](JSON/Request.md) which allows to reduce the number of low-level operations needed to emit a resut. Here is an example of the most simplisic asynchronous code implementation. Note the strict typing used with `$in` parameter. This is how we tell `Cro::RPC::JSON` about our intention to operate asynchronously: ``` route { get -> 'api' { json-rpc :web-socket, -> Supply:D $in { supply { whenever $in -> $req { $req.respond: { to-user => "a string", num => pi } } } } } } ``` **Note** that the same asynchronous code can be used for processing an HTTP request too. In this case `:web-socket` argument is not used, `get` turns into `post`, yet otherwise the sample doesn't change. But what remains the same is that `$in` would emit exactly one request object corresponding to the single HTTP `POST`. So, the only case when this approach makes sense if when the same code object is re-used for both WebSocket and HTTP modes. The above example can be extended to provide additional functionality when operating on a WebSocket: ``` route { get -> 'api' { json-rpc :web-socket, -> $in, $close { supply { whenever $in -> $req { $req.respond: { to-user => "a string", num => pi } } whenever $close -> $req { $close-code = (await $req.body).read-uint16(0); done; } whenever Supply.interval(1) { jrpc-notify %( :notification<tick-tock>, :params( { :time(now) } ) ) } } } } } ``` First of all, the absense of `Supply` in front of `$in` is not an error here. Another way to request asynchronous mode of operation is to use declare two parameters. In this case the second one is expected to be a close [`Promise`](https://docs.raku.org/type/Promise) as provided by [`Cro::HTTP::Router::WebSocket`](https://cro.services/docs/reference/cro-http-router-websocket#Receiving_close_messages). The last `whenever` block apparently produces a notification every second which is then pushed back to the client. `Cro::RPC::JSON` also provides a hybrid mode of operation where it is possible to provide asynchronous events alongside with a synchronous code. See `:async` argument of `json-rpc` trait and `json-rpc` sub. # MODULE HELPERS ## `json-rpc` `json-rpc` is a multi-dispatch `sub` which must be used inside `Cro` `get` or `post` blocks, depending on what transport protocol, HTTP or WebSockets, is to be served. In its most simplistic form `json-rpc` takes a single code object: ``` json-rpc -> $req { ... } ``` Or: ``` json-rpc -> Supply $in { ... } ``` As it was noted above, the type of argument determines wether the code block is to operate in synchronous or asynchronous mode. Adding a named argument `:web-socket` would tell `json-rpc` to wrap around `Cro`'s `web-socket` subroutine. Same rules about synchronous/asynchronous mode of operation apply: ``` json-rpc :web-socket, -> $req { ... } json-rpc :web-socket, -> Supply $in { ... } json-rpc :web-socket, -> $in, $close { ... } I<C<:web-socket> is also available as C<:ws> or C<:websocket> aliases.> ``` If the first positional argument of `json-rpc` is anything but a code then it is expected to be an object providing methods for JSON-RPC calls. I.e. those marked with `is json-rpc` trait: ``` class JRPC-Actor { method authorise(Str:D $name, Str:D $password) is json-rpc { ... } } route { my $actor = JRPC-Actor.new; get -> "api" { json-rpc $actor; } } ``` The `$actor` object can also be accompanied with `:web-socket` (`:ws`, `:websocket`) argument. ### `:async` When a synchronous code is used with `:web-socket` argument it is still possible to emit asynchronous notifications. This is done by passing `:async` named argument to the subroutine which is expected to be a code block which can accept a single argument – WebSocket `$close` [`Promise`](https://docs.raku.org/type/Promise); and which will return a [`Supply`](https://docs.raku.org/type/Supply). The supply is expected to emit JSONifiable notifications to be pushed back to the client code. For example, this is a code from *060-websocket.rakutest* test file: ``` json-rpc :ws, { {:foo<sync-bar>} }, async => -> $close { supply { my $count = 0; my $tap; whenever $close { # WebSocket close promise $close-code = (await .body).read-uint16(0); $tap.close; } $tap = do whenever Supply.interval(.1) { ++$count; emit { :notification("tick-tock"), :params({:$count}) } } } } ``` This little trick allows us to use same synchronous code for serving both HTTP and WebSocket protocols while still allow for asynchronous operations with WebSockets. This mode of operation is called *hybrid* because it combines both synchronous and asynchronous ones. **Note** that contrary to the asynchronous code above we don't use `jrpc-notify` to emit a notification. This is because in the case of asynchronous code there is no way for `Cro::RPC::JSON` core to tell the difference between a reponse to a JSON-RPC method call or a notification if they both are hashes, for example, as both are coming from the same supply. That's why one have to wrap them in either [`Cro::RPC::JSON::MethodResponse`](JSON/MethodResponse.md) or [`Cro::RPC::JSON::Notification`](JSON/Notification.md) containers. Besides, when it comes to responding to a method call in the asynchronous model the order of responses is not determined. That's why use of `$req.respond` ensures that the data emitted has the right `id` field set in JSON-RPC response object. ## `jrpc-request` Returns currently being processed [`Cro::RPC::JSON::Request`](JSON/Request.md) object where applicable and the object is not directly available. Mostly useful for methods of actor class. ## `jrpc-response` Returns currently being processed [`Cro::RPC::JSON::MethodResponse`](JSON/MethodResponse.md) object where applicable and the object is not directly available. Mostly useful for methods of actor class. Also available as `jrpc-request.jrpc-response`. ## `jrpc-protocol` A string representing the current transport protocol. Only one of two values is available: *HTTP* or *WebSocket*. ## `jrpc-async` A [`Bool`](https://docs.raku.org/type/Bool) which is *True* if the code object passed to `json-rpc` subroutine is detected as asynchronous. For object mode of operation it is always *False* for JSON-RPC methods and always *True* for `:async` and `:wsclose` methods (see `json-rpc` trait section below). **Note** that both `jrpc-protocol` and `jrpc-async` are only available outside of `supply` block of asynchronous code objects. Similarly, `jrpc-request` and `jrpc-response` are not available in asynchronous mode. ## `jrpc-notify` This subroutine is a conivenience means to reduce the boilerplate of asynchronous code emitting notifications. All it does is wraps it's argument into a [`Cro::RPC::JSON::Notification`](JSON/Notification.md) instance and calls `emit` with the object. # CREATING AN ACTOR CLASS Writing an actor class is the most advanced and the most simple way of implementing a complex API. As it was already stated before, the biggest *pro* of this approach is abstracting API implementation from the means of accessing it. In other words, normally it is sufficient to have: ``` use Cro::RPC::JSON:api<2>; class JRPC-Actor { method add(Int:D $a, Int:D $b) is json-rpc { $a + $b } } ``` The method is then available for both [Raku](https://raku.org) on the server side as: ``` my $sub = $actor.add(13, 42); ``` And for the client code in JavaScript running in a browser: ``` let WebSocket = require('rpc-websockets').Client; let ws = new WebSocket('ws://localhost:3000'); let sum = await ws.call("add", [13, 42]); ``` Similar JavaScript code can be imagined for any alternative client-side JSON-RPC implementation. Apparently, all one needs is to use `is json-rpc` trait to mark a method as a JSON-RPC compatible. **Note** that while we mostly talk about an *actor class* the trait can also be applied to methods in roles. Consuming such role turns a class into a JSON-RPC actor implementation automatically. Inheriting from an actor class also preserves access to the JSON-RPC methods unless they're redefined in a child class without `is json-rpc` trait. *t/005-trait.rakutest* test can be very helpful in providing examples of how things work with Raku OO model. ## Method Call Convention Methods exported for JSON-RPC are invoked with parameters received from a JSON-RPC request, de-serialized, and flattened. In other words it can be illustrated with: ``` $actor.jrpc-method( |from-json($json-params) ); ``` Apparently, this turns any JSON array into positional parameters; and any JSON object into named parameters. Due to the limitations of JSON format, there is no way to pass both named and positionals at the same time. The only exception from this rule are methods with a single parameter typed with [`Cro::RPC::JSON::Request`](JSON/Request.md). This way a method indicates that it wants to do in-depth analysis of the incoming requests and expects a raw request object. For developer conivenience the module provides automated serialization of method's return values and de-serialization of arguments. With this feature it's event more easy to write methods universal for both Raku and RPC side of things; and even less boilerplate for any kind of thunk methods. The most simple case is serialization of return values. It's done in a very straightforward way: a method return is passed to `JSON::Marshal::marshal` sub. The outcome is then sent back to the RPC client. Somewhat more complicate approach is used for method arguments recived via `params` key of JSON-RPC request. First of all, the module checks if `params` is an array. And if it is then it is considered as a list of positional arguments. This is an unbendable rule. If `params` is a JSON object and the callee method doesn't have a positional parameter then `params` is considered a set of named arguments. Otherwise it's considered to be the only positional argument of the method. Before submitting the arguments to the method `Cro::RPC::JSON` first tries to de-serialize them based on method's signature and parameter typing. The algorithm used is basically identical for both positionals and nameds: the module iterates over arguments, matches them to method parameters, and then `JSON::Unmarshal::unmarshal()` with parameter's type. For example: ``` class Product { has Int $.SKU; has Str $.name; } method to-inventory(Product:D $item, Int:D $count) is json-rpc { ... } ``` When `to-inventory` is invoked via this JSON-RPC request: ``` { id: 1, jsonrpc: "2.0", method: "to-inventory", params: [ { SKU: 42, name: "Traveller's Towel" }, 13 ] } ``` the first object in `params` array will be de-serialized into a `Product` instance. That's it, we now have method which can be transparently used by both Raky and RPC callers! If the method is changed to use named parameters: ``` method to-inventory(Product:D :$item, Int:D :$count) is json-rpc {...} ``` Then `params` must be turned into a JSON object like this: ``` { item: { SKU: 42, name: "Traveller's Towel" }, count: 13 } ``` And the outcome will be no different of the positional variant. Aliasing of named parameters is supported. With this signature: ``` method to-inventory(Product:D :product(:$item), Int:D :$count) is json-rpc {...} ``` We can use the following `params` JSON object: ``` { product: { SKU: 42, name: "Traveller's Towel" }, count: 13 } ``` `Any` type is special cased here. Parameters of `Any` type receive corresponding arguments from the request as-is, no unmarshaling attempted beyond de-stringification of a JSON entity: ``` method foo($x, $y) is json-rpc {...} params: [true, { a: 1 }] ``` `$x` here will be set to *True*, `$y` – to hash `{ a =` 1 }>. It is also possible to pass a single positional array argument with `params: [[1, 2, 3]]`. The unmarshalling will also work correctly for parameterized arrays and hashes. So, if we need to add several objects of the same kind we can do it like this: ``` method to-catalog(Product:D @items) is json-rpc {...} ``` And it will work with: ``` params: [ { SKU: 42, name: "Traveller's Towel" }, { SKU: 13, name: "A Happy Amulet" }, { SKU: 256, name: "Product 100000000" } ] ``` `to-catalog` will receive an array of `Product` instances. Slurpy parameters are supported as well as captures. The module doesn't attempt unmarshalling of arguments to be consumed by slurpies or captures because there is no way for us to know their types. The situation is pretty much identical for multi-dispatch methods where to know the eventual candidate to be invoked we nede to know argument types; but we can't know them because we don't know the candidate! For this reason de-serialization is only done based on `proto` method signature: ``` proto method categorize-product(Product:D, |) is json-rpc {*} multi method categorize-product(Product:D $item, Str:D $category-name) {...} multi method categorize-product(Product:D $item, Int:D $category-id) {...} params: [{ SKU: 42, name: "Traveller's Towel" }, "fictional"] params: [{ SKU: 13, name: "A Happy Amulet" }, 12] ``` Apparently, each of the `params` will dispatch as expected. ## Authorizing Method Calls `Cro::RPC::JSON` provide means to implement session-based authorization of a method call. It is based on the following two key components: * Session object, as [documented in a Cro paper](https://cro.services/docs/http-auth-and-sessions), available via `request.auth`. The object must consume [`Cro::RPC::JSON::Auth`](JSON/Auth.md) role and implement `json-rpc-authorize` method * Authorization object provided with `:auth` modifier of either `json-rpc` or `json-rpc-actor` traits (see below) The Cro's session object used to authenticate/authorize a HTTP session or a WebSocket connection is expected to provide means of authorizing JSON-RPC method calls too. For this purpose it is expected to consume [`Cro::RPC::JSON::Auth`](JSON/Auth.md) role and implement `json-rpc-authorize` method. Generally speaking, the method is expected to either authorize or prohit an RPC method call based on the available session data. For example, here is an implementation of the session object from a test suite: ``` my class SessionMock does Cro::RPC::JSON::Auth does Cro::HTTP::Auth { method json-rpc-authorize($meth-auth) { return False if $meth-auth eq 'admin'; return True if $meth-auth eq 'user' | 'group'; die "Can't authorize with ", $meth-auth, ": no such privilege"; } } ``` This one is really simplistic. It prohibits any activity if it requires *admin* privileges; and only allows anything requiring *user* or *group*. Apparently, the real life requires something more sophisticated, depending on the authorization model of your application. It is worth mentioning that the auth object associated with a method can be virtually of any type given it's a definite. For example, it can be a [`Junction`](https://docs.raku.org/type/Junction): ``` method self-destroy() is json-rpc(:auth('root' | 'admin')) {...} ``` Because defining the same auth object for every JSON-RPC method could be really boresome, it is possible to define the default one by associating it with actor class: ``` class Foo is json-rpc-actor(:auth<user>) { ... } ``` In this case every JSON-RPC method is considered having *user* auth associated with them unless otherwise specified manually per method declaration. The authorization takes place whenever a definite auth object can be associated with a method. I.e. it could be an object defined for the method itself; or a default one can be found. Note also that there is no way to bypass authorization in the latter case. There are some specifics of the authorization process to be considered when class inheritance is involved: * If a class inherits from one or more actor classes but is not formally declared as a JSON-RPC actor itself then the first defined auth object found on a parent actor class is used. * The found default auth object overrides any other default specified for classes/roles located further in MRO list. I.e. if classes `Foo` and `Bar` appear in MRO in the order of mentioning; and if `Foo` uses *manager* as the default auth, whereas `Bar` default is *admin*; then any JSON-RPC method from `Bar` with no explicit auth attached will be considered as having it set to *manager*. ## `is json-rpc` Method Trait In its most simplistic form the trait simply marks a method and exports it for JSON-RPC calls under the same name it is declared in the actor class. But sometimes we need to export it under a different name than the one available for Raku code. In this case we can pass the desired name as trait's first positional argument: ``` method add(Int:D $a, Int:D $b) is json-rpc("sum") { $a + $b } ``` Now we would have to replace *"add"* string in the last JavaScript example with *"sum"*. The trait also accepts a number of named arguments which are going to be discussed next. They're called *modifiers* as they modify the way the methods are treated by `Cro::RPC::JSON` core. It is important to remember that some modifiers make a method unavailable for JSON-RPC calls: ``` method helper() is json-rpc(:async) { ... } # Not available for JSON-RPC ``` Methods marked wit these modifiers become *ad-hoc* methods; the modifiers are correspondingly called *ad-hoc* too. One of the features making ad-hoc methods different from JSON-RPC exports is that they're not overridable in child classes. In other words, if class `Foo` inherits from `Bar` and both define a `:async` ad-hoc named `event-emitter` then both methods will be incorporated into JSON-RPC pipeline. This feature makes `submethod`s ideal candidates for ad-hoc implementation. Though it's pretty much a bad idea, but if an ad-hoc method is given a name then it becomes a JSON-RPC export too. If for some reason a developer considers this approach then it is better be done by means of a multi-dispatch via applying the trait to method's `proto`: ``` proto method universal(|) is json-rpc("foo", :async) {...} multi method universal(Promise:D $close) { ... } # Take care of :async multi method universal(|c) {...} # Take care of API calls. ``` It is also worth mentioning that applying the trait to a `multi` candidate is equivalent to applying it to its `proto`. While being generally useless withing a class, it allows us to turn a method of parent class into a JSON-RPC accessible one: ``` class Foo { has $.value; proto method add(|) {*} multi method add(::?CLASS:D $b) { $!value += $b.value } ... } class Bar is Foo { multi method add($a, $b) is json-rpc { $!value = $a.value + $b.value } } ``` So, it is now possible to use the single-argument version of `add` method by a remote client too. ### Ad-Hoc Modifier `:async` `:async` modifier must be used with methods providing asynchronous events for WebSocket transport. Rules similar to [`json-rpc`](#json-rpc) `:async` named argument apply: * the method must return a supply emitting either [`Cro::RPC::JSON::Notification`](JSON/Notification.md) instances or JSONifiable objects * the method may have a single parameter – the WebSocket `$close` [`Promise`](https://docs.raku.org/type/Promise) method event-emitter(Promise:D $close?) is json-rpc(:async) { supply { whenever Supply.interval(1) { emit { :namespace, params => %( time => now ) } } with $close { whenever $close -> $req { my $close-code = (await $req.body).read-uint16(0); self.cleanup($close-code); } } } } ### Ad-Hoc Modifier `:wsclose` This is another way to react to WebSocket close event. A method marked with this modifier will be called whenever WebSocket is closed by the client. The only argument passed to the method is the close code as given by the client: ``` method websocket-closed(Int:D $code) is json-rpc(:wsclose) { self.cleanup($code); } ``` ### Ad-Hoc Modifier `:last` `:last` methods are invoked when the incoming [`Supply`](https://docs.raku.org/type/Supply) of WebSocket requests is closed. The object mode of operations is handled by an asynchronous code similar to this pseudo-code: ``` supply { when $in -> $websocket-request { ... # Find a method on the object and call it with $websocket-request.params LAST { ... # Get all :last methods and call them. } } } ``` ### Ad-Hoc Modifier `:close` A `:close` method is invoked when the supply block processing WebSocket requests is closed. Done by `CLOSE` phaser on `supply {...}` from the previous section. ### Modifier `:auth(Any:D $auth-obj)` Non ad-hoc modifier. Defines an authorization object associated with a JSON-RPC exported method. See the section about method call authorization for more details. ## `is json-rpc-actor` Class/Role Trait It is not normally required to mark a class as a JSON-RPC actor explicitly because applying `json-rpc` trait to a method does it implicitly for us. In practice, this means that the class' `HOW` gets mixed in with `Cro::RPC::JSON::Metamodel::ClassHOW` role. But if we inherit from an actor class the child's `HOW` doesn't get the mixin. `Cro::RPC::JSON` can work with the child as well as with its parent, but sometime we may want the child to be formally declared an actor too. This is when `is json-rpc-actor` comes to help. ### `:auth(Any:D $auth-obj)` `:auth` modifier defines actor's default authorization object. If a JSON-RPC method doesn't have one associated with it (see `:auth` of `json-rpc` trait) then the default one is used. # NOTES ## Consuming A Role With JSON-RPC Methods A role cannot be a JSON-RPC actor. But if a method in it has `json-rpc` trait applied the role becomes a JSON-RPC actor implementation. But a class consuming the role becomes an actor implicitly. ## Cro's `request` Object One way or another every JSON-RPC request is bound to a HTTP request not matter of the underlying transport. For this reason a number of classes in `Cro::RPC::JSON` provide `request` accessor which contains an instance of [`Cro::HTTP::Request`](https://cro.services/docs/reference/cro-http-request) which started the current JSON-RPC pipeline. Also, Cro's `request` term provides access to the object wherever applicable. Note that for WebSockets transport the request object is the one about the initial HTTP request which was then upgraded. It can be used, for example, to validate the HTTP session "owning" the current WebSockets connection. # ERROR HANDLING `Cro::RPC::JSON` tries to do as much as possible to handle any server-side errors and report them back to the client in a most reasonable way. I.e. if server code dies while processing a method call the client will receive a JSON-RPC object with `error` key with correct error code, error message, and some additional data like server-side exception name and backtrace. But the thing to be remembered: all this related to the synchronous mode of operation only, which also includes actor classes method calls. The asynchronous mode is totally different here. Due to comparatively low-level approach, code in this mode has to take care of own exceptions. Otherwise if any exception gets leaked it breaks the processing pipeline and results in HTTP 500 response or in WebSocket closing with 1011. This is related to all cases, where a `Supply` is returned by a code, even to `:async` methods. # SEE ALSO [`Cro`](https://cro.services), [`Cro::RPC::JSON::Message`](JSON/Message.md), [`Cro::RPC::JSON::Request`](JSON/Request.md), [`Cro::RPC::JSON::MethodResponse`](JSON/MethodResponse.md), [`Cro::RPC::JSON::Notification`](JSON/Notification.md) # AUTHOR Vadim Belman [[email protected]](mailto:[email protected]) # LICENSE Artistic License 2.0 See the LICENSE file in this distribution.
## dist_zef-jonathanstowe-FastCGI-NativeCall-PSGI.md # FastCGI::NativeCall::PSGI This is a PSGI interface for [FastCGI::NativeCall](https://github.com/jonathanstowe/raku-fastcgi-nativecall) ![Build Status](https://github.com/jonathanstowe/raku-fcgi-psgi/workflows/CI/badge.svg) ## Synopsis Basic usage: ``` use FastCGI::NativeCall::PSGI; my $psgi = FastCGI::NativeCall::PSGI.new(path => "/tmp/fastcgi.sock", backlog => 32); sub dispatch-psgi($env) { return [ 200, { Content-Type => 'text/html' }, "Hello world" ]; } $psgi.run(&dispatch-psgi); ``` Using [Bailador](https://github.com/Bailador/Bailador): ``` use FastCGI::NativeCall::PSGI; use Bailador; get "/" => sub { "Hello world"; } my $psgi = FastCGI::NativeCall::PSGI.new(path => "/tmp/fastcgi.sock", backlog => 32); $psgi.run(get-psgi-app()); ``` Using [Crust](https://github.com/tokuhirom/p6-Crust): ``` use FastCGI::NativeCall::PSGI; use Crust::Builder; my &app = builder { mount "/" , sub (%env) { start { 200, [Content-Type => "text/html"], ["Hello world"] }; } }; my $psgi = FastCGI::NativeCall::PSGI.new(path => "/tmp/fastcgi.sock", backlog => 32); $psgi.run(&app); ``` A suitable nginx configuration for these can be found in the <examples> directory. If you are using Apache httpd with [mod\_fcgid](https://httpd.apache.org/mod_fcgid/mod/mod_fcgid.html) then your script will be executed by the server with its STDIN (file descriptor 0) reopened to a listening socket that has already been created for you, in this case your constructor will become: ``` my $psgi = FastCGI::NativeCall::PSGI.new(sock => 0); ``` There is a snippet of Apache configuration in the [examples](examples/apache.conf) directory. You will almost certainly want to tweak that to your own requirements. ## Description [FastCGI](https://fastcgi-archives.github.io/) is a protocol that allows an HTTP server to communicate with a persistent application over a socket, thus removing the process startup overhead of, say, traditional CGI applications. It is supported as standard (or through supporting modules,) by most common HTTP server software (such as Apache, nginx, lighthttpd and so forth.) This module builds on [FastCGI::NativeCall](https://github.com/jonathanstowe/raku-fastcgi-nativecall) to provide a PSGI/P6GI/P6W interface for web applications. Despite being single threaded it can be relatively high performance with appropriate tuning of the server configuration. ## Installation You will need an HTTP server that supports FastCGI to be able to use this. Assuming you have a working Rakudo installation then you should be able to insall it with *zef* ``` zef install FastCGI::NativeCall::PSGI # Or from a local clone zef install . ``` ## Support I am probably not the right person to be asking about the configuration of various server software to use FastCGI, you probably want to consult the manuals in the first place. Some parts of the support for the full P6GI/P6W spec may be incomplete but this should be filled out over time. In testing with [Siege](https://www.joedog.org/siege-home/) some frameworks performed remarkably worse than others, if you have a concern about the performance of your application please try to test with another host server as it may be the framework rather than this module. Please send suggests/patches etc to [github](https://github.com/jonathanstowe/raku-fcgi-psgi/issues) ## Copyright and Licence This is free software. Please see the <LICENCE> file for details. ``` Copyright (c) 2015, carlin <[email protected]> © 2017 - 2021 Jonathan Stowe ```
## dist_zef-lizmat-P5opendir.md [![Actions Status](https://github.com/lizmat/P5opendir/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/P5opendir/actions) [![Actions Status](https://github.com/lizmat/P5opendir/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/P5opendir/actions) [![Actions Status](https://github.com/lizmat/P5opendir/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/P5opendir/actions) # NAME Raku port of Perl's opendir() and related built-ins # SYNOPSIS ``` # exports opendir, readdir, telldir, seekdir, rewinddir, closedir use P5opendir; opendir(my $dh, $some_dir) || die "can't opendir $some_dir: $!"; my @dots = grep { .starts-with('.') && "$some_dir/$_".IO.f }, readdir($dh); closedir $dh; ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `opendir`, `readdir`, `telldir`, `seekdir`, `rewinddir` and `closedir` built-ins as closely as possible in the Raku Programming Language. # ORIGINAL PERL 5 DOCUMENTATION ``` opendir DIRHANDLE,EXPR Opens a directory named EXPR for processing by "readdir", "telldir", "seekdir", "rewinddir", and "closedir". Returns true if successful. DIRHANDLE may be an expression whose value can be used as an indirect dirhandle, usually the real dirhandle name. If DIRHANDLE is an undefined scalar variable (or array or hash element), the variable is assigned a reference to a new anonymous dirhandle; that is, it's autovivified. DIRHANDLEs have their own namespace separate from FILEHANDLEs. readdir DIRHANDLE Returns the next directory entry for a directory opened by "opendir". If used in list context, returns all the rest of the entries in the directory. If there are no more entries, returns the undefined value in scalar context and the empty list in list context. If you're planning to filetest the return values out of a "readdir", you'd better prepend the directory in question. Otherwise, because we didn't "chdir" there, it would have been testing the wrong file. opendir(my $dh, $some_dir) || die "can't opendir $some_dir: $!"; @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh); closedir $dh; As of Perl 5.12 you can use a bare "readdir" in a "while" loop, which will set $_ on every iteration. opendir(my $dh, $some_dir) || die; while(readdir $dh) { print "$some_dir/$_\n"; } closedir $dh; To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious failures, put this sort of thing at the top of your file to signal that your code will work monly on Perls of a recent vintage: use 5.012; # so readdir assigns to $_ in a lone while test telldir DIRHANDLE Returns the current position of the "readdir" routines on DIRHANDLE. Value may be given to "seekdir" to access a particular location in a directory. "telldir" has the same caveats about possible directory compaction as the corresponding system library routine. seekdir DIRHANDLE,POS Sets the current position for the "readdir" routine on DIRHANDLE. POS must be a value returned by "telldir". "seekdir" also has the same caveats about possible directory compaction as the corresponding system library routine. closedir DIRHANDLE Closes a directory opened by "opendir" and returns the success of that system call. ``` # PORTING CAVEATS The `readdir` function has three modes: ## list mode By default, `readdir` returns a list with all directory entries found. ``` my @entries = readdir($dh); ``` ## scalar context In scalar context, `readdir` returns one directory entry at a time. Add `Scalar` as the first positional variable to mimic this behaviour: ``` while readdir(Scalar, $dh, :scalar) -> $entry { say "found $entry"; } ``` ## void context In void context, `readdir` stores one directory entry at a time in `$_`. Add `Mu` as the first positional variable to mimic this behaviour: ``` .say while readdir(Mu, $dh, :void); ``` ## $\_ no longer accessible from caller's scope In future language versions of Raku, it will become impossible to access the `$_` variable of the caller's scope, because it will not have been marked as a dynamic variable. So please consider changing: ``` readdir; ``` to either: ``` readdir($_); ``` or, using the subroutine as a method syntax, with the prefix `.` shortcut to use that scope's `$_` as the invocant: ``` .&readdir; ``` # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! Source can be located at: <https://github.com/lizmat/P5opendir> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2020, 2021, 2023, 2024 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-lizmat-Identity-Utils.md [![Actions Status](https://github.com/lizmat/Identity-Utils/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Identity-Utils/actions) [![Actions Status](https://github.com/lizmat/Identity-Utils/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Identity-Utils/actions) [![Actions Status](https://github.com/lizmat/Identity-Utils/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/Identity-Utils/actions) # NAME Identity::Utils - Provide utility functions related to distribution identities # SYNOPSIS ``` use Identity::Utils; my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>:from<Perl5>"; say short-name($identity); # Foo::Bar say ver($identity); # 0.0.42 say without-ver($identity); # Foo::Bar:auth<zef:lizmat>:api<2.0>:from<Perl5> say version($identity); # v0.0.42 say auth($identity); # zef:lizmat say without-auth($identity); # Foo::Bar:ver<0.0.42>:api<2.0>:from<Perl5> say ecosystem($identity); # zef say nick($identity); # lizmat say api($identity); # 2.0 say without-api($identity); # Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:from<Perl5> say from($identity); # Perl5 say without-from($identity); # Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0> say sanitize($identity); # Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>:from<Perl5> say build("Foo::Bar", :ver<0.0.42>); # Foo::Bar:ver<0.0.42> say is-short-name($identity); # False say is-short-name("Foo::Bar"); # True say is-pinned($identity); # True say is-pinned("Foo::Bar"); # False my $spec = dependency-specification($identity); my $compunit = compunit($identity); my $meta = meta($identity, $repo); my $source-io = source-io($identity, $repo); my $source = source($identity, $repo); my $bytecode-io = bytecode-io($identity, $repo); my $bytecode = bytecode($identity, $repo); .say for latest-successors(@identities); use Identity::Utils <short-name auth>; # only import "short-name" and "auth" ``` # DESCRIPTION Identity::Utils provides some utility functions for inspecting various aspects of distribution identity strings. They assume any given string is a well-formed identity in the form `name:ver<0.0.1>:auth<eco:nick>` with an optional `api:<1>` field. A general note with regards to `api`: if it consists of `"0"`, then it is assumed there is **no** api field specified. # SELECTIVE IMPORTING ``` use Identity::Utils <short-name auth>; # only import "short-name" and "auth" ``` By default all utility functions are exported. But you can limit this to the functions you actually need by specifying the names in the `use` statement. To prevent name collisions and/or import any subroutine with a more memorable name, one can use the "original-name:known-as" syntax. A semi-colon in a specified string indicates the name by which the subroutine is known in this distribution, followed by the name with which it will be known in the lexical context in which the `use` command is executed. ``` use Identity::Utils <short-name:name>; # import "short-name" as "name" say name("Identity::Utils:auth<zef:lizmat>"); # Identity::Utils ``` # SUBROUTINES ## api ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>"; say api($identity); # 2.0 ``` Returns the `api` field of the given identity, or `Nil` if no `api` field could be found. ## auth ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>"; say auth($identity); # zef:lizmat ``` Returns the `auth` field of the given identity, or `Nil` if no `auth` field could be found. ## build ``` my $ver = "0.0.42"; my $auth = "zef:lizmat"; my $api = "2.0"; my $from = "Perl5"; say build("Foo::Bar", :$ver, :$auth, :$api, :$from); # Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>:from<Perl5> say build("Foo::Bar", :$ver, :nick<lizmat>); # Foo::Bar:ver<0.0.42>:auth<zef:lizmat> ``` Builds an identity string from the given short name and optional named arguments: * ver - the "ver" value to be used * auth - the "auth" value to be used, overrides "ecosystem" and "nick" * api - the "api" value to be used * from - the "from" value to be used, 'Perl6' and 'Raku' will be ignored * ecosystem - the ecosystem part of "auth", defaults to "zef" * nick - the nick part of "auth", unless overridden by "auth" ## bytecode ``` my $buf = bytecode($identity); # default: $*REPO my $buf = bytecode($identity, "."); # as if with -I. ``` Returns a `Buf` object with the precompiled bytecode of the given identity and the currently active repository ([`$*REPO`](https://docs.raku.org/language/compilation#$*REPO)). It is also possible to override the repository (chain) by specifying a second argument, this can be an object of type: * `Str` - indicate a path for a ::FileSystem repo, just as with -I. * `IO::Path` - indicate a path for a ::FileSystem repo * `CompUnit::Repository` - the actual repo to use Attempts to create the bytecode file if there isn't one yet. Returns `Nil` if the given identity could not be found, or there is no bytecode file for the short-name of the given identity (probably because it failed to compile). ## bytecode-io ``` my $io = bytecode-io($identity); # default: $*REPO my $io = bytecode-io($identity, "."); # as if with -I. ``` Returns an `IO::Path` object of the precompiled bytecode of the given identity and the currently active repository ([`$*REPO`](https://docs.raku.org/language/compilation#$*REPO)). It is also possible to override the repository (chain) by specifying a second argument, this can be an object of type: * `Str` - indicate a path for a ::FileSystem repo, just as with -I. * `IO::Path` - indicate a path for a ::FileSystem repo * `CompUnit::Repository` - the actual repo to use Attempts to create the bytecode file if there isn't one yet. Returns `Nil` if the given identity could not be found, or there is no bytecode file for the short-name of the given identity (probably because it failed to compile). ## compunit ``` my $compunit = compunit($identity); # default: $*REPO my $compunit = compunit($identity, "."); # as if with -I. my $compunit = compunit($identity, :need); # make bytecode ``` Returns a [`Compunit`](https://docs.raku.org/type/CompUnit) object for the given identity and the currently active repository ([`$*REPO`](https://docs.raku.org/language/compilation#$*REPO)). It is also possible to override the repository (chain) by specifying a second argument, this can be an object of type: * `Str` - indicate a path for a ::FileSystem repo, just as with -I. * `IO::Path` - indicate a path for a ::FileSystem repo * `CompUnit::Repository` - the actual repo to use A boolean named argument `need` can be specified to indicate that a bytecode file should be created if there is none for this compunit yet. Returns `Nil` if the given identity could not be found. ## dependency-specification ``` my $spec = dependency-specification($identity); ``` Creates a `CompUnit::DependencySpecification` object for the given identity. ## ecosystem ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>"; say ecosystem($identity); # zef ``` Returns the ecosystem part of the `auth` field of the given identity, or `Nil` if no `auth` field could be found. ## from ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>:from<Perl5>"; say from($identity); # Perl5 ``` Returns the `from` field of the given identity as a `Str`, or `Nil` if no `from` field could be found. ## is-pinned ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>"; say is-pinned($identity); # True say is-pinned("Foo::Bar"); # False ``` Returns a boolean indicating whether the given identity is considered to be pinned to a specific release. This implies: having an `auth` and having a version **without** a `+` or a `*` in it. ## is-short-name ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>"; say is-short-name($identity); # False say is-short-name("Foo::Bar"); # True ``` Returns a boolean indicating whether the given identity consists of just a `short-name`. ## latest-successors ``` .say for latest-successors(@identies); ``` Returns a sorted `Seq` of identities that have been filtered by the same semantics that are used when installing a module without specifying anything other than a short name of an identity. For instance, taking: ``` AccountableBagHash:ver<0.0.3>:auth<cpan:ELIZABETH> AccountableBagHash:ver<0.0.6>:auth<zef:lizmat> ``` would only return `AccountableBagHash:ver<0.0.6>:auth<zef:lizmat>` because it has a higher version number, and the ecosystems are different. ## meta ``` my $meta = meta($identity); # default: $*REPO my $meta = meta($identity, "."); # as if with -I. ``` Returns a hash with the meta information of the given identity and the currently active repository ([`$*REPO`](https://docs.raku.org/language/compilation#$*REPO)) as typically found in the `META6.json` file of a distribution. It is also possible to override the repository (chain) by specifying a second argument, this can be an object of type: * `Str` - indicate a path for a ::FileSystem repo, just as with -I. * `IO::Path` - indicate a path for a ::FileSystem repo * `CompUnit::Repository` - the actual repo to use Returns `Nil` if the given identity could not be found. ## nick ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>"; say nick($identity); # lizmat ``` Returns the nickname part of the `auth` field of the given identity, or `Nil` if no `auth` field could be found. ## sanitize ``` my $identity = "Foo::Bar:auth<zef:lizmat>:ver<0.0.42>:api<2.0>"; say sanitize($identity); # Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0> ``` Returns a version of the given identity in which any `ver`, `auth` and `api` fields are put in the correct order. ## short-name ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>"; say short-name($identity); # Foo::Bar ``` Returns the short name part of the given identity, or the identity itself if no `ver`, `auth` or `api` fields could be found. ## source ``` say source($identity); # default: $*REPO say source($identity, "."); # as if with -I. ``` Returns the source-code of the given identity and the currently active repository ([`$*REPO`](https://docs.raku.org/language/compilation#$*REPO)) as typically found in the `lib` directory of a distribution. It is also possible to override the repository (chain) by specifying a second argument, this can be an object of type: * `Str` - indicate a path for a ::FileSystem repo, just as with -I. * `IO::Path` - indicate a path for a ::FileSystem repo * `CompUnit::Repository` - the actual repo to use Returns `Nil` if the given identity could not be found, or there is no source-file for the short-name of the given identity. ## source-io ``` my $io = source-io($identity); # default: $*REPO my $io = source-io($identity, "."); # as if with -I. ``` Returns an `IO::Path` object of the source of the given identity and the currently active repository ([`$*REPO`](https://docs.raku.org/language/compilation#$*REPO)) as typically found in the `lib` directory of a distribution. It is also possible to override the repository (chain) by specifying a second argument, this can be an object of type: * `Str` - indicate a path for a ::FileSystem repo, just as with -I. * `IO::Path` - indicate a path for a ::FileSystem repo * `CompUnit::Repository` - the actual repo to use Returns `Nil` if the given identity could not be found, or there is no source-file for the short-name of the given identity. ## ver ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>"; say ver($identity); # 0.0.42 ``` Returns the `ver` field of the given identity as a `Str`, or `Nil` if no `ver` field could be found. ## version ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>"; say version($identity); # v0.0.42 ``` Returns the `ver` field of the given identity as a `Version` object, or `Nil` if no `ver` field could be found. ## without-api ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>"; say without-api($identity); # Foo::Bar:ver<0.0.42>:auth<zef:lizmat> ``` Returns the identity **without** any `api` field of the given identity. ## without-auth ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>"; say without-auth($identity); # Foo::Bar:ver<0.0.42>:api<2.0> ``` Returns the identity **without** any `auth` field of the given identity. ## without-from ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:from<Perl5>"; say without-from($identity); # Foo::Bar:ver<0.0.42>:auth<zef:lizmat> ``` Returns the identity **without** any `from` field of the given identity. ## without-ver ``` my $identity = "Foo::Bar:ver<0.0.42>:auth<zef:lizmat>:api<2.0>"; say without-ver($identity); # Foo::Bar:auth<zef:lizmat>:api<2.0> ``` Returns the identity **without** any `ver` field of the given identity. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Identity-Utils> . 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, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-lizmat-Prompt-Expand.md [![Actions Status](https://github.com/lizmat/Promp-Expand/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Promp-Expand/actions) [![Actions Status](https://github.com/lizmat/Promp-Expand/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Promp-Expand/actions) [![Actions Status](https://github.com/lizmat/Promp-Expand/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/Promp-Expand/actions) # NAME Prompt::Expand - provide prompt expansion logic # SYNOPSIS ``` use Prompt::Expand; say expand(":time: >"); # 19:24:11 > say expand(":yellow,date,reset: >", "NL"); # zon 19 jan 2025 > ``` # DESCRIPTION The `Prompt::Expand` distribution provides the logic to expand a string (usually intended to be used as a prompt for user input) according to number of escape sequences (`\x`) or placeholder specifications `:text:`. As such it exports an `expand` subroutine that takes such a format, and returns the expanded string. Placeholders are specified by an initial semi-colon (`:`), followed by one or more identifiers separated by commas, and ended with a final semi-colon. Expansion currently provided are: * ANSI color / formatting codes * strftime escape codes * emoji escape codes * other generally useful escapes Expansions involving date / time values, can be localized by specifying the language to be used, either as a string (e.g. `"NL"`) or as a custom Locale::Dates object. # EXPANSIONS ## ANSI color codes Note that **not** all of these are supported everywhere! | :text: | function | | --- | --- | | normal | reset to default | | bold | switch on bold characters | | dim | switch on dimmer characters | | italic | switch on italic characters | | underline | switch on underlined characters | | blink | switch on blinking characters | | inverse | switch on inverted characters | | hidden | switch on showing spaces instead of characters | | strikethrough | switch on strikethrough characters | | unbold | switch off bold characters | | unitalic | switch off italic characters | | ununderline | switch off underlined characters | | uninverse | switch off inverse characters | | black | switch to black foreground | | red | switch to red foreground | | green | switch to green foreground | | yellow | switch to yellow foreground | | blue | switch to blue foreground | | magenta | switch to magenta foreground | | cyan | switch to cyan foreground | | white | switch to white foreground | | default | switch to default foreground | | BLACK | switch to black background | | RED | switch to red background | | GREEN | switch to green background | | YELLOW | switch to yellow background | | BLUE | switch to blue background | | MAGENTA | switch to magenta background | | CYAN | switch to cyan background | | WHITE | switch to white background | | DEFAULT | switch to default background | ## Raku escape sequences Besides most of the [standard Raku escape sequences](https://docs.raku.org/language/quoting#Interpolating_escape_codes) with an associated `:text:` equivalent, also some other more interactive prompt related `:text` sequences: | :text: | escape | function | | --- | --- | --- | | bell | \a | audible / visible alert | | bksp | \b | backspace | | escape | \e | initiate ANSI escape sequence | | formfeed | \f | form feed (FF) | | reset | \c | reset to all ANSI defaults | | lf | \n | line feed (LF, newline, $?NL) | | cr | \r | Carriage Return (CR) | | tab | \t | tab | | bslash | \\ | backslash | | index | | $\*INDEX value | | symbol | | $\*SYMBOL value | | language | | language version | | release | | compiler release | | compiler | | compiler version | From [`DateTime::strftime`](https://raku.land/zef:lizmat/DateTime::strftime): | Code | :text: | Value | | --- | --- | --- | | %a | wkdname | abbreviated weekday name | | %A | weekdayname | full weekday name | | %b | mnthname | abbreviated month name | | %B | monthname | full month name | | %c | datetime | preferred date/time representation | | %C | century | century number (year div 100) | | %d | 0day | day of month ("01" .. "31") | | %D | usadate | short for: %m/%d/%y | | %e | day | day of month (" 1" .. "31") | | %f | minute | same as %M | | %F | isodate | short for: %Y/%m/%d | | %g | weekYY | YY of this week ("00" .. "99") | | %G | weekYYYY | full year of this week | | %h | mnthname | same as %b | | %H | 0hour | 24-hour hour ("00" .. "23") | | %I | 0amhour | 12-hour hour ("01" .. "12") | | %j | yearday | day of the year ("001" .. "366") | | %k | hour | 24-hour hour (" 1" .. "23") | | %l | amhour | 12-hour hour (" 1" .. "12") | | %L | year | same as %Y | | %m | month | month ("01" .. "12") | | %M | minute | minute ("00" .. "59") | | %n | newline | "\n" | | %p | AMPM | "AM" | "PM" | | %P | ampm | "am" | "pm" | | %r | amtime | short for: %I:%M:%S %p | | %R | HHMM | short for: %H:%M | | %s | epoch | seconds since epoch (midnight 1970-01-01 UTC) | | %S | second | second ("00" .. "59") | | %t | tab | "\t" | | %T | HHMMSS | short for: %H:%M:%S | | %u | weekday | weekday (1 .. 7) | | %U | weekSun | week number (first Sunday) ("00" .. "53") | | %v | DD-MON-YYYY | short for: %e-%b-%Y | | %V | weekISO | week number (ISO 8601) ("00" .. "53") | | %w | 0weekday | weekday (0 .. 6) | | %W | weekMon | week number (first Monday) ("00" .. "53") | | %x | date | preferred date representation | | %X | time | preferred time representation | | %y | YY | year without century ("00" .. "99") | | %Y | year | year (yyyy) | | %z | tzoffset | numeric timezone (±HHMM) | | %Z | timezone | timezone (no name: %z) | | %+ | unixdate | short for: %a %b %e %T %Z %G | | %% | percent | "%" | From [`Text::Emoji`](https://raku.land/zef:lizmat/Text::Emoji), all of the *1870* conversions are supported. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Prompt-Expand> . Comments and Pull Requests are welcome. If you like this module, or what I'm doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-HANENKAMP-AWS-Session.md # NAME AWS::Session - Common data useful for accessing and configuring AWS APIs # SYNOPSIS ``` use AWS::Session; my $session = AWS::Session.new( profile => 'my-profile', ); my $profile = $session.profile; my $region = $session.region; my $data-path = $session.data-path; my $config-file = $session.config-file; my $ca-bundle = $session.ca-bundle; my %api-versions = $session.api-versions; my $cred-file = $session.credentials-file; my $timeout = $session.metadata-service-timeout; my $attempts = $session.metadata-service-num-attempts; # Read the AWS configuration file my %config = $session.get-configuration; my %profile-conf = $session.get-profile-configuration('default'); my %current-conf = $session.get-current-configuration; # Read the AWS credentials file my %cred = $session.get-credentials; my %profile-cred = $session.get-profile-credentials('default'); my %current-cred = $session.get-current-credentials; ``` # DESCRIPTION AWS clients share some common configuration data. This is a configurable module for loading that data. # ATTRIBUTES Any attributes provided will override any configuration values found on the system through the environment, configuration, or defaults. ## profile The configuration files are in INI format. These are broken up into sections. Each section is a profile. This way you can have multiple AWS configurations, each with its own settings and credentials. ## region This is the AWS region code to use. ## data-path The botocore system uses data models to figure out how to interact with AWS APIs. This is the path where additional models can be loaded. ## config-file This is the location of the AWS configuration file. ## ca-bundle This is the location of the CA bundle to use. ## api-versions This is a hash of API versions to prefer for each named API. ## credentials-file This is the location of the credentials file. ## metadata-service-timeout This is the timeout to use with the metadata service. ## metadata-service-num-attempts This is the number of attempts to make when using the metadata service. ## session-configuration This is a map of configuration variable names to AWS::Session::Default objects, which define how to configure them. # HELPERS ## AWS::Session::Default This is a basic structural class. All attributes are optional. ### ATTRIBUTES #### config-file This is the name of the variable to use when loading the value from the configuration file. #### env-var This is an array of names of the environment variable to use for the value. #### default-value This is the default value to fallback to. #### converter This is a function that will convert values from the configuration file or environment variable to the appropriate object. # METHODS ## get-configuration ``` method get-configuration($config-file?, :$reload?) returns Hash ``` Returns the full contents of the configuration as a hash of hashes. Normally, this method caches the configuration. Setting the `:reload` flag will force the configuration cache to be ignored. ## get-profile-configuration ``` method get-profile-configuration(Str:D $profile, :$config-file?) returns Hash ``` Returns the named profile configuration. ## get-current-configuration ``` method get-current-configuration() returns Hash ``` Returns the configuration for the current profile. ## get-credentials ``` method get-credentials($credentials-file?) returns Hash ``` Returns the full contents of the credentials file as a hash of hashes. Unlike configuration, the contents of this file is not cached. ## get-profile-credentials ``` method get-profile-credentials(Str:D $profile, :$credentials-file?) returns Hash ``` Returns the named profile credentials. ## get-current-credentials ``` method get-current-credentials() returns Hash ``` Returns the credentials for the current profile. ## get-config-variable ``` method get-config-variable( Str $logical-name, Bool :$from-instance = True, Bool :$from-env = True, Bool :$from-config = True, ) ``` Loads the configuration named variable from the current configuration. This is loaded from the configuration file, environment, or whatever according to the default set in `session-configuration`. Returns `Nil` if no such configuration is defined for the given `$logical-name`. The boolean flags are used to select which methods will be consulted for determining the variable value. * from-instance When True, the local instance variable will be checked. * from-env When True, the process environment variables will be searched for the value. * from-config When True, the shared configuration file will be consulted for the value. The value will be pulled in the order listed above, with the first value found being the one chosen.