txt
stringlengths
93
37.3k
## dist_zef-dwarring-LWP-Simple.md # LWP::Simple for Raku ![Test Windows and MacOS](https://github.com/raku-community-modules/LWP-Simple/workflows/Test%20Windows%20and%20MacOS/badge.svg) This is a quick & dirty implementation of a LWP::Simple clone for Raku; it does both `GET` and `POST` requests. # Dependencies LWP::Simple depends on the modules MIME::Base64 and URI, which you can find at <http://modules.raku.org/>. The tests depends on [JSON::Tiny](https://github.com/moritz/json). Write: ``` zef install --deps-only . ``` You'll have to install [IO::Socket::SSL](https://github.com/sergot/io-socket-ssl) via ``` zef install IO::Socket::SSL ``` if you want to work with `https` too. # Synopsis ``` use LWP::Simple; my $content = LWP::Simple.get("https://raku.org"); my $response = LWP::Simple.post("https://somewhere.topo.st", { so => True } ``` # Methods ## get ( $url, [ %headers = {}, Bool :$exception ] ) Sends a GET request to the value of `$url`. Returns the content of the return request. Errors are ignored and will result in a `Nil` value unless `$exception` is set to `True`, in which case an `LWP::Simple::Response` object containing the status code and brief description of the error will be returned. Requests are make with a default user agent of `LWP::Simple/$VERSION Raku/$*PERL.compiler.name()` which may get blocked by some web servers. Try overriding the default user agent header by passing a user agent string to the `%headers` argument with something like `{ 'User-Agent' => 'Your User-Agent String' }` if you have trouble getting content back. # Current status You can use [HTTP::UserAgent](https://github.com/sergot/http-useragent) instead, with more options. However, this module will do just fine in most cases. The documentation of this module is incomplete. Contributions are appreciated. # Use Use the installed commands: ``` lwp-download.p6 http://eu.httpbin.org ``` Or ``` lwp-download.p6 https://docs.perl6.org ``` If `ÌO::Socket::SSL` has been installed. ``` lwp-get.p6 https://raku.org ``` will instead print to standard output. # Known bugs According to [issues raised](https://github.com/raku-community-modules/LWP-Simple/issues/40), [in this repo](https://github.com/raku-community-modules/LWP-Simple/issues/28), there could be some issues with older versions of MacOSx. This issue does not affect the functionality of the module, but just the test script itself, so you can safely install with `--force`. Right now, it's working correctly (as far as tests go) with Windows, MacOSx and Linux. # License This distribution is licensed under the terms of the [Artistic 2.0 license](https://www.perlfoundation.org/artistic-license-20.html). You can find a [copy](LICENSE) in the repository itself.
## dist_zef-thundergnat-Text-Sorensen.md [![Actions Status](https://github.com/thundergnat/Text-Sorensen/actions/workflows/test.yml/badge.svg)](https://github.com/thundergnat/Text-Sorensen/actions) # NAME Text::Sorensen Calculate the Sorensen-Dice or Jaccard similarity coefficient. # SYNOPSIS ``` use Text::Sorensen :sorensen; # test a word against a small list say sorensen('compition', 'completion', 'competition'); # ([0.777778 competition] [0.705882 completion]) # or against a large one my %hash = './unixdict.txt'.IO.slurp.words.race.map: { $_ => .&bi-gram }; .say for sorensen('compition', %hash).head(5); # [0.777778 competition] # [0.777778 compilation] # [0.777778 composition] # [0.705882 completion] # [0.7 decomposition] use Text::Sorensen :jaccard; .say for jaccard('compition', %hash).head(5); # [0.636364 competition] # [0.636364 compilation] # [0.636364 composition] # [0.545455 completion] # [0.538462 decomposition] ``` # DESCRIPTION Both Sorensen-Dice and Jaccard calculate a "similarity" between two tokenized groups of items. They can be used to compare many different types of tokenized objects; this module is optimized to do a text similarity calculation. Both methods use a similar algorithm and, though they assign different weights, return nearly identical relative coefficients, and may be readily converted from one to the other. You can easily convert back and forth: ``` # JI (Jaccard index) # SDI (Sorensen-Dice index) JI = SDI / (2 - SDI) SDI = 2 * JI / (1 + JI) ``` For both operations, each word / phrase is broken up into tokens for the comparison. The most typical tokenizing scheme for text is to break the words up into bi-grams: groups of two consecutive letters. For instance, the word 'differ' would be tokenized to the group: ``` 'di', 'if', 'ff', 'fe', 'er' ``` This tokenized word is then compared to another tokenized word to calculate the similarity. The bi-gram routine case-folds the words before tokenizing so the comparison routines ignore case differences. A great deal of the work is spent in tokenizing the words. If you plan to do multiple comparisons to a large group of words, it may be worthwhile to pre-tokenize the word list to reduce the working time. When using the module, you must specify which similarity routine(s) you want to import. There are the two basic similarity algorithms and several built-in, exported-on-demand aliases available. Optionally exported similarity routines: ``` :sorensen --> sub sorensen() # traditional spelling :sorenson --> sub sorenson() # alternate spelling :sdi --> sub sdi() # Sorensen-Dice index :dice --> sub dice() # let Dice have top billing for once :dsc --> sub dsc() # Dice similarity coefficient # All point to exactly the same routines behind the scenes. :jaccard --> sub jaccard() # Jaccard index ``` You'll need to import at least one similarity routine, or some combination, or :ALL. Always exported helper routine: ``` C<sub bi-gram()> # tokenize a word into a Bag of bi-grams ``` ### Sorensen-Dice ``` use Text::Sorensen :sorensen; # or some other alias ``` Sorensen-Dice, named after botanists Thorvald Sørensen and Lee Raymond Dice, measures the similarity of two groups by dividing twice the intersection token count by the total token count of both groups. ``` 2 * +(@a ∩ @b) / (@a ⊎ @b) ``` The index is known by several names, Sorensen-Dice index is probably most common, though Sorensen index and Dice's coefficient are also popular. Other variations include the "similarity coefficient" or "index", such as Dice similarity coefficient (DSC). The module provides multi subs for different use cases. For a one-off or low memory case, use: ``` sorensen($word, @list, :$ge) ``` Where $word is the word to be compared against, @list is a list or array of words to compare with $word, and :$ge is the minimum for the returned coefficients (default .5). (It's the coefficients **greater than or equal to** .5). The list of words will be tokenized, the coefficient calculated, entries with coefficients lower than the :$ge threshold filtered out and the remaining list sorted and returned. If you want all values to be returned, even ones that don't match at all, you'll need to specify :ge(0). It's a little unintuitive at first but can seriously reduce memory and time consumption for the common use case. Each word comparison will return a 2 element array consisting of: * the SDC from the :ge threshold (default .5) to 1 (identical). * the word that was checked. That works well but retokenizes the list every time it is invoked. If you want to reuse a list several times to check against mutiple words, it may be better to pre-tokenize the list and pass that to the coefficient function. Use the module supplied, always exported, sub bi-gram() on each element to pre-tokenize the list. ``` # returns the tokenized word as a Bag my $tokens = bi-gram($word); ``` Save the list as a hash of word / tokens pairs, then pass that into the coefficient function to avoid re-tokenizing every time. This is a nice parallelizable operation so .race can really speed it up. ``` my %hash = './unixdict.txt'.IO.slurp.words.race.map: { $_ => .&bi-gram }; sorensen($word, %hash) ``` The returned list has results less than the :ge threshold filtered out and is sorted by inverse coefficient (largest first) with a secondary alphabetical sort. See the following. We compare the typo 'compition' against an entire dictionary, filter out everything lower than .6 coefficient and return the sorted list. ``` .say for sorensen('compition', %hash, :ge(.6)); # [0.777778 competition] # [0.777778 compilation] # [0.777778 composition] # [0.705882 completion] # [0.7 decomposition] # [0.666667 compunction] # [0.666667 computation] ``` ### Jaccard ``` use Text::Sorensen :jaccard; ``` The Jaccard index (named for botanist Paul Jaccard) is calculated very similarly to the Sorensen-Dice index. Instead of the intersection token count divided by the total token count, it is the intersection token count divided by the difference between the total token count and the intersection token count. (Intersection over difference rather than intersection over sum). ``` +(@a ∩ @b) / ( (@a ⊎ @b) - (@a ∩ @b) ) ``` Jaccard coefficients tend to be even smaller than Sorensen-Dice but are similarly, a ratio between 0 and 1. Again, multis are provided for a one-off list: ``` my @results = jaccard($word, @list, :$ge); ``` or a multi use hash. ``` my @results = jaccard($word, @hash, :$ge); ``` The exact same tokenizer is used for each, and the same efficiencies come into play by pre-tokenizing dictionaries for repeated use. ``` .say for jaccard('maintainence', %hash, :ge(.45)); # [0.636364 maintain] # [0.615385 maintenance] ``` # 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_zef-slid1amo2n3e4-mv2d.md Fork of <https://github.com/raku-community-modules/App-MoarVM-Debug> ## Usage Start the debugger: ``` $ mv2d main.raku ``` Set a breakpoint on line 42: ``` > bp main.raku 42 ``` Then type resume to resume the thread to hit it: ``` > resume ``` Type `help` to see all of the commands. ## Known Issues The only stepping mode currently available is Step Into. Backtraces will show incorrect line numbers. Source can be located at: <https://github.com/slid1amo2n3e4/mv2d>. Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2017 - 2020 Edument AB Copyright 2024 The Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## definitehow.md class Metamodel::DefiniteHOW Metaobject for type definiteness ```raku class Metamodel::DefiniteHOW does Metamodel::Documenting { } ``` *Warning*: this class is part of the Rakudo implementation, and is not a part of the language specification. Type objects may be given a *type smiley*, which is a suffix that denotes their definiteness: ```raku say Any:D.^name; # OUTPUT: «Any:D␤» say Any:U.^name; # OUTPUT: «Any:U␤» say Any:_.^name; # OUTPUT: «Any␤» ``` Despite sharing a type with [`Any`](/type/Any), `Any:U` and `Any:D` in particular have different type-checking behaviors from it: ```raku say Any ~~ Any:D; # OUTPUT: «False␤» say Any ~~ Any:U; # OUTPUT: «True␤» say Any ~~ Any:_; # OUTPUT: «True␤» say Any.new ~~ Any:D; # OUTPUT: «True␤» say Any.new ~~ Any:U; # OUTPUT: «False␤» say Any.new ~~ Any:_; # OUTPUT: «True␤» ``` This happens because `Any:D` and `Any:U` are not created with [`Metamodel::ClassHOW`](/type/Metamodel/ClassHOW) like you might expect [`Any`](/type/Any) type objects to be, but `Metamodel::DefiniteHOW` instead. This HOW defines the behavior for definite type objects such as these. The following type declaration: ```raku my Any constant Definite = Any:D; ``` Is roughly equivalent to this code using the methods of `Metamodel::DefiniteHOW`: ```raku my Any constant Definite = Metamodel::DefiniteHOW.new_type: base_type => Any, definite => 1; ``` # [Methods](#class_Metamodel::DefiniteHOW "go to top of document")[§](#Methods "direct link") ## [method new\_type](#class_Metamodel::DefiniteHOW "go to top of document")[§](#method_new_type "direct link") ```raku method new_type(:$base_type!, :$definite!) ``` Creates a new definite type given a base type and definiteness. `$definite` should either be `1` for `:D` types or `0` for `:U` types. ## [method name](#class_Metamodel::DefiniteHOW "go to top of document")[§](#method_name "direct link") ```raku method name($definite_type) ``` Returns the name of a definite type. ## [method shortname](#class_Metamodel::DefiniteHOW "go to top of document")[§](#method_shortname "direct link") ```raku method shortname($definite_type) ``` Returns the shortname of a definite type. ## [method base\_type](#class_Metamodel::DefiniteHOW "go to top of document")[§](#method_base_type "direct link") ```raku method base_type($definite_type) ``` Returns the base type for a definite type: ```raku say Any:D.^base_type.^name; # OUTPUT: «Any␤» ``` ## [method definite](#class_Metamodel::DefiniteHOW "go to top of document")[§](#method_definite "direct link") ```raku method definite($definite_type) ``` Returns `1` if the definite type given is a `:D` type or `0` if it is a `:U` type. ## [method nominalize](#class_Metamodel::DefiniteHOW "go to top of document")[§](#method_nominalize "direct link") ```raku method nominalize($obj) ``` Produces a nominal type object for a definite type. This is its base type, which may also get nominalized if it has the `nominalizable` archetype. ## [method find\_method](#class_Metamodel::DefiniteHOW "go to top of document")[§](#method_find_method "direct link") ```raku method find_method($definite_type, $name) ``` Looks up a method on the base type of a definite type. ## [method type\_check](#class_Metamodel::DefiniteHOW "go to top of document")[§](#method_type_check "direct link") ```raku method type_check($definite_type, $checkee) ``` Performs a type-check of a definite type against `$checkee`. This will check if `$checkee` is of its base type, returning `True` if they match or `False` otherwise. This metamethod can get called when a definite type is on the left-hand side of a smartmatch, for instance. ## [method accepts\_type](#class_Metamodel::DefiniteHOW "go to top of document")[§](#method_accepts_type "direct link") ```raku method accepts_type($definite_type, $checkee) ``` Performs a type-check of `$checkee` against a definite type. This will check if `$checkee` is of its base type and matches its definiteness, returning `True` if they match or `False` otherwise. This metamethod can get called when the definite type is on the right-hand side of a smartmatch, for instance.
## dist_zef-raku-community-modules-Grammar-Profiler-Simple.md [![Actions Status](https://github.com/raku-community-modules/Grammar-Profiler-Simple/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/Grammar-Profiler-Simple/actions) # NAME Grammar::Profiler::Simple - Simple rule profiling for Raku grammars # SYNOPSIS ``` use Grammar::Profiler::Simple; my grammar MyGrammar { rule MyRule { ... } } reset-timing; MyGrammar.new.parse($string); say "MyRule was called &get-timing(MyGrammar,MyRule)<calls> times"; say "The total time executing MyRule was &get-timing(MyGrammar,MyRule)<time> seconds"; ``` # DESCRIPTION This module provides a simple profiler for Raku grammars. To enable profiling simply add ``` use Grammar::Profiler::Simple; ``` to your code. Any grammar in the lexical scope of the `use` statement will automatically have profiling information collected when the grammar is used. There are 2 bits of timing information collected: the number of times each rule was called and the cumulative time that was spent executing each rule. For example: say "MyRule was called &get-timing(MyGrammar,MyRule)} times"; say "The total time executing MyRule was &get-timing(MyGrammar,MyRule)} seconds"; # EXPORTED SUBROUTINES ## reset-timing Reset all time information collected since the start of the program or since the last call to `reset-timing` for all grammars, or for the specified grammar only (and all its rules), or for the specified grammar and rule only. ``` reset-timing; # all grammars and rules reset-timing(MyGrammar); # MyGrammar only reset-timing(MyGrammar, MyRule); # MyRule in MyGrammar only ``` ## get-timing Either returns all time information collected since the start of the program or since the last call to `reset-timing` for all grammars, or for the specified grammar only (and all its rules), or for the specified grammar and rule only. What is returned is always a `Hash`. ``` my %t := get-timing; # %<grammar><rules><calls|time> my %tg := get-timing(MyGrammar); # %<rules><calls|time> my %tgr := get-timing(MyGrammar, MyRule); # %<calls|time> ``` # AUTHOR Jonathan Scott Duff # COPYRIGHT AND LICENSE Copyright 2011 - 2017 Jonathan Scott Duff Copyright 2018 - 2022 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## raceseq.md class RaceSeq Performs batches of work in parallel without respecting original order. ```raku class RaceSeq does Iterable does Sequence { } ``` A `RaceSeq` is the intermediate object used when [`race`](/routine/race) is invoked on a [`Seq`](/type/Seq). In general, it's not intended for direct consumption by the developer. # [Methods](#class_RaceSeq "go to top of document")[§](#Methods "direct link") ## [method iterator](#class_RaceSeq "go to top of document")[§](#method_iterator "direct link") ```raku method iterator(RaceSeq:D: --> Iterator:D) ``` Returns the underlying iterator. ## [method grep](#class_RaceSeq "go to top of document")[§](#method_grep "direct link") ```raku method grep(RaceSeq:D: $matcher, *%options) ``` Applies `grep` to the `RaceSeq` similarly to how it would do it on a [`Seq`](/type/Seq). ```raku my @raced = (^10000).map(*²).race; @raced.grep( * %% 3 ).say; # OUTPUT: «(0 9 36 81 144 ...)␤» ``` When you use `race` on a [`Seq`](/type/Seq), this is the method that is actually called. ## [method map](#class_RaceSeq "go to top of document")[§](#method_map "direct link") ```raku method map(RaceSeq:D: $matcher, *%options) ``` Uses maps on the `RaceSeq`, generally created by application of `.race` to a preexisting [`Seq`](/type/Seq). ## [method invert](#class_RaceSeq "go to top of document")[§](#method_invert "direct link") ```raku method invert(RaceSeq:D:) ``` Inverts the `RaceSeq` created from a [`Seq`](/type/Seq) by `.race`. ## [method race](#class_RaceSeq "go to top of document")[§](#method_race "direct link") ```raku method race(RaceSeq:D:) ``` Returns the object. ## [method hyper](#class_RaceSeq "go to top of document")[§](#method_hyper "direct link") ```raku method hyper(RaceSeq:D:) ``` Creates a [`HyperSeq`](/type/HyperSeq) object out of the current one. ## [method serial](#class_RaceSeq "go to top of document")[§](#method_serial "direct link") ```raku multi method serial(RaceSeq:D:) ``` Converts the object to a [`Seq`](/type/Seq) and returns it. ## [method is-lazy](#class_RaceSeq "go to top of document")[§](#method_is-lazy "direct link") ```raku method is-lazy(--> False ) ``` Returns `False`. ## [method sink](#class_RaceSeq "go to top of document")[§](#method_sink "direct link") ```raku method sink(--> Nil) ``` Sinks the underlying data structure, producing any side effects. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `RaceSeq` raku-type-graph RaceSeq RaceSeq Any Any RaceSeq->Any Iterable Iterable RaceSeq->Iterable Sequence Sequence RaceSeq->Sequence Mu Mu Any->Mu PositionalBindFailover PositionalBindFailover Sequence->PositionalBindFailover [Expand chart above](/assets/typegraphs/RaceSeq.svg)
## dist_zef-FCO-ValueClass.md [![Actions Status](https://github.com/FCO/ValueClass/actions/workflows/test.yml/badge.svg)](https://github.com/FCO/ValueClass/actions) # NAME ValueClass - A way to create immutable value objects # SYNOPSIS ``` use ValueClass; value-class Bla { has $.a = 42; has @.b; has %.c; method TWEAK() { %!c := ValueMap.new: (a => 1) } } say Bla.new: :b[1,2,3]; # Bla.new(a => 42, b => Tuple.new(1, 2, 3), c => ValueMap.new((:a(1)))) ``` # DESCRIPTION ValueClass creates immutable objects. If you are only worried about other people mutating your objects, you may take a look at [ValueType](https://raku.land/zef:lizmat/ValueType). But if you want to avoid letting even yourself, on your internal methods, mutate your objects, you will probably need something like this module. Classes created using the value-class keyword will create objects that will die whenever anyone try to mutate them. It will also die when the object is created with any attribute that's not a value type. The object will become immutable just after TWEAK. So TWEAK is your last chance to mutate your objects. (It does not allow default values for `@` and `%` sigled attributes. You will need to use `TWEAK` to populate them) ValueType will change the default type for a attribute using the @ to Tuple and the % to ValueMap to make it possible to use Positionals and Associative on ValueClass. # AUTHOR Fernando Corrêa de Oliveira [fco@cpan.org](mailto:fco@cpan.org) # 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-jjmerelo-Math-ConvergenceMethods.md # Math-ConvergenceMethods [Test-install distro](https://github.com/JJ/Math-ConvergenceMethods/actions/workflows/test.yaml) ## Methods 1. Bisection [+info](https://en.wikipedia.org/wiki/Bisection_method) 2. *Regula falsi* [+info](https://en.wikipedia.org/wiki/False_position_method) 3. Secant [+info](https://en.wikipedia.org/wiki/Secant_method) 4. Newton-Rahpson [+info](https://en.wikipedia.org/wiki/Newton%27s_method) 5. Fixed-point iteration [+info](https://en.wikipedia.org/wiki/Fixed-point_iteration). This method returns the fixed point if it's found in the interval, not the zero of the function. 6. Steffensen [+info](https://en.wikipedia.org/wiki/Steffensen%27s_method) ## Stop conditions This modules uses three different stopping conditions. 1. Difference between two successive approximations 2. Relative difference between two successive approximations 3. Residue ## LICENSE (c) 2019 [Antonio Gámiz](https://github.com/antoniogamiz), 2022 [JJ Merelo](https://github.com/JJ). This has been releases under the GPL-3.0 license.
## dist_zef-jonathanstowe-Device-Velleman-K8055.md # Device::Velleman::K8055 ![Build Status](https://github.com/jonathanstowe/Device-Velleman-K8055/workflows/CI/badge.svg) A Raku interface to the [Velleman USB Experiment Kit](http://www.velleman.eu/products/view/?lang=en&id=351346). ## Synopsis ``` use Device::Velleman::K8055; my $device = Device::Velleman::K8055.new(address => 0); react { whenever Supply.interval(0.5) -> $i { if $i %% 2 { $device.set-all-digital(0b10101010); } else { $device.set-all-digital(0b01010101); } } whenever signal(SIGINT) { $device.close(:reset); exit; } } ``` See also the <examples> directory in the distribution. ## Description The Velleman K8055 is an inexpensive PIC based board that allows you to control 8 digital and 2 analogue outputs and read five digital and 2 analog inputs via USB. There are LEDs on the outputs that show the state of the outputs (which is largely how I've tested this.) I guess it would be useful for experimenting or prototyping but it's rather big (about three times as large as a Raspberry Pi) so you may be rather constrained if you want to use it in a project. This module has a fairly simple interface - I guess that a higher level abstraction could be provided but I only made it as an experiment and am not quite sure what interface would be best yet. I've used the [k8055 library by Jakob Odersky](https://github.com/jodersky/k8055) to do the low-level parts rather than binding libusb directly, but all the information is there is someone else wants to do that. ## Install You will need the development package of `libusb` in order to build this, this should be available through your system's package manager as `libusb-devel` or `libusb-dev` (if you are running a Linux.) At minimum it will require the 'usb.h' and the required library to link to in places where the C compiler can find them. On a system that uses `udev` (most probably Linux,) you will need to make some configuration changes in order to be able to use it as a non-privileged user. You will need to perform these changes with root privileges. Firstly copy the [k8055.rules](config/k8055.rules) file to the udev rules directory (`/etc/udev/rules.d` on a typical installation,) ``` cp config/k8055.rules /etc/udev/rules.d ``` Then create a new group called `k8055`: ``` groupadd -r k8055 ``` Finally add yourself (or other users that require access to the device,) to the new group: ``` usermod -a -G k8055 $(USER) ``` Where $(USER) is the user name of the user that want access. The access changes won't be available until the device is next plugged in and the user logs in again. If the above steps haven't been done before trying to install the module, it will attempt to skip most of the tests and may even succeed in installing but may not work well. If you have a working Rakudo installation you should be able to install with `zef` : ``` zef install Device::Velleman::K8055 ``` Other installers may be available in the future. ## Support This is largely experimental and might prove fiddly to install so I won't be entirely surprised if you have problems with it, if however you have any suggestions, feedback or improvements than please post them on [Github](https://github.com/jonathanstowe/Device-Velleman-K8055-Native/issues) or even better send a pull request. ## Copyright & Licence This is free software, see the <LICENCE> file in the distrubution. © Jonathan Stowe 2016 - 2019 The terms of the k8055 library used are described in its [README](https://github.com/jodersky/k8055/blob/master/README.md).
## dist_cpan-FRITH-Math-Libgsl-Elementary.md [![Build Status](https://travis-ci.org/frithnanth/raku-Math-Libgsl-Elementary.svg?branch=master)](https://travis-ci.org/frithnanth/raku-Math-Libgsl-Elementary) # NAME Math::Libgsl::Elementary - An interface to libgsl, the Gnu Scientific Library - elementary functions. # SYNOPSIS ``` use Math::Libgsl::Elementary :ALL; ``` # DESCRIPTION Math::Libgsl::Elementary provides an interface to the Elementary Functions in the libgsl, the GNU Scientific Library. This package provides both the low-level interface to the C library (Raw) and a more comfortable interface layer for the Raku programmer. Math::Libgsl::Elementary makes these tags available: * :elem * :smallint ### sub log1p(Num() $x --> Num) is export(:elem) Computes the value of log(1 + x). ### sub expm1(Num() $x --> Num) is export(:elem) Computes the value of exp(x) - 1. ### sub hypot(Num() $x, Num() $y --> Num) is export(:elem) Computes the value of sqrt(x² + y²). ### sub hypot3(Num() $x, Num() $y, Num() $z --> Num) is export(:elem) Computes the value of sqrt(x² + y² + z²). ### sub ldexp(Num() $x, Int $e --> Num) is export(:elem) Computes the value of x \* 2ᵉ. ### sub frexp(Num() $x --> List) is export(:elem) Computes the value of f such that x = f \* 2ᵉ. It returns a list of two values: f and e. ### sub int-pow(Num() $x, Int $e --> Num) is export(:smallint) Computes the value of xᵉ with e ∈ ℤ. ### sub uint-pow(Num() $x, UInt $e --> Num) is export(:smallint) Computes the value of xᵉ with e ∈ ℕ. ### sub pow2(Num() $x --> Num) is export(:smallint) Computes the value of x². ### sub pow3(Num() $x --> Num) is export(:smallint) Computes the value of x³. ### sub pow4(Num() $x --> Num) is export(:smallint) Computes the value of x⁴. ### sub pow5(Num() $x --> Num) is export(:smallint) Computes the value of x⁵. ### sub pow6(Num() $x --> Num) is export(:smallint) Computes the value of x⁶. ### sub pow7(Num() $x --> Num) is export(:smallint) Computes the value of x⁷. ### sub pow8(Num() $x --> Num) is export(:smallint) Computes the value of x⁸. ### sub pow9(Num() $x --> Num) is export(:smallint) Computes the value of x⁹. # 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::Elementary ``` # AUTHOR Fernando Santagata [nando.santagata@gmail.com](mailto:nando.santagata@gmail.com) # COPYRIGHT AND LICENSE Copyright 2020 Fernando Santagata This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-RBT-DBIish-Transaction.md # DBIish::Transaction ``` use DBIish::Transaction; use DBIish::Savepoint; my $t = DBIish::Transaction.new(connection => {DBIish.connect('Pg', :$database);}, :retry); $t.in-transaction: -> $dbh { # BEGIN issued at start $dbh.do(q{CREATE TABLE tab (col integer)}); my $sth = $dbh.prepare('INSERT INTO tab VALUES ($1);'); $sth.execute(1); # Also allows for savepoints on databases supporting this behaviour. # These are kinda like sub-transactions. Catch the exception to prevent the # outer transaction from being rolled back. try { my $sp = DBIish::Savepoint.new(connection => $dbh); $sp.in-savepoint: -> $sp-dbh { # SAVEPOINT issued at start my $updsth = $sp-dbh.prepare('UPDATE tab SET col = col + 1'); $updsth.execute(); $sth.execute('Insert Invalid Value'); # ROLLBACK TO <savepoint> issued due to the above failure. } } # COMMIT issued at end # Table "tab" contains a single record with col = 1 } $t.in-transaction: -> $dbh { my $sth = $dbh.prepare('INSERT INTO t VALUES ($1);'); $sth.execute(2); fail('Changed my mind about the insert'); # ROLLBACK due to the error } ``` ## Description This is a easy to use way of creating database transactions that always commit/rollback and can retry on temporary failures such as disconnect, deadlocks, serialization issues, or snapshot age. ## DBIish::Transaction ``` DBIish::Transaction.new(:connection, :retry, :max-retry-count, :begin, :rollback, :after-rollback, :commit); ``` ### :connection Either a DBDish::Connection, or a Callable which returns a DBDish::Connection. If a Callable is provided transactions may be retried if disconnect occurs when :retry is specified. A connection provided by a callable will be disposed of after completion (commit or rollback) of the transaction. It may also be disposed of and a new connection obtained during retry to resolve some error types. This is an example of a transaction using a connection pooler for higher performance, the automatic ability to retry on network issues, and an upper limit on simultaneous connections. It is recommended for any programs with concurrancy or on spotty networks. ``` use DBIish::Transaction; use DBIish::Pool; my $pool = DBIish::Pool.new(driver => 'Pg', :$database ,:max-connections(20)); my $t = DBIish::Transaction.new(connection => {$pool.get-connection()}, :retry); ``` A connection created outside `DBIish::Transaction` can can retry when the database gives a temporary failure such as a serialization error, but not when there are network issues. ``` use DBIish::Transaction; use DBIish; my $dbh = DBIish.connect('Pg', :$database); my $t = DBIish::Transaction.new(connection => $dbh, :retry); ``` ### :begin($dbh) ``` { $_.do(q{BEGIN}) } ``` By default this is a Callable which performs the simplest begin statement. You may want to modify transaction behaviour. Serializable Isolation level is highly recommended on supported products as this mode eliminates many potential errors due to otherwise silent race conditions. In the below example using `SERIALIZABLE` and `:retry`, the transaction will be attempted up to 4 times during serialization errors. This allows safe Raku read/modify/write without needing to worry about locking for race conditions or unexpected failure. ``` my $id = 1; my $t = DBIish::Transaction.new(:retry, connection => { DBIish.connect('Pg', :$database) }, begin => -> $dbh { $dbh.do(q{ BEGIN ISOLATION LEVEL SERIALIZABLE } ) }, :retry ).in-transaction: -> $dbh { my $sth = $dbh.prepare('SELECT col FROM tabl WHERE id = $1'); $sth.execute($id); my $row = $sth.row(:hash); my $sth = $dbh.prepare('UPDATE INTO tabl SET col = $2 WHERE id = $1'); $sth.execute( $id, $row<col> * complex_function() ); } ``` ### :rollback($dbh) ``` { $_.do(q{ROLLBACK}) } ``` By default this is a Callable which performs the simplest rollback statement. NOTE: `AND CHAIN` type modifications will require you to provide some non-trivial logic in the `begin` callable. ### :after-rollback(Int $transaction-retry-attempt) Callable which will be called after a rollback is attempted. This is useful for resetting state for another attempt at the DB transaction work, or for logging/debugging purposes. ### :commit($dbh) ``` { $_.do(q{COMMIT}) } ``` By default this is a Callable which performs the simplest commit statement. NOTE: `AND CHAIN` type modifications will require you to provide some non-trivial logic in the `begin` callable. ### :retry Catches errors [marked temporary](https://github.com/raku-community-modules/DBIish#statement-exceptions) by DBIish. The transaction in progress will be rolled back and a new transaction started. The function body is expected to be idempotent for non-database work as it may be executed multiple times. If `:connection` is provided a function, this will retry on a database connectivity issue as well by establishing a new connection and attempting to execute the transaction body. ### :max-retry-count Number of times to retry the work after a temporary failure before giving up. 3 by default. ## DBIish::Savepoint ``` DBIish::Transaction.new(:connection, :begin, :rollback, :commit); ``` ### :connection A DBDish::Connection with a currently active transaction. ### :begin($dbh) ``` { $_.do(q{SAVEPOINT <random name>}) } ``` By default this is a Callable which performs the simplest `SAVEPOINT` statement. A random name is selected. ### :rollback($dbh) ``` { $_.do(q{ROLLBACK TO SAVEPOINT <random name>}) } ``` By default this is a Callable which performs the simplest `ROLLBACK TO SAVEPOINT` statement. ### :after-rollback() Callable which will be called after a rollback is attempted. This is useful for resetting state for another attempt, or for logging/debugging purposes. ### :release($dbh) ``` { $_.do(q{RELEASE SAVEPOINT}) } ``` By default this is a Callable which performs the simplest `RELEASE SAVEPOINT` statement. This free's the savepoint related resources on the database side. ## LICENSE All files in this repository are licensed under the terms of the Creative Commons CC0 License; for details, please see the LICENSE file
## temp.md temp Combined from primary sources listed below. # [In Operators](#___top "go to top of document")[§](#(Operators)_prefix_temp "direct link") See primary documentation [in context](/language/operators#prefix_temp) for **prefix temp**. ```raku sub prefix:<temp>(Mu $a is rw) ``` "temporizes" the variable passed as the argument. The variable begins with the same value as it had in the outer scope, but can be assigned new values in this scope. Upon exiting the scope, the variable will be restored to its original value. ```raku my $a = "three"; say $a; # OUTPUT: «three␤» { temp $a; say $a; # OUTPUT: «three␤» $a = "four"; say $a; # OUTPUT: «four␤» } say $a; # OUTPUT: «three␤» ``` You can also assign immediately as part of the call to temp: ```raku temp $a = "five"; ``` Be warned the `temp` effects get removed once the block is left. If you were to access the value from, say, within a [`Promise`](/type/Promise) after the `temp` was undone, you'd get the original value, not the `temp` one: ```raku my $v = "original"; { temp $v = "new one"; start { say "[PROMISE] Value before block is left: `$v`"; sleep 1; say "[PROMISE] Block was left while we slept; value is now `$v`"; } sleep ½; say "About to leave the block; value is `$v`"; } say "Left the block; value is now `$v`"; sleep 2; # OUTPUT: # [PROMISE] Value before block is left: `new one` # About to leave the block; value is `new one` # Left the block; value is now `original` # [PROMISE] Block was left while we slept; value is now `original` ``` # [In Variables](#___top "go to top of document")[§](#(Variables)_prefix_temp "direct link") See primary documentation [in context](/language/variables#The_temp_prefix) for **The temp prefix**. Like `my`, `temp` restores the old value of a variable at the end of its scope. However, `temp` does not create a new variable. ```raku my $in = 0; # temp will "entangle" the global variable with the call stack # that keeps the calls at the bottom in order. sub f(*@c) { (temp $in)++; "<f>\n" ~ @c».indent($in).join("\n") ~ (+@c ?? "\n" !! "") ~ '</f>' }; sub g(*@c) { (temp $in)++; "<g>\n" ~ @c».indent($in).join("\n") ~ (+@c ?? "\n" !! "") ~ "</g>" }; print g(g(f(g()), g(), f())); # OUTPUT: «<g> # <g> # <f> # <g> # </g> # </f> # <g> # </g> # <f> # </f> # </g> # </g>␤» ```
## dist_zef-markldevine-KHPH.md # KHPH Keep Honest People Honest - String Obfuscation, Storage, & Retrieval # Disclaimer This module scrambles a string to help keep it private, but of course the scrambled string is inherently vulnerable to being unscrambled by someone other than the owner. One might ask, "Why even bother employing a scrambling function?" The pragmatic answer is that simply masking sensitive data from view can prevent many of the exposure scenarios that exist in the real world. Consider the egregious case where you need to run a program that absolutely requires you to include a *password* in its command line invocation. ``` myuid@myserver> /usr/local/bin/srvrconn -acct=USER72 -password=pAsSwOrD57! START INSTANCE ABC ``` If you run it interactively, your shell history will record the entire command line for posterity, including the exposed password. Then your system backup will make a copy of that, and who knows where that goes and for how long? If it were executed via a job scheduler, the password could be exposed in multiple places: crontab, logs, email, backups, etc. You might consider a solution where you put the secret characters in a file and judiciously apply DAC controls to restrict access (chown/chgrp/chmod). When it's time to use the password, you could read the secret string from the file and insert it where needed. But **root** would be able to look at your secret with a quick `cat` command, and then your secret wouldn't be a secret anymore. This module offers you a way to reduce the likelihood of baring your secret information to curious people who are just poking around. It helps reduce the number of surfaces where your private data is openly exposed. It does not purport to fully protect your private information from prying eyes, rather to make it opaque to glances. > ALWAYS ENCRYPT SENSITIVE DATA. Sensitive information that cannot be exposed warrants real security, not a privacy fence. # Description This module will scramble a string, stash it wherever you specify, then expose it to you whole again when you ask for it. **root** can’t expose it directly, unless **root** originally stored it. `su`’ing into the owner’s account from a different account won’t expose it directly either. It’s not in the direct line of sight by anyone other than the owner. # Synopsis ``` use KHPH; my $userid = 'testid'; my KHPH $secret-string .= new( :herald('myapp credentials'), :prompt($userid ~ ' password'), :stash-path('/tmp/myapp/' ~ $userid ~ '/mysecret'), :user-exclusive-at('/tmp/myapp/' ~ $userid); ); say $secret-string.expose; ``` # Methods ## .new() Generate a KHPH object #### :herald? * Optional announcement used only when interactively stashing the secret. #### :prompt? * Optional prompt string used only when interactively stashing the secret. #### :secret? * Optionally send the constructor the secret string. No prompting will occur. #### :stash-path! * Specify the path (directories/file) to create or find the stash file. Always include a subdirectory in the path, as KHPH will `chmod` the directory containing the stash file. #### :user-exclusive-at? * Optionally specify a segment of the :stash-path to exclude all group & other access (0700). ## .expose() Return the secret as a clear-text Str. # Example I The `myapp-pass.raku` script will manage the password stash of `myapp`. Run it interactively one time to stash your secret, then you (not someone else) can run it anytime to expose the secret. The `myapp-pass.raku` script: ``` #!/usr/bin/env raku use KHPH; KHPH.new(:stash-path('/tmp/.myapp/password.khph')).expose.print; ``` Run ~/myapp-pass.raku once interactively to stash the secret: ``` me@mysystem> ~/myapp-pass.raku && echo [1/2] Enter secret> aW3S0m3pA55w0rDI'LlN3VeRr3m3mB3R [2/2] Enter secret> aW3S0m3pA55w0rDI'LlN3VeRr3m3mB3R aW3S0m3pA55w0rDI'LlN3VeRr3m3mB3R me@mysystem> ``` > *Notice how the script dumps the secret when you personally run it? Have someone else log into the same system, have them run the same script, and see what they get. Have them `su` to your account and try again. Have them log in as **root** and give it a go. Have them `su` from **root** into your account and try. Have them `sudo su -` into your account and try again.* Then in your application client: ``` me@mysystem> /usr/bin/dsmadmc -id=MYSELF -password=`~/myapp-pass.raku` QUERY SESSION FORMAT=DETAILED ``` The password will be inserted into the command line and authentication will succeed. > **Note**: *The above example demonstrates a particular application client (familiar to some backup admins) that is more helpful than most, in that it re-writes the process' args after the program launches. `ps` will only display the string `-password=*******` instead of the actual password string. Not all application vendors pay attention to such details, so beware -- `ps` could be displaying the secret despite your efforts to protect it.* # Example II When crafting REST API clients, servers will often issue session tokens for subsequent connections. These authenticating session tokens remain valid for long intervals of time (hours, days, weeks) and should be protected like passwords. When stashing a token locally for reuse, minimally use KHPH instead of clear-text so that it isn't easily viewed by passersby. # Limitations Only developed on Linux. # Author Mark Devine [mark@markdevine.com](mailto:mark@markdevine.com)
## dist_cpan-CTILMES-NativeHelpers-Callback.md # NAME NativeHelpers::Callback - Helper for looking up perl objects from C callbacks # SYNOPSIS ``` use NativeHelpers::Callback; class thing is repr('CPointer') {} sub make_a_thing(--> thing) is native {} sub setcallback(&callback (int64 --> int32), int64) is native {} sub callit(--> int32) is native('./callback') {} class PerlObject { has thing $.thing; has int32 $.number; } sub my-callback(int64 $user-data --> int32) { NativeHelpers::Callback.lookup($user-data).number } my $object = PerlObject.new(thing => make_a_thing, number => 12); NativeHelpers::Callback.store($object, $object.thing); setcallback(&my-callback, NativeHelpers::Callback.id($object.thing)); my $ret = callit(); # You can also use option ":cb" to get a shorthand "cb": cb.store($object, $object.thing); cb.lookup($id); setcallback(&my-callback, cb.id($object.thing)); cb.remove($object.thing); ``` # DESCRIPTION C libraries often have callback routines allowing you to pass in an extra `void *` parameter of user data from which you are supposed to link into whatever functionality you need from within the callback. When using Perl routines as callbacks, naturally you want to pass in your Perl object. This is complicated by the fact that the Garbage Collector can potentially move Perl objects around so they may not be found where you initially put them. This simple helper object associates a perl object with some object that can be cast to a `int64` type so you can easily register the object (`store`/`remove`), and `lookup` from within a callback routine, associated with an `id` of that thing. Note this is 64-bit architecture specific, and assumes `void *` pointers are interchangeable with `int64`. Wherever you see a `void *` in a library.h file, just use `int64` for the Perl NativeCall subroutine that calls it. For example: ``` typedef int (*callback)(void *); void setcallback(callback cb, void *user_data); ``` goes to: ``` sub setcallback(&callback (int64 --> int32), int64) is native('./callback') {} ``` # COPYRIGHT and LICENSE Copyright 2019 Curt Tilmes This module is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-MARTIMM-Gnome-Gio.md ![gtk logo](https://martimm.github.io/gnome-gtk3/content-docs/images/gtk-perl6.png) # Gnome Gio ![L](http://martimm.github.io/label/License-label.svg) # Description From the Gnome documentation; GIO is striving to provide a modern, easy-to-use VFS API that sits at the right level in the library stack, as well as other generally useful APIs for desktop applications (such as networking and D-Bus support). The goal is to overcome the shortcomings of GnomeVFS and provide an API that is so good that developers prefer it over raw POSIX calls. Among other things that means using GObject. It also means not cloning the POSIX API, but providing higher-level, document-centric interfaces. That being said, the Raku implementation is not implementing all of it, only those parts interesting to the other packages like application, resource and settings handling or DBus I/O. Note that all modules are now in `:api<1>`. This is done to prevent clashes with future distributions having the same class names only differing in this api string. So, add this string to your import statements and dependency modules of these classes in META6.json. Furthermore add this api string also when installing with zef. Example; ``` use Gnome::Gtk3::Main:api<1>; use Gnome::Gtk3::Window:api<1>; use Gnome::Gtk3::Grid:api<1>; use Gnome::Gtk3::Button:api<1>; my Gnome::Gtk3::Main $m .= new; … etcetera … ``` # Documentation * [🔗 License document](http://www.perlfoundation.org/artistic_license_2_0) * [🔗 Release notes](https://github.com/MARTIMM/perl6-gnome-gio/blob/master/CHANGES.md) * [🔗 Issues](https://github.com/MARTIMM/gnome-gtk3/issues) # Installation Do not install this package on its own. Instead install `Gnome::Gtk3:api<1>`. `zef install 'Gnome::Gtk3:api<1>'` # Author Name: **Marcel Timmerman** Github account name: **MARTIMM** # Issues There are always some problems! If you find one please help by filing an issue at [my Gnome::Gtk3 github project](https://github.com/MARTIMM/perl6-gnome-gtk3/issues). # Attribution * The developers of Raku of course and the writers of the documentation which help me out every time again and again. * The builders of the GTK+ library and the documentation. * Other helpful modules for their insight and use.
## perl5var.md class X::Syntax::Perl5Var Compilation error due to use of Perl-only default variables ```raku class X::Syntax::Perl5Var does X::Syntax { } ``` Syntax error thrown when some piece of code tries to use one of the old Perl variables (and it does not error for some other reason). ```raku say $]; ``` dies with 「text」 without highlighting ``` ``` Unsupported use of $] variable; in Raku please use $*RAKU.version or $*RAKU.compiler.version ``` ``` For every unsupported variable (which include most `$^'letter'` constructs, as well as others like `$"`, the error message will mention that the variable is unsupported and the equivalent commands you could use.
## dist_zef-tbrowder-Proc-Easy.md [![Actions Status](https://github.com/tbrowder/Proc-Easy/workflows/test/badge.svg)](https://github.com/tbrowder/Proc-Easy/actions) # NAME **Proc::Easy** - Provides routine `run-command` to ease using Raku's **Proc** class. NOTE: This module replaces the `run-command` portion of the deprecated module `Proc::More`. Note also the API has changed slightly: the previous `:$all` option was removed and its behavior is now the default (i.e., all three of the output parameter values are returned as a list of three elements unless only one is selected as an option). # SYNOPSIS ``` use Proc::Easy; my $cmd = "some-user-prog arg1 arg2"; my $other-dir = $*TMPDIR"; my ($exitcode, $stderr, $stdout) = run-command $cmd, :dir($other-dir); ``` # DESCRIPTION **Proc::Easy** is designed to make using the `run` routine from class `Proc` easier for the usual, simple case when the myriad ways to use `Proc`'s `run` are not required. ## sub run-command ``` sub run-command(Str:D $cmd, :$exit, :$err, :$out, :$dir, # run command in dir 'dir' :$debug, ) is export {...} ``` ### Parameters: * `$cmd` - A string that contains a command suitable for using Raku's `run` routine * `:$exit` - Returns the exit code which should be zero (false) for a successful command execution * `:$err` - Returns `stderr` * `:$out` - Returns `stdout` * `:$dir` - Runs the command in directory 'dir' * `:$debug` - Prints extra info to stdout AFTER the `proc` command ### Returns: A three-element list of the exit code and results from `stderr` and `stdout`, respectively. Either of the three may be selected individually if desired. (If more than one is selected, only one is returned in the order of exit code, `stderr`, or `stdout`.) There is also the capability to send debug messages to `stdout` by including the `:$debug` option. # AUTHOR Tom Browder [tbrowder@cpan.org](mailto:tbrowder@cpan.org) # COPYRIGHT and LICENSE Copyright © 2017-2021 Tom Browder This library is free software; you may redistribute or modify it under the Artistic License 2.0.
## dist_zef-vushu-Raylib-Bindings.md ## raylib-raku (Raylib::Bindings) [![SparrowCI](https://ci.sparrowhub.io/project/git-vushu-raylib-raku/badge)](https://ci.sparrowhub.io) Autogenerated raylib-raku bindings, powered by raku grammar and actions. ### Preface To make Raku play together with Raylib, many of Raylib's functions has to be wrapped into a function, to support pass as pointer meaning we are `"pointerizing"` the functions. This is done automatically when generating the bindings. The bindings are also converted to `kebab-case` to fit Raku code style. #### On installation: * `Generator.rakumod` is fed `raylib.h` which gets parsed and translated via grammar and actions to Raku and C code. * `Bindings.rakumod` will be generated and placed into lib/Raylib * The pointerization and allocation C code gets compiled to be used by Raylib::Bindings. Raylib::Bindings comes with support for malloc-ing Raylib structs, Example the code below will allocate Color as a pointer. `my $white = Color.init(245, 245, 245, 255);` Almost all struct/class in Raylib::Bindings are equipped with an `init` function, which mallocs. Manually calling `free` isn't necessary, since every struct/class are also equipped with a `free` on destroy mechanism and gets handled by the GC. Here is the `DESTROY` method of `Color` ``` submethod DESTROY { free-Color(self); } ``` --- ### Prerequisite *install raylib from:* ``` https://github.com/raysan5/raylib ``` --- ### Install ``` zef install Raylib::Bindings ``` ### Install from repository ``` git clone git@github.com:vushu/raylib-raku.git cd raylib-raku zef install . ``` --- ### Examples ``` raku examples/window.raku raku examples/flying-butterfly.raku raku examples/rotating-butterfly.raku raku examples/3d-camera.raku ``` ### Mutable strings To parse mutable string use CArray[uint8] important to encode it as `utf-8` Example: ``` # .encode takes care of UTF-8 encoding. If $array is used # as a string by the native function, don't forget to append the # NULL byte that terminates a C string: ---------v my $array = CArray[uint8].new("Foo".encode.list, 0); ``` #### More examples at <https://www.raylib.com/examples.html> #### Cheatsheet <https://www.raylib.com/cheatsheet/cheatsheet.html> #### Wiki <https://github.com/raysan5/raylib/wiki> --- ### Screenshots ![Flying Camelia](screenshots/flying-butterfly.gif) ![Rotating Camelia](screenshots/rotating-butterfly.gif) ![2d camera](screenshots/3dcamera-example.png) --- #### Missing: * code comments needs to be included. * support for windows. ### Problem on some callbacks example for `set-audio-stream-callback`: the following happens: ``` MoarVM panic: native callback ran on thread (some-thread-id) unknown to MoarVM ``` Solution yet to be found. ***help is appreciated!***
## dist_cpan-TYIL-App-Assixt.md # Assixt `assixt` is a tool to help Perl 6 module developers along their journey of module inception, all the way through publishing it through [CPAN](https://www.cpan.org/). ## Installation `assixt` itself is available on CPAN, from the module `App::Assixt`. You can use `zef` to get it installed on your machine: ``` zef install App::Assixt ``` ### Installing the latest `master` commit If you're feeling experimental, you can help out by running the latest *passing* `master` commit. This release may contain more bugs than the stable release available from CPAN. However, these releases are also all candidates for becoming a stable release, and can therefore do very well with some in-the-field testing. You can download the latest `master` release from [the GitLab repository](https://gitlab.com/tyil/perl6-app-assixt), unpack it and install it with `zef`: ``` cd "$(mktemp -d)" curl -L -o assixt.zip https://gitlab.com/tyil/perl6-app-assixt/-/jobs/artifacts/master/download?job=App%3A%3AAssixt unzip assixt.zip zef install --force-install . ``` If all went well, you can now use `assixt` as you normally would. If you encounter any bugs or have any feedback of some kind, do not hesitate to [submit an issue](https://gitlab.com/tyil/perl6-app-assixt/issues)! ## Basic usage The most basic commands you will want to use are `new`, `touch`, and `push`. The first time you start using it, you are probably interested in `bootstrap config` as well, but there's a high chance you'll only use it once, so you don't have to remember it. This document only lists the bare basic information required to get you started, and I would recommend you read the module documentation to get familiar with all the possibilities. ### bootstrap config This command will walk through the configuration options, and save the values you supply to the configuration file. Some of these will simply be default values used when making use of `assixt`, so setting them to what you commonly would want can save you some time and effort later on in your life. ``` assixt bootstrap config ``` ### new The `new` command will ask you for some input, and then create the entire module skeleton for you. ``` assixt new Local::Test::Module ``` ### touch Using `touch` you can add new files to your module. While you could use the regular POSIX `touch` command for this, you may want to consider using the `assixt` version anyway. In addition to simply making the file, `assixt` will also update your `META6.json` to reference the newly created file. If directories need to be made to hold the file, these will also be made for you. And lastly, a small skeleton will be created in the file itself, so you don't need to bother yourself with the boilerplates. The `touch` command requires two arguments: the type of thing you want to add, and the name it should get. The types you'll want to use most often are `class` and `unit`. ``` assixt touch class Foo::Bar assixt touch unit Bar::Foo ``` ### push `push` is actually a shorthand for `bump`, `dist` and `upload`. As such, it will bump the version number and update the version number throughout the files in your module, then create a distribution of it (as a `.tar.gz` file) and finally try to upload that distribution to CPAN. ``` assixt push ``` If you don't want the version to be altered, you can use the `--no-bump` argument. ``` assixt --no-bump push ``` ## Documentation This project contains documentation in the module itself. You can access this most easily using the `p6man` utility. For instance, to get information on the `new` command, use the following invocation: ``` p6man App::Assixt::Commands::New ``` For general information of the module and all available subcommands, use `p6man App::Assixt`. For general information about the `assixt` script itself, use `p6man assixt`. The documentation can probably be improved at many points at this point in time. If you find any issues, please report them [on the repository](https://gitlab.com/tyil/perl6-app-assixt), or send a merge request to fix it immediately as well.
## dist_cpan-JMASLAK-Keyring.md [![Build Status](https://travis-ci.org/jmaslak/Raku-Keyring.svg?branch=master)](https://travis-ci.org/jmaslak/Raku-Keyring) # NAME Keyring - Raku OS Keyring Support Library # SYNOPSIS ``` use Keyring; my $keyring = Keyring.new; # # Using Procedural Interface # $keyring.store("MCP", "Root Password", "Pa$$w0rd"); $value = $keyring.get("MCP", "Root Password"); $keyring.delete("MCP", "Root Password"); # # Using Subscript Interface # $keyring{"MCP" => "Root Password"} = "Pa$$w0rd"; $value = $keyring{"MCP" => "Root Password"); $keyring{"MCP" => "Root Password"}:delete; ``` # DESCRIPTION This module uses the Gnome keyring (the standard keyring used on most Linux distributions) or the OSX keychain, if able, to store and retrieve secrets, such as passwords. To use the Gnome keyring, the `libsecret-tools` package must be installed (so the `secret` command is available). On Debian-based systems, this can be installed as follows: ``` sudo apt-get install libsecret-tools ``` If neither the Gnome keyring or the OSX keychain is available, an in-process keychain is used instead (this keychain is implemented as an in-memory hash table, so all contents are erased when the process exits). Additional keychain backends can be used, see Keychain::Backend for more information. # SECURITY NOTE For the Gnome keyring, the `secret` command is used to store and retrieve secrets. Note that any user process can use the `secret` CLI utility, so it is important to keep untrusted programs from executing this utility when the keychain is unlocked. In addition, it uses the search path to locate the `secret` utility, so ensure that your `$ENV{PATH}` settings are secure. For the OS X keychain, the `security` command is used to store and retrieve the secrets. Note that any user process can use this CLI utility, so, like with Gnome keyring, it's important to ensure untrusted programs cannot run as a user with access to sensitive keychain contents! Also, like the Gnome keyring support, `$ENV{PATH}` is used to locate the `security` executable, so it is important that the search path be used in a secure way. For both environments, the secrets (but not necessarily the attributes or labels) are transferred in a secure way via a pipe/socket with the external application. # VARIABLES ## @default-backends ``` # Configure Keyring to not use the in-memory backend @Keyring.default-backends .= grep( { $_ !~~ Keyring::Backend::Memory } ); $keyring = Keyring.new; # Will not use in-memory backend ``` This variable contains a list of classes, in priority order, to be considered for usage. The example above removes the Keyring::Backend::Memory backend, so that the keyring module won't fall-back to that module. You can also add additional keyring backend modules to this list. Generally, it's recommended you add them to the front of the array to use them (the first backend with a `works()` method that returns true will be used; the `Memory` backend always "works" so any backend listed after the `Memory` backend won't be used). Note that the keyring backend is selected during the first call to any of the methods in this class. # CONSTRUCTOR ``` $keyring = Keyring.new; ``` The constructor typically does not take an argument, but will accept a named argument of `backend` containing an instance of a Keyring::Backend class, if you desire to directly use a backend. # ATTRIBUTES ## backend ``` $keyring.backend($backend) if $keyring.backend.defined { say("Backend successfully initialized"); } ``` This attribute allows access to the backend used by this module. It should be an instance of a `Keyring::Backend` object. If this attribute is not set, it is initialized on the first method call to the `Keyring` instance, using the `@default-backends` variable to determine which backends to query. # PROCEDURAL INTERFACE METHODS ## get(Str:D $attribute, Str:D $label -->Str) ``` say("Password is: " ~ $keyring.get("foo", "bar")); ``` This queries the backend for a corresponding attribute and label's password. Note that both the attribute and label must match the data store's values to return a password. Either the password is returned (if found), or an undefined `Str` object is returned. Note that you should generally handle the case where this module returns an undefined value, as if the module is executed on a machine without a usable keyring, it will default to using the in-memory beckend, which is empty when first used. If this method is called while the `backend` attribute is not yet initialized, it will attempt to locate a suitable keystore using the `@default-backends` variable. Should no backend be suitable, this method will `die()`. ## store(Str:D $attribute, Str:D $label, Str:D $secret -->Bool) ``` $keyring.store("foo", "bar", "password") ``` This stores a secret (password) in the keyring being used, which will be associated with the attribute and label provided. If this method is called while the `backend` attribute is not yet initialized, it will attempt to locate a suitable keystore using the `@default-backends` variable. Should no backend be suitable, this method will `die()`. ## delete(Str:D $attribute, Str:D $label -->Bool) ``` $keyring.delete("foo", "bar") ``` This deletes the secret for the corresponding attribute and label from the user's keyring. If this method is called while the `backend` attribute is not yet initialized, it will attempt to locate a suitable keystore using the `@default-backends` variable. Should no backend be suitable, this method will `die()`. # SUBSCRIPT INTERFACE METHODS The standard subscript methods (like a `Hash`) will work with this object. Note that the hash "key" is really the attribute and label passed as a `Pair` object (the "key" of the pair is the attribute, the value is the label). All standard hash methods work except for binding a value. # AUTHOR Joelle Maslak [jmaslak@antelope.net](mailto:jmaslak@antelope.net) # 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.
## dist_zef-sdondley-Proc-Easier.md [![Actions Status](https://github.com/sdondley/Proc-Easier/actions/workflows/test.yml/badge.svg)](https://github.com/sdondley/Proc-Easier/actions) # NAME Proc::Easier - run processes with OO goodness # SYNOPSIS ``` use Proc::Easier; # run a command cmd('ls'); # run command and assign resultant Proc::Easier object to a scalar my $cmd = cmd('ls'); # get info about the object say $cmd.out; say $cmd.err; say $cmd.exit; # exitcode # dump info about the command for debugging say $cmd; # run a command, say its output say cmd('ls').out; # run a command, say its error say cmd('ls').err; # run a command from a different directory cmd('ls', '/home/dir'); # run a command, die if error encountered, then print info cmd('a-bad-command', :die); # make :die the default for all commands until its turned off autodie(:on); cmd('kjkjsdkjf'); # this dies # turn off :die until its turned back on autodie(:off); cmd('kjkjsdkjf'); # this doesn't die # create a command with standard OO, don't run it immediately my $cmd= Proc::Easier.new(cmd => 'ls', :lazy); # run the command $cmd.run; ``` # DESCRIPTION Proc::Easier is a convenient wrapper for the `run` command using a OO interface to make issuing commands from Raku much easier. # PROC::EASIER Class ## Class methods ### sub cmd ( Str $cmd, Bool :$dir = '', Bool :$die = False, Bool :$lazy = False ) ``` cmd('ls', '/some/dir', :die); ``` Convenience method for constructing a `Proc::Easier` object. Accepts a command, an optional directory command to run the command from, an an option to die if an error is encountered, and an optoin to make the command "lazy." Lazy commands will not be executed unless the run method is called on the object. Otherwise, oonce the object is constructed, the command will be immediately executed. ### multi sub autodie(Bool :$off) ### multi sub autodie(Bool :$on) ``` autodie(:on); autodie(:off); ``` Turns on/off the autodie switch. All subsequent `Proc::Easier` commands will behave as if the `:die` feature has been turned on or off. Default is off. ## Object methods ### method new( Str:D :$cmd, Str :$dir = '', Bool :$die = False, Bool :$lazy ) Accepts the same four named variables as the `cmd` convenience method. ### run() Runs the command. ### out() Returns the string from stdout, if any. ### err() Returns the string from stderr, if any. ### exitcode() ### exit() Returns the exit code from the shell, '0' indicates success, other numbers indicate an error. ### caller-file() Returns the name of the file where the call was made. ### caller-line() Returns the line number of the file where the call was made. ## Attributes ### has Str $.cmd is rw; Contains the original command. ### has Str $.dir is rw; The directory where the command will be execute. ### has Bool $.die is rw; Whether the command will die if an error is encountered. # AUTHOR Steve Dondley [s@dondley.com](mailto:s@dondley.com) # ACKNOWLEDGEMENTS Thanks to tbrowder for the `Proc::Easy` distribution which shamelessly inspired the name of this module and furnished some code and ideas to recycle, too. # COPYRIGHT AND LICENSE Copyright 2022 Steve Dondley This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-FRITH-Math-Libgsl-Interpolation.md [![Actions Status](https://github.com/frithnanth/raku-Math-Libgsl-Interpolation/workflows/test/badge.svg)](https://github.com/frithnanth/raku-Math-Libgsl-Interpolation/actions) # NAME Math::Libgsl::Interpolation - An interface to libgsl, the Gnu Scientific Library - Interpolation # SYNOPSIS ``` use Math::Libgsl::Constants; use Math::Libgsl::Interpolation; my constant \N = 4; my Num @x = 0e0, .1e0, .27e0, .3e0; my Num @y = .15e0, .7e0, -.1e0, .15e0; my $s = Math::Libgsl::Interpolation::OneD.new(:type(CSPLINE_PERIODIC), :size(N), :spline).init(@x, @y); for ^100 -> $i { my Num $xi = (1 - $i / 100) * @x[0] + ($i / 100) * @x[N - 1]; my Num $yi = $s.eval: $xi; printf "%g %g\n", $xi, $yi; } ``` # DESCRIPTION Math::Libgsl::Interpolation is an interface to the interpolation functions of libgsl, the Gnu Scientific Library. This module exports two classes: * Math::Libgsl::Interpolation::OneD * Math::Libgsl::Interpolation::TwoD ## Math::Libgsl::Interpolation::OneD ### new(Int $type!, Int $size!) ### new(Int :$type!, Int :$size!) This **multi method** constructor requires two simple or named arguments, the type of interpolation and the size of the array of data points. ### init(Num() @xarray where ([<] @xarray), Num() @yarray --> Math::Libgsl::Interpolation::OneD) This method initializes the interpolation internal data using the X and Y coordinate arrays. It must be called each time one wants to use the object to evaluate interpolation points on another data set. The X array has to be strictly ordered, with increasing x values. This method returns **self**, so it may be chained. ### min-size(--> UInt) This method returns the minimum number of points required by the interpolation object. ### name(--> Str) This method returns the name of the interpolation type. ### find(Num() @xarray, Num() $x --> UInt) This method performs a lookup action on the data array **@xarray** and returns the index i such that @xarray[i] <= $x < @xarray[i+1]. ### reset(--> Math::Libgsl::Interpolation::OneD) This method reinitializes the internal data structure and deletes the cache. It should be used when switching to a new dataset. This method returns **self**, so it may be chained. ### eval(Num() $x where $!spline.interp.xmin ≤ \* ≤ $!spline.interp.xmax --> Num) This method returns the interpolated value of y for a given point x, which is inside the range of the x data set. ### eval-deriv(Num() $x where $!spline.interp.xmin ≤ \* ≤ $!spline.interp.xmax --> Num) This method returns the derivative of an interpolated function for a given point x, which is inside the range of the x data set. ### eval-deriv2(Num() $x where $!spline.interp.xmin ≤ \* ≤ $!spline.interp.xmax --> Num) This method returns the second derivative of an interpolated function for a given point x, which is inside the range of the x data set. ### eval-integ(Num() $a where $!spline.interp.xmin ≤ \*, Num() $b where { $b ≤ $!spline.interp.xmax && $b ≥ $a } --> Num) This method returns the numerical integral result of an interpolated function over the range [$a, $b], two points inside the x data set. ## Math::Libgsl::Interpolation::TwoD ### new(Int $type!, Int $xsize!, Int $ysize!) ### new(Int :$type!, Int :$xsize!, Int :$ysize!) This **multi method** constructor requires three simple or named arguments, the type of interpolation and the size of the arrays of the x and y data points. ### init(Num() @xarray where ([<] @xarray), Num() @yarray where ([<] @yarray), Num() @zarray where \*.elems == @xarray.elems \* @yarray.elems --> Math::Libgsl::Interpolation::TwoD) This method initializes the interpolation internal data using the X, Y, and Z coordinate arrays. It must be called each time one wants to use the object to evaluate interpolation points on another data set. The X and Y arrays have to be strictly ordered, with increasing values. The Z array, which represents a grid, must have a dimension of size xsize \* ysize. The position of grid point (x, y) is given by y \* xsize + x. This method returns **self**, so it may be chained. ### min-size(--> UInt) This method returns the minimum number of points required by the interpolation object. ### name(--> Str) This method returns the name of the interpolation type. ### eval(Num() $x where $!spline.interp.xmin ≤ \* ≤ $!spline.interp.xmax, Num() $y where $!spline.interp.ymin ≤ \* ≤ $!spline.interp.ymax --> Num) This method returns the interpolated value of z for a given point (x, y), which is inside the range of the x and y data sets. ### extrap(Num() $x, Num() $y --> Num) This method returns the interpolated value of z for a given point (x, y), with no bounds checking, so when the point (x, y) is outside the range, an extrapolation is performed. ### deriv-x(Num() $x where $!spline.interp.xmin ≤ \* ≤ $!spline.interp.xmax, Num() $y where $!spline.interp.ymin ≤ \* ≤ $!spline.interp.ymax --> Num) This method returns the interpolated value of ∂z/∂x for a given point (x, y), which is inside the range of the x and y data sets. ### deriv-y(Num() $x where $!spline.interp.xmin ≤ \* ≤ $!spline.interp.xmax, Num() $y where $!spline.interp.ymin ≤ \* ≤ $!spline.interp.ymax --> Num) This method returns the interpolated value of ∂z/∂y for a given point (x, y), which is inside the range of the x and y data sets. ### deriv-xx(Num() $x where $!spline.interp.xmin ≤ \* ≤ $!spline.interp.xmax, Num() $y where $!spline.interp.ymin ≤ \* ≤ $!spline.interp.ymax --> Num) This method returns the interpolated value of ∂²z/∂²x for a given point (x, y), which is inside the range of the x and y data sets. ### deriv-yy(Num() $x where $!spline.interp.xmin ≤ \* ≤ $!spline.interp.xmax, Num() $y where $!spline.interp.ymin ≤ \* ≤ $!spline.interp.ymax --> Num) This method returns the interpolated value of ∂²z/∂²y for a given point (x, y), which is inside the range of the x and y data sets. ### deriv-xy(Num() $x where $!spline.interp.xmin ≤ \* ≤ $!spline.interp.xmax, Num() $y where $!spline.interp.ymin ≤ \* ≤ $!spline.interp.ymax --> Num) This method returns the interpolated value of ∂²z/∂x∂y for a given point (x, y), which is inside the range of the x and y data sets. ## Accessory subroutines ### bsearch(Num() @xarray, Num() $x, UInt $idx-lo = 0, UInt $idx-hi = @xarray.elems - 1 --> UInt) This sub returns the index i of the array @xarray such that @xarray[i] <= $x < @xarray[i+1]. The index is searched for in the range [$idx-lo, $idx-hi]. ### min-size(Int $type --> UInt) ### min-size1d(Int $type --> UInt) ### min-size2d(Int $type --> UInt) These subs return the minimum number of points required by the interpolation object, without the need to create an object. min-size is an alias for min-size1d. # 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::Interpolation ``` # AUTHOR Fernando Santagata [nando.santagata@gmail.com](mailto:nando.santagata@gmail.com) # COPYRIGHT AND LICENSE Copyright 2021 Fernando Santagata This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-MELEZHIK-Sparrowdo-Cordova-OSx-Fortify.md # Sparrowdo::Cordova::OSx::Fortify Sparrowdo module to run HP Fortify scan against Cordova/OSx project. # USAGE ``` $ zef install Sparrowdo::Cordova::OSx::Fortify $ sparrowdo --local_mode --no_sudo --cwd=/path/to/cordova/project \ --module_run=Cordova::OSx::Fortify@scan-file=out.fpr,build-id=test ``` # Parameters ## scan-file Name of generated scan file, the file will be created at the project root directory ( set by `cwd` parameter ). Default value is `out.fpr`. ## configuration Xcode build configuration. Default value is `Debug`. ## skip-pod-setup Don't run `pod setup` if set. ## build-id Sets HP Fortify build ID. Default value is `test` # Author Alexey Melezhik
## dist_zef-dwarring-HTML-Canvas.md [![Actions Status](https://github.com/css-raku/HTML-Canvas-raku/workflows/test/badge.svg)](https://github.com/css-raku/HTML-Canvas-raku/actions) # HTML-Canvas-raku This is a Raku module for composing and rendering HTML-5 canvases. It supports the majority of the [HTML Canvas 2D Context](https://www.w3.org/TR/2dcontext/) API. A canvas may be constructed via the API, then rendered to JavaScript via the `toDataURL()`, `.js()` or `.to-html()` methods, or saved to a Cairo-supported format such as PNG, SVG or PDF. The module includes classes: * `HTML::Canvas`, a Raku implementation of the basic HTML Canvas 2D API. * `HTML::Canvas::Image` - for image loading in a variety of formats * `HTML::Canvas::Gradient` - for image gradients * `HTML::Canvas::Path2` - for path objects * `HTML::Canvas::To::Cairo` - a built-in renderer, which can output to several formats, including PNG, SVG and PDF. # Install This package depends on Cairo, FontConfig, Font::FreeType, Text::FriBidi and HarfBuzz. Additional fonts may also be required on your system: * the [freetype](https://www.freetype.org/download.html) native library needs to be on your system to enable Font::FreeType installation * Text::FriBidi is required for handling of bi-directional text. * the native `Cairo` library is also needed. See instructions at <https://cairographics.org/download/>. * Installation of the [fontconfig](https://www.freedesktop.org/wiki/Software/fontconfig/) native library is also required. # Example ``` use v6; # Create a simple Canvas. Save as PNG and HTML use HTML::Canvas; my HTML::Canvas $canvas .= new: :width(150), :height(100); $canvas.context: -> \ctx { ctx.strokeRect(0, 0, 150, 100); ctx.save; { ctx.fillStyle = "orange"; ctx.fillRect(10, 10, 50, 50); ctx.fillStyle = "rgba(0, 0, 200, 0.3)"; ctx.fillRect(35, 35, 50, 50); }; ctx.restore; ctx.font = "18px Arial"; ctx.fillText("Hello World", 40, 75); } # save canvas as PNG use Cairo; my Cairo::Image $img = $canvas.image; $img.write_png: "examples/canvas-demo.png"; # also save canvas as HTML, source and data URL: # 1. Save source Javascript my $html = "<html><body>{ $canvas.to-html }</body></html>"; "examples/canvas-demo-js.html".IO.spurt: $html; # 2. Save data URL Image my $data-uri = $canvas.toDataURL(); $html = "<html><body><img src='$data-uri'/></body></html>"; "examples/canvas-demo-url.html".IO.spurt: $html; ``` ![canvas-demo.png](examples/canvas-demo.png) ## Saving as PDF ``` use v6; use Cairo; use HTML::Canvas; use HTML::Canvas::To::Cairo; # create a 128 X 128 point PDF my Cairo::Surface::PDF $surface .= create("examples/read-me-example.pdf", 128, 128); # create a PDF with two pages # use a common cache for objects shared between pages such as # fonts and images. This reduces both processing times and PDF file sizes. my HTML::Canvas::To::Cairo::Cache $cache .= new; for 1..2 -> $page { my HTML::Canvas $canvas .= new: :$surface, :$cache; $canvas.context: { .font = "10pt times-roman bold"; .fillStyle = "blue"; .strokeStyle = "red"; .save; { .fillStyle = "rgba(1.0, 0.2, 0.2, 0.25)"; .rect(15, 20, 50, 50); .fill; .stroke; }; .restore; .fillText("Page $page/2", 12, 12); }; $surface.show_page; } $surface.finish; ``` ## Images The `HTML::Canvas::Image` class is used to upload images for inclusion in HTML documents, and/or rendering by back-ends. ``` use HTML::Canvas; use HTML::Canvas::Image; my HTML::Canvas $canvas .= new; my @html-body; # add the image, as a hidden DOM item my HTML::Canvas::Image \image .= open("t/images/camelia-logo.png"); @html-body.push: $canvas.to-html: image, :style("visibility:hidden"); # draw it $canvas.context: -> \ctx { ctx.drawImage(image, 10, 10 ); }; @html-body.push: $canvas.to-html; my $html = "<html><body>" ~ @html-body.join ~ "</body></html>"; ``` `HTML::Canvas::Image` can load a variety of image formats. The built-in `HTML::Canvas::To::Cairo` renderer only supports PNG images, as below: Currently supported image formats are: | Back-end | PNG | GIF | JPEG | BMP | | --- | --- | --- | --- | --- | | `HTML::Canvas (HTML)` | X | X | X | X | | `HTML::Canvas::To::Cairo` | X | | | | | `HTML::Canvas::To::PDF` | X | X | X | | ## Paths `HTML::Canvas::Path2D` can be used to create a re-usable path that can be passed to calls to the `fill()` or `stroke()` methods: ``` use HTML::Canvas; use HTML::Canvas::Path2D; my HTML::Canvas $canvas .= new; $canvas.context: -> \ctx { # Create path my HTML::Canvas::Path2D \region .= new; region.moveTo(30, 90); region.lineTo(110, 20); region.lineTo(240, 130); region.lineTo(60, 130); region.lineTo(190, 20); region.lineTo(270, 90); region.closePath(); ctx.fillStyle = 'green'; ctx.fill(region, 'evenodd'); ctx.translate(100, 100); ctx.fillStyle = 'blue'; ctx.fill(region); } ``` The following methods can be used in path construction: * `moveTo(Numeric \x, Numeric \y)` * `lineTo(Numeric \x, Numeric \y)` * `quadraticCurveTo(Numeric \cx, Numeric \cy, Numeric \x, Numeric \y)` * `bezierCurveTo(Numeric \cx1, Numeric \cy1, Numeric \cx2, Numeric \cy2, Numeric \x, Numeric \y)` * `rect(Numeric \x, Numeric \y, Numeric \w, Numeric \h)` * `arc(Numeric \x, Numeric \y, Numeric \r, Numeric \startAngle, Numeric \endAngle, Bool \antiClockwise = False)` * `closePath()` ## Font Loading ### Font Resources This module integrates with the [CSS::Font::Resources](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/Font/Resources) module. A list of `@font-face` CSS font descriptors can be passed to the canvas object to specify font sources. Fonts are resolved the same way as [`@font-face` rules in a stylesheet](https://www.w3.org/TR/2018/REC-css-fonts-3-20180920/#font-resources). For example: ``` use HTML::Canvas; use HTML::Canvas::To::Cairo; use CSS::Font::Descriptor; use Cairo; my CSS::Font::Descriptor $ugly .= new: :font-family<arial>, :src<url(resources/font/FreeMono.ttf)>; my HTML::Canvas $canvas .= new: :font-face[$ugly], :width(650), :height(400); $canvas<scale>(2.0, 3.0); $canvas<font> = "30px Arial"; $canvas.fillText("Hello World",10,50); # save canvas as PNG my Cairo::Surface $surface = $canvas.image; $surface.write_png: "tmp/ariel-ugly.png"; ``` Note that supported fonts may be backend dependant. * `HTML::Canvas::To::Cairo` supports almost all common font formats via the FreeType/Cairo integration * `HTML::Canvas::To::PDF` supports a smaller set of font formats; Fonts with extensions `*.otf`, `*.ttf`, `*.cff`, `*.pfa`, `*.pfb` should work. But resources with extensions `*.woff`, `*.woff2`, and `*.eot` are ignored. ### Font System Loading Local fonts and fonts without matching `@font-face` font descriptors are resolved using FontConfig. If FontConfig fails to find a matching font, HTML::Canvas falls back to using a mono-spaced font (FreeMono). ## Methods The methods below implement the majority of the W3C [HTML Canvas 2D Context](https://www.w3.org/TR/2dcontext/) API. ## Setters/Getters #### lineWidth ``` has Numeric $.lineWidth = 1.0; ``` #### globalAlpha ``` has Numeric $.globalAlpha = 1.0; ``` #### lineCap ``` subset LineCap of Str where 'butt'|'round'|'square'; has LineCap $.lineCap = 'butt'; ``` #### lineJoin ``` subset LineJoin of Str where 'bevel'|'round'|'miter'; has LineJoin $.lineJoin = 'bevel'; ``` #### font ``` has Str $.font = '10pt times-roman'; ``` #### textBaseline ``` subset Baseline of Str where 'alphabetic'|'top'|'hanging'|'middle'|'ideographic'|'bottom'; has Baseline $.textBaseline = 'alphabetic'; ``` #### textAlign ``` subset TextAlignment of Str where 'start'|'end'|'left'|'right'|'center'; has TextAlignment $.textAlign = 'start'; ``` #### direction ``` subset TextDirection of Str where 'ltr'|'rtl'; has TextDirection $.direction = 'ltr'; ``` #### fillStyle ``` subset ColorSpec where Str|HTML::Canvas::Gradient|HTML::Canvas::Pattern; has ColorSpec $.fillStyle is rw = 'black'; ``` #### strokeStyle ``` has ColorSpec $.strokeStyle is rw = 'black'; ``` #### setLineDash/getLineDash/lineDash ``` has Numeric @.lineDash; ``` #### lineDashOffset ``` has Numeric $.lineDashOffset = 0.0; ``` ## Graphics State #### `save()` #### `restore()` #### `scale(Numeric $x, Numeric $y)` #### `rotate(Numeric $rad)` #### `translate(Numeric $x, Numeric $y)` #### `transform(Numeric \a, Numeric \b, Numeric \c, Numeric \d, Numeric \e, Numeric \f)` #### `setTransform(Numeric \a, Numeric \b, Numeric \c, Numeric \d, Numeric \e, Numeric \f)` ## Painting Methods #### `clearRect(Numeric $x, Numeric $y, Numeric $w, Numeric $h)` #### `fillRect(Numeric $x, Numeric $y, Numeric $w, Numeric $h)` #### `strokeRect(Numeric $x, Numeric $y, Numeric $w, Numeric $h)` #### `beginPath()` #### `fill(FillRule $rule?)` or `fill(HTML::Canvas::Path2D $path, FillRule $rule?)` #### `stroke(HTML::Canvas::Path2D $path?)` #### `clip()` #### `fillText(Str $text, Numeric $x, Numeric $y, Numeric $max-width?)` #### `strokeText(Str $text, Numeric $x, Numeric $y, Numeric $max-width?)` #### `measureText(Str $text)` ## Path Methods #### `closePath()` #### `moveTo(Numeric \x, Numeric \y)` #### `lineTo(Numeric \x, Numeric \y)` #### `quadraticCurveTo(Numeric \cp1x, Numeric \cp1y, Numeric \x, Numeric \y)` #### `bezierCurveTo(Numeric \cp1x, Numeric \cp1y, Numeric \cp2x, Numeric \cp2y, Numeric \x, Numeric \y)` #### `rect(Numeric $x, Numeric $y, Numeric $w, Numeric $h)` #### `arc(Numeric $x, Numeric $y, Numeric $radius, Numeric $startAngle, Numeric $endAngle, Bool $counterClockwise?)` ## Images Patterns and Gradients #### drawImage: ``` multi method drawImage( $image, Numeric \sx, Numeric \sy, Numeric \sw, Numeric \sh, Numeric \dx, Numeric \dy, Numeric \dw, Numeric \dh); multi method drawImage(CanvasOrXObject $image, Numeric $dx, Numeric $dy, Numeric $dw?, Numeric $dh?) ``` #### `createLinearGradient(Numeric $x0, Numeric $y0, Numeric $x1, Numeric $y1)` #### `createRadialGradient(Numeric $x0, Numeric $y0, Numeric $r0, Numeric $x1, Numeric $y1, Numeric:D $r1)` #### `createPattern($image, HTML::Canvas::Pattern::Repetition $repetition = 'repeat')` Example: ``` use HTML::Canvas; use HTML::Canvas::Image; my HTML::Canvas \ctx .= new; my @html-body; ## Images ## my HTML::Canvas::Image \image .= open("t/images/crosshair-100x100.jpg"); # save to HTML @html-body.push: ctx.to-html: image, :style("visibility:hidden"); # draw on the canvas ctx.drawImage(image, 20, 10, 50, 50); ## Patterns ## my \pat = ctx.createPattern(image,'repeat'); ctx.fillStyle = pat; ctx.translate(10,50); ctx.fillRect(10,10,150,100); ## Gradients with ctx.createRadialGradient(75,50,5,90,60,100) -> $grd { $grd.addColorStop(0,"red"); $grd.addColorStop(0.5,"white"); $grd.addColorStop(1,"blue"); ctx.fillStyle = $grd; ctx.translate(10,200); ctx.fillRect(10, 10, 150, 100); } say ctx.js; ``` ## Image Data Currently support for `getImageData` and `putImageData` (3 argument format) only. #### `getImageData(Numeric sx, Numeric sy, Numeric sw, Numeric sh)` #### `putImageData(image-data, Numeric dx, Numeric dy)` ## Additional Rendering Backends * [HTML::Canvas::To::PDF](https://pdf-raku.github.io/HTML-Canvas-To-PDF-raku) - render to PDF, using the Raku [PDF](https://pdf-raku.github.io) tool-chain.
## versioning.md role Metamodel::Versioning Metaobjects that support versioning ```raku role Metamodel::Versioning { ... } ``` *Warning*: this role is part of the Rakudo implementation, and is not a part of the language specification. [Metamodel](/language/mop) role for (optionally) versioning metaobjects. When you declare a type, you can pass it a version, author, and/or API and get them, like so: ```raku class Versioned:ver<0.0.1>:auth<github:Kaiepi>:api<1> { } say Versioned.^ver; # OUTPUT: «v0.0.1␤» say Versioned.^auth; # OUTPUT: «github:Kaiepi␤» say Versioned.^api; # OUTPUT: «1␤» ``` This is roughly equivalent to the following, which also sets them explicitly: ```raku BEGIN { class Versioned { } Versioned.^set_ver: v0.0.1; Versioned.^set_auth: 'github:Kaiepi'; Versioned.^set_api: <1>; } say Versioned.^ver; # OUTPUT: «v0.0.1␤» say Versioned.^auth; # OUTPUT: «github:Kaiepi␤» say Versioned.^api; # OUTPUT: «1␤» ``` # [Methods](#role_Metamodel::Versioning "go to top of document")[§](#Methods "direct link") ## [method ver](#role_Metamodel::Versioning "go to top of document")[§](#method_ver "direct link") ```raku method ver($obj) ``` Returns the version of the metaobject, if any, otherwise returns [`Mu`](/type/Mu). ## [method auth](#role_Metamodel::Versioning "go to top of document")[§](#method_auth "direct link") ```raku method auth($obj) ``` Returns the author of the metaobject, if any, otherwise returns an empty string. ## [method api](#role_Metamodel::Versioning "go to top of document")[§](#method_api "direct link") ```raku method api($obj) ``` Returns the API of the metaobject, if any, otherwise returns an empty string. ## [method set\_ver](#role_Metamodel::Versioning "go to top of document")[§](#method_set_ver "direct link") ```raku method set_ver($obj, $ver) ``` Sets the version of the metaobject. ## [method set\_auth](#role_Metamodel::Versioning "go to top of document")[§](#method_set_auth "direct link") ```raku method set_auth($obj, $auth) ``` Sets the author of the metaobject. ## [method set\_api](#role_Metamodel::Versioning "go to top of document")[§](#method_set_api "direct link") ```raku method set_api($obj, $api) ``` Sets the API of the metaobject.
## compunit.md class CompUnit CompUnit ```raku class CompUnit {} ``` The `CompUnit` represents the meta-information about a compilation unit. This usually relates to source code that resides in a file on a filesystem, rather than code that is executed using an `EVAL` statement. # [Methods](#class_CompUnit "go to top of document")[§](#Methods "direct link") ## [method auth](#class_CompUnit "go to top of document")[§](#method_auth "direct link") ```raku method auth(--> Str:D) ``` Returns the authority information with which the `CompUnit` object was created (if any). ## [method distribution](#class_CompUnit "go to top of document")[§](#method_distribution "direct link") ```raku method distribution(--> Distribution:D) ``` Returns the [`Distribution`](/type/Distribution) object with which the `CompUnit` object was created (if any). ## [method from](#class_CompUnit "go to top of document")[§](#method_from "direct link") ```raku method from(--> Str:D) ``` Returns the name of the language with which the `CompUnit` object was created (if any). It will be `Raku` by default. ## [method precompiled](#class_CompUnit "go to top of document")[§](#method_precompiled "direct link") ```raku method precompiled(--> Bool:D) ``` Returns whether the `CompUnit` object originated from a precompiled source. ## [method repo](#class_CompUnit "go to top of document")[§](#method_repo "direct link") ```raku method repo(--> CompUnit::Repository:D) ``` Returns the [`CompUnit::Repository`](/type/CompUnit/Repository) object with which the `CompUnit` object was created. ## [method repo-id](#class_CompUnit "go to top of document")[§](#method_repo-id "direct link") ```raku method repo-id(--> Str:D) ``` Returns the identification string with which the `CompUnit` object can be identified in the associated [repo](#method_repo). ## [method short-name](#class_CompUnit "go to top of document")[§](#method_short-name "direct link") ```raku method short-name(--> Str:D) ``` Returns The short name with which the `CompUnit` object was created (if any). ## [method version](#class_CompUnit "go to top of document")[§](#method_version "direct link") ```raku method version(--> Version:D) ``` Returns the version information with which the `CompUnit` object was created (if any). # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `CompUnit` raku-type-graph CompUnit CompUnit Any Any CompUnit->Any Mu Mu Any->Mu [Expand chart above](/assets/typegraphs/CompUnit.svg)
## dist_zef-grondilu-EC.md [![SparrowCI](https://ci.sparrowhub.io/project/gh-grondilu-elliptic-curves-raku/badge)](https://ci.sparrowhub.io) # Elliptic Curves Cryptography in raku secp256k1 and ed25519 in [raku](http://raku.org) ## Synopsis ``` { use secp256k1; say key-range; say $_*G for 1..10; use Test; is 35*G + 5*G, 40*G; } { use ed25519; # create a key # - randomly : my ed25519::Key $key .= new; # - from a seed : my blob8 $secret-seed .= new: ^256 .roll: 32; my ed25519::Key $key .= new: $secret-seed; # use key to sign a message my $signature = $key.sign: "Hello world!"; # verify signature use Test; lives-ok { ed25519::verify "foo", $key.sign("foo"), $key.point }; dies-ok { ed25519::verify "foo", $key.sign("bar"), $key.point }; } ``` ## References * [RFC 8032](http://www.rfc-editor.org/info/rfc8032) * Jacobian coordinates: * [WikiBooks entry](https://en.wikibooks.org/wiki/Cryptography/Prime_Curve/Jacobian_Coordinates) * [hyperelliptic.org page](http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html) * Chalkias, Konstantinos, et. al. ["Taming the many EdDSAs."](https://eprint.iacr.org/2020/1244.pdf) *Security Standardisation Research Conference*, Dec. 2020
## dist_cpan-GDONALD-ORM-ActiveRecord.md # ORM::ActiveRecord ORM::ActiveRecord is an [object-relational mapping](https://en.wikipedia.org/wiki/Object-relational_mapping) module for Raku that *mostly* follows the [Active Record Pattern](https://en.wikipedia.org/wiki/Active_record_pattern). ## Documentation <http://docs.rakuist.io/orm-activerecord> ## Install using zef ``` zef install --/test ORM::ActiveRecord ``` `--/test` is suggested because you probably don't have a test database setup. ## Simple Example ``` my $user = User.create({fname => 'Greg'}); my $page = Page.create({:$user, name => 'Rakuist'}); say $user.pages.first.name; Rakuist say $page.user.fname; Greg my $alfred = User.create({fname => 'Fred'}); $page.update({user => $fred}); say $page.user.fname; Fred ``` Please see the [documentation](http://docs.rakuist.io/orm-activerecord) for more examples. ## Build Status [![Build Status](https://travis-ci.org/rakuist/ORM-ActiveRecord.svg?branch=master)](https://travis-ci.org/rakuist/ORM-ActiveRecord) ## License ORM::ActiveRecord is released under the [Artistic License 2.0](https://opensource.org/licenses/Artistic-2.0) ## Features * Model: * belongs-to * has-many * has-many -> through * where: all, first, count * Validations * Conditionals: if, unless, on, create, update * Acceptance * Confirmation * Exclusion * Format * Inclusion * Length * Minimum * Maximum * In a range * Is exactly * Numericality * Less than * Less than or equal * Greater than * Greater than or equal * In a range * Presence * Uniqueness * Unique Scope * Callbacks * after: create, save, update * before: create, save, update * Scopes * Dirty * Custom Errors * Migrations * PostgreSQL support ## TODO * Includes: for has-many records * Migration generator * Model generator * Support for MySQL, SQLite, and Oracle.
## dist_zef-thundergnat-Sort-Naturally.md [![Actions Status](https://github.com/thundergnat/Sort-Naturally/actions/workflows/test.yml/badge.svg)](https://github.com/thundergnat/Sort-Naturally/actions) # NAME Sort::Naturally Provides a transform routine to modify sorting into a "natural" order. # SYNOPSIS ``` use Sort::Naturally; # sort strings containing a mix of letters and digits sensibly my @a = <1 11 100 14th 2 210 21 30 3rd d1 Any any d10 D2 D21 d3 aid Are ANY >; say @a.sort: { .&naturally }; ``` yields: ``` 1 2 3rd 11 14th 21 30 100 141 210 aid ANY Any any Are d1 D2 d3 d10 D21 ``` compared to `@a.sort`: ``` 1 100 11 141 14th 2 21 210 30 3rd ANY Any Are D2 D21 aid any d1 d10 d3 ``` # DESCRIPTION This implementation of a natural sort order transform will yield results similar, though not identical to the Perl 5 Sort::Naturally. When sorting strings that contain groups of digits, it will sort the groups of consecutive digits by "order of magnitude", then lexically by lower-cased terms. Order of magnitude is something of a simplification. The transformation routine &naturally doesn't try to interpret or evaluate a group of digits as a number, it just counts how many digits are in each group and uses that as its order of magnitude. The implications are: * It doesn't understand the (non)significance of leading zeros in numbers; 0010, 0100 and 1000 are all treated as being of the same order of magnitude and will all be sorted to be after 20 and 200. This is the correct behavior for strings of digits where leading zeros are significant, like zip codes or phone numbers. * It doesn't understand floating point numbers; the groups of digits before and after a decimal point are treated as two separate numbers for sorting purposes. * It doesn't understand or deal with scientific or exponential notation. However, that also means: * You are not limited by number magnitude. It will sort arbitrarily large numbers with ease regardless of the math capability of your hardware/OS. * It is quite speedy. (For liberal values of speedy.) Since it doesn't need to interpret numbers by value it eliminates a lot of code that would do that. It could have been modified to ignore leading zeros, and in fact I experimented with that bit, but ran into issues with strings where leading zeros WERE significant. Just remember, it is for sorting strings, not numbers. It makes some attempt at treating groups of digits in a kind of numbery way, but they are still strings. If you truly want to sort numbers, use a numeric sort. # USAGE Sort::Naturally provides a transformation routine: `&naturally`, which you can use as a sorting block modifier. It performs a transform of the terms so they will end up in the natural order. ### BACKWARD COMPATIBILITY BREAKING CHANGES Previous versions provided some pre-made augmented methods and infix comparators that are no longer provided. Partially because they were causing compilation failures due to incomplete and not yet implemented compiler features, and partially because I decided it was a bad idea to unnecessarily pollute the name-space. If you would like to have the syntactic sugar, it can be added easily. To create the method `.nsort` that can be used similar to `.sort`: ``` use Sort::Naturally; use MONKEY-TYPING; augment class Any { method nsort (*@) { self.list.flat.sort( { .&naturally } ) }; } ``` *(Note: since this was originally written, augmenting rules have changed in Raku. Now, if you augment a parent class (Any), you must then re-compose any subtypes that you want to see the augmentation.)* For a natural sorting infix comparator: `sub infix:<ncmp>($a, $b) { $a.&naturally cmp $b.&naturally }` ### PERL 5 BACKWARD COMPATIBILITY Perl 5 Sort::Naturally has an odd convention in that numbers at the beginning of strings are sorted in ASCII order (digits sort before letters) but numbers embedded inside strings are sorted in non-ASCII order (digits sort after letters). While this is just plain strange in my opinion, some people may rely on or prefer this behavior so Raku `Sort::Naturally` has a "p5 compatibility mode" routine. `p5naturally()`. for comparison: ``` (' sort:',<foo12z foo foo13a fooa Foolio Foo12a foolio foo12 foo12a 9x 14>\ .sort).join(' ').say; (' naturally:',<foo12z foo foo13a fooa Foolio Foo12a foolio foo12 foo12a 9x 14>\ .sort({ .&naturally })).join(' ').say; ('p5naturally:',<foo12z foo foo13a fooa Foolio Foo12a foolio foo12 foo12a 9x 14>\ .sort({ .&p5naturally })).join(' ').say; ``` yields: ``` sort: 14 9x Foo12a Foolio foo foo12 foo12a foo12z foo13a fooa foolio naturally: 9x 14 foo foo12 Foo12a foo12a foo12z foo13a fooa Foolio foolio p5naturally: 9x 14 foo fooa Foolio foolio foo12 Foo12a foo12a foo12z foo13a ``` # BUGS Tests and the p5 routine will fail under locales that specify lower case letters to sort before upper case. (EBCDIC locales notably). They will still sort *consistently*, just not in the order advertised. I can probably implement some kind of run time check to modify the behavior based on current locale. I'll look into it more seriously later if necessary. Right now, there are no Raku compilers for any EBCDIC OSs so it is not really an issue yet. # AUTHOR Stephen Schulze (also known as thundergnat) # LICENSE Licensed under The Artistic 2.0; see LICENSE.
## junction.md class Junction Logical superposition of values ```raku class Junction is Mu { } ``` A junction is an unordered composite value of zero or more values. Junctions *autothread* over many operations, which means that the operation is carried out for each junction element (also known as *eigenstate*), and the result is the junction of the return values of all those operators. Junctions collapse into a single value in Boolean context, so when used in a conditional, a negation or an explicit coercion to Bool through the `so` or `?` prefix operators. The semantics of this collapse depend on the *junction type*, which can be `all`, `any`, `one` or `none`. | type | constructor | operator | True if ... | | --- | --- | --- | --- | | all | all | & | no value evaluates to False | | any | any | | | at least one value evaluates to True | | one | one | ^ | exactly one value evaluates to True | | none | none | | no value evaluates to True | As the table shows, in order to create junctions you use the command that represents the type of `Junction` followed by any object, or else call [`.all`](/routine/all), [`.none`](/routine/none) or [`.one`](/routine/one) on the object. ```raku say so 3 == (1..30).one; # OUTPUT: «True␤» say so ("a" ^ "b" ^ "c") eq "a"; # OUTPUT: «True␤» ``` Junctions are very special objects. They fall outside the [`Any`](/type/Any) hierarchy, being only, as any other object, subclasses of [`Mu`](/type/Mu). That enables a feature for most methods: autothreading. Autothreading happens when a junction is bound to a parameter of a code object that doesn't accept values of type `Junction`. Instead of producing an error, the signature binding is repeated for each value of the junction. Example: ```raku my $j = 1|2; if 3 == $j + 1 { say 'yes'; } ``` First autothreads over the `infix:<+>` operator, producing the Junction `2|3`. The next autothreading step is over `infix:<==>`, which produces `False|True`. The `if` conditional evaluates the junction in Boolean context, which collapses it to `True`. So the code prints `yes\n`. The type of a `Junction` does *not* affect the number of items in the resultant `Junction` after autothreading. For example, using a [one](/routine/one) `Junction` during [`Hash`](/type/Hash) key lookup, still results in a `Junction` with several items. It is only in Boolean context would the type of the `Junction` come into play: ```raku my %h = :42foo, :70bar; say %h{one <foo meow>}:exists; # OUTPUT: «one(True, False)␤» say so %h{one <foo meow>}:exists; # OUTPUT: «True␤» say %h{one <foo bar>}:exists; # OUTPUT: «one(True, True)␤» say so %h{one <foo bar>}:exists; # OUTPUT: «False␤» ``` Note that the compiler is allowed, but not required, to parallelize autothreading (and Junction behavior in general), so it is usually an error to autothread junctions over code with side effects. Autothreading implies that the function that's autothreaded will also return a Junction of the values that it would usually return. ```raku (1..3).head( 2|3 ).say; # OUTPUT: «any((1 2), (1 2 3))␤» ``` Since [`.head`](/routine/head) returns a list, the autothreaded version returns a `Junction` of lists. ```raku 'walking on sunshine'.contains( 'king'&'sun' ).say; # OUTPUT: «all(True, True)␤» ``` Likewise, [`.contains`](/routine/contains) returns a Boolean; thus, the autothreaded version returns a `Junction` of Booleans. In general, all methods and routines that take an argument of type `T` and return type `TT`, will also accept junctions of `T`, returning junctions of `TT`. Implementations are allowed to short-circuit Junctions. For example one or more routine calls (`a()`, `b()`, or `c()`) in the code below might not get executed at all, if the result of the conditional has been fully determined from routine calls already performed (only one truthy return value is enough to know the entire Junction is true): ```raku if a() | b() | c() { say "At least one of the routines was called and returned a truthy value" } ``` Junctions are meant to be used as matchers in a Boolean context; introspection of junctions is not supported. If you feel the urge to introspect a junction, use a [`Set`](/type/Set) or a related type instead. Usage examples: ```raku my @list = <1 2 "Great">; @list.append(True).append(False); my @bool_or_int = grep Bool|Int, @list; sub is_prime(Int $x) returns Bool { # 'so' is for Boolean context so $x %% none(2..$x.sqrt); } my @primes_ending_in_1 = grep &is_prime & / 1$ /, 2..100; say @primes_ending_in_1; # OUTPUT: «[11 31 41 61 71]␤» my @exclude = <~ .git>; for dir(".") { say .Str if .Str.ends-with(none @exclude) } ``` Special care should be taken when using `all` with arguments that may produce an empty list: ```raku my @a = (); say so all(@a) # True, because there are 0 Falses ``` To express "all, but at least one", you can use `@a && all(@a)` ```raku my @a = (); say so @a && all(@a); # OUTPUT: «False␤» ``` Negated operators are special-cased when it comes to autothreading. `$a !op $b` is rewritten internally as `!($a op $b)`. The outer negation collapses any junctions, so the return value always a plain [`Bool`](/type/Bool). ```raku my $word = 'yes'; my @negations = <no none never>; if $word !eq any @negations { say '"yes" is not a negation'; } ``` Note that without this special-casing, an expression like `$word ne any @words` would always evaluate to `True` for non-trivial lists on one side. For this purpose, `infix:<ne>` counts as a negation of `infix:<eq>`. In general it is more readable to use a positive comparison operator and a negated junction: ```raku my $word = 'yes'; my @negations = <no none never>; if $word eq none @negations { say '"yes" is not a negation'; } ``` # [Failures and exceptions](#class_Junction "go to top of document")[§](#Failures_and_exceptions "direct link") [`Failure`](/type/Failure)s are just values like any other, as far as Junctions are concerned: ```raku my $j = +any "not a number", "42", "2.1"; my @list = gather for $j -> $e { take $e if $e.defined; } @list.say; # OUTPUT: «[42 2.1]␤» ``` Above, we've used prefix `+` operator on a `Junction` to coerce the strings inside of it to [`Numeric`](/type/Numeric). Since the operator returns a [`Failure`](/type/Failure) when a [`Str`](/type/Str) that doesn't contain a number gets coerced to [`Numeric`](/type/Numeric), one of the elements in the `Junction` is a [`Failure`](/type/Failure). Failures do not turn into exceptions until they are used or sunk, but we can check for definedness to avoid that. That is what we do in the loop that runs over the elements of the junction, adding them to a list only if they are defined. The exception *will* be thrown, if you try to use the [`Failure`](/type/Failure) as a value—just like as if this [`Failure`](/type/Failure) were on its own and not part of the `Junction`: ```raku my $j = +any "not a number", "42", "2.1"; try say $j == 42; $! and say "Got exception: $!.^name()"; # OUTPUT: «Got exception: X::Str::Numeric␤» ``` Note that if an exception gets thrown when *any* of the values in a `Junction` get computed, it will be thrown just as if the problematic value were computed on its own and not with a `Junction`; you can't just compute the values that work while ignoring exceptions: ```raku sub calc ($_) { die when 13 } my $j = any 1..42; say try calc $j; # OUTPUT: «Nil␤» ``` Only one value above causes an exception, but the result of the [`try` block](/language/exceptions#try_blocks) is still a [`Nil`](/type/Nil). A possible way around it is to cheat and evaluate the values of the `Junction` individually and then re-create the `Junction` from the result: ```raku sub calc ($_) { die when 13 } my $j = any 1..42; $j = any (gather $j».take).grep: {Nil !=== try calc $_}; say so $j == 42; # OUTPUT: «True␤» ``` # [Smartmatching](#class_Junction "go to top of document")[§](#Smartmatching "direct link") Note that using `Junction`s on the right-hand side of `~~` works slightly differently than using Junctions with other operators. Consider this example: ```raku say 25 == (25 | 42); # OUTPUT: «any(True, False)␤» – Junction say 25 ~~ (25 | 42); # OUTPUT: «True␤» – Bool ``` The reason is that `==` (and most other operators) are subject to auto-threading, and therefore you will get a Junction as a result. On the other hand, `~~` will call `.ACCEPTS` on the right-hand-side (in this case on a Junction) and the result will be a [`Bool`](/type/Bool). # [Methods](#class_Junction "go to top of document")[§](#Methods "direct link") ## [method new](#class_Junction "go to top of document")[§](#method_new "direct link") ```raku multi method new(Junction: \values, Str :$type!) multi method new(Junction: Str:D \type, \values) ``` These constructors build a new junction from the type that defines it and a set of values. ```raku my $j = Junction.new(<Þor Oðinn Loki>, type => "all"); my $n = Junction.new( "one", 1..6 ) ``` The main difference between the two multis is how the type of the `Junction` is passed as an argument; either positionally as the first argument, or as a named argument using `type`. ## [method defined](#class_Junction "go to top of document")[§](#method_defined "direct link") ```raku multi method defined(Junction:D:) ``` Checks for definedness instead of Boolean values. ```raku say ( 3 | Str).defined ; # OUTPUT: «True␤» say (one 3, Str).defined; # OUTPUT: «True␤» say (none 3, Str).defined; # OUTPUT: «False␤» ``` [`Failure`](/type/Failure)s are also considered non-defined: ```raku my $foo=Failure.new; say (one 3, $foo).defined; # OUTPUT: «True␤» ``` Since 6.d, this method will autothread. ## [method Bool](#class_Junction "go to top of document")[§](#method_Bool "direct link") ```raku multi method Bool(Junction:D:) ``` Collapses the `Junction` and returns a single Boolean value according to the type and the values it holds. Every element is transformed to [`Bool`](/type/Bool). ```raku my $n = Junction.new( "one", 1..6 ); say $n.Bool; # OUTPUT: «False␤» ``` All elements in this case are converted to `True`, so it's false to assert that only one of them is. ```raku my $n = Junction.new( "one", <0 1> ); say $n.Bool; # OUTPUT: «True␤» ``` Just one of them is truish in this case, `1`, so the coercion to [`Bool`](/type/Bool) returns `True`. ## [method Str](#class_Junction "go to top of document")[§](#method_Str "direct link") ```raku multi method Str(Junction:D:) ``` Autothreads the `.Str` method over its elements and returns results as a `Junction`. Output methods that use `.Str` method ([print](/routine/print) and [put](/routine/put)) are special-cased to autothread junctions, despite being able to accept a [`Mu`](/type/Mu) type. ## [method iterator](#class_Junction "go to top of document")[§](#method_iterator "direct link") ```raku multi method iterator(Junction:D:) ``` Returns an iterator over the `Junction` converted to a [`List`](/type/List). ## [method gist](#class_Junction "go to top of document")[§](#method_gist "direct link") ```raku multi method gist(Junction:D:) ``` Collapses the `Junction` and returns a [`Str`](/type/Str) composed of the type of the junction and the [gists](/routine/gist) of its components: ```raku <a 42 c>.all.say; # OUTPUT: «all(a, 42, c)␤» ``` ## [method raku](#class_Junction "go to top of document")[§](#method_raku "direct link") ```raku multi method raku(Junction:D:) ``` Collapses the `Junction` and returns a [`Str`](/type/Str) composed of [raku](/routine/raku) of its components that [evaluates](/routine/EVAL) to the equivalent `Junction` with equivalent components: ```raku <a 42 c>.all.raku.put; # OUTPUT: «all("a", IntStr.new(42, "42"), "c")␤» ``` ## [infix `~`](#class_Junction "go to top of document")[§](#infix_~ "direct link") ```raku multi infix:<~>(Str:D $a, Junction:D $b) multi infix:<~>(Junction:D $a, Str:D $b) multi infix:<~>(Junction:D \a, Junction:D \b) ``` The infix `~` concatenation can be used to merge junctions into a single one or merge Junctions with strings. The resulting junction will have all elements merged as if they were joined into a nested loop: ```raku my $odd = 1|3|5; my $even = 2|4|6; my $merged = $odd ~ $even; say $merged; # OUTPUT: «any(12, 14, 16, 32, 34, 36, 52, 54, 56)␤» say "Found 34!" if 34 == $merged; # OUTPUT: «Found 34!␤» my $prefixed = "0" ~ $odd; say "Found 03" if "03" == $prefixed; # OUTPUT: «Found 03!␤» my $postfixed = $odd ~ "1"; say "Found 11" if 11 == $postfixed; # OUTPUT: «Found 11!␤» ``` On the other hand, the versions of `~` that use a string as one argument will just concatenate the string to every member of the Junction, creating another Junction with the same number of elements. # [See Also](#class_Junction "go to top of document")[§](#See_Also "direct link") * <https://perlgeek.de/blog-en/perl-5-to-6/08-junctions.html> * <https://web.archive.org/web/20190608135817/http://perl6maven.com/perl6-is-a-value-in-a-given-list-of-values> * <https://perl6advent.wordpress.com/2009/12/13/day-13-junctions/> # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Junction` raku-type-graph Junction Junction Mu Mu Junction->Mu [Expand chart above](/assets/typegraphs/Junction.svg)
## dist_zef-lizmat-META-constants.md [![Actions Status](https://github.com/lizmat/META-constants/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/META-constants/actions) [![Actions Status](https://github.com/lizmat/META-constants/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/META-constants/actions) [![Actions Status](https://github.com/lizmat/META-constants/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/META-constants/actions) # NAME META::constants - distribution related constants from META info # SYNOPSIS ``` use META::constants $?DISTRIBUTION; say NAME; say DESCRIPTION; say VERSION; say API; say AUTH; say AUTHORS; say SOURCE-URL; say CREDITS; ``` # DESCRIPTION META::constants provides an easy way to access information in a module's META information. It is intended to be called inside the code of a module only, although anything that provides a `.meta` method, can be used. # EXPORTED CONSTANTS * NAME - the "name" field * DESCRIPTION - the "description" field * VERSION - the "version" field as a Version object * AUTH - the "auth" field * API - the "api" field * AUTHORS - the "authors" field, joined by ', ' * SOURCE-URL - the "source-url" field with ".git" removed * CREDITS - a credit text created from above * META - the meta information hash itself # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) Source can be located at: <https://github.com/lizmat/META-constants> . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2022, 2024 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-cygx-App-SixLib.md # 6lib Manage symlink-based repositories of local Perl6 modules # Synopsis ``` Usage: 6lib init -- create repository in current working directory 6lib add [<libs> ...] -- eagerly add libs to repository 6lib rm [<libs> ...] -- lazily remove libs from repository 6lib sync -- synchronize repository with indexed libs 6lib list -- list indexed libs 6lib prune -- lazily remove missing libs from index 6lib flush -- delete precompilation cache 6lib clear -- clear repository but keep index 6lib clobber -- remove repository 6lib -C <dir> [<command> ...] -- specify location of target repository ``` # Example Usage ``` perl6 -Ilib -I../other/lib script.p6 # equivalent call using a local repository 6lib init 6lib add . ../other perl6 -I.6lib script.p6 # equivalent call using a global repository export PERL6LIB=$HOME/.6lib 6lib -C $HOME init 6lib -C $HOME add . ../other perl6 script.p6 ``` # Description Modules are identified by their absolute paths. For each file in a module's `lib` subdirectory, a symbolic link is created in the `.6lib` repository. Paths to module directories are kept in an index file `.6lib/lib.list`. ### Warning When adding source files to a module's `lib` directory, you need to re-add the module or call `6lib sync` afterwards! # A Note on Windows Usage The creation of symbolic links in non-administrator mode is only permitted if *Developer mode* has been enabled. This can be done in Windows 10 in the settings under *Update & security* / *For developers*. # Bugs and Development Development happens at [GitHub](https://github.com/cygx/6lib). If you found a bug or have a feature request, use the [issue tracker](https://github.com/cygx/6lib/issues) over there. # Copyright and License Copyright (C) 2019 by cygx <[cygx@cpan.org](mailto:cygx@cpan.org)> Distributed under the [Boost Software License, Version 1.0](https://www.boost.org/LICENSE_1_0.txt)
## dist_zef-lizmat-P5getpwnam.md [![Actions Status](https://github.com/lizmat/P5getpwnam/workflows/test/badge.svg)](https://github.com/lizmat/P5getpwnam/actions) # NAME Raku port of Perl's getpwnam() and associated built-ins # SYNOPSIS ``` use P5getpwnam; say "logged in as {getlogin || '(unknown)'}"; my @result = getpwnam(~$*USER); ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `getpwnam` and associated built-ins as closely as possible in the Raku Programming Language. It exports: ``` endpwent getlogin getpwent getpwnam getpwuid setpwent ``` # ORIGINAL PERL DOCUMENTATION ``` getpwnam NAME getpwuid UID getpwent setpwent endpwent These routines are the same as their counterparts in the system C library. In list context, the return values from the various get routines are as follows: # 0 1 2 3 4 ( $name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell, $expire ) = getpw* # 5 6 7 8 9 (If the entry doesn't exist you get an empty list.) The exact meaning of the $gcos field varies but it usually contains the real name of the user (as opposed to the login name) and other information pertaining to the user. Beware, however, that in many system users are able to change this information and therefore it cannot be trusted and therefore the $gcos is tainted (see perlsec). The $passwd and $shell, user's encrypted password and login shell, are also tainted, for the same reason. In scalar context, you get the name, unless the function was a lookup by name, in which case you get the other thing, whatever it is. (If the entry doesn't exist you get the undefined value.) For example: $uid = getpwnam($name); $name = getpwuid($num); In getpw*() the fields $quota, $comment, and $expire are special in that they are unsupported on many systems. If the $quota is unsupported, it is an empty scalar. If it is supported, it usually encodes the disk quota. If the $comment field is unsupported, it is an empty scalar. If it is supported it usually encodes some administrative comment about the user. In some systems the $quota field may be $change or $age, fields that have to do with password aging. In some systems the $comment field may be $class. The $expire field, if present, encodes the expiration period of the account or the password. For the availability and the exact meaning of these fields in your system, please consult getpwnam(3) and your system's pwd.h file. You can also find out from within Perl what your $quota and $comment fields mean and whether you have the $expire field by using the "Config" module and the values "d_pwquota", "d_pwage", "d_pwchange", "d_pwcomment", and "d_pwexpire". Shadow password files are supported only if your vendor has implemented them in the intuitive fashion that calling the regular C library routines gets the shadow versions if you're running under privilege or if there exists the shadow(3) functions as found in System V (this includes Solaris and Linux). Those systems that implement a proprietary shadow password facility are unlikely to be supported. getlogin This implements the C library function of the same name, which on most systems returns the current login from /etc/utmp, if any. If it returns the empty string, use "getpwuid". $login = getlogin || getpwuid($<) || "Kilroy"; Do not consider "getlogin" for authentication: it is not as secure as "getpwuid". ``` # 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 [liz@raku.rocks](mailto:liz@raku.rocks) 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/P5getpwnam> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2020, 2021, 2023 Elizabeth Mattijsen Re-imagined from Perl as part of the CPAN Butterfly Plan. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-MELEZHIK-Tomty.md # Tomty Tomty - Raku Test Framework. # Install ``` zef install Tomty ``` # Build Status [![Build Status](https://travis-ci.org/melezhik/Tomty.svg?branch=master)](https://travis-ci.org/melezhik/Tomty) # Usage ``` 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 Sparrow6 scenario: ``` tomty --edit test-meta6-file-exist #!perl6 bash "test -f META6.json" ``` You can write more advanced tests, for example: ``` # Check if perl6.org is accessible tomty --edit test-perl6-org-alive #!perl6 http-ok("http://perl6.org"); # Check if META6.json file is a valid json tomty --edit test-meta6-is-valid-json #!perl6 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 Perl6 and technically speaking are plain Perl6 Hashes * Environment configuration files should be placed at `.tomty/conf` directory: `.tomty/env/config.pl6`: ``` { dbname => "products", dbhost => "localhost" } ``` When tomty runs it picks the `.tomty/env/config.pl6` 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}.pl6` file and refer to it through `--env=$env` parameter: ``` nano .tomty/env/config.prod.pl6 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 Perl6 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 ``` ## 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` 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. Usefull * `--verbose` Runs tests in verbose mode, print more details about every test * `--color` Run in color mode * `--list` List tests * `--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` Conditionally skip tagged tests: ``` tomty --skip=slow ``` You can skip over multiple tags, split by comma: ``` tomty --skip=slow,windows # skip slow or windows tests ``` * `--only` Conditionally run only tagged tests: ``` tomty --only=database ``` You can excute over multiple tags, split by comma: ``` tomty --only=database,frontend # execute only database or frontend tests ``` # 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_zef-lizmat-Rakudo-Cache.md [![Actions Status](https://github.com/lizmat/Rakudo-Cache/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Rakudo-Cache/actions) [![Actions Status](https://github.com/lizmat/Rakudo-Cache/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Rakudo-Cache/actions) [![Actions Status](https://github.com/lizmat/Rakudo-Cache/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/Rakudo-Cache/actions) # NAME Rakudo::Cache - maintain a local cache of Rakudo source # SYNOPSIS ``` use Rakudo::Cache; my $rc = Rakudo::Cache.new(:cache($io)) my @huh = $rc.update; ``` # DESCRIPTION The `Rakudo::Cache` distribution provides the logic to create lists of files according to a set of criteria of an installed Rakudo runtime. These lists of files can then be used by applications such as [`App::Rak`](https://raku.land/zef:lizmat/App::Rak) to easily perform targeted searches. It also provides a `update-rakudo-cache` script for easy updating, which should usually only be after a Rakudo update. It looks at the files in the "rakudo", "nqp","MoarVM" and "roast" repositories as installed inside the root of a Rakudo distribution. It performs the following heuristics on the files in these repositories: ## nqp Any path ending with `.nqp` or containing `/src/Raku/ast`. ## doc Any path ending in `.pod`, `.pod6`, `.rakudoc`, `.md`, `.txt`, `.rtf` or containing `/docs/` and being a text file, or any filename ending in just uppercase letters. ### raku Any path ending with `.rakumod`, `.raku`, `.p6`, or `/t/harness6`. ### perl Any path ending with `.pl`, `.pm`, or `/t/harness5`. ## c Any path ending with `.c`, `.h`, or `.cpp`. ## js Any path ending with `.js`. ## java Any path ending with `.java`. ## shell Any path ending with `.sh`, `.ps1`, `.bat`, or `.in`. ## yaml Any path ending with `.yml`. # SETUP METHODS ## new ``` my $rc = Rakudo::Cache.new; # cache at ~/.raku/cache my $rc = Rakudo::Cache.new(:cache($io)); # cache at $io my @huh = $rc.update; ``` The `new` method takes one optional named argument: `:cache`. It specifies the `IO::Path` object where the cache should be located. If not specified, will default to: * the RAKU\_RAKUDO\_CACHE environment variable * the subdirectory .raku/cache in $\*HOME * the subdirectory .raku/cache in $\*TMPDIR After instantion, the `IO::Path` used can be obtained by the `cache` method. ## update ``` my @huh = $rc.update; ``` The `update` method performs the update and returns a list of paths that could not be categorized using current semantics. # HELPER METHODS All helper method names start with "rakudo-" and return the `IO::Path` of the associated list of files. | method | description | | --- | --- | | rakudo-c | all C programming language related files | | rakudo-doc | all documentation files | | rakudo-java | all Java programming language related files | | rakudo-js | all Javascript programming language related files | | rakudo-nqp | all NQP related files | | rakudo-perl | all Perl programming language related files | | rakudo-raku | all Raku Programming Language related files | | rakudo-shell | all shell scripts / batch files | | rakudo-test | all testing related files | | rakudo-yaml | all files containing YAML of some sort | | rakudo-all | all of the above | # SCRIPTS ``` $ update-rakudo-cache Found 170 files that couldn't be categorized: .../rakudo/.gitattributes .../rakudo/.gitignore ... ``` The `update-rakudo-cache` script looks at the source files of the executable, updates the paths in the cache and shows the paths of the files that couldn't be interpreted. If you feel that a file is in this list that shouldn't be, please [create an issue for it](https://github.com/lizmat/Rakudo-Cache/issues/new). # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) Source can be located at: <https://github.com/lizmat/Rakudo-Cache> . 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.
## nil.md class Nil Absence of a value or a benign failure ```raku class Nil is Cool { } ``` The value `Nil` may be used to fill a spot where a value would normally go, and in so doing, explicitly indicate that no value is present. It may also be used as a cheaper and less explosive alternative to a [`Failure`](/type/Failure). (In fact, class [`Failure`](/type/Failure) is derived from `Nil`, so smartmatching `Nil` will also match [`Failure`](/type/Failure).) The class `Nil` is the same exact thing as its only possible value, `Nil`. ```raku say Nil === Nil.new; # OUTPUT: «True␤» ``` Along with [`Failure`](/type/Failure), `Nil` and its subclasses may always be returned from a routine even when the routine specifies a particular return type. It may also be returned regardless of the definedness of the return type, however, `Nil` is considered undefined for all other purposes. ```raku sub a( --> Int:D ) { return Nil } a().say; # OUTPUT: «Nil␤» ``` `Nil` is what is returned from empty routines or closure, or routines that use a bare `return` statement. ```raku sub a { }; a().say; # OUTPUT: «Nil␤» sub b { return }; b().say; # OUTPUT: «Nil␤» say (if 1 { }); # OUTPUT: «Nil␤» { ; }().say; # OUTPUT: «Nil␤» say EVAL ""; # OUTPUT: «Nil␤» ``` In a list, `Nil` takes the space of one value. Iterating `Nil` behaves like iteration of any non-iterable value, producing a sequence of one `Nil`. (When you need the other meaning, the special value [Empty](/type/Slip#constant_Empty) is available to take no spaces when inserted into list, and to return no values when iterated.) ```raku (1, Nil, 3).elems.say; # OUTPUT: «3␤» (for Nil { $_ }).raku.say; # OUTPUT: «(Nil,)␤» ``` Any method call on `Nil` of a method that does not exist, and consequently, any subscripting operation, will succeed and return `Nil`. ```raku say Nil.ITotallyJustMadeThisUp; # OUTPUT: «Nil␤» say (Nil)[100]; # OUTPUT: «Nil␤» say (Nil){100}; # OUTPUT: «Nil␤» ``` When assigned to a [container](/language/containers), the `Nil` value (but not any subclass of `Nil`) will attempt to revert the container to its default value; if no such default is declared, Raku assumes [`Any`](/type/Any). Since a hash assignment expects two elements, use `Empty` not `Nil`, e.g. ```raku my %h = 'a'..'b' Z=> 1..*; # stuff happens %h = Empty; # %h = Nil will generate an error ``` However, if the container type is constrained with `:D`, assigning `Nil` to it will immediately throw an exception. (In contrast, an instantiated [`Failure`](/type/Failure) matches `:D` because it's a definite value, but will fail to match the actual nominal type unless it happens to be a parent class of [`Failure`](/type/Failure).) Native types can not have default values nor hold a type object. Assigning `Nil` to a native type container will fail with a runtime error. ```raku my Int $x = 42; $x = Nil; $x.say; # OUTPUT: «(Int)␤» sub f( --> Int:D ){ Nil }; # this definedness constraint is ignored my Int:D $i = f; # this definedness constraint is not ignored, so throws CATCH { default { put .^name, ': ', .Str } }; # OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $y; expected Int but got Any (Any)» sub g( --> Int:D ){ fail "oops" }; # this definedness constraint is ignored my Any:D $h = g; # failure object matches Any:D, so is assigned ``` but ```raku my Int:D $j = g; # It will throw both exceptions: # Earlier failure: # oops # in sub g at <unknown file> line 1 # in block <unit> at <unknown file> line 1 # # Final error: # Type check failed in assignment to $j; expected Int:D but got Failure (Failure.new(exception...) # in block <unit> at <unknown file> line 1 ``` Because an untyped variable is type [`Any`](/type/Any), assigning a `Nil` to one will result in an [(Any)](/type/Any) type object. ```raku my $x = Nil; $x.say; # OUTPUT: «(Any)␤» my Int $y = $x; # will throw an exception CATCH { default { put .^name, ': ', .Str } }; # OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $y; expected Int but got Any (Any)␤» ``` If you are looking for a variable which transforms objects into type objects when said variable appears on the right-hand side, you can type the container as `Nil`. ```raku my Nil $x; my Str $s = $x; $s.say; # OUTPUT: «(Str)␤» ``` There is an important exception to this transforms-into-type-object rule: assigning `Nil` to a variable which has a default will restore that default. ```raku my Int $x is default(42) = -1; my $y = 1; for $x, $y -> $val is rw { $val = Nil unless $val > 0 } $x.say; # OUTPUT: «42␤» ``` Methods such as `BIND-POS`, `ASSIGN-KEY`, `ASSIGN-POS` will die; `BIND-KEY` will produce a failure with an [`X::Bind`](/type/X/Bind) exception in it, and `STORE` will produce an [`X::Assignment::RO`](/type/X/Assignment/RO) exception. # [Methods](#class_Nil "go to top of document")[§](#Methods "direct link") ## [method append](#class_Nil "go to top of document")[§](#method_append "direct link") ```raku method append(*@) ``` Warns the user that they tried to append onto a `Nil` (or derived type object). ## [method gist](#class_Nil "go to top of document")[§](#method_gist "direct link") ```raku method gist(--> Str:D) ``` Returns `"Nil"`. ## [method Str](#class_Nil "go to top of document")[§](#method_Str "direct link") ```raku method Str() ``` Warns the user that they tried to stringify a `Nil`. ## [method new](#class_Nil "go to top of document")[§](#method_new "direct link") ```raku method new(*@) ``` Returns `Nil` ## [method prepend](#class_Nil "go to top of document")[§](#method_prepend "direct link") ```raku method prepend(*@) ``` Warns the user that they tried to prepend onto a `Nil` or derived type object. ## [method push](#class_Nil "go to top of document")[§](#method_push "direct link") ```raku method push(*@) ``` Warns the user that they tried to push onto a `Nil` or derived type object. ## [method unshift](#class_Nil "go to top of document")[§](#method_unshift "direct link") ```raku method unshift(*@) ``` Warns the user that they tried to unshift onto a `Nil` or derived type object. ## [method ords](#class_Nil "go to top of document")[§](#method_ords "direct link") Returns an empty [`Seq`](/type/Seq), but will also issue a warning depending on the context it's used (for instance, a warning about using it in string context if used with `say`). ## [method chrs](#class_Nil "go to top of document")[§](#method_chrs "direct link") Will return `\0`, and also throw a warning. ## [method FALLBACK](#class_Nil "go to top of document")[§](#method_FALLBACK "direct link") ```raku method FALLBACK(| --> Nil) {} ``` The [fallback method](/language/typesystem#index-entry-FALLBACK_(method)) takes any arguments and always returns a `Nil`. ## [method Numeric](#class_Nil "go to top of document")[§](#method_Numeric "direct link") ```raku method Numeric() ``` Warns the user that they tried to numify a `Nil`. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Nil` raku-type-graph Nil Nil Cool Cool Nil->Cool Mu Mu Any Any Any->Mu Cool->Any Failure Failure Failure->Nil [Expand chart above](/assets/typegraphs/Nil.svg)
## dist_cpan-BDUGGAN-Log-Async.md # Log::Async Thread-safe asynchronous logging using supplies. [![SparrowCI](https://ci.sparrowhub.io/project/gh-bduggan-raku-log-async/badge)](https://ci.sparrowhub.io) # Synopsis ``` use Log::Async; logger.send-to($*OUT); trace 'how'; debug 'now'; warning 'brown'; info 'cow'; fatal 'ow'; (start debug 'one') .then({ debug 'two' }); (start debug 'buckle') .then({ debug 'my shoe' }); sleep 1; my $when = now + 1; for ^100 { Promise.at($when) .then({ debug "come together"}) .then({ debug "right now"}) .then({ debug "over me"}); } logger.send-to("/var/log/hal.errors", :level(ERROR)); error "I'm sorry Dave, I'm afraid I can't do that"; ``` # Description `Log::Async` provides asynchronous logging using the supply and tap semantics of Perl 6. Log messages are emitted asynchronously to a supply. Taps are only executed by one thread at a time. By default a single tap is created which prints the timestamp, level and message to stdout. # Exports **trace, debug, info, warning, error, fatal**: each of these asynchronously emits a message at that level. **enum Loglevels**: TRACE DEBUG INFO WARNING ERROR FATAL **class Log::Async**: Does the real work. **sub logger**: return or create a logger singleton. **sub set-logger**: set a new logger singleton. # Log::Async Methods ### add-tap(Code $code,:$level,:$msg) ``` my $tap = logger.add-tap({ say $^m<msg> ~ '!!!!!' }, :level(FATAL)); logger.add-tap({ $*ERR.say $^m<msg> }, :level(DEBUG | ERROR)); logger.add-tap({ say "# $^m<msg>"}, :level(* < ERROR) ); logger.add-tap({ say "meow: " ~ $^m<msg> }, :msg(rx/cat/)); logger.add-tap(-> $m { say "thread { $m<THREAD>.id } says $m<msg>" }); logger.add-tap(-> $m { say "$m<when> {$m<frame>.file} {$m<frame>.line} $m<level>: $m<msg>" }); logger.add-tap(-> $m { say "{ $m<when>.utc } ($m<level>) $m<msg>", :level(INFO..WARNING) }); ``` Add a tap, optionally filtering by the level or by the message. `$code` receives a hash with the keys `msg` (a string), `level` (a Loglevel), `when` (a DateTime), `THREAD` (the caller's $\*THREAD), `frame` (the current callframe), and possibly `ctx` (the context, see below). `$level` and `$msg` are filters: they will be smartmatched against the level and msg keys respectively. `add-tap` returns a tap, which can be sent to `remove-tap` to turn it off. ### remove-tap($tap) ``` logger.remove-tap($tap) ``` Closes and removes a tap. ### send-to(Str $filename, Code :$formatter, |args) ``` send-to(IO::Handle $handle) send-to(IO::Path $path) logger.send-to('/tmp/out.log'); logger.send-to('/tmp/out.log', :level( * >= ERROR)); logger.send-to('/tmp/out.log', formatter => -> $m, :$fh { $fh.say: "{$m<level>.lc}: $m<msg>" }); logger.send-to($*OUT, formatter => -> $m, :$fh { $fh.say: "{ $m<frame>.file } { $m<frame>.line } { $m<frame>.code.name }: $m<msg>" }); ``` Add a tap that prints timestamp, level and message to a file or filehandle. `formatter` is a Code argument which takes `$m` (see above), as well as the named argument `:$fh` -- an open filehandle for the destination. Additional args (filters) are sent to add-tap. ### close-taps ``` logger.close-taps ``` Close all the taps. ### done ``` logger.done ``` Tell the supplier it is done, then wait for the supply to be done. This is automatically called in the END phase. ### untapped-ok ``` logger.untapped-ok = True ``` This will suppress warnings about sending a log message before any taps are added. # Context To display stack trace information, logging can be initialized with `add-context`. This sends a stack trace with every log request (so may be expensive). Once `add-context` has been called, a `ctx` element will be passed which is a `Log::Async::Context` object. This has a `stack` method which returns an array of backtrace frames. ``` logger.add-context; logger.send-to('/var/log/debug.out', formatter => -> $m, :$fh { $fh.say: "file { $m<ctx>.file}, line { $m<ctx>.line }, message { $m<msg> }" } ); logger.send-to('/var/log/trace.out', formatter => -> $m, :$fh { $fh.say: $m<msg>; $fh.say: "file { .file}, line { .line }" for $m<ctx>.stack; } ); ``` A custom context object can be used as an argument to add-context. This object should have a `generate` method. `generate` will be called to generate context whenever a log message is sent. For instance: ``` my $context = Log::Async::Context.new but role { method generate { ... } method custom-method { ... } }; logger.add-context($context); # later logger.add-tap(-> $m { say $m.ctx.custom-method } ) ``` # More Examples ### Send debug messages to stdout. ``` logger.send-to($*OUT,:level(DEBUG)); ``` ### Send warnings, errors, and fatals to a log file. ``` logger.send-to('/var/log/error.log',:level(* >= WARNING)); ``` ### Add a tap that prints the file, line number, message, and utc timestamp. ``` logger.send-to($*OUT, formatter => -> $m, :$fh { $fh.say: "{ $m<when>.utc } ({ $m<frame>.file } +{ $m<frame>.line }) $m<level> $m<msg>" }); trace 'hi'; # output: 2017-02-20T14:00:00.961447Z (eg/out.raku +10) TRACE hi ``` # Caveats Because messages are emitted asynchronously, the order in which they are emitted depends on the scheduler. Taps are executed in the same order in which they are emitted. Therefore timestamps in the log might not be in chronological order. # Author Brian Duggan # Contributors Bahtiar Gadimov Curt Tilmes Marcel Timmerman Juan Julián Merelo Guervós Slobodan Mišković
## dist_zef-Scimon-Game-Sudoku.md [![Build Status](https://travis-ci.org/Scimon/p6-Game-Sudoku.svg?branch=master)](https://travis-ci.org/Scimon/p6-Game-Sudoku) # NAME Game::Sudoku - Store, validate and solve sudoku puzzles # SYNOPSIS ``` use Game::Sudoku; # Create an empty game my $game = Game::Sudoku.new(); # Set some cells $game.cell(0,0,1).cell(0,1,2); # Test the results $game.valid(); $game.full(); $game.complete(); # Get possible values for a cell $game.possible(0,2); ``` # DESCRIPTION Game::Sudoku is a simple library to store, test and attempt to solve sudoku puzzles. Currently the libray can be used as a basis for doing puzzles and can solve a number of them. I hope to add additional functionality to it in the future. The Game::Sudoku::Solver module includes documenation for using the solver. # METHODS ## new( Str :code -> Game::Sudoku ) The default constructor will accept and 81 character long string comprising of combinations of 0-9. This code can be got from an existing Game::Sudoku object by calling it's .Str method. ## valid( -> Bool ) Returns True if the sudoku game is potentially valid, IE noe row, colum or square has 2 of any number. A valid puzzle may not be complete. ## full( -> Bool ) Returns True if the sudoku game has all it's cells set to a non zero value. Note that the game may not be valid. ## complete( -> Bool ) Returns True is the sudoku game is both valid and full. ## possible( Int, Int, Bool :$set -> List ) Returns the sorted Sequence of numbers that can be put in the current cell. Note this performs a simple check of the row, column and square the cell is in it does not perform more complex logical checks. Returns an empty List if the cell already has a value set or if there are no possible values. If the optional :set parameter is passed then returns a Set of the values instead. ## cell( Int, Int -> Int ) ## cell( Int, Int, Int -> Game::Sudoku ) Getter / Setter for individual cells. The setter returns the updated game allowing for method chaining. Note that attempting to set a value defined in the constructor will not work, returning the unchanged game object. ## row( Int -> List(List) ) Returns the list of (x,y) co-ordinates in the given row. ## col( Int -> List(List) ) Returns the list of (x,y) co-ordinates in the given column. ## square( Int -> List(List) ) ## square( Int, Int -> List(List) ) Returns the list of (x,y) co-ordinates in the given square of the grid. A square can either be references by a cell within it or by it's index. ``` 0|1|2 ----- 3|4|5 ----- 6|7|8 ``` ## reset( Str :$code ) Resets the puzzle to the state given in the $code argument. If the previous states initial values are all contained in the new puzzle then they will not be updated. Otherwise the puzzle will be treated as a fresh one with the given state. # AUTHOR Simon Proctor [simon.proctor@gmail.com](mailto:simon.proctor@gmail.com) # COPYRIGHT AND LICENSE Copyright 2017 Simon Proctor This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-HYTHM-Grid_1.md # NAME Grid - Role for Arrays. # SYNOPSIS ``` use Grid; my @grid = < a b c d e f g h i j k l m n o p q r s t u v w x >; @grid does Grid[:4columns]; ``` # DESCRIPTION Grid is a `Role` that transforms an `Array` to `Array+{Grid}`, And provides additional methods (e.g flip, rotate, transpose). To flip a `Grid` horizontaly or vertically: ``` @grid.flip: :horizontal @grid.flip: :vertical ``` It is also possible to apply methods to a subgrid of `Grid`, provided a valid subgrid indices: ``` my @indices = 9, 10, 13, 14; @grid.flip: :vertical(@indices); # or my @vertical = 9, 10, 13, 14; @grid.flip: :@vertical;` ``` `Grid` preserves the overall shape, So some operations require `is-square` to be `True` for `Grid` (or Subgrid), otherwise fails and returns `self`. # EXAMPLES ### grid ``` @grid.grid; a b c d e f g h i j k l m n o p q r s t u v w x ``` ### flip ``` a b c d d c b a e f g h h g f e i j k l :horizontal l k j i m n o p -----------------> p o n m q r s t t s r q u v w x x w v u a b c d u v w x e f g h q r s t i j k l :vertical m n o p m n o p -----------------> i j k l q r s t e f g h u v w x a b c d a b c d a b c d e f g h e i m q i j k l :@diagonal f j n r m n o p -----------------> g k o s q r s t subgrid [ 4 ... 19 ] h l p t u v w x u v w x a b c d a b c d e f g h t p l h i j k l :@antidiagonal s o k g m n o p -----------------> r n j f q r s t [ 4 ... 19 ] q m i e u v w x u v w x a b c d a b c d e f g h e f g h i j k l :diagonal i j k l m n o p -----------------> m n o p q r s t q r s t u v w x u v w x # fails becuase Grid.is-square === False ``` ### rotate ``` a b c d e f g h u q m i e a i j k l :clockwise v r n j f b m n o p -----------------> w s o k g c q r s t x t p l h d u v w x a b c d a b c d e f g h e f g h i j k l :@anticlockwise i k o l m n o p -----------------> m j n p q r s t [ 9, 10, 13, 14 ] q r s t u v w x u v w x a b c d d a b c e f g h h e f g i j k l :right l i j k m n o p -----------------> p m n o q r s t t q r s u v w x x u v w a b c d c d a b e f g h g h e f i j k l :2left k l i j m n o p -----------------> o p m n q r s t s t q r u v w x w x u v a b c d m n o p e f g h q r s t i j k l :3down u v w x m n o p -----------------> a b c d q r s t e f g h u v w x i j k l a b c d e f g h e f g h i j k l i j k l :7up m n o p m n o p -----------------> q r s t q r s t u v w x u v w x a b c d ``` ### transpose ``` a b c d e f g h a e i m q u i j k l b f j n r v m n o p -----------------> c g k o s w q r s t d h l p t x u v w x a b c d a b c d e f g h e f g h i j k l :@indices i j n l m n o p -----------------> m k o p q r s t [ 9, 10, 13, 14 ] q r s t u v w x u v w x a b c d a b c d e f g h e f g h i j k l :@indices i j k l m n o p ----------------> m n o p q r s t [ 5, 6, 9, 10, 13, 14 ] q r s t u v w x u v w x # fails becuase Subgrid.is-square === False ``` ### append ``` a b c d a b c d e f g h e f g h i j k l :@rows i j k l m n o p -----------------> m n o p q r s t [ 0, 1, 2, 3 ] q r s t u v w x u v w x 0 1 2 3 a b c d a b c d 0 e f g h e f g h 1 i j k l :@columns i j k l 2 m n o p -----------------> m n o p 3 q r s t [ 0, 1, 2, 3, 4, 5 ] q r s t 4 u v w x u v w x 5 ``` ### prepend ``` a b c d 0 1 2 3 e f g h a b c d i j k l :@rows e f g h m n o p -----------------> i j k l q r s t [ 0, 1, 2, 3 ] m n o p u v w x q r s t u v w x a b c d 0 a b c d e f g h 1 e f g h i j k l :@columns 2 i j k l m n o p -----------------> 3 m n o p q r s t [ 0, 1, 2, 3, 4, 5 ] 4 q r s t u v w x 5 u v w x ``` ### pop ``` a b c d e f g h a b c d i j k l :2rows e f g h m n o p -----------------> i j k l q r s t m n o p u v w x a b c d a b c e f g h e f g i j k l :1columns i j k m n o p -----------------> m n o q r s t q r s u v w x u v w ``` ### shift ``` a b c d e f g h i j k l i j k l :2rows m n o p m n o p -----------------> q r s t q r s t u v w x u v w x a b c d d e f g h h i j k l :3columns l m n o p -----------------> p q r s t t u v w x x ``` # METHODS ### grid ``` method grid { ... } ``` Prints a `:$!columns` `Grid`. ### columns ``` method columns { ... } ``` Returns `Grid`'s columns count. ### rows ``` method columns { ... } ``` Returns `Grid`'s rows count. ### check ``` multi method check ( :@rows! --> Bool:D ) { ... } ``` Check if Rows can fit in `Grid`. ``` multi method check ( :@columns! --> Bool:D ) { ... } ``` Check if Columns can fit in `Grid`. ### reshape ``` method reshape ( Grid:D: Int :$columns! where * > 0 --> Grid:D ) { ... } ``` ### flip ``` multi method flip ( Grid:D: Int:D :$horizontal! --> Grid:D ) { ... } ``` Horizontal Flip. ``` multi method flip ( Grid:D: Int:D :$vertical! --> Grid:D ) { ... } ``` Verical Flip. ``` multi method flip ( Grid:D: Int:D :$diagonal! --> Grid:D ) { ... } ``` Diagonal Flip. ``` multi method flip ( Grid:D: Int:D :$antidiagonal! --> Grid:D ) { ... } ``` Anti-Diagonal Flip. ``` multi method flip ( Grid:D: :@horizontal! --> Grid:D ) { ... } ``` Horizontal Flip (Subgrid). ``` multi method flip ( Grid:D: :@vertical! --> Grid:D ) { ... } ``` Vertical Flip (Subgrid). ``` multi method flip ( Grid:D: :@diagonal! --> Grid:D ) { ... } ``` Diagonal Flip (Subgrid). ``` multi method flip ( Grid:D: :@antidiagonal! --> Grid:D ) { ... } ``` Anti-Diagonal Flip (Subgrid). ### rotate ``` multi method rotate ( Grid:D: Int:D :$left! --> Grid:D ) { ... } ``` Left Rotate. (Columns) ``` multi method rotate ( Grid:D: Int:D :$right! --> Grid:D ) { ... } ``` Right Rotate. (Columns) ``` multi method rotate ( Grid:D: Int:D :$up! --> Grid:D ) { ... } ``` Up Rotate. (Rows) ``` multi method rotate ( Grid:D: Int:D :$down! --> Grid:D ) { ... } ``` Up Rotate. (Rows) ``` multi method rotate ( Grid:D: Int:D :$clockwise! --> Grid:D ) { ... } ``` Clockwise Rotate. ``` multi method rotate ( Grid:D: Int:D :$anticlockwise! --> Grid:D ) { ... } ``` Anti-Clockwise Rotate. ``` multi method rotate ( Grid:D: :@clockwise! --> Grid:D ) { ... } ``` Clockwise Rotate (Subgrid) ``` multi method rotate ( Grid:D: :@anticlockwise! --> Grid:D ) { ... } ``` Clockwise Rotate (Subgrid) ### transpose ``` multi method transpose ( Grid:D: --> Grid:D ) { ... } ``` Transpose. ``` multi method transpose ( Grid:D: :@indices! --> Grid:D ) { ... } ``` Transpose (Subgrid) ### append ``` multi method append ( Grid:D: :@rows! --> Grid:D ) { ... } ``` Append Rows. ``` multi method append ( Grid:D: :@columns! --> Grid:D ) { ... } ``` Append Columns. ### Prepend ``` multi method prepend ( Grid:D: :@rows! --> Grid:D ) { ``` Prepend Rows. ``` multi method prepend ( Grid:D: :@columns! --> Grid:D ) { ... } ``` Prepend Columns. ### push ``` multi method push ( Grid:D: :@rows! --> Grid:D ) { ... } ``` Push Rows. ``` multi method push ( Grid:D: :@columns! --> Grid:D ) { ``` Push Columns. ### pop ``` multi method pop ( Grid:D: Int :$rows! --> Grid:D ) { ... } ``` Pop Rows. ``` multi method pop ( Grid:D: Int :$columns! --> Grid:D ) { ... } ``` Pop Columns. ### shift ``` multi method shift ( Grid:D: Int :$rows! --> Grid:D ) { ... } ``` Shift Rows. ``` multi method shift ( Grid:D: Int :$columns! --> Grid:D ) { ... } ``` Shift Columns. ### unshift ``` multi method unshift ( Grid:D: :@rows! --> Grid:D ) { ... } ``` Unshift Rows. ``` multi method unshift ( Grid:D: :@columns! --> Grid:D ) { ``` Unshift Columns. ### has-subgrid ``` method has-subgrid( :@indices!, :$square = False --> Bool:D ) { ... } ``` Returns `True` if `:@indices` is a subgrid of `Grid`, `False` otherwise. ### is-square ``` method is-square ( --> Bool:D ) { ... } ``` Returns `True` if `Grid` is a square, False otherwise. # AUTHOR Haytham Elganiny [elganiny.haytham@gmail.com](mailto:elganiny.haytham@gmail.com) # COPYRIGHT AND LICENSE Copyright 2019 Haytham Elganiny This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-HANENKAMP-ModelDB.md # NAME ModelDB - an MVP ORM # SYNOPSIS ``` use DBIish; use ModelDB; module Model { use ModelDB::ModelBuilder; model Person { has Int $.person-id is column is primary; has Str $.name is column is rw has Int $.age is column is rw; has Str $.favorite-color is column is rw; } model Pet { has Str $.pet-id is column is primary; has Str $.name is column is rw; has Str $.animal is column is rw; } } class Schema is ModelDB::Schema { use ModelDB::SchemaBuilder; has ModelDB::Table[Person] $.persons is table; has ModelDB::Table[Pet] $.pets is table; } my $dbh = DBIish.connect('SQLite', :database<db.sqlite3>); my $schema = Schema.new(:$dbh); my $person = $schema.persons.create(%( name => 'Steve', age => 9, favorite-color => 'cyan', )); $person.name = 'Alex'; $person.age = 4; $person.favorite-color = 'green'; $schema.persons.update($person); my $by-id = $schema.pets.find(pet-id(1)); my @cats = $schema.pets.search(:animal<cat>).all; ``` # DESCRIPTION This is a minimalist object relational mapping tool. It helps with mapping your database objects into Perl from an RDBMS. I am experimenting with this API to see what I can learn about RDBMS patterns, problems, and specific issues as related to Perl 6. As such, this is highly experimental and I make no promises as regards the API. Though, I do use it in some production-ish code, so I don't want to change too much too fast. My intent, though, is to use what I learn here to build a different library in a different namespace that does what I really want based on what I learn here. My goals include: # over Pod::Defn<140403348404624> Pod::Defn<140403348404568> Pod::Defn<140403332796200> Pod::Defn<140403332796256> Pod::Defn<140403332796312> # back Performance and multiple RDBMS support are anti-goals. This will likely only support MySQL (and forks) and SQLite because that's what I care about. I do not plan to make performance improvements unless required and I especially do not intend to add any optimizations that harm code readability of even the internals unless required.
## dist_cpan-SAMCV-Git-Log.md # NAME Git::Log # AUTHOR Samantha McVey (samcv) [samantham@posteo.net](mailto:samantham@posteo.net) # SYNOPSIS Gets the git log as a Perl 6 object # DESCRIPTION The first argument is the command line args wanted to be passed into `git log`. Optionally you can also get the files changes as well as the number of lines added or deleted. Returns an array of hashes in the following format: `ID => "df0c229ad6ba293c67724379bcd3d55af6ea47a0", AuthorName => "Author's Name", AuthorEmail => "sample.email@not-a.url" ...` If the option :get-changes is used (off by default) it will also add a 'changes' key in the following format: `changes => { $[ { filename => 'myfile.txt', added => 10, deleted => 5 }, ... ] }` If there is a field that you need that is not offered, then you can supply an array, :@fields. Format is an array of pairs: `ID => '%H', AuthorName => '%an' ...` you can look for more [here](https://git-scm.com/docs/pretty-formats). These are the default fields: ``` my @fields-default = 'ID' => '%H', 'AuthorName' => '%an', 'AuthorEmail' => '%ae', 'AuthorDate' => '%aI', 'Subject' => '%s', 'Body' => '%b' ; ``` # EXAMPLES ``` # Gets the git log for the specified repository, from versions 2018.06 to master git-log(:path($path.IO), '2018.06..master') # Gets the git log for the current directory, and does I<not> get the files # changed in that commit git-log(:!get-changes) ``` # LICENSE This is free software; you can redistribute it and/or modify it under the Artistic License 2.0. ### sub git-log ``` sub git-log( *@args, :@fields = { ... }, IO::Path :$path, Bool:D :$get-changes = Bool::False, Bool:D :$date-time = Bool::False ) returns Mu ``` git-log's first argument is an array that is passed to C and optionally you can provide a path so a directory other than the current are used.
## take.md role CX::Take Take control exception ```raku role CX::Take does X::Control { } ``` A [control exception](/language/exceptions#Control_exceptions) triggered by `take`. # [Methods](#role_CX::Take "go to top of document")[§](#Methods "direct link") ## [method message](#role_CX::Take "go to top of document")[§](#method_message "direct link") ```raku method message() ``` Returns `'<take control exception>'`.
## dist_zef-slid1amo2n3e4-App-MoarVM-Debug.md Fork of <https://github.com/raku-community-modules/App-MoarVM-Debug> ## Usage Start the debugger: ``` $ mv2d main.raku ``` Set a breakpoint on line 42: ``` > bp main.raku 42 ``` Then type resume to resume the thread to hit it: ``` > resume ``` Type `help` to see all of the commands. ## Known Issues The only stepping mode currently available is Step Into. Backtraces will show incorrect line numbers. Source can be located at: <https://github.com/slid1amo2n3e4/mv2d>. Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2017 - 2020 Edument AB Copyright 2024 The Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-SEGOMOS-fez.md # zef ecosystem - cli ## fez fez is the command line tool used to manage your ecosystem user/pass. * [current functionality](#current-functionality) * [module management](#module-management) * [plugins](#plugins) * [faq](#faq) * [articles-about-fez](#articles-about-fez) * [license](#license) * [authors](#authors) ### 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: xyz@abc.com >>= 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 ``` ### checkbuild This is the check fez runs when you run `fez upload` ``` $ fez checkbuild >>= Inspecting ./META6.json >>= meta<provides> looks OK >>= meta<resources> looks OK >>= fez:ver<11>:auth<zef:tony-o> looks OK ``` -or if you have errors- ``` $ fez checkbuild >>= Inspecting ./META6.json >>= meta<provides> looks OK =<< File "resources/config.json" in dir not found in meta<resources> >>= fez:ver<11>:auth<zef:tony-o> could use some sprucing up ``` 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 git archive 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 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)
## last.md role CX::Last Last control exception ```raku role CX::Last does X::Control { } ``` A [control exception](/language/exceptions#Control_exceptions) that is thrown when `last` is called. # [Methods](#role_CX::Last "go to top of document")[§](#Methods "direct link") ## [method message](#role_CX::Last "go to top of document")[§](#method_message "direct link") ```raku method message() ``` Returns `'<last control exception>'`. Since this type of exception is to be consumed by type and not really by the content of the message, this is a generic message, similar to all other `CX::*` exceptions.
## dist_zef-lizmat-P5unlink.md [![Actions Status](https://github.com/lizmat/P5unlink/actions/workflows/test.yml/badge.svg)](https://github.com/lizmat/P5unlink/actions) # NAME Raku port of Perl's unlink() built-in # SYNOPSIS ``` use P5unlink; say unlink("foobar"); # 1 if successful, 0 if not with "foobar" { say unlink; # 1 if succesful, 0 if not } say unlink(@paths); # number of files removed ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `unlink` built-in as closely as possible in the Raku Programming Language. # ORIGINAL PERL DOCUMENTATION ``` unlink LIST unlink Deletes a list of files. On success, it returns the number of files it successfully deleted. On failure, it returns false and sets $! (errno): my $unlinked = unlink 'a', 'b', 'c'; unlink @goners; unlink glob "*.bak"; On error, "unlink" will not tell you which files it could not remove. If you want to know which files you could not remove, try them one at a time: foreach my $file ( @goners ) { unlink $file or warn "Could not unlink $file: $!"; } Note: "unlink" will not attempt to delete directories unless you are superuser and the -U flag is supplied to Perl. Even if these conditions are met, be warned that unlinking a directory can inflict damage on your filesystem. Finally, using "unlink" on directories is not supported on many operating systems. Use "rmdir" instead. If LIST is omitted, "unlink" uses $_. ``` # PORTING CAVEATS ## removing directories *not* supported As the original documents indicate, use `rmdir` instead. ## $\_ 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: ``` unlink; ``` to either: ``` unlink($_); ``` or, using the subroutine as a method syntax, with the prefix `.` shortcut to use that scope's `$_` as the invocant: ``` .&unlink; ``` # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) 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/P5unlink> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2023 Elizabeth Mattijsen Re-imagined from Perl as part of the CPAN Butterfly Plan. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-jonathanstowe-Tinky-Declare.md # Tinky::Declare Declarative creation of Tinky machines ![Build Status](https://github.com/jonathanstowe/Tinky-Declare/workflows/CI/badge.svg) ## Synopsis This is the functional equivalent to the [Tinky synopsis](https://github.com/jonathanstowe/Tinky/blob/master/README.md#synopsis): ``` use Tinky; use Tinky::Declare; class Ticket does Tinky::Object { has Str $.ticket-number = (^100000).pick.fmt("%08d"); has Str $.owner; } my $workflow = workflow 'ticket-workflow', { initial-state 'new'; workflow-state 'new'; workflow-state 'open'; workflow-transition 'open', 'new', 'open'; workflow-state 'rejected' , { on-enter -> $object { say "** sending rejected e-mail for Ticket '{ $object.ticket-number }' **"; } } workflow-transition 'reject', 'new', 'rejected'; workflow-transition 'reject', 'open','rejected'; workflow-transition 'reject', 'stalled','rejected'; workflow-state 'in-progress'; workflow-state 'stalled'; workflow-transition 'stall', 'open', 'stalled'; workflow-transition 'stall', 'in-progress', 'stalled', { on-apply-transition -> $object { say "** rescheduling tickets for '{ $object.owner }' on ticket stall **"; } } workflow-state 'completed'; workflow-transition 'unstall', 'stalled', 'in-progress'; workflow-transition 'take', 'open', 'in-progress'; workflow-transition 'complete', 'open', 'complete'; workflow-transition 'complete', 'in-progress', 'complete'; on-transition -> ( $transition, $object ) { say "Ticket '{ $object.ticket-number }' went from { $transition.from.name }' to '{ $transition.to.name }'"; } on-final-state -> ( $state, $object) { say "** updating performance stats with Ticket '{ $object.ticket-number }' entered State '{ $state.name }'" } }; my $ticket-a = Ticket.new(owner => "Operator A"); $ticket-a.apply-workflow($workflow); $ticket-a.open; $ticket-a.take; $ticket-a.next-states>>.name.say; $ticket-a.state = $workflow.state('stalled'); $ticket-a.reject; ``` There are further [examples in the distribution](examples). ## Description This provides a declarative interface to create [Tinky](https://github.com/jonathanstowe/Tinky) 'workflow' objects. You probably want to familiarise yourself with the [Tinky documentation](https://github.com/jonathanstowe/Tinky/blob/master/Documentation.md) to get an idea of what is going on under the hood. Essentially it creates a small DSL that allows you to create a [Tinky::Workflow](https://github.com/jonathanstowe/Tinky/blob/master/Documentation.md#class-tinkyworkflow) populated with the [State](https://github.com/jonathanstowe/Tinky/blob/master/Documentation.md#class-tinkystate) and [Transition](https://github.com/jonathanstowe/Tinky/blob/master/Documentation.md#class-tinkystate) objects that describe the workflow. Because the underlying objects are created for you only those features of Tinky that don't require sub-classing are exposed, such as tapping the supplies for leaving and entering a state (or all states,) the application of a transition (or all transitions,) and application of the workflow to an object, as well as [validation callbacks](https://github.com/jonathanstowe/Tinky/blob/master/Documentation.md#subset-validatecallback) for all of those events. The full documentation is [in the distribution](Documentation.md). ## Installation Assuming that you have a working installation of Rakudo you should be able to install this with *zef* : ``` zef install Tinky::Declare # Or from a checkout of this repository zef install . ``` ## Support Hopefully this will prove useful, if only as an inspiration to make something better. Please post any suggestions/fixes/patches at [Github](https://github.com/jonathanstowe/Tinky-Declare/issues) ## Licence & Copyright This is free software. Please see <LICENCE> for the details. © Jonathan Stowe 2021
## dist_zef-jonathanstowe-Audio-Encode-LameMP3.md # Audio-Encode-LameMP3 Encode PCM Audio data to MP3 in Raku using a binding to liblame ![Build Status](https://github.com/jonathanstowe/Audio-Encode-LameMP3/workflows/CI/badge.svg) ## Description This module provides a simple binding to "lame" an MP3 encoding library. <http://lame.sourceforge.net/> With this you can encode PCM data to MP3 at any bitrate or quality supported by the lame library. The interface is somewhat simplified in comparison to that of lame and some of the esoteric or rarely used features may not be supported. Because marshalling large arrays and buffers between Raku space and the native world may be too slow for some use cases the interface provides for passing and returning native CArrays (and their sizes) for the use of other native bindings (e.g. Audio::Sndfile, Audio::Libshout) where speed may prove important, which , for me at least, is quite a common use-case. The 'raku-lame-encode' example demonstrates this way of using the interface. For interest the first thing I encoded was: <https://soundcloud.com/rabidgravy/udy-ryu-rabid-gravy-revolutionary-suicide-mix> which is a remix I made of a track by the lovely Aaron Udy. ## Installation You will need to have "lame" installed on your system in order to be able to use this. Most Linux distributions offer it as a package, but because there are certain patent issues surrounding the MP3 codec some distributions may either have it in an optional repository or not have it at all. If you are on some platform that doesn't provide lame as a package then you may be able to install it from source: <http://lame.sourceforge.net/> I am however unlikely to be able to offer help with installing it this way, also bear in mind that if you install a newer version than I have to test with then this may not work. Assuming you have a working Rakudo installation you should be able to install this with *zef* : ``` # From the source directory zef install . # Remote installation zef install Audio::Encode-LameMP3 ``` The tests take a little longer than I would like largely because there's quite a lot of file I/O involved. ## Support Suggestions/patches are welcomed via github at <https://github.com/jonathanstowe/Audio-Encode-LameMP3> I have tested this and found it to work with my installation of libmp3lame so it should work anywhere else the library is installed, if however you experience a problem with the encoding, please test with the 'lame' binary that is installed with libmp3lame before reporting a bug. Obviously because the actual encoding is done by the native library, I'm not able to comment on the perceived quality or otherwise of the results. ## Licence This library only binds to a "lame" installation you may have on your system, any licensing issues regarding the MP3 codec relate to the implementation of the codec and I cannot answer questions related to the licensing of that library. Please see the <LICENCE> file in the distribution regarding the licence for this library module. © Jonathan Stowe 2015 - 2021
## dist_zef-elcaro-Slang-Otherwise.md # NAME Slang::Otherwise - Slang to add 'otherwise' block to 'for' loops # SYNOPSIS This slang adds syntax for an `otherwise` block that will run if the for loop is not entered. ``` use Slang::Otherwise; for dir.grep(*.basename.contains: 'xyx') -> $f { say "Found $f" } otherwise { say 'Got nothing' } ``` # CREDITS & NOTES This code is shamelessly taken from a [blog post by Damian Conway](https://blogs.perl.org/users/damian_conway/2019/09/itchscratch.html). Damian's slang called the block `else`, but the post spawned some discussion about whether that is a good name, also taking into consideration that Python's `for`/`else` does something entirely different. In [commenting on the article](https://www.reddit.com/r/perl6/comments/d5u1mv/itchscratch_damian_conway/), several people suggested `otherwise`, which is a good a name as any. # LICENCE ``` The Artistic License 2.0 ``` See LICENSE file in the repository for the full license text.
## dist_zef-japhb-MUGS-UI-CLI.md [![Actions Status](https://github.com/Raku-MUGS/MUGS-UI-CLI/workflows/test/badge.svg)](https://github.com/Raku-MUGS/MUGS-UI-CLI/actions) # NAME MUGS-UI-CLI - CLI UI for MUGS, including App and game UIs # SYNOPSIS ``` # Set up a full-stack MUGS-UI-CLI development environment mkdir MUGS cd MUGS git clone git@github.com:Raku-MUGS/MUGS-Core.git git clone git@github.com:Raku-MUGS/MUGS-Games.git git clone git@github.com:Raku-MUGS/MUGS-UI-CLI.git cd MUGS-Core zef install --exclude="pq:ver<5>:from<native>" . mugs-admin create-universe cd ../MUGS-Games zef install . cd ../MUGS-UI-CLI zef install --deps-only . # Or skip --deps-only if you prefer ### LOCAL PLAY # Play games using a local CLI UI, using an internal stub server and ephemeral data mugs-cli # Play games using an internal stub server accessing the long-lived data set mugs-cli --universe=<universe-name> # 'default' if set up as above # Log in and play games on a WebSocket server using a local CLI UI mugs-cli --server=<host>:<port> ### GAME SERVERS # Start a TLS WebSocket game server on localhost:10000 using fake certs mugs-ws-server # Specify a different MUGS identity universe (defaults to "default") mugs-ws-server --universe=other-universe # Start a TLS WebSocket game server on different host:port mugs-ws-server --host=<hostname> --port=<portnumber> # Start a TLS WebSocket game server using custom certs mugs-ws-server --private-key-file=<path> --certificate-file=<path> # Write a Log::Timeline JSON log for the WebSocket server LOG_TIMELINE_JSON_LINES=log/mugs-ws-server mugs-ws-server ``` # DESCRIPTION **NOTE: See the [top-level MUGS repo](https://github.com/Raku-MUGS/MUGS) for more info.** MUGS::UI::CLI is a CLI app (`mugs-cli`) and a set of UI plugins to play each of the games in [MUGS-Core](https://github.com/Raku-MUGS/MUGS-Core) and [MUGS-Games](https://github.com/Raku-MUGS/MUGS-Games) via the CLI. This Proof-of-Concept release only contains very simple turn-based guessing and interactive fiction games, plus a simple lobby for creating identities and choosing games to play. Future releases will include many more games and genres, plus better handling of asynchronous events such as inter-player messaging. # 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 [gjb@sonic.net](mailto:gjb@sonic.net) (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_cpan-JMASLAK-Sys-HostAddr.md [![Build Status](https://travis-ci.org/jmaslak/Raku-Sys-HostAddr.svg?branch=master)](https://travis-ci.org/jmaslak/Raku-Sys-HostAddr) # NAME Sys::Domainname - Get IP address information about this host # SYNOPSIS ``` use Sys::Domainname; my $sysaddr = Sys::HostAddr.new; my $string = $sysaddr->public; my @addresses = $sysaddr->addresses; my @interfaces = $sysaddr->interfaces; my @on-int-addresses = $sysaddr->addresses-on-interface('eth0'); ``` # DESCRIPTION This module provides methods for determining IP address information about a local host. # WARNING This module only functions on relatively recent Linux. # ATTRIBUTES ## ipv This attribute refers to the IP Version the class operates against. It must be set to either `4` or `6`. This defaults to `4`. ## ipv4-url This is the API URL used to obtain the host's public IPv4 address. It defaults to using `https://api.ipify.org`. The URL must return the address as a plain text response. ## ipv6-url This is the API URL used to obtain the host's public IPv4 address. It defaults to using `https://api6.ipify.org`. The URL must return the address as a plain text response. ## user-agent This is the user agent string used to idenfiy this module when making web calls. It defaults to this module's name and version. ## filter-localhost If `filter-localhost` is true, only non-localhost addresses will be returned by this class's methods. This defaults to true. Localhost is defined as any IPv4 address that begins with `127.` or the IPv6 address `::1`. ## filter-link-local If `filter-link-local` is true, only non-link-local addresses will be returned by this class's methods. This defaults to true and has no impact when `ipv` is set to `4`. Link local is defined as any IPv4 address that belong to `fe80::/10`. # METHODS ## public(-->Str:D) ``` my $ha = Sys::HostAddr.new; say "My public IP: { $ha.public }"; ``` Returns the public IP address used by this host, as determined by contacting an external web service. When the `ipv` property is set to `6`, this may return an IPv4 address if the API endpoint is not reachable via IPv6. ## interfaces(-->Seq:D) ``` my $ha = Sys::HostAddr.new; @interfaces = $ha.interfaces.list; ``` Returns the interface names for the interfaces on the system. Note that all interfaces available to the `ip` command will be returned, even if they do not have IP addresses assigned. If the `ip` command cannot be executed (for instance, on Windows), this will return a sequene with no members. ## addresses(-->Seq:D) ``` my $ha = Sys::HostAddr.new; @addresses = $ha.addresses.list; ``` Returns the addresses on the system. If the `ip` command cannot be executed (for instance, on Windows), this will return a sequene with no members. ## addresses-on-interface(Str:D $interface -->Seq:D) ``` my $ha = Sys::HostAddr.new; @addresses = $ha.addresses-on-interface("eth1").list; ``` Returns the addresses on the interface provided. If the `ip` command cannot be executed (for instance, on Windows), this will return a sequene with no members. ## guess-ip-for-host(Str:D $ip -->Str) ``` my $ha = Sys::HostAddr.new; $address = $ha.guess-ip-for-host('192.0.2.1'); ``` Returns an address associated with the interface used to route packets to the given destination. Where more than one address exists on that interface, or more than one interface has a route to the given host, only one will be returned. This will return `Str` (undefined type object) if either the host isn't routed in the routing table or if the `ip` command cannot be executed (for instance, on Windows). ## guess-main(-->Str) ``` my $ha = Sys::HostAddr.new; $address = $ha.guess-main-for-ipv4 ``` Returns the result of either `.guess-ip-for-host('0.0.0.0')` or `.guess-ip-for-host('2000::')` depending on the value of `$.ipv4`. ## guess-main-for-ipv6(-->Str) ``` my $ha = Sys::HostAddr.new; $address = $ha.guess-main-for-ipv6 ``` Returns the result of `.guess-ip-for-host('2000::')`. # AUTHOR Joelle Maslak [jmaslak@antelope.net](mailto:jmaslak@antelope.net) Inspired by Perl 5 `Sys::Hostname` by Jeremy Kiester. # 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.
## dist_cpan-BDUGGAN-Digest-SHA1-Native.md # Digest::SHA1::Native Fast SHA1 computation using NativeCall to C. # Synopsis ``` use Digest::SHA1::Native; say sha1-hex("The quick brown fox jumps over the lazy dog"); say sha1-hex("The quick brown fox jumps over the lazy dog".encode); say sha1("The quick brown fox jumps over the lazy dog")».fmt('%02x').join; ``` ``` 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12 ``` # Description `sha1-hex` accepts a string or bytes (a Buf or Blob) and returns a hex string. `sha1` converts the hex into binary (i.e. it returns a Blob). # Examples From <https://en.wikipedia.org/wiki/Hash-based_message_authentication_code#Examples>: ``` use Digest::HMAC; use Digest::SHA1::Native; say hmac-hex("key","The quick brown fox jumps over the lazy dog",&sha1); ``` `de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9`
## dist_zef-jonathanstowe-Lumberjack-Dispatcher-EventSource.md # Lumberjack::Dispatcher::EventSource A Dispatcher for Lumberjack that emits the log messages as server sent events ![Build Status](https://github.com/jonathanstowe/Lumberjack-Dispatcher-EventSource/workflows/CI/badge.svg) ## Synopsis ``` use Lumberjack; use Lumberjack::Dispatcher::EventSource; use Cro::HTTP::Router; use Cro::HTTP::Server; my $dispatcher = Lumberjack::Dispatcher::EventSource.new Lumberjack.dispatchers.append: $dispatcher; my $app = route { get -> { content 'text/event-stream', $dispatcher.Supply; } }; my Cro::Service $log = Cro::HTTP::Server.new(:host<localhost>, :port<7798>, application => $app); $log.start; react whenever signal(SIGINT) { $log.stop; exit; } ``` There is a slightly more comprehensive example in the <examples> directory. ## Description This is a [Lumberjack::Dispatcher](https://github.com/jonathanstowe/Lumberjack/blob/master/Documentation.md#lumberjackdispatcher) implementation that emits the log messages as JSON (as formatted by `Lumberjack::Message::JSON`,) on a supply in the format of [Server Sent Events](https://www.w3.org/TR/eventsource/). The `Supply` can be passed as a response to a web toolkit that supports chunked encoding such as `Cro` or `Crust`. This may be useful if you want to expose your logging to the web or to some log archiver or something. The exact format of the JSON emitted is documented by [Lumberjack::Message::JSON](https://github.com/jonathanstowe/Lumberjack-Message-JSON) ## Installation Assuming you have a working Rakudo installation then you can install this with *zef* : ``` zef install Lumberjack::Dispatcher::EventSource ``` ## Support This is a very simple module, really just the composition of some existing things, so it's most likely that if there are bugs they are in `EventSource::Server` or `Lumberjack::Message::JSON` However please feel free to report any issues/suggestions/whatever at [Github](https://github.com/jonathanstowe/Lumberjack-Dispatcher-EventSource/issues). ## Licence and Copyright This is free software, please see the <LICENCE> file in the distribution for more details. © Jonathan Stowe 2021-
## dist_zef-jonathanstowe-Cro-HTTP-BodySerializerJSONClass.md # Cro::HTTP::BodySerializerJSONClass A Cro::HTTP::BodySerializer that knows about JSON::Class objects ![Build Status](https://github.com/jonathanstowe/cro-http-bodyserializerjsonclass/workflows/CI/badge.svg) ## Synopsis ``` use Cro::HTTP::Router; use Cro::HTTP::Server; use JSON::Class; use Cro::HTTP::BodySerializerJSONClass; class Foo does JSON::Class { has DateTime $.date is marshalled-by('Str') = DateTime.now; } my $app = route { get -> { content 'application/json', Foo.new; } }; my Cro::Service $service = Cro::HTTP::Server.new( host => 'localhost', port => 7798, application => $app, add-body-serializers => [ Cro::HTTP::BodySerializerJSONClass] ); $service.start; react whenever signal(SIGINT) { $service.stop; exit; } ``` ## Description This provides a body serializer for `Cro::HTTP` that allows you to pass an object that does `JSON::Class` as an `application/json` response body. It simply needs to be added to the body serializers with the `add-body-serializers` parameter to the constructor of the `Cro::HTTP::Server`. Similarly it can be used to serialize a request body of a `Cro::HTTP::Client` if the `add-body-serializers` is provided to the constructor of `Cro::HTTP::Client`. It might simplify programme design by using, for example, existing objects as the response to a web request. ## Installation Assuming you have a working Rakudo installation you should be able to install this with *zef* : ``` zef install Cro::HTTP::BodySerializerJSONClass ``` ## Support Please feel free to post suggestions/patches/etc at [Github](https://github.com/jonathanstowe/cro-http-bodyserializerjsonclass/issues). ## Licence & Copyright This library is free software. Please see the <LICENCE> file in the distribution. © Jonathan Stowe 2021
## dist_zef-raku-community-modules-IRC-Utils.md [![Actions Status](https://github.com/raku-community-modules/IRC-Utils/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/IRC-Utils/actions) # NAME IRC::Utils - handy IRC utilities for use in other IRC-related modules # SYNOPSIS ``` use IRC::Utils; my Str $nick = '[foo]^BAR^[baz]'; my Str $uc_nick = uc_irc($nick); my Str $lc_nick = lc_irc($nick); # Check equivalence of two nicknames if eq_irc($uc_nick, $lc_nick) { say "These nicknames are the same!"; } # Check if nickname conforms to RFC1459 if is_valid_nick_name($nick) { say "Nickname is valid!"; } ``` # DESCRIPTION The `IRC::Utils` module provides a procedural interface for performing many common IRC-related tasks such as comparing nicknames, changing user modes, normalizing ban masks, etc. It is meant to be used as a base module for creating other IRC-related modules. Internet Relay Chat (IRC) is a teleconferencing system used for real-time Internet chatting and conferencing. It is primarily used for group communication but also allows private one-to-one messages. The protocol is published in RFC 1459 <https://www.rfc-editor.org/rfc/rfc1459.txt>. # SUBROUTINES Unlike the `IRC::Utils` module for Perl 5, you do not need to specify the `:ALL` tag when importing the module. Therefore, the following subroutines are exported into the caller's namespace by default. ## uc\_irc(Str $value, Str $type?) Converts a string to uppercase that conforms to the allowable characters as defined by RFC 1459. The `$value` parameter represents the string to convert to uppercase. The `$type` parameter is an optional string that represents `$value`'s casemapping. It can be 'rfc1459', 'strict-rfc1459', or 'ascii'. If not given, it defaults to 'rfc1459'. Returns the value of `$value` converted to uppercase according to `$type`. Example: ``` my Str $uc_hello = uc_irc('Hello world!'); say $hello; # Output: HELLO WORLD! ``` -head2 lc\_irc(Str $value, Str $type?) Converts a string to lowercase that conforms to the allowable characters as defined by RFC 1459. The `$value` parameter represents the string to convert to lowercase. The `$type` parameter is an optional string that represents `$value`'s casemapping. It can be 'rfc1459', 'strict-rfc1459', or 'ascii'. If not given, it defaults to 'rfc1459'. Returns the value of `$value` converted to lowercase according to `$type`. Example: ``` my Str $lc_hello = lc_irc('HELLO WORLD!'); say $lc_irc; # Output: hello world! ``` ## eq\_irc(Str $first, Str $second, Str $type?) Checks the equivalence of two strings that conform to the allowable characters as defined by RFC 1459. The `$first` parameter is the first string to compare. The `$second` parameter is the second string to compare. The `$type` parameter is an optional string that represents the casemapping of `$first` and `$second`. It can be 'rfc1459', 'strict-rfc1459', or 'ascii'. If not given, it defaults to 'rfc1459'. Returns `Bool::True` if the two strings are equivalent and `Bool::False` otherwise. Example: ``` my Str $upper = '[F00~B4R~B4Z]'; my Str $lower = '{f00~b4r~b4z}'; my Bool $equal = eq_irc(); say 'They're equal!' if $equal; # Output: They're equal! ``` ## parse\_mode\_line(@mode) Parses a list representing an IRC status mode line. The `@mode` parameter is an array representing the status mode line to parse. You may also pass an array or hash to specify valid channel and status modes. If not given, the valid channel modes default to `<beI k l imnpstaqr>` and the valid status modes default to `{o => '@', h => '%', v => '+'}` . Returns a hash containing two keys: `modes` and `args`. The `modes` key is an array of normalized modes. The `args` key is an array that represents the relevant arguments to the modes in `modes`. If for any reason the mode line in `@mode` can not be parsed, a `Nil` hash will be returned. Example: ``` my %hash = parse_mode_line(<ov foo bar>); say %hash<modes>[0]; # +o say %hash<modes>[1]; # +v say %hash<args>[0]; # foo say %hash<args>[1]; # bar ``` ## normalize\_mask(Str $mask) Fully qualifies or "normalizes" an IRC host/server mask. The `$mask` argument is a string representing a host/server mask. Returns `$mask` as a fully qualified mask. Example: ``` my Str $mask = normalize_mask('*@*'); say $mask; # Output: *!*@* ``` ## numeric\_to\_name(Int $code) Converts an IRC reply or error code to its corresponding string representation. This includes all values defined by RFC 1459 and also a few network-specific extensions. The `$code` parameter is an integer representing the numeric code to convert. For instance, 461 which is `ERR_NEEDMOREPARAMS`. Returns the string representation of `$code`. Example: ``` my Str $topic = numeric_to_name(332); say $topic; # Output: RPL_TOPIC ``` ## name\_to\_numeric(Str $name) Converts a string representation of an IRC reply or error code into its corresponding numeric code. This includes all values defined by RFC 1459 and also a few network-specific extensions. The `$name` parameter is a string representing the reply or error code. For instance, `ERR_NEEDMOREPARAMS` is 461. Returns the numerical representation of `$name`. Example: ``` my Int $topic name_to_numeric('RPL_TOPIC'); say $topic; # Output: 332 ``` ## is\_valid\_nick\_name(Str $nick) Checks if an IRC nickname is valid. That is, it conforms to the allowable characters defined in RFC 1459. The `$nick` parameter is a string representing the nickname to validate. Returns `Bool::True` if `$nick` is a valid IRC nickname and `Bool::False` otherwise. Example: ``` my Bool $valid_nick = is_valid_nick_name('{foo_bar_baz}'); say 'Nickname is valid!' if $valid_nick; # Output: Nickname is valid! ``` ## is\_valid\_chan\_name(Str $chan, Str @types?) Checks if an IRC channel name is valid. That is, it conforms to the allowable characters defined in RFC 1459. The `$chan` parameter is a string representing the channel name to check. The `@types` parameter is an optional anonymous list of channel types. For instance, '#'. If not given, it defaults to `['#', '&']`. Returns `Bool::True` if `$nick` is a valid IRC channel name and `Bool::False` otherwise. Example: ``` my Bool $valid_chan = is_valid_chan_name('#foobar'); say 'Channel name is valid!' if $valid_chan; # Output: Channel name is valid! ``` ## unparse\_mode\_line(Str $line) Condenses or "unparses" an IRC mode line. The `$line` parameter is a string representing an arbitrary number of mode changes. Returns the condensed version of `$line` as a string. Example: ``` my Str $mode = unparse_mode_line('+m+m+m-i+i'); say $mode; # Output: +mmm-i+i ``` ## gen\_mode\_change(Str $before, Str $after) Determines the changes made between two IRC user modes. The `$before` parameter is a string representing the user mode before the change. The `$after` parameter is a string representing the user mode after the change. Returns a string representing the modes that changed between `$before` and `$after`. That is, any modes that were added or removed from `$before` to create `$after`. Example: ``` my Str $mode_change = gen_mode_change('abcde', 'befmZ'); say $mode_change; # Output: -acd+fmZ ``` ## matches\_mask(Str $mask, Str $match, Str $mapping?) Determines whether a particular user/server matches an IRC mask. The `$mask` parameter is a string representing the IRC mask to match against. The `$match` parameter is a string representing the user/server to check. The `$mapping` parameter is an optional string that specifies which casemapping to use for `$mask` and `$match`. It can be 'rfc1459', 'strict-rfc1459', or 'ascii'. If not given, it defaults to 'rfc1459'. Example: ``` my Str $banmask = 'foobar*!*@*'; my Str $user = 'foobar!baz@qux.net'; my Bool $matches = matches_mask($banmask, $user); say "The user $user is banned" if $matches; # Output: The user foobar!baz@qux.net is banned ``` ## parse\_user(Str $user) Parses a fully-qualified IRC username and splits it into the parts representing the nickname, username, and hostname. The `$user` parameter is a string representing the fully-qualified username to parse. It must be of the form `nick!user@host`. Returns a list containing the nickname, username, and hostname parts of `$user`. Example: ``` my Str ($nick, $user, $host) = parse_user('foo!bar@baz.net'); say $nick # Output: foo say $user # Output: bar say $host # Output: baz.net ``` ## has\_color(Str $string) Checks if a string contains any embedded color codes. The `$string` parameter is the string to check. Returns `Bool::True` if `$string` contains any embedded color codes and `Bool::False` otherwise. Example: ``` my Bool $color = has_color("\x0304,05This is a colored message\x03"); say 'Oh, pretty colors!' if $color; # Output: Oh, pretty colors! ``` ## has\_formatting(Str $string) Checks if a string contains any embedded text formatting codes. The `$string` parameter is the string to check. Returns `Bool::True` if `$string` contains any embedded formatting codes and `Bool::False` otherwise. Example: ``` my Bool $fmt_text = has_formatting("This message has \x1funderlined\x0f text"); say 'I got some formatted text!' if $fmt_text; # Output: I got some formatted text! ``` ## strip\_color(Str $string) Strips a string of all embedded color codes (if any). The `$string` parameter is the string to strip. Returns the string given in `$string` with all embedded color codes removed. If the given string does not contain any color codes, the original string is returned as is. Example: ``` my Str $stripped = strip_color("\x03,05Look at the pretty colors!\x03"); say $stripped; # Output: Look at the pretty colors! ``` ## strip\_formatting(Str $string) Strips a string of all embedded text formatting codes (if any). The `$string` parameter is the string to strip. Returns the string given in `$string` with all embedded text formatting codes removed. If the given string does not contain any text formatting codes, the original string is returned as is. Example: ``` my Str $stripped = strip_formatting('This is \x02strong\x0f!"); say $stripped; # Output: This is strong! ``` # back # CONSTANTS The following constants are provided to embed color and formatting codes in IRC messages. ## Normal text ``` NORMAL ``` ## Formatting ``` BOLD UNDERLINE REVERSE ITALIC FIXED ``` ## Colors ``` WHITE BLACK BLUE GREEN RED BROWN PURPLE ORANGE YELLOW LIGHT_GREEN TEAL LIGHT_CYAN LIGHT_BLUE PINK GREY LIGHT_GREY ``` To terminate a single formatting code, you must use its respective constant. Additionally, you may use the `NORMAL` constant to terminate *all* formatting codes (including colors). Conversely, a single color code must be terminated with the `NORMAL` constant. However, this has the side effect of also terminating any other formatting codes. Example: ``` my Str $foo = 'Oh hai! I haz ' ~ GREEN ~ 'green ' ~ NORMAL ~ 'text!'; my Str $bar = BOLD ~ UNDERLINE ~ 'K thx bye!' ~ NORMAL; ``` # AUTHOR Kevin Polulak # COPYRIGHT AND LICENSE Copyright 2011 Kevin Polulak Copyright 2012 - 2022 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-jforget-Date-Calendar-Julian.md # NAME Date::Calendar::Julian - Conversions from / to the Julian calendar # SYNOPSIS What is the peculiarity of 15 February for people using the Julian calendar? And can you please print it in, say, Dutch? ``` use Date::Calendar::Julian; my Date $feb15-grg; my Date::Calendar::Julian $palindrome-jul; $feb15-grg .= new(2020, 2, 15); $palindrome-jul .= new-from-date($feb15-grg); say $palindrome-jul; # --> 2020-02-02 $palindrome-jul.locale = 'nl'; say $palindrome-jul.strftime("%A %e %B %Y"); # --> zaterdag 2 februari 2020 my Str $s1 = $palindrome-jul.strftime("%Y%m%d"); if $s1 eq $s1.flip { say "$s1 is a palindrome in YYYYMMDD format!"; } $s1 = $palindrome-jul.strftime("%d%m%Y"); if $s1 eq $s1.flip { say "$s1 is a palindrome in DDMMYYYY format!"; } $s1 = $palindrome-jul.strftime("%m%d%Y"); if $s1 eq $s1.flip { say "$s1 is a palindrome in MMDDYYYY format!"; } ``` The Perl & Raku Conference was scheduled to end on 1st August when using the Julian calendar. What is the corresponding Gregorian date? ``` use Date::Calendar::Julian; my Date::Calendar::Julian $TPRC-Amsterdam-jul; my Date $TPRC-Amsterdam-grg; $TPRC-Amsterdam-jul .= new(year => 2020 , month => 8 , day => 1); $TPRC-Amsterdam-grg = $TPRC-Amsterdam-jul.to-date; say $TPRC-Amsterdam-grg; # --> 2020-08-14 ``` # INSTALLATION ``` zef install Date::Calendar::Julian ``` or ``` git clone https://github.com/jforget/raku-Date-Calendar-Julian.git cd raku-Date-Calendar-Julian zef install . ``` # DESCRIPTION Date::Calendar::Julian is a class representing dates in the Julian calendar. It allows you to convert an Julian date into Gregorian (or possibly other) calendar and the other way. With class Date::Calendar::Julian::AUC, you can count the years since the founding of Rome. # AUTHOR Jean Forget # COPYRIGHT AND LICENSE Copyright (c) 2020, 2021, 2024 Jean Forget This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-KOBOLDWIZ-Game-Decision.md A package for statitical decision theory (e.g. in games) for building adaptive systems. Needs Game::Bayes and Game::Stats packages.
## gist.md gist Combined from primary sources listed below. # [In Submethod](#___top "go to top of document")[§](#(Submethod)_method_gist "direct link") See primary documentation [in context](/type/Submethod#method_gist) for **method gist**. ```raku multi method gist(Submethod:D:) ``` Returns the name of the submethod. # [In Exception](#___top "go to top of document")[§](#(Exception)_method_gist "direct link") See primary documentation [in context](/type/Exception#method_gist) for **method gist**. ```raku multi method gist(Exception:D:) ``` Returns whatever the exception printer should produce for this exception. The default implementation returns message and backtrace separated by a newline. ```raku my $e = X::AdHoc.new(payload => "This exception is pretty bad"); try $e.throw; if ($!) { say $!.gist; }; # OUTPUT: «This exception is pretty bad # in block <unit> at <unknown file> line 1␤» ``` # [In IO::Handle](#___top "go to top of document")[§](#(IO::Handle)_method_gist "direct link") See primary documentation [in context](/type/IO/Handle#method_gist) for **method gist**. ```raku method gist(IO::Handle:D: --> Str:D) ``` Returns a string containing information which [`.path`](/type/IO/Handle#method_path), if any, the handle is created for and whether it is [`.opened`](/type/IO/Handle#method_opened). ```raku say IO::Handle.new; # IO::Handle<(Any)>(closed) say "foo".IO.open; # IO::Handle<"foo".IO>(opened) ``` # [In Mu](#___top "go to top of document")[§](#(Mu)_routine_gist "direct link") See primary documentation [in context](/type/Mu#routine_gist) for **routine gist**. ```raku multi gist(+args --> Str) multi method gist( --> Str) ``` Returns a string representation of the invocant, optimized for fast recognition by humans. As such lists will be truncated at 100 elements. Use `.raku` to get all elements. The default `gist` method in `Mu` re-dispatches to the [raku](/routine/raku) method for defined invocants, and returns the type name in parenthesis for type object invocants. Many built-in classes override the case of instances to something more specific that may truncate output. `gist` is the method that [say](/routine/say) calls implicitly, so `say $something` and `say $something.gist` generally produce the same output. ```raku say Mu.gist; # OUTPUT: «(Mu)␤» say Mu.new.gist; # OUTPUT: «Mu.new␤» ``` # [In role Blob](#___top "go to top of document")[§](#(role_Blob)_method_gist "direct link") See primary documentation [in context](/type/Blob#method_gist) for **method gist**. ```raku method gist(Blob:D: --> Str:D) ``` Returns the string containing the "gist" of the `Blob`, **listing up to the first 100** elements, separated by space, appending an ellipsis if the `Blob` has more than 100 elements. ```raku put Blob.new(1, 2, 3).gist; # OUTPUT: «Blob:0x<01 02 03>␤» put Blob.new(1..2000).gist; # OUTPUT: # Blob:0x<01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 # 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C # 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 40 41 42 43 # 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A # 5B 5C 5D 5E 5F 60 61 62 63 64 ...> ``` # [In Complex](#___top "go to top of document")[§](#(Complex)_method_gist "direct link") See primary documentation [in context](/type/Complex#method_gist) for **method gist**. ```raku method gist(Complex:D: --> Str:D) ``` Returns a string representation of the form "1+2i", without internal spaces. (Str coercion also returns this.) ```raku say (1-4i).gist; # OUTPUT: «1-4i␤» ``` # [In Version](#___top "go to top of document")[§](#(Version)_method_gist "direct link") See primary documentation [in context](/type/Version#method_gist) for **method gist**. ```raku method gist(Version:D: --> Str:D) ``` Returns a string representation of the invocant, just like [`Str`](#method_Str), prepended with a lowercase `v`. ```raku my $v1 = v1.0.1; my $v2 = Version.new('1.0.1'); say $v1.gist; # OUTPUT: «v1.0.1␤» say $v2.gist; # OUTPUT: «v1.0.1␤» ``` # [In Backtrace](#___top "go to top of document")[§](#(Backtrace)_method_gist "direct link") See primary documentation [in context](/type/Backtrace#method_gist) for **method gist**. ```raku multi method gist(Backtrace:D:) ``` Returns string `"Backtrace(42 frames)"` where the number indicates the number of frames available via [list](/routine/list) method. # [In Array](#___top "go to top of document")[§](#(Array)_method_gist "direct link") See primary documentation [in context](/type/Array#method_gist) for **method gist**. Exactly the same as [`List.gist`](/type/List#method_gist), except using square brackets for surrounding delimiters. # [In List](#___top "go to top of document")[§](#(List)_method_gist "direct link") See primary documentation [in context](/type/List#method_gist) for **method gist**. ```raku multi method gist(List:D: --> Str:D) ``` Returns the string containing the parenthesized "gist" of the List, **listing up to the first 100** elements, separated by space, appending an ellipsis if the List has more than 100 elements. If List [`is-lazy`](/routine/is-lazy), returns string `'(...)'` ```raku put (1, 2, 3).gist; # OUTPUT: «(1 2 3)␤» put (1..∞).List.gist; # OUTPUT: «(...)␤» put (1..200).List.gist; # OUTPUT: # (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 # 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 # 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 # 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 # 96 97 98 99 100 ...) ``` # [In IO::Notification::Change](#___top "go to top of document")[§](#(IO::Notification::Change)_method_gist "direct link") See primary documentation [in context](/type/IO/Notification/Change#method_gist) for **method gist**. ```raku multi method gist(IO::Notification::Change:D:) ``` Returns the path and event attributes, separated by semicolon. # [In Attribute](#___top "go to top of document")[§](#(Attribute)_method_gist "direct link") See primary documentation [in context](/type/Attribute#method_gist) for **method gist**. ```raku multi method gist(Attribute:D:) ``` Returns the name of the type followed by the name of the attribute. ```raku class Hero { has @!inventory; has Str $.name; submethod BUILD( :$name, :@inventory ) { $!name = $name; @!inventory = @inventory } } say Hero.^attributes(:local)[0]; # OUTPUT: «Positional @!inventory␤» ``` Since say implicitly calls `.gist`, that is what produces the output here. # [In Junction](#___top "go to top of document")[§](#(Junction)_method_gist "direct link") See primary documentation [in context](/type/Junction#method_gist) for **method gist**. ```raku multi method gist(Junction:D:) ``` Collapses the `Junction` and returns a [`Str`](/type/Str) composed of the type of the junction and the [gists](/routine/gist) of its components: ```raku <a 42 c>.all.say; # OUTPUT: «all(a, 42, c)␤» ``` # [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_gist "direct link") See primary documentation [in context](/type/IO/Path#method_gist) for **method gist**. ```raku method gist(IO::Path:D: --> Str:D) ``` Returns a string, part of which contains either the value of [`.absolute`](/type/IO/Path#method_absolute) (if path is absolute) or [`.path`](/type/IO/Path#attribute_path). Note that no escaping of special characters is made, so e.g. `"\b"` means a path contains a backslash and letter "b", not a backspace. ```raku say "foo/bar".IO; # OUTPUT: «"foo/bar".IO␤» say IO::Path::Win32.new: 「C:\foo/bar\」; # OUTPUT: «"C:\foo/bar\".IO␤» ``` # [In role Sequence](#___top "go to top of document")[§](#(role_Sequence)_method_gist "direct link") See primary documentation [in context](/type/Sequence#method_gist) for **method gist**. ```raku multi method gist(::?CLASS:D:) ``` Returns the [gist](/type/List#method_gist) of the [cached](/type/PositionalBindFailover#method_cache) sequence. # [In Date](#___top "go to top of document")[§](#(Date)_method_gist "direct link") See primary documentation [in context](/type/Date#method_gist) for **method gist**. ```raku multi method gist(Date:D: --> Str:D) ``` Returns the date in `YYYY-MM-DD` format ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)) ```raku say Date.new('2015-12-24').gist; # OUTPUT: «2015-12-24␤» ``` # [In role Systemic](#___top "go to top of document")[§](#(role_Systemic)_method_gist "direct link") See primary documentation [in context](/type/Systemic#method_gist) for **method gist**. ```raku method gist( Systemic:D: ) ``` Instance method returning the name and version of the object. ```raku say $*RAKU.gist; # OUTPUT: «Raku (6.d)␤» ``` `$*RAKU` is an object of the [`Raku`](/type/Raku) type, which mixes in this role and thus implements this method. # [In ForeignCode](#___top "go to top of document")[§](#(ForeignCode)_method_gist "direct link") See primary documentation [in context](/type/ForeignCode#method_gist) for **method gist**. ```raku method gist( ForeignCode:D: ) ``` Returns the name of the code by calling `name`. # [In Nil](#___top "go to top of document")[§](#(Nil)_method_gist "direct link") See primary documentation [in context](/type/Nil#method_gist) for **method gist**. ```raku method gist(--> Str:D) ``` Returns `"Nil"`. # [In Map](#___top "go to top of document")[§](#(Map)_method_gist "direct link") See primary documentation [in context](/type/Map#method_gist) for **method gist**. ```raku method gist(Map:D: --> Str:D) ``` Returns the string containing the "gist" of the `Map`, sorts the pairs and lists **up to the first 100**, appending an ellipsis if the `Map` has more than 100 pairs.
## dist_zef-lizmat-span.md [![Actions Status](https://github.com/lizmat/span/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/span/actions) [![Actions Status](https://github.com/lizmat/span/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/span/actions) [![Actions Status](https://github.com/lizmat/span/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/span/actions) # NAME span - Provide Haskell's span functionality # SYNOPSIS ``` use span; .say for span * < 10, 2, 2, 2, 5, 5, 7, 13, 9, 6, 2, 20, 4; # (2 2 2 5 5 7) # (13 9 6 2 20 4) .say for span (* < 10, * < 20), 2, 2, 2, 5, 5, 7, 13, 9, 6, 2, 20, 4; # (2 2 2 5 5 7) # (13 9 6 2) # (20 4) .say for span Int, 2, 2, 2, 5, 5, "a", "b", "c"; # (2 2 2 5 5) # (a b c) ``` # DESCRIPTION NOTE: this distribution has been deprecated in favour of the [snip](https://raku.land/zef:lizmat/snip) distribution. The `span` distribution exports a single subroutine `span` that mimics the functionality provided by [Haskell's span functionality](https://hackage.haskell.org/package/base-4.16.1.0/docs/Prelude.html#v:span). The `span` subroutine takes a matcher much like `grep` does, which can be a `Callable` or any other object that can have the `ACCEPTS` method called on it. # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) Source can be located at: <https://github.com/lizmat/span> . 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, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-FRITH-Math-Libgsl-Multiset.md [![Actions Status](https://github.com/frithnanth/raku-Math-Libgsl-Multiset/workflows/test/badge.svg)](https://github.com/frithnanth/raku-Math-Libgsl-Multiset/actions) # NAME Math::Libgsl::Multiset - An interface to libgsl, the Gnu Scientific Library - Multisets. # SYNOPSIS ``` use Math::Libgsl::Multiset; ``` # DESCRIPTION Math::Libgsl::Multiset is an interface to the multiset functions of libgsl, the Gnu Scientific Library. This package provides both the low-level interface to the C library (Raw) and a more comfortable interface layer for the Raku programmer. ### new(:$n!, :$k!) ### new($n!, $k!) The constructor accepts two parameters: the total number of elements in the set and the number of elements chosen from the set; the parameters can be passed as Pair-s or as single values. The multiset object is already initialized in lexicographically first multiset, i.e. 0 repeated $k times. All the following methods *throw* on error if they return **self**, otherwise they *fail* on error. ### init(:$start? = TOP) This method initialize the multiset object and returns **self**. The default is to initialize the object in lexicographically first multiset, but by specifying the optional parameter **$start** as **BOTTOM** the initialization is performed in the lexicographically last multiset, i.e. $n − 1 repeated $k times. TOP and BOTTOM are declared as values of the Starting-point enum. ### copy($src! where \* ~~ Math::Libgsl::Combination) This method copies the multiset **$src** into the current multiset object and returns **self**. ### get(Int $elem! --> Int) This method returns the multiset value at position **$elem**. ### all(--> Seq) This method returns a Seq of all the elements of the current multiset. ### size(--> List) This method returns the (n, k) parameters of the current multiset object. ### is-valid(--> Bool) This method checks whether the current multiset is valid: the k elements should lie in the range 0 to $n − 1, with each value occurring once at most and in nondecreasing order. ### next() ### prev() These functions advance or step backwards the multiset and return **self**, useful for method chaining. ### bnext(--> Bool) ### bprev(--> Bool) These functions advance or step backwards the multiset and return a Bool: **True** if successful or **False** if there's no more multiset to produce. ### write(Str $filename! --> Int) This method writes the multiset data to a file. ### read(Str $filename! --> Int) This method reads the multiset data from a file. The multiset must be of the same size of the one to be read. ### fprintf(Str $filename!, Str $format! --> Int) This method writes the multiset data to a file, using the format specifier. ### fscanf(Str $filename!) This method reads the multiset data from a file. The multiset must be of the same size of the one to be read. # 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::Combination ``` # AUTHOR Fernando Santagata [nando.santagata@gmail.com](mailto:nando.santagata@gmail.com) # COPYRIGHT AND LICENSE Copyright 2020 Fernando Santagata This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-TYIL-HTTP-API-MusicBrainz.md ### has URL $!root-url The base URL object to create all URLs from. ### has Mu $!user-agent The user agent which will be used internally for handling HTTP requests. ### method search ``` method search( Str:D $entity, Str:D $query, Int $limit = 30, Int $offset = 0 ) returns Mu ``` Private method to perform search requests. ## class Str:D $entity The name of the entity to search for. ## class Str:D $query The query to search for. ## class Int $limit = 30 The number of results to fetch. ## class Int $offset = 0 The offset from the start. ### method http-request ``` method http-request( URL:D $url ) returns Associative ``` Private method to handle the actual HTTP requests. ## class URL:D $url The URL to make the request to. ## class $query A string to search for. ## class Int $limit = Int The maximum number of results to fetch. ## class Int $offset = Int An offset from the start of the result set. # NAME HTTP::API::MusicBrainz # VERSION 0.0.1 # AUTHOR Patrick Spek [p.spek@tyil.nl](mailto:p.spek@tyil.nl) # LICENSE Copyright © 2020 This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
## dist_zef-antononcube-Text-Calendar.md # Text::Calendar Raku package with text calendar functions for displaying monthly, yearly, and custom calendars. ### Motivation * For data science applications I need sparse calendars that contain only some of the dates * I want to facilitate making and displaying calendars in Jupyter notebooks using Markdown and HTML layouts * I like the "transposed" calendar layout of UNIX' `ncal` * I am interested in comparisons of calendar making (i) with LLM applications, and (ii) in the "hard way" ### Alternative implementations * ["App::Cal"](https://raku.land/zef:coke/App::Cal), [WCp1]. * ["Calendar"](https://raku.land/zef:tbrowder/Calendar), [TBp1]. Compared to [WCp1] and [TBp1], this package, "Text::Calendar", is lightweight and with no dependencies. ### Extensions The package ["Markup::Calendar"](https://raku.land/zef:antononcube/Markup::Calendar), [AAp2], provides calendars in HTML and Markdown formats. --- ## Installation From [Zef ecosystem](https://raku.land): ``` zef install Text::Calendar ``` From GitHub: ``` zef install https://github.com/antononcube/Raku-Text-Calendar.git ``` --- ## Examples ### Emacs style: this month with ones before and after Load the package and show today's date: ``` use Text::Calendar; Date.today; ``` ``` # 2024-02-09 ``` Default, "Emacs style" calendar: ``` calendar(); ``` ``` # January February March # Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su # 1 2 3 4 5 6 7 1 2 3 4 1 2 3 # 8 9 10 11 12 13 14 5 6 7 8 9 10 11 4 5 6 7 8 9 10 # 15 16 17 18 19 20 21 12 13 14 15 16 17 18 11 12 13 14 15 16 17 # 22 23 24 25 26 27 28 19 20 21 22 23 24 25 18 19 20 21 22 23 24 # 29 30 31 26 27 28 29 25 26 27 28 29 30 31 ``` Compare the output above with the that of UNIX (macOS) function `cal`: ``` cal -3 -h ``` ``` # 2024 # January February March # Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa # 1 2 3 4 5 6 1 2 3 1 2 # 7 8 9 10 11 12 13 4 5 6 7 8 9 10 3 4 5 6 7 8 9 # 14 15 16 17 18 19 20 11 12 13 14 15 16 17 10 11 12 13 14 15 16 # 21 22 23 24 25 26 27 18 19 20 21 22 23 24 17 18 19 20 21 22 23 # 28 29 30 31 25 26 27 28 29 24 25 26 27 28 29 30 # 31 ``` Here is the "transposed" version (or UNIX `ncal` style): ``` say "ncal style:\n", calendar(:transposed); ``` ``` # ncal style: # January 2024 February 2024 March 2024 # Mo 1 8 15 22 29 5 12 19 26 4 11 18 25 # Tu 2 9 16 23 30 6 13 20 27 5 12 19 26 # We 3 10 17 24 31 7 14 21 28 6 13 20 27 # Th 4 11 18 25 1 8 15 22 29 7 14 21 28 # Fr 5 12 19 26 2 9 16 23 1 8 15 22 29 # Sa 6 13 20 27 3 10 17 24 2 9 16 23 30 # Su 7 14 21 28 4 11 18 25 3 10 17 24 31 ``` ### Yearly ``` calendar-year(2024, per-row=>6) ``` ``` # 2024 # # January February March April May June # Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su # 1 2 3 4 5 6 7 1 2 3 4 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 1 2 # 8 9 10 11 12 13 14 5 6 7 8 9 10 11 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9 # 15 16 17 18 19 20 21 12 13 14 15 16 17 18 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16 # 22 23 24 25 26 27 28 19 20 21 22 23 24 25 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23 # 29 30 31 26 27 28 29 25 26 27 28 29 30 31 29 30 27 28 29 30 31 24 25 26 27 28 29 30 # # July August September October November December # Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su # 1 2 3 4 5 6 7 1 2 3 4 1 1 2 3 4 5 6 1 2 3 1 # 8 9 10 11 12 13 14 5 6 7 8 9 10 11 2 3 4 5 6 7 8 7 8 9 10 11 12 13 4 5 6 7 8 9 10 2 3 4 5 6 7 8 # 15 16 17 18 19 20 21 12 13 14 15 16 17 18 9 10 11 12 13 14 15 14 15 16 17 18 19 20 11 12 13 14 15 16 17 9 10 11 12 13 14 15 # 22 23 24 25 26 27 28 19 20 21 22 23 24 25 16 17 18 19 20 21 22 21 22 23 24 25 26 27 18 19 20 21 22 23 24 16 17 18 19 20 21 22 # 29 30 31 26 27 28 29 30 31 23 24 25 26 27 28 29 28 29 30 31 25 26 27 28 29 30 23 24 25 26 27 28 29 ``` **Remark:** The command used above has the same effect as `calendar-year(per-row=>6)`. I.e. the first, year argument can be `Whatever` and the current year be "deduced" as `Date.today.year`. ### Specific year-month pairs ``` calendar([2022=>2, 2023=>11, 2024 => 2]) ``` ``` # February November February # Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su # 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 # 7 8 9 10 11 12 13 6 7 8 9 10 11 12 5 6 7 8 9 10 11 # 14 15 16 17 18 19 20 13 14 15 16 17 18 19 12 13 14 15 16 17 18 # 21 22 23 24 25 26 27 20 21 22 23 24 25 26 19 20 21 22 23 24 25 # 28 27 28 29 30 26 27 28 29 ``` ### Month dataset Using month dataset allows of utilizing HTML formatting in Markdown files or Jupyter notebooks. Here is an example using ["Data::Translators"](https://raku.land/zef:antononcube/Data::Translators), [AAp2]: ``` use Data::Translators; my $m = 'February'; my $res = to-html(calendar-month-dataset(2024, $m), field-names => calendar-weekday-names); '<h4>' ~ $m ~ '</h4>' ~ $res.subst('<td>7</td>', '<td><span style="color: red"><b>7</b></span></td>') ``` #### February | Mo | Tu | We | Th | Fr | Sa | Su | | --- | --- | --- | --- | --- | --- | --- | | | | | 1 | 2 | 3 | 4 | | 5 | 6 | **7** | 8 | 9 | 10 | 11 | | 12 | 13 | 14 | 15 | 16 | 17 | 18 | | 19 | 20 | 21 | 22 | 23 | 24 | 25 | | 26 | 27 | 28 | 29 | | | | **Remark:** The package ["Markup::Calendar"](https://raku.land/zef:antononcube/Markup::Calendar), [AAp1], provides extensions of "Text::Calendar" for getting calendars in HTML and Markdown formats. --- ## Implementation notes The initial codes for `calendar-month-block` and `calendar` were taken from <https://rosettacode.org/wiki/Calendar#Raku> . The modifications done are for: * Different signatures for making calendars * Using of specs that are lists of year-month pairs * Have the transposed, `ncal` style layout Significant modifications are expected for calendars based on ranges of days. (The lists can be both dense or sparse.) --- ## TODO * Features * DONE Month block string * DONE Yearly calendar * DONE Calendar for span of months * I.e. "Emacs style" * DONE Calendar for a spec that is a list of year-month pairs * TODO Sparse calendar * Only for specified days * Days are specified with a list * DONE transposed or `ncal` mode * DONE Month block dataset * TODO Language localization * Using the short names of weekdays in "Date::Names", [TBp2] * Specified first day of week (e.g. Monday, not Sunday) * TODO Make sure month blocks align in multi-row layouts * Like, year calendars * For transposed only * TODO Return a list of pairs with year-month keys and month-text-block keys * Using adverb `:pairs` * Unit tests * DONE Sanity / signatures * TODO Correctness * Monthly * Yearly * Span * Documentation * DONE Basic README * DONE Detailed usage messages * TODO Comparison with LLMs --- ## References [AAp1] Anton Antonov, [Markup::Calendar Raku package](https://github.com/antononcube/Raku-Markup-Calendar), (2024), [GitHub/antononcube](https://github.com/antononcube). [AAp2] Anton Antonov, [Data::Translators Raku package](https://github.com/antononcube/Raku-Data-Translators), (2023), [GitHub/antononcube](https://github.com/antononcube). [TBp1] Tom Browder, [Calendar Raku package](https://github.com/tbrowder/Calendar), (2020-2024), [GitHub/tbrowder](https://github.com/tbrowder). [TBp2] Tom Browder, [Date::Names Raku package](https://github.com/tbrowder/Date-Names), (2019-2024), [GitHub/tbrowder](https://github.com/tbrowder). [WCp1] Will Coleda, [App::Cal Raku packate](https://github.com/coke/raku-cal), (2022-2024), [GitHub/coke](https://github.com/coke).
## dist_github-FCO-ProblemSolver.md [![Build Status](https://travis-ci.org/FCO/ProblemSolver.svg?branch=master)](https://travis-ci.org/FCO/ProblemSolver) # ProblemSolver ``` use ProblemSolver; my ProblemSolver $problem .= new; $problem.add-variable: "a", ^100; $problem.add-variable: "b", ^100; $problem.add-constraint: -> :$a!, :$b! {$a * 3 == $b + 14}; $problem.add-constraint: -> :$a!, :$b! {$a * 2 == $b}; say $problem.solve # ((a => 14 b => 28)) ``` ``` # SEND + MORE = MONEY use ProblemSolver; my ProblemSolver $problem .= new: :stop-on-first-solution; $problem.add-variable: "S", 1 ..^ 10; $problem.add-variable: "E", ^10; $problem.add-variable: "N", ^10; $problem.add-variable: "D", ^10; $problem.add-variable: "M", 1 ..^ 10; $problem.add-variable: "O", ^10; $problem.add-variable: "R", ^10; $problem.add-variable: "Y", ^10; $problem.unique-vars: <S E N D M O R Y>; $problem.add-constraint: -> :$S!, :$E!, :$N!, :$D!, :$M!, :$O!, :$R!, :$Y! { note "$S$E$N$D + $M$O$R$E == $M$O$N$E$Y"; 1000*$S + 100*$E + 10*$N + $D + 1000*$M + 100*$O + 10*$R + $E == 10000*$M + 1000*$O + 100*$N + 10*$E + $Y }; say $problem.solve # You can wait for ever... ``` ``` # 4 queens use ProblemSolver; class Point { has Int $.x; has Int $.y; method WHICH { "{self.^name}(:x($!x), :y($!y))" } method gist {$.WHICH} } sub MAIN(Int $n = 4) { my ProblemSolver $problem .= new: :stop-on-first-solution; sub print-board(%values) { my @board; for %values.kv -> $key, (:x($row), :y($col)) { @board[$row; $col] = $key; } for ^$n -> $row { for ^$n -> $col { if @board[$row; $col]:exists { print "● " } else { print "◦ " } } print "\n" } print "\n" } $problem.print-found = -> %values { print "\e[0;0H\e[0J"; print-board(%values); } my @board = (^$n X ^$n).map(-> ($x, $y) {Point.new: :$x, :$y}); my @vars = (1 .. $n).map: {"Q$_"}; for @vars -> $var { $problem.add-variable: $var, @board; } $problem.unique-vars: @vars; $problem.constraint-vars: -> $q1, $q2 { $q1.x != $q2.x && $q1.y != $q2.y && $q1.x - $q1.y != $q2.x - $q2.y && $q1.x + $q1.y != $q2.x + $q2.y }, @vars; my @response = $problem.solve; say "\n", "=" x 30, " Answers ", "=" x 30, "\n"; for @response -> %ans { print-board(%ans) } } ``` ``` # colorize map use ProblemSolver; my ProblemSolver $problem .= new: :stop-on-first-solution; my @colors = <green yellow blue white>; my @states = < acre alagoas amapa amazonas bahia ceara espirito-santo goias maranhao mato-grosso mato-grosso-do-sul minas-gerais para paraiba parana pernambuco piaui rio-de-janeiro rio-grande-do-norte rio-grande-do-sul rondonia roraima santa-catarina sao-paulo sergipe tocantins >; for @states -> $state { $problem.add-variable: $state, @colors; } $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <acre amazonas>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <amazonas roraima>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <amazonas rondonia>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <amazonas para>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <para amapa>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <para tocantins>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <para mato-grosso>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <para maranhao>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <maranhao tocantins>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <maranhao piaui>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <piaui ceara>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <piaui pernambuco>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <piaui bahia>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <ceara rio-grande-do-norte>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <ceara paraiba>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <ceara pernambuco>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <rio-grande-do-norte paraiba>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <pernambuco alagoas>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <alagoas sergipe>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <sergipe bahia>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <bahia minas-gerais>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <bahia espirito-santo>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <bahia tocantins>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <bahia goias>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso goias>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso tocantins>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso rondonia>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso mato-grosso-do-sul>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso-do-sul goias>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso-do-sul minas-gerais>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso-do-sul sao-paulo>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso-do-sul parana>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <sao-paulo minas-gerais>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <sao-paulo rio-de-janeiro>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <rio-de-janeiro espirito-santo>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <rio-de-janeiro minas-gerais>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <minas-gerais espirito-santo>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <parana santa-catarina>; $problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <santa-catarina rio-grande-do-sul>; my %res = $problem.solve.first; my $size = %res.keys.map(*.chars).max; for %res.kv -> $state, $color { printf "%{$size}s => %s\n", $state, $color; } ```
## dist_zef-raku-community-modules-Math-Random.md [![Actions Status](https://github.com/raku-community-modules/Math-Random/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Math-Random/actions) [![Actions Status](https://github.com/raku-community-modules/Math-Random/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Math-Random/actions) [![Actions Status](https://github.com/raku-community-modules/Math-Random/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Math-Random/actions) # NAME Math::Random - Random numbers à la java.util.Random ## Background I was bothered by Rakus's primitive random number handling (only `rand` and `srand`, with no mechanism to have multiple generators in parallel), so, instead of bugging some random people about it, I decided to write a module! # SYNOPSIS ``` use Math::Random::JavaStyle; # uses same mechanics as # java.util.Random my $j = Math::Random::JavaStyle.new; $j.setSeed(9001); say $j.nextInt; say $j.nextLong; say $j.nextDouble; say $j.nextInt(100); say $j.nextLong(100_000_000_000); say $j.nextDouble(100); say $j.nxt(256); # generate a random 256-bit integer say $j.nextGaussian; use Math::Random::MT; my $m64 = Math::Random::MT.mt19937_64; #... ``` # DESCRIPTION Math::Random provides a `Math::Random` role, and two classes using this role: `Math::Random::JavaStyle` (which uses the same mechanics as `java.util.Random`), and `Math::Random::MT` (which provides a mersenne twister with a long period of 219937 – 1). # USAGE The `Math::Random` role requires two methods to be implemented: ``` method setSeed(Int:D $seed --> Nil) { ... } method nxt(Int:D $bits --> Int:D) { ... } ``` Unlike in Java's equivalent, `nxt` is required to accept as large of an input as possible. # METHODS ## setSeed(Int $seed) Sets the random seed. ## nextInt Returns a random unsigned 32-bit integer. ## nextInt(Int $max) Returns a random nonnegative integer less than `$max`. The upper bound must not exceed `2**32`. ## nextLong Returns a random unsigned 64-bit integer. ## nextLong(Int $max) Returns a random nonnegative integer less than `$max`. The upper bound must not exceed `2**64`. ## nextBoolean Returns `True` or `False`. ## nextDouble Returns a random `Num` in the range [0.0, 1.0). ## nextDouble(Num $max) Returns a random `Num` in the range [0.0, `$max`). ## nextGaussian Returns a random value according to the normal distribution. ## nxt(Int $bits) Returns a random integer with `$bits` bits. # ACKNOWLEDGEMENTS Oracle's documentation on `java.util.Random`, as well as Wikipedia's article on the Mersenne Twister generator. # TODO * Provide constructors that also set the seed. * Ensure thread safety, or create a thread-safe wrapper * Provide higher-level methods * Tests? They won't be easy to pull off, so if anyone wants to PR... # AUTHORS * +merlan #flirora * Raku Community # COPYRIGHT AND LICENSE Copyright 2015 - 2017 +merlan #flirora Copyright 2024 Raku Commuity This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-raku-community-modules-Template6.md [![Actions Status](https://github.com/raku-community-modules/Template6/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/Template6/actions) # NAME Template6 - A Template Engine for Raku # SYNOPSIS ``` use Template6; ``` # DESCRIPTION Inspired by Template Toolkit from Perl, Template6 is a simple template engine designed to be a content-neutral template language. This project does not intend to create an exact clone of Template Toolkit. Some features from TT are not planned for inclusion, and likewise, some feature will be included that are not in TT. Not all features will work the same either. ## Currently implemented features ### GET and SET statements, including implicit versions. * [% get varname %] * [% varname %] * [% set varname = value %] * [% varname = value %] ### FOR statement. This replaces the FOREACH statement in TT2. It can be used in one of four ways: * [% for listname as itemname %] * [% for listname -> itemname %] * [% for itemname in listname %] * [% for itemname = listname %] If used with Hashes, you'll need to query the .key or .value accessors. ### IF/ELSIF/ELSE/UNLESS statements. These are very simplistic at the moment, but work for basic tests. * Querying nested data structures using a simple dot operator syntax. * CALL and DEFAULT statements. * INSERT, INCLUDE and PROCESS statements. ## Differences with Template Toolkit * You should use explicit quotes, including in INSERT/INCLUDE/PROCESS directives. * UNLESS-ELSE is not supported - Raku also doesn't support this syntax * All statement directives are case insensitive. * There are no plans for the INTERPOLATE option/style. * Anything not yet implemented (see TODO below.) ## Caveats * Whitespace control is not implemented, so some things are fairly odd. See TODO. * A lot of little nit-picky stuff, likely related to the whitespace issue. ## TODO ### Short Term Goals * WRAPPER statement * block statements * given/when statements * Add 'absolute' and 'relative' options to Template6::Provider::File * Whitespace control * Precompiled/cached templates * Tag styles (limited to definable start\_tag and end\_tag) ### Long Term Goals * Filters * Variable interpolation (in strings, variable names, etc.) * Capture of directive output * Directive comments * Side-effect notation * Multiple directives in a single statement tag set * Macros, plugins, etc. ## Possible future directions I would also like to investigate the potential for an alternative to Template6::Parser that generates Raku closures without the use of EVAL. This would be far trickier, and would not be compatible with the precompiled templates, but would be an interesting exercise nonetheless. # AUTHOR Timothy Totten # COPYRIGHT AND LICENSE Copyright 2012 - 2017 Timothy Totten Copyright 2018 - 2023 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## signatures.md ## Chunk 1 of 2 Signature literals A guide to signatures in Raku [`Signatures`](/type/Signature) appear inside parentheses after [subroutine](/type/Sub) and [method](/type/Method) names, on blocks after a `->` or `<->` arrow, as the input to [variable declarators](/language/variables#Variable_declarators_and_scope) like [`my`](/syntax/my), or as a separate term starting with a colon. ```raku sub f($x) { } # ^^^^ Signature of sub f my method x() { } # ^^ Signature of a method my $s = sub (*@a) { } # ^^^^^ Signature of an anonymous function for <a b c> -> $x { } # ^^ Signature of a Block my ($a, @b) = 5, (6, 7, 8); # ^^^^^^^^ Signature of a variable declarator my $sig = :($a, $b); # ^^^^^^^^ Standalone Signature object ``` Signature literals can be used to define the signature of a callback or a closure. ```raku sub f(&c:(Int)) { } sub will-work(Int) { } sub won't-work(Str) { } f(&will-work); f(&won't-work); CATCH { default { put .^name, ': ', .Str } }; # OUTPUT: «X::TypeCheck::Binding::Parameter: Constraint type check failed in binding to parameter '&c'␤» f(-> Int { 'this works too' } ); ``` You can use any kind of literal, including numeric ones, as part of a signature; this is generally used in conjunction with multis ```raku proto stuff(|) {*} multi stuff(33) { 58 } multi stuff(⅓) { 43 } multi stuff(Int) { 3 } multi stuff(Complex) { 66 } say stuff($_) for (33, ⅓, i, 48); # OUTPUT: «58␤43␤66␤3␤» ``` However, you can't use `True` or `False` as literals in signatures since they will always succeed (or fail). A warning will be issued if you do so: ```raku sub foo(True) {}; my $sig = :( True ); ``` They will both warn "Literal values in signatures are smartmatched against and smartmatch with `True` will always succeed. Use the `where` clause instead.". Use of `False` will produce a similar warning. Smartmatching signatures against a [`List`](/type/List) is supported. ```raku my $sig = :(Int $i, Str $s); say (10, 'answer') ~~ $sig; # OUTPUT: «True␤» my $sub = sub ( Str $s, Int $i ) { return $s xx $i }; say $sub.signature ~~ :( Str, Int ); # OUTPUT: «True␤» given $sig { when :(Str, Int) { say 'mismatch' } when :($, $) { say 'match' } default { say 'no match' } } # OUTPUT: «match␤» ``` It matches the second `when` clause since `:($, $)` represents a [`Signature`](/type/Signature) with two scalar, anonymous, arguments, which is a more general version of `$sig`. When smartmatching against a [`Hash`](/type/Hash), the signature is assumed to consist of the keys of the [`Hash`](/type/Hash). ```raku my %h = left => 1, right => 2; say %h ~~ :(:$left, :$right); # OUTPUT: «True␤» ``` [`Signature`](/type/Signature) literals can contain string/numeric literals ```raku my $sig = :('Þor', Str, Int); say <Þor Hammer 1> ~~ $sig; # OUTPUT: «True␤» ``` And they can also contain the invocant marker ```raku class Foo { method bar( $self: ){ "baz" } }; say Foo.^methods.first(*.name eq 'bar').signature ~~ :($: *%) ; # OUTPUT: «True␤» ``` # [Parameter separators](#Signature_literals "go to top of document")[§](#Parameter_separators "direct link") A signature consists of zero or more [`Parameter`](/type/Parameter)s, separated by commas. ```raku my $sig = :($a, @b, %c); sub add($a, $b) { $a + $b }; ``` As an exception the first parameter may be followed by a colon instead of a comma to mark the invocant of a method. This is done in order to distinguish it from what would then be a regular positional parameter. The invocant is the object that was used to call the method, which is usually bound to [`self`](/routine/self). By specifying it in the signature, you can change the variable name it is bound to. ```raku method ($a: @b, %c) {}; # first argument is the invocant class Foo { method whoami($me:) { "Well I'm class $me.^name(), of course!" } } say Foo.whoami; # OUTPUT: «Well I'm class Foo, of course!␤» ``` # [Type constraints](#Signature_literals "go to top of document")[§](#Type_constraints "direct link") Parameters can optionally have a type constraint (the default is [`Any`](/type/Any)). These can be used to restrict the allowed input to a function. ```raku my $sig = :(Int $a, Str $b); ``` Type constraints can have any compile-time defined value ```raku subset Positive-integer of Int where * > 0; sub divisors(Positive-integer $n) { $_ if $n %% $_ for 1..$n }; CATCH { default { put .^name, ': ', .Str; .resume } }; divisors 2.5; # OUTPUT: «X::TypeCheck::Binding::Parameter: Type check failed in binding to parameter '$n'; expected Positive-integer but got Rat (2.5)␤» divisors -3; # OUTPUT: «X::TypeCheck::Binding::Parameter: Constraint type check failed in binding to parameter '$n'; expected Positive-integer but got Int (-3)␤» ``` Please note that in the code above type constraints are enforced at two different levels: the first level checks if it belongs to the type in which the subset is based, in this case [`Int`](/type/Int). If it fails, a `Type check` error is produced. Once that filter is cleared, the constraint that defined the subset is checked, producing a `Constraint type check` error if it fails. Type constraints can define multiple allowable types ```raku sub abbrev($arg where Str|List|Hash) {...} # throws if $arg is not one of those types ``` Anonymous arguments are fine too, if you don't actually need to refer to a parameter by name, for instance to distinguish between different signatures in a [multi](/language/functions#Multi-dispatch) or to check the signature of a [`Callable`](/type/Callable). ```raku my $sig = :($, @, %a); # two anonymous and a "normal" parameter $sig = :(Int, Positional); # just a type is also fine (two parameters) sub baz(Str) { "Got passed a Str" } ``` Type constraints may also be [type captures](/language/signatures#Type_captures). In addition to those *nominal* types, additional constraints can be placed on parameters in the form of code blocks which must return a true value to pass the type check ```raku sub f(Real $x where { $x > 0 }, Real $y where { $y >= $x }) { } ``` The code in `where` clauses has some limitations: anything that produces side-effects (e.g., printing output, pulling from an iterator, or increasing a state variable) is not supported and may produce surprising results if used. Also, the code of the `where` clause may run more than once for a single typecheck in some implementations. The `where` clause doesn't need to be a code block, anything on the right of the `where`-clause will be used to [smartmatch](/language/operators#infix_~~) the argument against it. So you can also write: ```raku multi factorial(Int $ where 0) { 1 } multi factorial(Int $x) { $x * factorial($x - 1) } ``` The first of those can be shortened to ```raku multi factorial(0) { 1 } ``` i.e., you can use a literal directly as a type and value constraint on an anonymous parameter. **Tip:** pay attention to not accidentally leave off a block when you, say, have several conditions: ```raku -> $y where .so && .name {}( sub one {} ); # WRONG!! -> $y where { .so && .name } {}( sub two {} ); # OK! -> $y where .so & .name.so {}( sub three {} ); # Also good ``` The first version is wrong and will issue a warning about a sub object coerced to string. The reason is the expression is equivalent to `($y ~~ ($y.so && $y.name))`; that is "call `.so`, and if that is `True`, call `.name`; if that is also `True` use its value for smartmatching…". It's the **result** of `(.so && .name)` it will be smartmatched against, but we want to check that both `.so` and `.name` are truthy values. That is why an explicit Block or a [`Junction`](/type/Junction) is the right version. All previous arguments that are not part of a sub-signature in a [`Signature`](/type/Signature) are accessible in a `where`-clause that follows an argument. Therefore, the `where`-clause of the last argument has access to all arguments of a signature that are not part of a sub-signature. For a sub-signature place the `where`-clause inside the sub-signature. ```raku sub foo($a, $b where * == $a ** 2) { say "$b is a square of $a" } foo 2, 4; # OUTPUT: «4 is a square of 2␤»» # foo 2, 3; # OUTPUT: «Constraint type check failed in binding to parameter '$b'…» ``` ## [Constraining optional arguments](#Signature_literals "go to top of document")[§](#Constraining_optional_arguments "direct link") [Optional arguments](#Optional_and_mandatory_arguments) can have constraints, too. Any `where` clause on any parameter will be executed, even if it's optional and not provided by the caller. In that case you may have to guard against undefined values within the `where` clause. ```raku sub f(Int $a, UInt $i? where { !$i.defined or $i > 5 }) { ... } ``` ## [Constraining slurpy arguments](#Signature_literals "go to top of document")[§](#Constraining_slurpy_arguments "direct link") [Slurpy arguments](#Slurpy_parameters) can not have type constraints. A `where`-clause in conjunction with a [`Junction`](/type/Junction) can be used to that effect. ```raku sub f(*@a where {$_.all ~~ Int}) { say @a }; f(42); f(<a>); CATCH { default { say .^name, ' ==> ', .Str } } # OUTPUT: «[42]␤Constraint type check failed in binding to parameter '@a' ...» ``` ## [Constraining named arguments](#Signature_literals "go to top of document")[§](#Constraining_named_arguments "direct link") Constraints against [named arguments](#Positional_vs._named_arguments) apply to the value part of the [colon-pair](/type/Pair). ```raku sub f(Int :$i){}; f :i<forty-two>; CATCH { default { say .^name, ' ==> ', .Str } } # OUTPUT: «X::TypeCheck::Binding::Parameter ==> Type check failed in # binding to parameter '$i'; expected Int but got Str ("forty-two")␤» ``` ## [Constraining argument definiteness](#Signature_literals "go to top of document")[§](#Constraining_argument_definiteness "direct link") Normally, a type constraint only checks whether the value of the parameter is of the correct type. Crucially, both *object instances* and *type objects* will satisfy such a constraint as illustrated below: ```raku say 42.^name; # OUTPUT: «Int␤» say 42 ~~ Int; # OUTPUT: «True␤» say Int ~~ Int; # OUTPUT: «True␤» ``` Note how both `42` and [`Int`](/type/Int) satisfy the match. Sometimes we need to distinguish between these object instances (`42`) and type objects ([`Int`](/type/Int)). Consider the following code: ```raku sub limit-lines(Str $s, Int $limit) { my @lines = $s.lines; @lines[0 .. min @lines.elems, $limit].join("\n") } say (limit-lines "a \n b \n c \n d \n", 3).raku; # "a \n b \n c \n d " say limit-lines Str, 3; CATCH { default { put .^name, ': ', .Str } }; # OUTPUT: «X::Multi::NoMatch: Cannot resolve caller lines(Str: ); # none of these signatures match: # (Str:D $: :$count!, *%_) # (Str:D $: $limit, *%_) # (Str:D $: *%_)» say limit-lines "a \n b", Int; # Always returns the max number of lines ``` Here we really only want to deal with string instances, not type objects. To do this, we can use the `:D` type constraint. This constraint checks that the value passed is an *object instance*, in a similar fashion to calling its [DEFINITE](/language/mop#DEFINITE) (meta)method. To warm up, let's apply `:D` to the right-hand side of our humble [`Int`](/type/Int) example: ```raku say 42 ~~ Int:D; # OUTPUT: «True␤» say Int ~~ Int:D; # OUTPUT: «False␤» ``` Note how only `42` matches `Int:D` in the above. Returning to `limit-lines`, we can now amend its signature to catch the error early: ```raku sub limit-lines(Str:D $s, Int $limit) { }; say limit-lines Str, 3; CATCH { default { put .^name ~ '--' ~ .Str } }; # OUTPUT: «Parameter '$s' of routine 'limit-lines' must be an object instance of type 'Str', # not a type object of type 'Str'. Did you forget a '.new'?» ``` This is much better than the way the program failed before, since here the reason for failure is clearer. It's also possible that *type objects* are the only ones that make sense for a routine to accept. This can be done with the `:U` type constraint, which checks whether the value passed is a type object rather than an object instance. Here's our [`Int`](/type/Int) example again, this time with `:U` applied: ```raku say 42 ~~ Int:U; # OUTPUT: «False␤» say Int ~~ Int:U; # OUTPUT: «True␤» ``` Now `42` fails to match `Int:U` while [`Int`](/type/Int) succeeds. Here's a more practical example: ```raku sub can-turn-into(Str $string, Any:U $type) { return so $string.$type; } say can-turn-into("3", Int); # OUTPUT: «True␤» say can-turn-into("6.5", Int); # OUTPUT: «True␤» say can-turn-into("6.5", Num); # OUTPUT: «True␤» say can-turn-into("a string", Num); # OUTPUT: «False␤» ``` Calling `can-turn-into` with an object instance as its second parameter will yield a constraint violation as intended: ```raku say can-turn-into("a string", 123); # OUTPUT: «Parameter '$type' of routine 'can-turn-into' must be a type object # of type 'Any', not an object instance of type 'Int'...» ``` For explicitly indicating the normal behavior, that is, not constraining whether the argument will be an instance or a type object, `:_` can be used but this is unnecessary since this is the default constraint (of this kind) on arguments. Thus, `:(Num:_ $)` is the same as `:(Num $)`. To recap, here is a quick illustration of these type constraints, also known collectively as *type smileys*: ```raku # Checking a type object say Int ~~ Any:D; # OUTPUT: «False␤» say Int ~~ Any:U; # OUTPUT: «True␤» say Int ~~ Any:_; # OUTPUT: «True␤» # Checking a subset subset Even of Int where * // 2; say 3 ~~ Even:D; # OUTPUT: «True␤» say 3 ~~ Even:U; # OUTPUT: «False␤» say Int ~~ Even:U; # OUTPUT: «True␤» # Checking an object instance say 42 ~~ Any:D; # OUTPUT: «True␤» say 42 ~~ Any:U; # OUTPUT: «False␤» say 42 ~~ Any:_; # OUTPUT: «True␤» # Checking a user-supplied class class Foo {}; say Foo ~~ Any:D; # OUTPUT: «False␤» say Foo ~~ Any:U; # OUTPUT: «True␤» say Foo ~~ Any:_; # OUTPUT: «True␤» # Checking an instance of a class my $f = Foo.new; say $f ~~ Any:D; # OUTPUT: «True␤» say $f ~~ Any:U; # OUTPUT: «False␤» say $f ~~ Any:_; # OUTPUT: «True␤» ``` The [Classes and Objects](/language/classtut) document further elaborates on the concepts of instances and type objects and discovering them with the `.DEFINITE` method. Keep in mind all parameters have values; even optional ones have default values that are the type object of the constrained type for explicit type constraints. If no explicit type constraint exists, the default value is an [`Any`](/type/Any) type object for methods, submethods, and subroutines, and a [`Mu`](/type/Mu) type object for blocks. This means that if you use the `:D` type smiley, you'd need to provide a default value or make the parameter required. Otherwise, the default value would be a type object, which would fail the definiteness constraint. ```raku sub divide (Int:D :$a = 2, Int:D :$b!) { say $a/$b } divide :1a, :2b; # OUTPUT: «0.5␤» ``` The default value will kick in when that particular parameter, either positional or named, gets no value *at all*. ```raku sub f($a = 42){ my $b is default('answer'); say $a; $b = $a; say $b }; f; # OUTPUT: «42␤42␤» f Nil; # OUTPUT: «Nil␤answer␤» ``` `$a` has 42 as its default value. With no value, `$a` will be assigned the default value declared in the [`Signature`](/type/Signature). However, in the second case, it *does* receive a value, which happens to be [`Nil`](/type/Nil). Assigning [`Nil`](/type/Nil) to any variable resets it to its default value, which has been declared as `'answer'` by use of the *default* trait. That explains what happens the second time we call `f`. Routine parameters and variables deal differently with default value, which is in part clarified by the different way default values are declared in each case (using `=` for parameters, using the `default` trait for variables). Note: in 6.c language, the default value of `:U`/`:D` constrained variables was a type object with such a constraint, which is not initializable, thus you cannot use the `.=` operator, for example. ```raku use v6.c; my Int:D $x .= new: 42; # OUTPUT: You cannot create an instance of this type (Int:D) # in block <unit> at -e line 1 ``` In the 6.d language, the default *default* is the type object without the smiley constraint: ```raku use v6.d; my Int:D $x .= new: 42; # OUTPUT: «42␤» ``` A closing remark on terminology: this section is about the use of the type smileys `:D` and `:U` to constrain the definiteness of arguments. Occasionally *definedness* is used as a synonym for *definiteness*; this may be confusing, since the terms have subtly different meanings. As explained above, *definiteness* is concerned with the distinction between type objects and object instances. A type object is always indefinite, while an object instance is always definite. Whether an object is a type object/indefinite or an object instance/definite can be verified using the [DEFINITE](/language/mop#DEFINITE) (meta)method. *Definiteness* should be distinguished from *definedness*, which is concerned with the difference between defined and undefined objects. Whether an object is defined or undefined can be verified using the `defined`-method, which is implemented in class [`Mu`](/type/Mu). By default a type object is considered undefined, while an object instance is considered defined; that is: `.defined` returns `False` on a type object, and `True` otherwise. But this default behavior may be overridden by subclasses. An example of a subclass that overrides the default `.defined` behavior is [`Failure`](/type/Failure), so that even an instantiated [`Failure`](/type/Failure) acts as an undefined value: ```raku my $a = Failure; # Initialize with type object my $b = Failure.new("foo"); # Initialize with object instance say $a.DEFINITE; # OUTPUT: «False␤» : indefinite type object say $b.DEFINITE; # OUTPUT: «True␤» : definite object instance say $a.defined; # OUTPUT: «False␤» : default response say $b.defined; # OUTPUT: «False␤» : .defined override ``` ## [Constraining signatures of](#Signature_literals "go to top of document") [`Callable`](/type/Callable)s[§](#Constraining_signatures_of_Callables "direct link") :u whitespace allowed): ```raku sub apply(&l:(Int:D --> Int:D), Int:D \n) { l(n) } sub identity(Int:D \i --> Int:D) { i } sub double(Int:D \x --> Int:D) { 2 * x } say apply &identity, 10; # OUTPUT: «10␤» say apply &double, 10; # OUTPUT: «20␤» ``` Typed [lambdas](/language/functions#Blocks_and_lambdas) also work with constrained callable parameters. ```raku say apply -> Int:D \x --> Int:D { 2 * x }, 3; # OUTPUT: «6␤» say apply -> Int:D \x --> Int:D { x ** 3 }, 3; # OUTPUT: «27␤» ``` Note that this shorthand syntax is available only for parameters with the `&` sigil. For others, you need to use the long version: ```raku sub play-with-tens($c where .signature ~~ :(Int, Str)) { say $c(10, 'ten') } sub by-joining-them(Int $i, Str $s) { $s ~ $i } play-with-tens &by-joining-them; # OUTPUT: «ten10␤» play-with-tens -> Int \i, Str \s { s x (1..10).roll mod i }; # OUTPUT: «tenten␤» sub g(Num $i, Str $s) { $s ~ $i } # play-with-tens(&g); # Constraint type check failed ``` ## [Constraining return types](#Signature_literals "go to top of document")[§](#Constraining_return_types "direct link") There are multiple ways to constrain return types on a [`Routine`](/type/Routine). All versions below are currently valid and will force a type check on successful execution of a routine. [`Nil`](/type/Nil) and [`Failure`](/type/Failure) are always allowed as return types, regardless of any type constraint. This allows [`Failure`](/type/Failure) to be returned and passed on down the call chain. ```raku sub foo(--> Int) { Nil }; say foo.raku; # OUTPUT: «Nil␤» ``` Type captures are not supported. ### [Return type arrow: `--`>](#Signature_literals "go to top of document")[§](#Return_type_arrow:_--> "direct link") This form of indicating return types (or constants) in the signature is preferred, since it can handle constant values while the others can't. For consistency, it is the only form accepted on this site. The return type arrow has to be placed at the end of the parameter list, with or without a `,` before it. ```raku sub greeting1(Str $name --> Str) { say "Hello, $name" } # Valid sub greeting2(Str $name, --> Str) { say "Hello, $name" } # Valid sub favorite-number1(--> 42) { } # OUTPUT: 42 sub favorite-number2(--> 42) { return } # OUTPUT: 42 ``` If the type constraint is a constant expression, it is used as the return value of the routine. Any return statement in that routine has to be argumentless. ```raku sub foo(Str $word --> 123) { say $word; return; } my $value = foo("hello"); # OUTPUT: hello say $value; # OUTPUT: 123 ``` ```raku # The code below will not compile sub foo(Str $word --> 123) { say $word; return $word; } my $value = foo("hello"); say $value; ``` ### [`returns`](#Signature_literals "go to top of document")[§](#returns "direct link") The keyword `returns` following a signature declaration has the same function as `-->` with the caveat that this form does not work with constant values. You cannot use it in a block either. That is why the pointy arrow form is always preferred. ```raku sub greeting(Str $name) returns Str { say "Hello, $name" } # Valid ``` ```raku sub favorite-number returns 42 { } # This will fail. ``` ### [`of`](#Signature_literals "go to top of document")[§](#of "direct link") `of` is just the real name of the `returns` keyword. ```raku sub foo() of Int { 42 }; # Valid ``` ```raku sub foo() of 42 { }; # This will fail. ``` ### [prefix(C-like) form](#Signature_literals "go to top of document")[§](#prefix(C-like)_form "direct link") This is similar to placing type constraints on variables like `my Type $var = 20;`, except the `$var` is a definition for a routine. ```raku my Int sub bar { 1 }; # Valid ``` ```raku my 42 sub bad-answer {}; # This will fail. ``` ## [Coercion type](#Signature_literals "go to top of document")[§](#Coercion_type "direct link") To accept one type but coerce it automatically to another, use the accepted type as an argument to the target type. If the accepted type is [`Any`](/type/Any) it can be omitted. ```raku sub f(Int(Str) $want-int, Str() $want-str) { say $want-int.^name ~ ' ' ~ $want-str.^name } f '10', 10; # OUTPUT: «Int Str␤» sub foo(Date(Str) $d) { say $d.^name; say $d }; foo "2016-12-01"; # OUTPUT: «Date␤2016-12-01␤» ``` The coercion is performed by calling the method with the name of the type to coerce to, if it exists. In this example, we're calling the builtin method [`Date`](/type/Date) on the [`Str`](/type/Str) class. The method is assumed to return the correct type—no additional checks on the result are currently performed. Coercion can also be performed on return types: ```raku sub square-str (Int $x --> Str(Int)) { $x² } for 2,4, *² … 256 -> $a { say $a, "² is ", square-str( $a ).chars, " figures long"; } # OUTPUT: «2² is 1 figures long␤ # 4² is 2 figures long␤ # 16² is 3 figures long␤ # 256² is 5 figures long␤» ``` In this example, coercing the return type to [`Str`](/type/Str) allows us to directly apply string methods, such as the number of characters. **Note**: The appropriate method must be available on the argument, so be careful when trying to coerce custom types. ```raku class Foo { } sub bar(Foo(Int) $x) { say $x } bar(3); # OUTPUT: «Impossible coercion from 'Int' into 'Foo': no acceptable coercion method found␤» ``` # [Slurpy parameters](#Signature_literals "go to top of document")[§](#Slurpy_parameters "direct link") A function is variadic if it can take a varying number of arguments; that is, its arity is not fixed. Therefore, [optional](/language/signatures#Optional_and_mandatory_arguments), named, and slurpy parameters make routines that use them *variadic*, and by extension are called variadic arguments. Here we will focus on slurpy parameters, or simply *slurpies*. An array or hash parameter can be marked as *slurpy* by leading single (\*) or double asterisk (\*\*) or a leading plus (+). A slurpy parameter can bind to an arbitrary number of arguments (zero or more), and it will result in a type that is compatible with the sigil. These are called "slurpy" because they slurp up any remaining arguments to a function, like someone slurping up noodles. ```raku my $sig1 = :($a, @b); # exactly two arguments, second must be Positional my $sig2 = :($a, *@b); # at least one argument, @b slurps up any beyond that my $sig3 = :(*%h); # no positional arguments, but any number # of named arguments sub one-arg (@) { } sub slurpy (*@) { } one-arg (5, 6, 7); # ok, same as one-arg((5, 6, 7)) slurpy (5, 6, 7); # ok slurpy 5, 6, 7 ; # ok # one-arg(5, 6, 7) ; # X::TypeCheck::Argument # one-arg 5, 6, 7 ; # X::TypeCheck::Argument sub named-names (*%named-args) { %named-args.keys }; say named-names :foo(42) :bar<baz>; # OUTPUT: «foo bar␤» ``` Positional and named slurpies can be combined; named arguments (i.e., [`Pair`](/type/Pair)s) are collected in the specified hash, positional arguments in the array: ```raku sub combined-slurpy (*@a, *%h) { { array => @a, hash => %h } } # or: sub combined-slurpy (*%h, *@a) { ... } say combined-slurpy(one => 1, two => 2); # OUTPUT: «{array => [], hash => {one => 1, two => 2}}␤» say combined-slurpy(one => 1, two => 2, 3, 4); # OUTPUT: «{array => [3 4], hash => {one => 1, two => 2}}␤» say combined-slurpy(one => 1, two => 2, 3, 4, five => 5); # OUTPUT: «{array => [3 4], hash => {five => 5, one => 1, two => 2}}␤» say combined-slurpy(one => 1, two => 2, 3, 4, five => 5, 6); # OUTPUT: «{array => [3 4 6], hash => {five => 5, one => 1, two => 2}}␤» ``` Note that positional parameters aren't allowed after slurpy (or, in fact, after any type of variadic) parameters: ```raku :(*@args, $last); # ===SORRY!=== Error while compiling: # Cannot put required parameter $last after variadic parameters ``` Normally a slurpy parameter will create an [`Array`](/type/Array) (or compatible type), create a new [`Scalar`](/type/Scalar) container for each argument, and assign the value from each argument to those [`Scalar`](/type/Scalar)s. If the original argument also had an intermediary [`Scalar`](/type/Scalar) it is bypassed during this process, and is not available inside the called function. Sigiled parameters will always impose a context on the collected arguments. Sigilless parameters can also be used slurpily, preceded by a + sign, to work with whatever initial type they started with: ```raku sub zipi( +zape ) { zape.^name => zape }; say zipi( "Hey "); # OUTPUT: «List => (Hey )␤» say zipi( 1...* ); # OUTPUT: «Seq => (...)␤» ``` Slurpy parameters have special behaviors when combined with some [traits and modifiers](#Parameter_traits_and_modifiers), as described in [the section on slurpy array parameters](/language/signatures#Types_of_slurpy_array_parameters). Methods automatically get a `*%_` slurpy named parameter added if they don't have another slurpy named parameter declared. # [Types of slurpy array parameters](#Signature_literals "go to top of document")[§](#Types_of_slurpy_array_parameters "direct link") There are three variations to slurpy array parameters. * The single asterisk form flattens passed arguments. * The double asterisk form does not flatten arguments. * The plus form flattens according to the single argument rule. Each will be described in detail in the next few sections. As the difference between each is a bit nuanced, examples are provided for each to demonstrate how each slurpy convention varies from the others. ## [Flattened slurpy](#Signature_literals "go to top of document")[§](#Flattened_slurpy "direct link") Slurpy parameters declared with one asterisk will flatten arguments by dissolving one or more layers of bare [`Iterable`](/type/Iterable)s. ```raku my @array = <a b c>; my $list := <d e f>; sub a(*@a) { @a.raku.say }; a(@array); # OUTPUT: «["a", "b", "c"]␤» a(1, $list, [2, 3]); # OUTPUT: «[1
## signatures.md ## Chunk 2 of 2 , "d", "e", "f", 2, 3]␤» a([1, 2]); # OUTPUT: «[1, 2]␤» a(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, 1, 2, 3, 4, 5]␤» a(($_ for 1, 2, 3)); # OUTPUT: «[1, 2, 3]␤» ``` A single asterisk slurpy flattens all given iterables, effectively hoisting any object created with commas up to the top level. ## [Unflattened slurpy](#Signature_literals "go to top of document")[§](#Unflattened_slurpy "direct link") Slurpy parameters declared with two stars do not flatten any [`Iterable`](/type/Iterable) arguments within the list, but keep the arguments more or less as-is: ```raku my @array = <a b c>; my $list := <d e f>; sub b(**@b) { @b.raku.say }; b(@array); # OUTPUT: «[["a", "b", "c"],]␤» b(1, $list, [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]␤» b([1, 2]); # OUTPUT: «[[1, 2],]␤» b(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤» b(($_ for 1, 2, 3)); # OUTPUT: «[(1, 2, 3),]␤» ``` The double asterisk slurpy hides the nested comma objects and leaves them as-is in the slurpy array. ## [Single argument rule slurpy](#Signature_literals "go to top of document")[§](#Single_argument_rule_slurpy "direct link") A slurpy parameter created using a plus engages the *"single argument rule"*, which decides how to handle the slurpy argument based upon context. Basically, if only a single argument is passed and that argument is [`Iterable`](/type/Iterable), that argument is used to fill the slurpy parameter array. In any other case, `+@` works like `**@`. ```raku my @array = <a b c>; my $list := <d e f>; sub c(+@b) { @b.raku.say }; c(@array); # OUTPUT: «["a", "b", "c"]␤» c(1, $list, [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]␤» c([1, 2]); # OUTPUT: «[1, 2]␤» c(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤» c(($_ for 1, 2, 3)); # OUTPUT: «[1, 2, 3]␤» ``` For additional discussion and examples, see [Slurpy Conventions for Functions](/language/functions#Slurpy_conventions). # [Type captures](#Signature_literals "go to top of document")[§](#Type_captures "direct link") Type captures allow deferring the specification of a type constraint to the time the function is called. They allow referring to a type both in the signature and the function body. ```raku sub f(::T $p1, T $p2, ::C){ # $p1 and $p2 are of the same type T, that we don't know yet # C will hold a type we derive from a type object or value my C $division = $p1 / $p2; return sub (T $p1) { $division * $p1; } } # The first parameter is Int and so must be the 2nd. # We derive the 3rd type from calling the operator that is used in &f. my &s = f(10, 2, Int.new / Int.new); say s(2); # 10 / 2 * 2 == 10 ``` # [Positional vs. named arguments](#Signature_literals "go to top of document")[§](#Positional_vs._named_arguments "direct link") An argument can be *positional* or *named*. By default, arguments are positional, except slurpy hash and arguments marked with a leading colon `:`. The latter is called a [colon-pair](/type/Pair). Check the following signatures and what they denote: ```raku $sig1 = :($a); # a positional argument $sig2 = :(:$a); # a named argument of name 'a' $sig3 = :(*@a); # a slurpy positional argument $sig4 = :(*%h); # a slurpy named argument ``` On the caller side, positional arguments are passed in the same order as the arguments are declared. ```raku sub pos($x, $y) { "x=$x y=$y" } pos(4, 5); # OUTPUT: «x=4 y=5» ``` In the case of named arguments and parameters, only the name is used for mapping arguments to parameters. If a fat arrow is used to construct a [`Pair`](/type/Pair) only those with valid identifiers as keys are recognized as named arguments. ```raku sub named(:$x, :$y) { "x=$x y=$y" } named( y => 5, x => 4); # OUTPUT: «x=4 y=5» ``` You can invoke the routine using a variable with the same name as the named argument; in that case `:` will be used for the invocation so that the name of the variable is understood as the key of the argument. ```raku sub named-shortcut( :$shortcut ) { say "Looks like $shortcut" } named-shortcut( shortcut => "to here"); # OUTPUT: «Looks like to here␤» my $shortcut = "Þor is mighty"; named-shortcut( :$shortcut ); # OUTPUT: «Looks like Þor is mighty␤» ``` It is possible to have a different name for a named argument than the variable name: ```raku sub named(:official($private)) { "Official business!" if $private } named :official; ``` # [Argument aliases](#Signature_literals "go to top of document")[§](#Argument_aliases "direct link") The [colon-pair](/type/Pair) syntax can be used to provide aliases for arguments: ```raku sub alias-named(:color(:$colour), :type(:class($kind))) { say $colour ~ " " ~ $kind } alias-named(color => "red", type => "A"); # both names can be used alias-named(colour => "green", type => "B"); # more than two names are ok alias-named(color => "white", class => "C"); # every alias is independent ``` The presence of the colon `:` will decide whether we are creating a new named argument or not. `:$colour` will not only be the name of the aliased variable, but also a new named argument (used in the second invocation). However, `$kind` will just be the name of the aliased variable, that does not create a new named argument. More uses of aliases can be found in [sub MAIN](/language/create-cli#sub_MAIN). A function with named arguments can be called dynamically, dereferencing a [`Pair`](/type/Pair) with `|` to turn it into a named argument. ```raku multi f(:$named) { note &?ROUTINE.signature }; multi f(:$also-named) { note &?ROUTINE.signature }; for 'named', 'also-named' -> $n { f(|($n => rand)) # OUTPUT: «(:$named)␤(:$also-named)␤» } my $pair = :named(1); f |$pair; # OUTPUT: «(:$named)␤» ``` The same can be used to convert a [`Hash`](/type/Hash) into named arguments. ```raku sub f(:$also-named) { note &?ROUTINE.signature }; my %pairs = also-named => 4; f |%pairs; # OUTPUT: «(:$also-named)␤» ``` A [`Hash`](/type/Hash) that contains a list may prove problematic when slipped into named arguments. To avoid the extra layer of containers coerce to [`Map`](/type/Map) before slipping. ```raku class C { has $.x; has $.y; has @.z }; my %h = <x y z> Z=> (5, 20, [1,2]); say C.new(|%h.Map); # OUTPUT: «C.new(x => 5, y => 20, z => [1, 2])␤» ``` You can create as many aliases to a named argument as you want: ```raku sub alias-named(:color(:$colour), :variety(:style(:sort(:type(:class($kind)))))) { return $colour ~ " " ~ $kind } say alias-named(color => "red", style => "A"); say alias-named(colour => "green", variety => "B"); say alias-named(color => "white", class => "C"); ``` You can create named arguments that do not create any variables by making the argument an alias for an [anonymous argument](#index-entry-anonymous_arguments). This can be useful when using named arguments solely as a means of selecting a `multi` candidate, which is often the case with traits, for instance: ```raku # Timestamps calls to a routine. multi trait_mod:<is>(Routine:D $r is raw, :timestamped($)!) { $r does my role timestamped { has Instant:D @.timestamps }; $r.wrap: -> | { ENTER $r.timestamps.push: now; callsame }; } sub foo is timestamped { } foo; say +&foo.?timestamps; # OUTPUT: «1␤» ``` # [Optional and mandatory arguments](#Signature_literals "go to top of document")[§](#Optional_and_mandatory_arguments "direct link") Positional parameters are mandatory by default, and can be made optional with a default value or a trailing question mark: ```raku $sig1 = :(Str $id); # required parameter $sig2 = :($base = 10); # optional parameter, default value 10 $sig3 = :(Int $x?); # optional parameter, default is the Int type object ``` Named parameters are optional by default, and can be made mandatory with a trailing exclamation mark: ```raku $sig1 = :(:%config); # optional parameter $sig2 = :(:$debug = False); # optional parameter, defaults to False $sig3 = :(:$name!); # mandatory 'name' named parameter ``` Default values can depend on previous parameters, and are (at least notionally) computed anew for each call ```raku $sig1 = :($goal, $accuracy = $goal / 100); $sig2 = :(:$excludes = ['.', '..']); # a new Array for every call ``` ## [Was an argument passed for a parameter?](#Signature_literals "go to top of document")[§](#Was_an_argument_passed_for_a_parameter? "direct link") Table showing checks of whether an argument was passed for a given parameter: | Parameter kind | Example | Comment | Check for no arg passed | | --- | --- | --- | --- | | Slurpy | \*@array | Don't check using .defined | if not @array | | Required | $foo | Can't be omitted | (not applicable) | | Optional | @bar = default | Pick a suitable default¹ | if @bar =:= default | ¹ A suitable default is an Object that has a distinct identity, as may be checked by the [`WHICH`](https://docs.raku.org/type/Mu#method_WHICH) method. A parameter with a default is always *optional*, so there is no need to mark it with a `?` or the `is optional` trait. Then you can use the `=:=` [container identity operator](https://docs.raku.org/language/operators#infix_=:=) in the body of the routine to check whether this exact default was bound to the parameter. Example with a positional parameter: ```raku my constant PositionalAt = Positional.new; sub a (@list = PositionalAt) { say @list =:= PositionalAt } a; # OUTPUT: «True␤» a [1, 2, 3]; # OUTPUT: «False␤» ``` Example with some scalar parameters: ```raku my constant AnyAt = Any.new; sub b ($x=AnyAt, :$y=AnyAt) { say $x =:= AnyAt; say $y =:= AnyAt } b 1; # OUTPUT: «False␤True␤» b 1, :2y; # OUTPUT: «False␤False␤» ``` If your parameters are typed, then the [type smileys](https://docs.raku.org/language/glossary#Type_smiley) can be used with [`multi`](https://docs.raku.org/language/functions#Multi-dispatch)s like this: ```raku multi c (Int:U $z) { say 'Undefined' } multi c (Int:D $z) { say 'Defined' } multi c (Int $z?) { say 'Omitted' } c; #Omitted c (Int); #Undefined c 42; #Defined ``` The examples use names like `PositionalAt` to reflect that the `.WHICH` test returns an object of type [`ObjAt`](/type/ObjAt), you are free to make up you own names. # [Dynamic variables](#Signature_literals "go to top of document")[§](#Dynamic_variables "direct link") [Dynamic variables](/language/variables#The_*_twigil) are allowed in signatures although they don't provide special behavior because argument binding does connect two scopes anyway. # [Destructuring arguments](#Signature_literals "go to top of document")[§](#Destructuring_arguments "direct link") Non-scalar parameters can be followed or substituted by a sub-signature in parentheses, which will destructure the argument given. The destructuring of a list is just its elements: ```raku sub first(@array ($first, *@rest)) { $first } ``` or ```raku sub first([$f, *@]) { $f } ``` While the destructuring of a hash is its pairs: ```raku sub all-dimensions(% (:length(:$x), :width(:$y), :depth(:$z))) { $x andthen $y andthen $z andthen True } ``` Pointy loops can also destructure hashes, allowing assignment to variables: ```raku my %hhgttu = (:40life, :41universe, :42everything); for %hhgttu -> (:$key, :$value) { say "$key → $value"; } # OUTPUT: «universe → 41␤life → 40␤everything → 42␤» ``` In general, an object is destructured based on its attributes. A common idiom is to unpack a [`Pair`](/type/Pair)'s key and value in a for loop: ```raku for <Peter Paul Merry>.pairs -> (:key($index), :value($guest)) { } ``` However, this unpacking of objects as their attributes is only the default behavior. To make an object get destructured differently, change its [`Capture`](/routine/Capture) method. # [Sub-signatures](#Signature_literals "go to top of document")[§](#Sub-signatures "direct link") To match against a compound parameter use a sub-signature following the argument name in parentheses. ```raku sub foo(|c(Int, Str)){ put "called with {c.raku}" }; foo(42, "answer"); # OUTPUT: «called with \(42, "answer")␤» ``` # [Long names](#Signature_literals "go to top of document")[§](#Long_names "direct link") To exclude certain parameters from being considered in multiple dispatch, separate them with a double semicolon. ```raku multi f(Int $i, Str $s;; :$b) { say "$i, $s, {$b.raku}" }; f(10, 'answer'); # OUTPUT: «10, answer, Any␤» ``` # [Capture parameters](#Signature_literals "go to top of document")[§](#Capture_parameters "direct link") Prefixing a parameter with a vertical bar `|` makes the parameter a [`Capture`](/type/Capture), using up all the remaining positional and named arguments. This is often used in `proto` definitions (like `proto foo (|) {*}`) to indicate that the routine's [`multi` definitions](/syntax/multi) can have any [type constraints](#Type_constraints). See [proto](/language/functions#proto) for an example. If bound to a variable, arguments can be forwarded as a whole using the slip operator `|`. ```raku sub a(Int $i, Str $s) { say $i.^name ~ ' ' ~ $s.^name } sub b(|c) { say c.^name; a(|c) } b(42, "answer"); # OUTPUT: «Capture␤Int Str␤» ``` # [Parameter traits and modifiers](#Signature_literals "go to top of document")[§](#Parameter_traits_and_modifiers "direct link") By default, parameters are bound to their argument and marked as read-only. One can change that with traits on the parameter. The `is copy` trait causes the argument to be copied, and allows it to be modified inside the routine ```raku sub count-up($x is copy) { $x = ∞ if $x ~~ Whatever; .say for 1..$x; } ``` The `is rw` trait, which stands for *is read-write*, makes the parameter bind to a variable (or other writable container). Assigning to the parameter changes the value of the variable at the caller side. ```raku sub swap($x is rw, $y is rw) { ($x, $y) = ($y, $x); } ``` On slurpy parameters, `is rw` is reserved for future use by language designers. The [`is raw` trait](/type/Parameter#method_raw) is automatically applied to parameters declared with a [backslash](/language/variables#Sigilless_variables) or a [plus sign](#Single_argument_rule_slurpy) as a "sigil", and may also be used to make normally sigiled parameters behave like these do. In the special case of slurpies, which normally produce an [`Array`](/type/Array) full of [`Scalar`](/type/Scalar)s as described above, `is raw` will instead cause the parameter to produce a [`List`](/type/List). Each element of that list will be bound directly as raw parameter. To explicitly ask for a read-only parameter use the `is readonly` trait. Please note that this applies only to the container. The object inside can very well have mutator methods and Raku will not enforce immutability on the attributes of the object. Traits can be followed by the where clause: ```raku sub ip-expand-ipv6($ip is copy where m:i/^<[a..f\d\:]>**3..39$/) { } ```
## dist_cpan-TYIL-Matrix-Bot.md # NAME Matrix::Bot # AUTHOR Patrick Spek [p.spek@tyil.work](mailto:p.spek@tyil.work) # VERSION 0.2.0 # Description A framework for writing Matrix bots # Installation Install this module through [zef](https://github.com/ugexe/zef): ``` zef install Matrix::Bot ``` # Usage ## Configuring the bot First off, you have to instantiate the bot correctly. For this, a few arguments must be passed to `new`. ``` use Matrix::Bot; my $bot = Matrix::Bot.new( home-server => "https://matrix.org", username => %*ENV<USER>, password => "", access-token => "", plugins => [], ); $bot.run; ``` You must specify a password or access-token. If you supply both, the password will be ignored, and the access-token will be used directly. The list of plugins has to be filled with classes which implement `Matrix::Bot::Plugin`. The `run` call starts the bots event loop. It will connect to Matrix, and start retrieving new messages on the channels it is joined in. ## Plugins The simplest usage of the module would be using the `handle-room-text` method in a plugin. For instance, to repond to `"ping"` messages with a `"pong"`, you can write a plugin as follows. ``` use Matrix::Bot::Plugin; class Local::Matrix::Plugin is Matrix::Bot::Plugin { multi method handle-room-text ($e where * eq "ping") { "pong" } } ``` ## Logging There is logging available in the module, through [`LogP6`](https://modules.perl6.org/dist/LogP6:cpan:ATROXAPER). This same logging object can be accessed by plugins, so they can log to the same stream when desired. To show all logging, you can set up a `filter`. ``` use LogP6 :configure; filter(name => "", level => $trace, :update); ``` If you only want certain logging to be shown, you can set up one or more `cliche` calls instead. For instance, the following `cliche` shows only the messages on a channel. ``` cliche( name => "messages", matcher => "Matrix::Bot/message", grooves => ( writer( pattern => "%msg", handle => $*OUT, filter(level => $info), ), ), ); ``` More information on how to use `cliche`s, `filter`s and `LogP6` in general can be found in the `LogP6` documentation. The following traits are used throughout `Matrix::Bot`: * `Matrix::Bot` * `Matrix::Bot/message` * `Matrix::Bot/plugin($name)` (The `$name` corresponds to the name of the plugin's class) # License This module is distributed under the terms of the AGPL-3.0.
## dist_zef-kuerbis-Term-TablePrint.md # NAME Term::TablePrint - Print a table to the terminal and browse it interactively. # SYNOPSIS ``` use Term::TablePrint :print-table; my @table = ( [ 'id', 'name' ], [ 1, 'Ruth' ], [ 2, 'John' ], [ 3, 'Mark' ], [ 4, 'Nena' ], ); # Functional style: print-table( @table ); # or OO style: my $pt = Term::TablePrint.new(); $pt.print-table( @table, :mouse(1) ); ``` # DESCRIPTION `print-table` shows a table and lets the user interactively browse it. It provides a cursor which highlights the row on which it is located. The user can scroll through the table with the different cursor keys. ## KEYS Keys to move around: * the ArrowDown key (or the j key) to move down and the ArrowUp key (or the k key) to move up. * the PageUp key (or Ctrl-P) to go to the previous page, the PageDown key (or Ctrl-N) to go to the next page. * the Insert key to go back 10 pages, the Delete key to go forward 10 pages. * the Home key (or Ctrl-A) to jump to the first row of the table, the End key (or Ctrl-E) to jump to the last row of the table. If *table-expand* is set to `0`, the Enter key closes the table if the cursor is on the first row. If *table-expand* is enabled and the cursor is on the first row, pressing Enter three times in succession closes the table. If the cursor is auto-jumped to the first row, it is required only one Enter to close the table. If the cursor is not on the first row: * with the option *table-expand* disabled the cursor jumps to the table head if Enter is pressed. * with the option *table-expand* enabled each column of the selected row is output in its own line preceded by the column name if Enter is pressed. Another Enter closes this output and goes back to the table output. If a row is selected twice in succession, the pointer jumps to the first row. If the size of the window has changed, the screen is rewritten as soon as the user presses a key. Ctrl-F opens a prompt. A regular expression is expected as input. This enables one to only display rows where at least one column matches the entered pattern. See option [search](#search). ## Output If the option table-expand is enabled and a row is selected with Enter, each column of that row is output in its own line preceded by the column name. If the table has more rows than the terminal, the table is divided up on as many pages as needed automatically. If the cursor reaches the end of a page, the next page is shown automatically until the last page is reached. Also if the cursor reaches the topmost line, the previous page is shown automatically if it is not already the first page. For the output on the screen the table elements are modified. All the modifications are made on a copy of the original table data. * If an element is not defined the value from the option *undef* is assigned to that element. * Each character tabulation (`\t`) is replaces with a space. * Vertical tabulations (`\v+`) are squashed to two spaces. * Code points from the ranges of `control`, `surrogate` and `noncharacter` are removed. * If the option *squash-spaces* is enabled leading and trailing spaces are removed and multiple consecutive spaces are squashed to a single space. * If an element looks like a number it is right-justified, else it is left-justified. If the terminal is too narrow to print the table, the columns are adjusted to the available width automatically. * First, if the option *trunc-fract-first* is enabled and if there are numbers that have a fraction, the fraction is truncated up to two decimal places. * Then columns wider than *min-col-width* are trimmed. See option [min-col-width](#min-col-width). * If it is still required to lower the row width all columns are trimmed until they fit into the terminal. # CONSTRUCTOR The constructor method `new` can be called with named arguments. For the valid options see [OPTIONS](#OPTIONS). Setting the options in `new` overwrites the default values for the instance. # ROUTINES ## print-table `print-table` prints the table passed with the first argument. ``` print-table( @table, *%options ); ``` The first argument is an list of arrays. The first array of these arrays holds the column names. The following arrays are the table rows where the elements are the field values. The following arguments set the options (key-values pairs). # OPTIONS Defaults may change in future releases. ## prompt String displayed above the table. ## color If this option is enabled, SRG ANSI escape sequences can be used to color the screen output. Colors are reset to normal after each table cell. 0 - off (default) 1 - on (current selected element not colored) 2 - on (current selected element colored) ## decimal-separator If set, numbers use *decimal-separator* as the decimal separator instead of the default decimal separator. Allowed values: a character with a print width of `1`. If an invalid values is passed, *decimal-separator* falls back to the default value. Default: . (dot) ## footer If set (string), *footer* is added in the bottom line. ## max-rows Set the maximum number of used table rows. The used table rows are kept in memory. To disable the automatic limit set *max-rows* to `0`. If the number of table rows is equal to or higher than *max-rows*, the last row of the output says `REACHED LIMIT "MAX_ROWS": $limit` or `=LIMIT= $limit` if the previous doesn't fit in the row. Default: 50\_000 ## max-width-exp Set a maximum width of the expanded table row output. (See option [table-expand](#table-expand)). ## min-col-width The columns with a width below or equal *min-col-width* are only trimmed if it is still required to lower the row width despite all columns wider than *min-col-width* have been trimmed to *min-col-width*. Default: 30 ## mouse Set the *mouse* mode (see option `mouse` in [Term::Choose](https://github.com/kuerbis/Term-Choose-p6)). Default: 0 ## pad-row-edges Add a space at the beginning and end of each row. 0 - off (default) 1 - enabled ## progress-bar Set the progress bar threshold. If the number of fields (rows x columns) is higher than the threshold, a progress bar is shown while preparing the data for the output. Setting the value to `0` disables the progress bar. Default: 5\_000 ## save-screen 0 - off (default) 1 - use the alternate screen ## search Set the behavior of Ctrl-F. 0 - off 1 - case-insensitive search (default) 2 - case-sensitive search ## squash-spaces If *squash-spaces* is enabled, consecutive spaces are squashed to one space and leading and trailing spaces are removed. Default: 0 ## tab-width Set the number of spaces between columns. If *format* is set to `2` and *tab-width* is even, the spaces between the columns are *tab-width* + 1 print columns. Default: 2 ## table-expand If *table-expand* is enabled and Enter is pressed, the selected table row prints with each column on a new line. Pressing Enter again closes this view. The next Enter key press will automatically jump the cursor to the first row. If the cursor has automatically jumped to the first row, pressing Enter will close the table instead of expanding the first row. Pressing any key other than Enter resets these special behaviors. ``` .----------------------------. .----------------------------. |col1 | col2 | col3 | col3 | | | |-----|--------|------|------| |col1 : .......... | |.... | ...... | .... | .... | | | |.... | ...... | .... | .... | |col2 : .....................| >|.... | ...... | .... | .... | | .......... | |.... | ...... | .... | .... | | | |.... | ...... | .... | .... | |col3 : ....... | |.... | ...... | .... | .... | | | |.... | ...... | .... | .... | |col4 : ............. | |.... | ...... | .... | .... | | | '----------------------------' '----------------------------' ``` If *table-expand* is set to `0`, the cursor jumps to the to first row (if not already there) when Enter is pressed. 0 - off 1 - on (default) ## trunc-fract-first If the terminal width is not wide enough and this option is enabled, the first step to reduce the width of the columns is to truncate the fraction part of numbers to 2 decimal places. ## undef Set the string that will be shown on the screen instead of an undefined field. Default: "" (empty string) # ENVIRONMET VARIABLES ## multithreading `Term::TablePrint` uses multithreading when preparing the list for the output; the number of threads to use can be set with the environment variable `TC_NUM_THREADS`. # REQUIREMENTS ## Escape sequences The control of the cursor location, the highlighting of the cursor position is done via escape sequences. By default `Term::Choose` uses `tput` to get the appropriate escape sequences. If the environment variable `TC_ANSI_ESCAPES` is set to a true value, hardcoded ANSI escape sequences are used directly without calling `tput`. The escape sequences to enable the *mouse* mode are always hardcoded. If the environment variable `TERM` is not set to a true value, `vt100` is used instead as the terminal type for `tput`. ## Monospaced font It is required a terminal that uses a monospaced font which supports the printed characters. ## Restrictions Term::TablePrint is not installable on Windows. # CREDITS Thanks to the people from [Perl-Community.de](http://www.perl-community.de), from [stackoverflow](http://stackoverflow.com) and from #perl6 on irc.freenode.net for the help. # AUTHOR Matthäus Kiem [cuer2s@gmail.com](mailto:cuer2s@gmail.com) # LICENSE AND COPYRIGHT Copyright 2016-2025 Matthäus Kiem. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-alabamenhu-Intl-Number-Plural.md # IntlNumberPlural A number to determine the plural count category of a number for use in localization contexts **Warning:** The name may change in the near-ish future (mid 2021) to be cohesive with other modules. If it changes, I will continue to `provide` under the current name for at least one year. To use: ``` use Intl::Number::Plural # English Arabic Russian plural-count 0; # other zero many plural-count 1; # one one one plural-count 2; # other two few plural-count 3; # other few few plural-count 6; # other few many ``` There are six strings that can be returned by the function: **zero**, **one**, **two**, **few**, **many**, and **other**. *Other* is the default and is used for all values in languages that do not have grammatical number. Note that (as evidenced by the above table), the labels don't always correspond to what one might intuitively think. Consequently, this is a module generally oriented towards makes of localization frameworks, and less so towards end-users. The `plural-count` sub currently takes one or two positional arguments: * **`number`** (required) The number whose count is to be determined. * **`from`, `to`** The count is calculated for a range (`from .. to`). There are two optional named parameters * **`:language`** The language to be used in determining the count. Defaults to `user-language`. * **`:type`** Acceptable values are **cardinal** and **ordinal**, defaults to *cardinal*. Some languages behave differently for these two types of numbers. Ignored for range calculations which always use *cardinal* ## Dependencies * `Intl::CLDR` Houses the data for calculating the counts * `Intl::UserLanguage` Determines the default language when not provided ## Todo * Use `Intl::CLDR` enums once available. * Add tests for major languages ## Version History * **v0.5.4** * Fixed a small bug (*mod* → *%* for CLDR's *mod*) * **v0.5.3** * Updated CLDR reference (was `.plurals` in beta, now is `.grammar.plurals`) * **v0.5.2** * Added support for ranged * **v0.5.1** * Initial release as separate module * **v0.1** – **v0.5** * Included as a part of `Intl::CLDR` ## License and Copyright © 2020-2021 Matthew Stephen Stuckwisch. Licensed under the Artistic License 2.0.
## print.md print Combined from primary sources listed below. # [In IO::Socket::Async](#___top "go to top of document")[§](#(IO::Socket::Async)_method_print "direct link") See primary documentation [in context](/type/IO/Socket/Async#method_print) for **method print**. ```raku method print(IO::Socket::Async:D: Str $str --> Promise) ``` Attempt to send `$str` on the `IO::Socket::Async` that will have been obtained indirectly via `connect` or `listen`, returning a [`Promise`](/type/Promise) that will be kept with the number of bytes sent or broken if there was an error sending. # [In IO::Handle](#___top "go to top of document")[§](#(IO::Handle)_method_print "direct link") See primary documentation [in context](/type/IO/Handle#method_print) for **method print**. ```raku multi method print(**@text --> True) multi method print(Junction:D --> True) ``` Writes the given `@text` to the handle, coercing any non-[`Str`](/type/Str) objects to [`Str`](/type/Str) by calling [`.Str`](/routine/Str) method on them. [`Junction`](/type/Junction) arguments [autothread](/language/glossary#Autothreading) and the order of printed strings is not guaranteed. See [write](/routine/write) to write bytes. Attempting to call this method when the handle is [in binary mode](/type/IO/Handle#method_encoding) will result in [`X::IO::BinaryMode`](/type/X/IO/BinaryMode) exception being thrown. ```raku my $fh = 'path/to/file'.IO.open: :w; $fh.print: 'some text'; $fh.close; ``` # [In role IO::Socket](#___top "go to top of document")[§](#(role_IO::Socket)_method_print "direct link") See primary documentation [in context](/type/IO/Socket#method_print) for **method print**. ```raku method print(IO::Socket:D: Str(Cool) $string) ``` Writes the supplied string to the socket, thus sending it to other end of the connection. The binary version is [method write](#method_write). Fails if the socket is not connected. # [In Proc::Async](#___top "go to top of document")[§](#(Proc::Async)_method_print "direct link") See primary documentation [in context](/type/Proc/Async#method_print) for **method print**. ```raku method print(Proc::Async:D: Str() $str, :$scheduler = $*SCHEDULER) ``` Write the text data in `$str` to the standard input stream of the external program, encoding it as UTF-8. Returns a [`Promise`](/type/Promise) that will be kept once the data has fully landed in the input buffer of the external program. The `Proc::Async` object must be created for writing (with `Proc::Async.new(:w, $path, @args)`). Otherwise an [`X::Proc::Async::OpenForWriting`](/type/X/Proc/Async/OpenForWriting) exception will the thrown. `start` must have been called before calling method print, otherwise an [`X::Proc::Async::MustBeStarted`](/type/X/Proc/Async/MustBeStarted) exception is thrown. # [In Mu](#___top "go to top of document")[§](#(Mu)_method_print "direct link") See primary documentation [in context](/type/Mu#method_print) for **method print**. ```raku multi method print(--> Bool:D) ``` Prints value to `$*OUT` after stringification using `.Str` method without adding a newline at end. ```raku "abc\n".print; # OUTPUT: «abc␤» ``` # [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_sub_print "direct link") See primary documentation [in context](/type/independent-routines#sub_print) for **sub print**. ```raku multi print(**@args --> True) multi print(Junction:D --> True) ``` Prints the given text on standard output (the [`$*OUT`](/language/variables#index-entry-%24%2AOUT) filehandle), coercing non-[`Str`](/type/Str) objects to [`Str`](/type/Str) by calling [`.Str` method](/routine/Str). [`Junction`](/type/Junction) arguments [autothread](/language/glossary#Autothreading) and the order of printed strings is not guaranteed. ```raku print "Hi there!\n"; # OUTPUT: «Hi there!␤» print "Hi there!"; # OUTPUT: «Hi there!» print [1, 2, 3]; # OUTPUT: «1 2 3» print "Hello" | "Goodbye"; # OUTPUT: «HelloGoodbye» ``` To print text and include the trailing newline, use [`put`](/type/independent-routines#sub_put).
## dist_github-scovit-NativeHelpers-CBuffer.md [![Build Status](https://travis-ci.org/scovit/NativeHelpers-CBuffer.svg?branch=master)](https://travis-ci.org/scovit/NativeHelpers-CBuffer) # NAME NativeHelpers::CBuffer - A type for storing a caller allocated Buffer # SYNOPSIS ``` use NativeHelpers::CBuffer; class CBuffer is repr('CPointer') is export ``` The CBuffer object, is `repr("CPointer")`, as such, it can be directly used in `NativeCall` signatures in the place of a Pointer. # DESCRIPTION NativeHelpers::CBuffer is a convinent way to store buffers and C NULL terminated strings # EXAMPLE ``` use NativeHelpers::CBuffer; my CBuffer $buf = CBuffer.new(100); # Allocates a buffer of 100 bytes sub strncpy(CBuffer, Str, size_t) is native { }; strncpy($buf, "Uella!", 100); say $buf; # Uella! ``` # METHODS ## multi new (Int) ``` multi method new(Int $size, :$with, :$of-type where { $of-type ∈ $types } = uint8) ``` Allocates a buffer of size `$size` elements, of type `$of-type` and with content a copy of `$with`. Where `$with` can be either a Str or a Blob, and `$of-type` can be any of: ``` my $types = (uint8, int8, uint16, int16, uint32, int32, uint64, int64, size_t, long, ulong, longlong, ulonglong); ``` ## multi new (Blob) ``` multi method new(Blob $init) ``` Allocates a buffer and store the content of the `$init` parameter. ## multi new (Str) ``` multi method new(Str $init) ``` Allocates a buffer and store the content of the `$init` parameter as a NULL-terminated ASCII string. ## elems ``` method elems(--> Int:D) ``` Return the number of elements stored ## bytes ``` method bytes(--> Int:D) ``` Return the number of bytes stored ## type ``` method type() ``` Return the type of the elements stored ## Blob ``` method Blob(--> Blob:D) ``` Return a copy of the content as a Blob ## Pointer ``` method Pointer(--> Pointer) ``` Return the pointer to the allocated buffer of type Pointer[self.type] ## Str ``` method Str(--> Str:D) ``` Return a Str with the content decoded as null-terminated ASCII ## gist same as `method Str` ## free ``` method free() ``` Calls `free` the allocated buffer # BUGS, TODOS and WARNINGS At the moment, the `CBuffer` is immutable on the `perl` side, once created and initialized, it's content can be modified only by `C` functions. At the moment, the CBuffer is not resizable. The `CBuffer` uses `NativeCall` to allocate memory, beware of not using `CBuffer` in modules to allocate runtime memory during compilation. In other words, do not use `CBuffer.new` in `BEGIN` blocks or `constant` declarations, any abuse will result in Segmentation faults and/or memory corruption! In order to declare `C`-stile `#define` constants in modules, use `perl` sub (or macro) instead: ``` # the following, is equivalent to #define STRING_CONST "The string" sub STRING_CONST is export { CBuffer.new("The string") }; ``` # AUTHOR Vittore F. Scolari [vittore.scolari@pasteur.fr](mailto:vittore.scolari@pasteur.fr) # COPYRIGHT AND LICENSE Copyright 2017 Institut Pasteur This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-antononcube-WWW-Gemini.md # WWW::Gemini Raku package for connecting with [Google's Gemini](https://gemini.google.com/app). It is based on the Web API described in [Gemini's API documentation](https://ai.google.dev/docs/gemini_api_overview). The design and implementation of the package closely follows those of ["WWW::PaLM"](https://raku.land/zef:antononcube/WWW::PaLM), [AAp1], and ["WWW::OpenAI"](https://raku.land/zef:antononcube/WWW::OpenAI), [AAp2]. ## Installation From [Zef ecosystem](https://raku.land): ``` zef install WWW::Gemini ``` From GitHub: ``` zef install https://github.com/antononcube/Raku-WWW-Gemini ``` --- ## Usage examples Show models: ``` use WWW::Gemini; gemini-models() ``` ``` # (models/chat-bison-001 models/text-bison-001 models/embedding-gecko-001 models/gemini-1.0-pro-vision-latest models/gemini-pro-vision models/gemini-1.5-pro-latest models/gemini-1.5-pro-001 models/gemini-1.5-pro-002 models/gemini-1.5-pro models/gemini-1.5-flash-latest models/gemini-1.5-flash-001 models/gemini-1.5-flash-001-tuning models/gemini-1.5-flash models/gemini-1.5-flash-002 models/gemini-1.5-flash-8b models/gemini-1.5-flash-8b-001 models/gemini-1.5-flash-8b-latest models/gemini-1.5-flash-8b-exp-0827 models/gemini-1.5-flash-8b-exp-0924 models/gemini-2.0-flash-exp models/gemini-2.0-flash models/gemini-2.0-flash-001 models/gemini-2.0-flash-exp-image-generation models/gemini-2.0-flash-lite-001 models/gemini-2.0-flash-lite models/gemini-2.0-flash-lite-preview-02-05 models/gemini-2.0-flash-lite-preview models/gemini-2.0-pro-exp models/gemini-2.0-pro-exp-02-05 models/gemini-exp-1206 models/gemini-2.0-flash-thinking-exp-01-21 models/gemini-2.0-flash-thinking-exp models/gemini-2.0-flash-thinking-exp-1219 models/learnlm-1.5-pro-experimental models/gemma-3-27b-it models/embedding-001 models/text-embedding-004 models/gemini-embedding-exp-03-07 models/gemini-embedding-exp models/aqa models/imagen-3.0-generate-002) ``` Show text generation: ``` .say for gemini-generate-content('what is the population in Brazil?', format => 'values'); ``` ``` # The population of Brazil is estimated to be around **214 million** people. ``` Using a synonym function: ``` .say for gemini-generation('Who wrote the book "Dune"?'); ``` ``` # {candidates => [{avgLogprobs => -0.096543987592061356, content => {parts => [{text => Frank Herbert wrote the book "Dune". # }], role => model}, finishReason => STOP, safetyRatings => [{category => HARM_CATEGORY_HATE_SPEECH, probability => NEGLIGIBLE} {category => HARM_CATEGORY_DANGEROUS_CONTENT, probability => NEGLIGIBLE} {category => HARM_CATEGORY_HARASSMENT, probability => NEGLIGIBLE} {category => HARM_CATEGORY_SEXUALLY_EXPLICIT, probability => NEGLIGIBLE}]}], modelVersion => gemini-2.0-flash-lite, usageMetadata => {candidatesTokenCount => 9, candidatesTokensDetails => [{modality => TEXT, tokenCount => 9}], promptTokenCount => 7, promptTokensDetails => [{modality => TEXT, tokenCount => 7}], totalTokenCount => 16}} ``` ### Embeddings Show text embeddings: ``` use Data::TypeSystem; my @vecs = gemini-embed-content(["say something nice!", "shout something bad!", "where is the best coffee made?"], format => 'values'); say "Shape: ", deduce-type(@vecs); .say for @vecs; ``` ``` # Shape: Vector(Vector((Any), 768), 3) # [0.016757688 0.017702084 -0.043992538 -0.025983252 0.052694283 0.023884298 0.013686326 -0.02248133 0.0021763463 0.040576532 -0.013036139 0.015129898 0.009404442 0.01522977 0.0011340177 -0.029875923 0.02219129 0.021630127 0.03814696 0.007994547 0.014330443 0.040917326 -0.014014356 0.011249091 0.023865165 -0.025344135 0.020038605 -0.038383674 -0.039518733 -0.014953337 -0.02870626 0.03086878 -0.042787425 -0.0027894953 0.017162042 -0.070672944 -0.016016882 0.024234159 0.010077978 0.0014812651 0.040401507 -0.04346081 -0.036537044 0.0052581728 0.0064726775 0.008173016 -0.029299207 0.027511297 -0.0058303797 -0.023713073 0.039252512 0.0033487938 0.03993644 -0.015658226 -0.017031452 -0.022707172 0.06679675 0.0032277305 -0.02230025 0.022152044 0.014874753 -0.00136873 0.03352251 -0.004448758 -0.026943868 -0.058405127 -0.037803523 0.004574509 0.03462886 -0.005420063 -0.024909113 -0.06207924 0.0428224 0.0013599173 0.0115842065 -0.1609258 -0.016668154 0.05684006 -0.008497979 -0.023582436 0.010075421 -0.0649313 -0.09365824 -0.033277307 -0.09147627 0.019106463 -0.045750245 -0.017805588 0.017972797 0.039208062 -0.028703427 -0.012423551 0.047374453 -0.063771494 0.0014980073 0.080718316 -0.038440213 -0.04490549 0.048766267 -0.00539962 ...] # [0.033223055 0.0018116906 -0.07440699 -0.021762004 0.03228775 0.01939071 -0.003863616 -0.027377095 -0.005019851 0.056212872 -0.008741259 0.004262736 -0.031406447 0.008458018 0.007313063 -0.05057528 -0.005300286 0.01239522 0.045507118 0.017396107 0.011812003 0.029268533 -0.015651813 -0.00051697926 0.033039205 -0.0017556052 0.04230599 -0.050437044 -0.043366376 -0.025667293 -0.02911765 0.020267427 -0.042375922 0.0062713847 -0.009924581 -0.086508036 -0.022569956 0.021235818 0.02843833 -0.01756704 0.014417602 -0.020378849 -0.025663767 0.008375962 0.010325511 0.02015601 -0.024495931 0.024163608 0.0004565165 -0.053494856 0.041665524 -0.008337157 0.05229979 -0.03135205 -0.010063192 -0.055503994 0.070490986 0.0024730589 -0.019906597 0.034515504 0.0072045126 0.00527267 0.022652755 0.0032228027 -0.0141800335 -0.08241557 -0.039493777 0.0031935328 0.06465964 0.015602824 0.00011159801 -0.05484996 0.027683752 0.0032429171 0.0077458476 -0.15004066 -0.011095668 0.05837049 -0.005506853 -0.00490528 0.0020464614 -0.038616516 -0.085237235 -0.027988821 -0.06611261 -0.0068490556 -0.046393704 -0.008605833 0.034311775 0.057340316 -0.030115634 -0.013788929 0.059153043 -0.052877385 0.0007674474 0.09155664 -0.042497538 -0.030687789 0.058013633 -0.02028198 ...] # [0.022394778 -0.018040124 -0.06426291 -0.030636443 0.06152724 0.041886065 0.0022014293 -0.024257991 -0.0008098655 0.06305947 -0.049472377 0.014230655 0.012662819 0.012242868 -0.011617146 -0.0030664655 0.009305501 0.04141168 0.015957626 -0.021132912 0.030400734 0.014732859 0.024730343 0.033294734 0.012882391 -0.044954527 -0.02226508 -0.02660306 -0.058380716 -0.015444529 -0.038664952 0.061456345 -0.019217914 -0.0030133845 0.025284873 -0.062444218 -0.028374035 0.051177934 -0.00067920226 0.03622383 0.0015576679 -0.02543983 -0.06441596 0.043261006 -0.022205064 -0.016973468 -0.037551437 0.039916117 -0.010860435 -0.04229822 -0.003984979 -0.008206024 0.06703648 -0.013566753 -0.010782353 -0.032107145 0.019341437 -0.03323596 0.0021504916 0.057485633 0.0005013569 -0.014395545 0.016636325 0.013845575 -0.0056640115 -0.07107777 -0.026741741 0.024641562 0.04340025 -0.014085341 -0.023847742 -0.038530726 0.055751357 -0.0059098457 9.220572e-05 -0.10960976 -0.035261758 0.06804779 0.023865573 -0.019269407 0.0055465116 -0.0643797 -0.029776486 0.0044847145 -0.037864756 0.019152425 -0.05479892 0.011452832 0.0020205271 0.056901388 -0.02289676 0.007318042 0.06186679 -0.015762676 -0.008857981 0.06432067 -0.044738866 -0.026204024 0.029963357 -0.022567322 ...] ``` ### Counting tokens Here we show how to find the number of tokens in a text: ``` my $text = q:to/END/; AI has made surprising successes but cannot solve all scientific problems due to computational irreducibility. END gemini-count-tokens($text, format => 'values'); ``` ``` # 20 ``` ### Vision If the function `gemini-completion` is given a list of images, textual results corresponding to those images is returned. The argument "images" is a list of image URLs, image file names, or image Base64 representations. (Any combination of those element types.) Here is an example with [this image](https://raw.githubusercontent.com/antononcube/Raku-WWW-Gemini/main/resources/ThreeHunters.jpg): ``` my $fname = $*CWD ~ '/resources/ThreeHunters.jpg'; my @images = [$fname,]; say gemini-generation("Give concise descriptions of the images.", :@images, format => 'values'); ``` ``` # Here are concise descriptions of the images: # # **Original Image:** A colorful, whimsical painting of three raccoons perched on a tree branch, surrounded by butterflies and autumn foliage. # # **Crop 1:** Close-up of two raccoons on a branch, with butterflies and colorful leaves in the background. # # **Crop 2:** Close-up of three raccoons on a branch, with butterflies and colorful leaves in the background. # # **Crop 3:** A raccoon on a tree branch with butterflies and colorful leaves in the background. # # **Crop 4:** Close-up of three raccoons on a branch, with butterflies and colorful leaves in the background. # # **Crop 5:** Close-up of three raccoons on a branch, with butterflies and colorful leaves in the background. # # **Crop 6:** A raccoon on a tree branch with butterflies and colorful leaves in the background. ``` When a file name is given to the argument "images" of `gemini-completion` then the function `encode-image` of ["Image::Markup::Utilities"](https://raku.land/zef:antononcube/Image::Markup::Utilities), [AAp4], is applied to it. --- ## Command Line Interface ### Maker suite access The package provides a Command Line Interface (CLI) script: ``` gemini-prompt --help ``` ``` # Usage: # gemini-prompt [<words> ...] [--path=<Str>] [-n[=UInt]] [--mt|--max-output-tokens[=UInt]] [-m|--model=<Str>] [-t|--temperature[=Real]] [-a|--auth-key=<Str>] [--timeout[=UInt]] [-f|--format=<Str>] [--method=<Str>] -- Command given as a sequence of words. # # --path=<Str> Path, one of 'generateContent', 'embedContent', 'countTokens', or 'models'. [default: 'generateContent'] # -n[=UInt] Number of completions or generations. [default: 1] # --mt|--max-output-tokens[=UInt] The maximum number of tokens to generate in the completion. [default: 100] # -m|--model=<Str> Model. [default: 'Whatever'] # -t|--temperature[=Real] Temperature. [default: 0.7] # -a|--auth-key=<Str> Authorization key (to use Gemini API.) [default: 'Whatever'] # --timeout[=UInt] Timeout. [default: 10] # -f|--format=<Str> Format of the result; one of "json", "hash", "values", or "Whatever". [default: 'values'] # --method=<Str> Method for the HTTP POST query; one of "tiny" or "curl". [default: 'tiny'] ``` **Remark:** When the authorization key argument "auth-key" is specified set to "Whatever" then `gemini-prompt` attempts to use one of the env variables `GEMINI_API_KEY` or `PALM_API_KEY`. --- ## Mermaid diagram The following flowchart corresponds to the steps in the package function `gemini-prompt`: ``` graph TD UI[/Some natural language text/] TO[/"Gemini<br/>Processed output"/] WR[[Web request]] Gemini{{Gemini}} PJ[Parse JSON] Q{Return<br>hash?} MSTC[Compose query] MURL[[Make URL]] TTC[Process] QAK{Auth key<br>supplied?} EAK[["Try to find<br>GEMINI_API_KEY<br>or<br>PALM_API_KEY<br>in %*ENV"]] QEAF{Auth key<br>found?} NAK[/Cannot find auth key/] UI --> QAK QAK --> |yes|MSTC QAK --> |no|EAK EAK --> QEAF MSTC --> TTC QEAF --> |no|NAK QEAF --> |yes|TTC TTC -.-> MURL -.-> WR -.-> TTC WR -.-> |URL|Gemini Gemini -.-> |JSON|WR TTC --> Q Q --> |yes|PJ Q --> |no|TO PJ --> TO ``` --- ## TODO * TODO Implementation * DONE Function calling support * TODO Image generation * TODO Image editing * TODO Audio generation * TODO Live AI support * TODO Documentation * DONE Core functionalities * DONE Function calling / tool workflow notebook * TODO Image generation * TODO Comparison of OpenAI vs Google image generation * TODO Thinking model(s) demo --- ## References ### Articles [AA1] Anton Antonov, ["Workflows with LLM functions"](https://rakuforprediction.wordpress.com/2023/08/01/workflows-with-llm-functions/), (2023), [RakuForPredictions at WordPress](https://rakuforprediction.wordpress.com). [AA2] Anton Antonov, ["Number guessing games: Gemini vs ChatGPT"](https://rakuforprediction.wordpress.com/2023/08/06/number-guessing-games-gemini-vs-chatgpt/) (2023), [RakuForPredictions at WordPress](https://rakuforprediction.wordpress.com). [ZG1] Zoubin Ghahramani, ["Introducing Gemini 2"](https://blog.google/technology/ai/google-gemini-2-ai-large-language-model/), (2023), [Google Official Blog on AI](https://blog.google/technology/ai/). ### Packages, platforms [AAp1] Anton Antonov, [WWW::PaLM Raku package](https://github.com/antononcube/Raku-WWW-PaLM), (2023-2024), [GitHub/antononcube](https://github.com/antononcube). [AAp2] Anton Antonov, [WWW::OpenAI Raku package](https://github.com/antononcube/Raku-WWW-OpenAI), (2023-2024), [GitHub/antononcube](https://github.com/antononcube). [AAp3] Anton Antonov, [LLM::Functions Raku package](https://github.com/antononcube/Raku-LLM-Functions), (2023-2024), [GitHub/antononcube](https://github.com/antononcube). [AAp4] Anton Antonov, [Image::Markup::Utilities Raku package](https://github.com/antononcube/Raku-Image-Markup-Utilities), (2023-2024), [GitHub/antononcube](https://github.com/antononcube). [AAp5] Anton Antonov, [ML::FindTextualAnswer Raku package](https://github.com/antononcube/Raku-ML-FindTextualAnswer), (2023-2024), [GitHub/antononcube](https://github.com/antononcube).
## dist_zef-jonathanstowe-XML-Class.md # XML::Class Role to Serialize/De-Serialize a Raku class to/from XML ![Build Status](https://github.com/jonathanstowe/XML-Class/workflows/CI/badge.svg) ## Synopsis ``` use XML::Class; class Foo does XML::Class[xml-element => 'foo', xml-namespace => "http://example.com/"] { has Int $.version = 0; has Str $.zub is xml-element; } my $f = Foo.new(zub => "pow"); say $f.to-xml; # <?xml version="1.0"?><foo xmlns="http://example.com/" version="0"><zub>pow</zub></foo> ``` ## Description This provides a relatively easy way to instantiate a Raku object from XML and create XML that describes the Raku class in a consistent manner. It is somewhat inspired by the XmlSerialization class of the .Net framework, but there are other antecedents. Using a relatively static definition of the relation between a class and XML that represents it means that XML can be consistently parsed and generated in a way that should always remain valid to the original description. This module aims to map between Raku object attributes and XML by providing some default behaviours and some attribute traits to alter that behaviour to model the XML. By default scalar attributes whose value type can be expressed as an XML simple type (e.g. strings, real numbers, boolean, datetimes) will be serialised as attribute values or (with an `xml-element` trait,) as elements with simple content. Positional attributes will always be serialised as a sequence of elements (with an optional container specified by a trait,) likewise associative attributes (though the use of these is discouraged as there is no constraint on the names of the elements which are taken from the keys of the Hash.) Raku classes are expressed as XML complex types with the same serialisation as above. Provision is also made for the serialisation and de-serialisation of other than the builtin types to simple contemt (trivial examples might be Version objects for instance,) and for the handling of data that might be unknown at definition time (such as the xsd:Any in SOAP head and body elements,) by the use of "namespace maps". There are things that explicitly aren't catered for such as "mixed content" (that is where XML markup may be within text content as in XHTML for example,) but that shouldn't be a problem for data storage or messaging applications for the most part. The full documentation is available as POD or as [Markdown](Documentation.md) ## 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 XML::Class ``` Other install mechanisms may be become available in the future. ## Support Although there are quite a few tests for this I'm sure they don't cover all the possible cases. So if you find something that isn't tested for and doesn't work quite as expected please let me know. Suggestions/patches are welcomed via [github](https://github.com/jonathanstowe/XML-Class) ## Licence This is free software. Please see the <LICENCE> file in the distribution © Jonathan Stowe 2016 - 2021
## dist_zef-jonathanstowe-URI-FetchFile.md # URI-FetchFile Raku module to retrieve a file from the internet by the best available method ![Build Status](https://github.com/jonathanstowe/URI-FetchFile/workflows/CI/badge.svg) ## Synopsis ``` use URI::FetchFile; if fetch-uri('http://rakudo.org/downloads/star/rakudo-star-2016.10.tar.gz', 'rakudo-star-2016.10.tar.gz') { # do something with the file } else { die "couldn't get file"; } ``` ## Description This provides a simple method of retrieving a single file via HTTP using the best available method whilst trying to limit the dependencies. It is intended to be used by installers or builders that may need to retrieve a file but otherwise have no need for an HTTP client. It will try to use the first available method from: ``` * HTTP::UserAgent * LWP::Simple * curl * wget ``` Please feel free to suggest and/or implement other mechanisms. ## Installation Assuming you have a working installation of Rakudo you can install this using `zef` : ``` zef install URI::FetchFile ``` Other mechanisms may become available in the future. ## Support Please make any reports, suggestions etc to [Github](https://github.com/jonathanstowe/URI-FetchFile/issues) ## Licence and Copyright This is free software please see the the <LICENCE> file for details. © Jonathan Stowe 2016 - 2021
## dist_zef-lizmat-App-Rak.md ## Chunk 1 of 3 [![Actions Status](https://github.com/lizmat/App-Rak/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/App-Rak/actions) [![Actions Status](https://github.com/lizmat/App-Rak/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/App-Rak/actions) [![Actions Status](https://github.com/lizmat/App-Rak/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/App-Rak/actions) # NAME App::Rak - 21st century grep / find / ack / ag / rg on steroids # SYNOPSIS ``` # look for "foo" in current directory recursively $ rak foo # look for "foo" in directory "bar" recursively $ rak foo bar # look for "foo" as word in current directory $ rak '/ << foo >> /' # look for "foo", only produce filenames $ rak foo --files-with-matches # also produce 2 lines before and after $ rak foo --before=2 --after=2 # lines with foo AND bar $ rak foo --and=bar ``` # DESCRIPTION App::Rak provides a CLI called `rak` that allows you to look for a pattern in (a selection of files) from one or more directories recursively. It has been modelled after utilities such as `grep`, `ack`, `ag` and `rg`, with a little bit of `find` mixed in, and `-n` and `-p` parameters of many programming languages. Note: this project is now in beta-development phase. Comments, suggestions and bug reports continue to be more than welcome! # PATTERN SPECIFICATION Patterns will be interpreted in the following ways if **no** `--type` has been specified, or `--type=auto` has been specified. ### / regex / If the pattern starts and ends with `/`, then it indicates a Raku [regex](https://docs.raku.org/language/regexes). **No** special processing of the given string between slashes will be done: the given pattern will be parsed as a regex verbatim. During the search process, each item will be matched against this regex. Any `--ignorecase` or `--ignoremark` arguments will be honoured. One can also specify the regex type with `--type=regex`, so that `/ foo /` can be considered a shortcut for `--type=regex foo`. ### { code } If the pattern starts with `{` and ends with `}`, then it indicates Raku code to be executed. **No** special processing of the given string between the curly braces will be done: the given code will be compiled as Raku code. During the search process, this code will be run for each item, available in `$_`. To facilitate the use of libraries that wish to access that topic, it is also available as the `$*_` dynamic variable. The dynamic variable `$*SOURCE` will contain the `IO::Path` object of the file being processed. Note that the Raku code will be called in a thread **unsafe** manner. The dynamic variable `$*_` will contain the topic with which the code was called. This to allow custom libraries to easily obtain the topic without the user needing to specify that again. One can also specify the code type with `--type=code`, so that `{ .uc }` can be considered a shortcut for `--type=code .uc`. ### \*code If the pattern starts with `*`, then this is a short way of specifying Raku code as a pattern, using [Whatever-currying](https://docs.raku.org/type/Whatever#index-entry-Whatever-currying) semantics. Otherwise the same as `{ code }`. ### ^string If the pattern starts with `^`, then it indicates the string should be at the **start** of each item. Basically a shortcut to specifying `--type=starts-with string`. Any `--smartcase`, `--smartmark`, `--ignorecase` or `--ignoremark` arguments will be honoured. ### string$ If the pattern ends with `$`, then it indicates the string should be at the **end** of each item. Basically a shortcut to specifying `--type=ends-with string`. Any `--smartcase`, `--smartmark`, `--ignorecase` or `--ignoremark` arguments will be honoured. ### ^string$ If the pattern starts with `^` and ends with `$`, then it indicates that the string should be equal to the item. Basically a shortcut to specifying `--type=equal string`. Any `--smartcase`, `--ignorecase` or `--ignoremark` arguments will be honoured. ### §string If the pattern starts with `§`, then it indicates that the string should occur as a word (with word-boundaris on both ends) in the item. Basically a shortcut to specifying `--type=words string`. Any `--smartcase`, `--smartmark`, `--ignorecase` or `--ignoremark` arguments will be honoured. ### !specification If the pattern starts with `!`, then it indicates that the result of the pattern specification should be negated. ### &specification If the pattern starts with `&`, then it indicates that the result of the pattern specification should be true **as well as** the result of the previous pattern specification. ### s:string If the pattern starts with 's:', then it indicates that the string should be split on whitespace, and each part should be considered a separate pattern specification. Basically a shortcut to specifying `--type=split string`. ### jp:path If the pattern start with 'jp:', then interpret the rest of the pattern as a `JSON path`. Only makes sense when used together with `--json-per-file`, `--json-per-line` or `--json-per-elem`. Requires that the [`JSON::Path`](https://raku.land/cpan:JNTHN/JSON::Path) module is installed. Basically a shortcut to specifying `path --type=json-path`. ### string If there are no special start or end markers, then it indicates that the string should occur somewhere in the item. Basically a shortcut to specifying `string --type=contains`. Any `--smartcase`, `--smartmark`, `--ignorecase` or `--ignoremark` arguments will be honoured. # POSITIONAL ARGUMENTS ## pattern The pattern to search for, if no pattern was specified any other way. Patterns can also be specified with the `--pattern`, `--not` and `--patterns-from` options, in which case **all** other positional arguments are considered to be path specifications. ## path(s) Optional. Either indicates the path of the directory (and its sub-directories), or the file that will be searched, or a URL that will produce a file to be searched. By default, all directories that do not start with a period, and which are not symbolic links, will be recursed into (but this can be changed with the `--dir` option). By default, all files with known extensions will be searched in the directories. This can be changed with the `--file` option, or specialized version of that like `--extensions`. Paths can also be specified with the `--paths` option, in which case there should only be a positional argument for the pattern, or none if `--pattern` option was used for the pattern specification. # ON CALLABLES AS PATTERN `Callables` can be specified by a string starting with `*.` (so-called [Whatever currying](https://docs.raku.org/type/Whatever), or as a string starting with `{` and ending with `}`. Note that if a `Callable` is specified as a pattern, then no highlighting can be performed as it cannot signal why or where a match occurred. The return value of the pattern `Callable` match is interpreted in the following way: ## True If the `Bool`ean True value is returned, assume the pattern is found. Produce the item unless `--invert-match` was specified. ## False If the `Bool`ean False value is returned, assume the pattern is **not** found. Do **not** produce the item unless `--invert-match` was specified. ## Nil If `Nil` is returned, assume the pattern is **not** found. This typically happens when a `try` is used in a pattern, and an execution error occurred. Do **not** produce the item unless `--invert-match` was specified. ## Empty If the empty `Slip` is returned, assume the pattern is **not** found. Do **not** produce the item unless `--invert-match` was specified. Shown in stats as a `passthru`. ## any other Slip If a non-empty `Slip` is returned, produce the values of the `Slip` separately for the given item (each with the same item number). ### any other value Produce that value. # PHASERS IN CALLABLE PATTERNS The Raku Programming Language has a number of unique features that can be used with patterns that are executable code. One of them is the use of so-called [phasers](https://docs.raku.org/language/phasers) (pieces of code that will be executed automatically when a certain condition has been met. `App::Rak` currently supports all of Raku's [loop phasers](https://docs.raku.org/language/phasers#FIRST): | phaser | event | | --- | --- | | FIRST | code to run when searching starts | | NEXT | code to run when searching a file is done | | LAST | code to run when searching is done | These phasers will be called in a **thread-safe** manner. ``` # show number of files inspected before the search result $ rak '{ state $s = 0; NEXT $s++; LAST say "$s files"; .contains("foo")}' # show number of files inspected after of the search result $ rak '{ state $s = 0; NEXT $s++; END say "$s files"; .contains("foo")}' ``` Note that the use of the `LAST` phaser will make the search run eagerly, meaning that no results will be shown until the search has been completed. Any other phasers that do not require special attention by `App::Rak` are also supported in any code specified (such as `BEGIN` and `END`). # ON THE INTERPRETATION OF OPTIONS All options when using App::Rak, start with either one dash `-` or two dashes `--`. If an option starts with two dashes, it is a so-called "long option". Any characters after the dashes are considered to be the single name of the option. If an option starts with a single dash, then it is considered to be a collection of "short options", each of 1 letter. If the number of short options is 1, then it can be followed by a numerical value (without equal sign). If the specification of the option does **not** contain an equal sign `=`, then the option is interpreted as a boolean option. By default, such a flag is considered to represent `True`. The value can be negated in two ways: * a slash before the name * the string "no-" before the name Some examples: * -i Option "i" is True. * -j5 Option "j" has the value 5. * -im Options "i" and "m" are True. * -/i Option "i" is False. * -/im Options "i" and "m" are False. * -no-i Option "i" is False. * --foo Option "foo" is True. * --/foo Option "foo" is False. * --no-foo Option "foo" is False. If the specification of an option contains an equal sign after the name, then whatever follows that, is considered the value of that option. Whether or not that value needs to be quoted, and how they are to be quoted, really depends on the shell that you use to access `rak`. Generally, if the value consists of alphanumeric characters only, no quoting is necessary. Otherwise it's better to quote your values. Some examples: * -s=foo Option "s" has the value "foo". * -t='foo bar' Option "t" has the value "foo bar". * --frobnicate=yes Option "frobnicate" has the value "yes". # CREATING YOUR OWN OPTIONS App::Rak provides **many** options. If you are happy with a set of options for a certain workflow, You can use the `--save` option to save that set of options and than later access them with the given name: ``` # create -i shortcut for ignoring case $ rak --ignorecase --save=i Saved option '-i' as: --ignorecase # create -m shortcut for ignoring accents $ rak --ignoremark --save=m Saved option '-m' as: --ignoremark # same as --ignorecase --ignoremark $ rak foo -im ``` Generally speaking, the most used boolean options can be saved as single letter options: this allows multiple options to be specified in a single, short manner (as shown above). To better document / remember what a particular custom option is meant to do, you can add a description with the `--description` option. ``` # add a description to the -i custom option $ rak --description='Search without caring for uppercase' --save=i Saved '--description='Search without caring for uppercase'' as: -i # add an option -g for searching only git files $ rak --description='Committed files only' --under-version-control --save=g Saved '--description='Committed files only' --under-version-control' as: -g ``` There is also a special named option that indicates the options that will be automatically activated on any invocation: `(default)`. ``` # enable --smartcase by default on every run $ rak --smartcase --save='(default)' Saved '--smartcase' as: (default) ``` You can use the `--list-custom-options` to see what options you have saved before. Custom options are saved in `~/.rak-config.json`. You can override this by specifying the `RAK_CONFIG` environment variable. ``` # read custom options from ".custom.json" (in the current directory) $ RAK_CONFIG=.custom.json rak foo ``` You can also use the `RAK_CONFIG` variable to disable loading any configuration by not specifying a value: ``` # start rak without any custom configuration $ RAK_CONFIG= rak foo ``` # SUPPORTED OPTIONS All options are optional. Any unexpected options, will cause an exception to be thrown with the unexpected options listed and possible alternatives mentioned. Unless specifically indicated otherwise, using the negation of a flag has the same effect as **not** specifying it. ## --absolute Flag. If specified indicates that whenever paths are shown, they will be shown as absolute paths. Defaults to `False`, which will cause paths to be produced as paths relative to the current directory. ## --accept=code Specifies the code that should be executed that should return `True` if the path is acceptable, given an `IO::Path` object of the path. See also `--deny`. ``` # Include files that have "use Test" in them $ rak --accept='*.slurp.contains("use Test")' ``` ## --accessed=condition If specified, indicates the `Callable` that should return True to include a file in the selection of files to be checked. The access time of the file (number of seconds since epoch, as a `Num` value) will be passed as the only argument. Note that many file systems do not actually support this reliably. See "CHECKING TIMES ON FILES" for more information about features that can be used inside the `Callable`. ## --ack Attempt to interpret following arguments as if they were arguments to the [`ack`](https://metacpan.org/pod/ack) utility. This is incomplete and may be subtly different in behaviour. Intended as a temporary measure for people used to using `ack`, while they train their muscle memory to use **rak** instead. If you'd like a list of the option configuration, you can use the `--list-custom-options` argument. ``` # Show the current mappinng of "ack" to "rak" options $ rak --ack --list-custom-options ``` ## --after-context=N Indicate the number of lines that should be shown **after** any line that matches. Defaults to **0**. Will be overridden by a `--context` argument. ## --allow-loose-escapes Only applicable if `--csv-per-line` has been specified. Flag. If specified, indicates that **any** character may be escaped. ## --allow-loose-quotes Only applicable if `--csv-per-line` has been specified. Flag. If specified, indicates that fields do not need to be quoted to be acceptable. ## --allow-whitespace Only applicable if `--csv-per-line` has been specified. Flag. If specified, indicates that whitespace is allowed around separators. ## --also-first[=N] Indicates the number of lines from the start of the file that should be shown **if** there is a match. If not specified, **0** will be assumed. If specified as a flag, **1** will be assumed. ## --always-first[=N] Indicates the number of lines from the start of the file that will **always** be shown, regardless of whether there is a match or not. If not specified, **0** will be assumed. If specified as a flag, **1** will be assumed. ## --auto-decompress Flag. If specified with a True value, will accept compressed files with the `.gz` (gzip) or `.bz2` (bzip2) extension, if the extension was otherwise acceptable. Will automatically decompress files for inspection. ## --and=foo Specify **additional** pattern that should match as well as any previously specified pattern to produce a full match. ## --andnot=foo Specify **additional** pattern that should **not** match as well as any previously specified pattern to produce a full match. ## --auto-diag Only applicable if `--csv-per-line` has been specified. Flag. If (implicitly) specified, will show diagnostic information about problems that occurred during parsing of the CSV file. The default is `True`. ## --backtrace Flag. When specified with a True value, will interpret either standard input, or a single file, as a Raku backtrace. And produce a result containing the lines of source code from that backtrace. Can be used together with `--context`, `--before-context`, `--after-context`, `--edit` and `--vimgrep`. Any pattern specification will only be used for highlighting. If **not** used in combination with `--edit` or `--vimgrep`, will assume a context of 2 lines. ``` # look at source of a stacktrace $ raku script 2>&1 | rak --backtrace # inspect the source of a stacktrace in an editor $ raku script 2>&1 | rak --backtrace --edit # inspect a backtrace stored in a file $ rak --backtrace filename ``` ## --backup[=extension] Indicate whether backups should be made of files that are being modified. If specified without extension, the extension `.bak` will be used. ## --batch[=N] Indicate the number of files that should be checked per thread. If specified as a flag, will assue `1`. Defaults to `64` if not specified. See also <--degree>. ## --before-context=N Indicate the number of lines that should be shown **before** any line that matches. Defaults to **0**. Will be overridden by a `--context` argument. ## --blame-per-file Flag. Only makes sense if the pattern is a `Callable`. If specified, indicates that each of the selected files will be provided as [`Git::Blame::File`](https://raku.land/zef:lizmat/Git::Blame::File#methods-on-gitblamefile) objects if `git blame` can be performed on the a selected file. If that is not possible, then the selected file will be ignored. If information can be obtained, then the associated `Git::Blame::File` object will be presented to the pattern `Callable`. If the Callable returns `True`, then the filename will be produced. If anything else is returned, then the stringification of that object will be produced. Requires the [`Git::Blame::File`](https://raku.land/zef:lizmat/Git::Blame::File) Raku module to be installed. ``` # show files with more than 10 commits $ rak '*.commits > 10' --blame-per-file --files-with-matches ``` ## --blame-per-line Flag. Only makes sense if the pattern is a `Callable`. If specified, indicates that each line from the selected files will be provided as [`Git::Blame::Line`](https://raku.land/zef:lizmat/Git::Blame::File#accessors-on-gitblameline) objects if `git blame` can be performed on the a selected file. If that is not possible, then the selected file will be ignored. If information can be obtained, then the associated `Git::Blame::Line` object will be presented to the pattern `Callable`. If the Callable returns `True`, then the short representation of the `git blame` information will be produced. If the returned value is anything else, then the stringification of that object will be produced. ``` # show git blame on lines of which the author is "Scooby Doo" $ rak '{ .author eq "Scooby Doo" }' --blame-per-line ``` Requires that the [`Git::Blame::File`](https://raku.land/zef:lizmat/Git::Blame::File) module is installed. ## --blocks=condition If specified, indicates the `Callable` that should return True to include a file in the selection of files to be checked. The number of logical blocks that a file takes up in the filesystem, will be passed as the only argument. ``` # show files that consist of at least 3 blocks $ rak --find --blocks='* >= 3' ``` ## --break[=string] Indicate whether there should be a visible division between matches of different files. Can also be specified as a string to be used as the divider. Defaults to `True` (using an empty line as a divider) if `--group-matches` is (implicitly) set to `True`, else defaults to `False`. ## --checkout=branch Only valid if the current directory is under git version control. Indicate the branch to checkout by the general matching logic of App::Rak. Will produce listing of matching branches if more than one, or say that there is no match. Branches need not have been checked out locally yet. ## --categorize=categorizer If specified, indicates the `Callable` that should return zero or more keys for a given line to have it categorized. This effectively replaces the filename if a line by its key in the result. See also `--classify`. ``` # categorize by the first two letters of a line $ rak --categorize='*.substr(0,2).comb' ``` ## --classify=classifier If specified, indicates the `Callable` that should return a key for a given line to have it classified. This effectively replaces the filename if a line by its key in the result. See also `--categorize`. ``` # classify by the last letter of a line $ rak --classify='*.substr(*-1)' ``` ## --context=N Indicate the number of lines that should be produced **around** any line that matches. Defaults to **0**. ## --count-only Flag. Indicate whether just the number of lines with matches should be calculated. When specified with a `True` value, will show a "N matches in M files" by default, and if the `:files-with-matches` (or `files-without matches`) option is also specified with a `True` value, will just show total counts. See also `--stats-only`. ## --created=condition If specified, indicates the `Callable` that should return True to include a file in the selection of files to be checked. The creation time of the file (number of seconds since epoch, as a `Num` value) will be passed as the only argument. See "CHECKING TIMES ON FILES" for more information about features that can be used inside the `Callable`. ## --csv-per-line Flag. Only makes sense if the pattern is a `Callable`. If specified with a `True` value, indicates that selected files should be interpreted as comma separated values (CSV). Each row from the selected files will be provided as a list of strings (or as `CSV::Field` objects if `--keep-meta` was specified). Attempt to interpret file as a CSV file, and pass each row as a List to to the pattern Callable. Only files with extensions from the `#csv` group will be tried, unless overridden by any explicit extension specification. More documentation can be found with the [Text::CSV](https://raku.land/github:Tux/Text::CSV) module itself. ``` # Show the values of the column named "foo" of the rows in the "info.csv" # file if the column named "bar" is equal to "foo" $ rak --csv-per-line '{.<foo> if .<bar> eq "foo"}' info.csv # Show the values of the first column of the rows in the "info.csv" file # if the second column is equal to "foo" $ rak --csv-per-line --/headers '{.[0] if .[1] eq "foo"}' info.csv ``` ## --degree[=N | code] Indicate the number of worker threads that should be maximally. Defaults to the number of cores minus 1 if not specified. Assumes `1` if specified as a flag. Can also take a `Callable` specification, in which case the number of CPU cores will be presented to that Callable as the only argument. See also <--batch>. ## --deny=code Specifies the code that should be executed that should return `True` if the path is **NOT** acceptable, given an `IO::Path` object of the path. See also `--accept`. ``` # Include files that **NOT** have "use Test" in them $ rak --deny='*.slurp.contains("use Test")' ``` ## --description=text Specify a description to be saved with the custom option. This will be shown prominently with --list-custom-options. If it is the only argument apart from --save, then the discription will be added (if there was no description yet) or replace the current description of the option. ## --device-number=condition If specified, indicates the `Callable` that should return True to include a file in the selection of files to be checked. The device number of the filesystem on which the file is located, will be passed as the only argument. ## --dir=condition If specified, indicates the `Callable` that should return True to have a directory be included for further recursions in file selection. The basename of the directory will be passed as the only argument. Defaults to all directories that do not start with a period. Can specify as a flag to include **all** directories for recursion. ## --dont-catch Flag. If specified as a flag, will **not** catch any error during processing, but will throw any error again. Defaults to `False`, making sure that errors **will** be caught. Mainly intended for debugging and error reporting. ## --dryrun Flag. Indicate to **not** actually make any changes to any content modification if specified with a `True` value. Only makes sense together with the `--modify-files` and the `--rename-files` option. ## --eco-code=[rea|fez] Indicate that **all** the files that can contain Raku code in the local ecosystem cache (as generated by [`Ecosystem::Cache`](https://raku.land/zef:lizmat/Ecosystem::Cache)) should be searched. If specified as a flag, will assume the `"rea"` (Raku Ecosystem Archive). ## --eco-doc=[rea|fez] Indicate that **all** the files that can contain documentation in the local ecosystem cache (as generated by [`Ecosystem::Cache`](https://raku.land/zef:lizmat/Ecosystem::Cache)) should be searched. If specified as a flag, will assume the `"rea"` (Raku Ecosystem Archive). ## --eco-meta[=name1,name2] Intended to be used by Raku ecosystem maintainers. Indicates the name of zero or more Raku ecosystems of which to inspect the `META6.json` information of all its modules. Currently supported names are: | name | description | | --- | --- | | p6c | the original git ecosystem (deprecated) | | cpan | the ecosystem piggybacking on PAUSE / CPAN (deprecated) | | fez | the currently recommended ecosystem for new modules / updates | | rea | the Raku Ecosystem Archive | Defaults to `rea` if specified as a flag. Implies `--json-per-elem`. ``` # show all unique module names by an author from the REA $ rak '{ .author eq "Scooby Doo" }' --eco-meta # same, but now from the p6c and cpan ecosystems $ rak '{ .author eq "Scooby Doo" }' --eco-meta=p6c,cpan ``` Assumes `zef` is installed and its meta information is available. ## --eco-provides=[rea|fez] Indicate that the module files (from the `"provides"` section of the meta-information in a distribution) in the local ecosystem cache (as generated by [`Ecosystem::Cache`](https://raku.land/zef:lizmat/Ecosystem::Cache)) should be searched. If specified as a flag, will assume the `"rea"` (Raku Ecosystem Archive). ## --eco-scripts=[rea|fez] Indicate that the scripts (from the `"bin"` directory of a distribution) in the local ecosystem cache (as generated by [`Ecosystem::Cache`](https://raku.land/zef:lizmat/Ecosystem::Cache)) should be searched. If specified as a flag, will assume the `"rea"` (Raku Ecosystem Archive). ## --eco-tests=[rea|fez] Indicate that the test files (from the `"t"` and `"xt"` directories of a distribution) in the local ecosystem cache (as generated by [`Ecosystem::Cache`](https://raku.land/zef:lizmat/Ecosystem::Cache)) should be searched. If specified as a flag, will assume the `"rea"` (Raku Ecosystem Archive). ## --edit[=editor] Indicate whether the patterns found should be fed into an editor for inspection and/or changes. Defaults to `False`. Optionally takes the name of the editor to be used. If no editor is specified, will use what is in the `EDITOR` environment variable. If that is not specified either, will call "vim". Requires the [`Edit::Files`](https://raku.land/zef:lizmat/Edit::Files) Raku module to be installed. ## --encoding[=utf8-c8] Indicate the encoding to be used when reading text files. Defaults to [`utf8-c8`](https://docs.raku.org/language/unicode#UTF8-C8). Other encodings are e.g. `utf8` and `ascii`. ## --eol=lf|cr|crlf Only applicable if `--csv-per-line` has been specified. Indicate a line ending different from the standard line ending assumed by the system. Can be specified as `lf` for a single LineFeed character, `cr` for a single CarriageReturn character, or `crlf` for a combination of a CarriageReturn and a LineFeed character. ## --escape=char Only applicable if `--csv-per-line` has been specified. Indicates the escape character to be used to escape characters in a field. Defaults to **double quote**. ## --exec=invocation If specified, indicates the name of a program and its arguments to be executed. Any `$_` in the invocation string will be replaced by the file being checked. The file will be included if the program runs to a successful conclusion. ## --execute-raku[=code] Flag or code specification. When specified with a True value, will use the pattern as the name of a script to execute. If code is specified will execute that code. If the code consists of "-", then will read code from STDIN to execute. Any execution error's backtrace will be used to produce a result with the lines of source code of that backtrace. Can be used together with `--context`, `--before-context`, `--after-context`, `--edit` and `--vimgrep`. Will assume a context of 2 lines if **not** used in combination with `--edit` or `--vimgrep`, If `--verbose` is specified, will try to create an extended (--ll-exception) backtrace. ``` # look at source of a stacktrace after running script $ rak --execute-raku script # inspect the source of a stacktrace in an editor $ rak --execute-raku script --edit # inspect a backtrace from execution of code read from STDIN $ cat script | rak --execute-raku=- ``` ## --extensions=spec Indicate the extensions of the filenames that should be inspected. By default, only files with known extensions, will be searched. Extensions can be specified as a comma-separated list of either a a predefined group of extensions (indicated by `#name`), a single extension, or `*` to indicate all known extensions. ``` # inspect files with extensions used by Raku and Perl $ rak foo --extensions=#raku,#perl # inspect files with presumable Markdown content $ rak foo --extensions=md,markdown # inspect files without extension $ rak foo --extensions= # inspect files without extension or with the extension "foo" $ rak foo --extensions=,foo ``` Predefined groups are `#raku`, `#perl`, `#cro`, `#text`, `#c`, `#c++`, `#yaml`, `#ruby`, `#python`, `#r`, `#wl`, `#html`, `#markdown`, `#js`, `#json`, `#jsonl`, `#csv`, `#config`, and `#text`. The `--list-known-extensions` argument can be used to see which predefined groups of extensions are supported, and which extensions they cover. ## --file=condition If specified, indicates the `Callable` that should return True to have a file be included in the file selection process. The basename of the file will be passed as the only argument. Defaults to `True`, indicating that all files should be included. If `--/file` is specified, then only directory paths will be accepted. This only makes sense if `--find` is also specified. ## --file-separator-null Flag. Indicate to separate filenames by null bytes rather than newlines if the `--files-with-matches` or `--files-without-matches` option are specified with a `True` value. ## --files-from=filename Indicate the path of the file to read filenames from instead of the expansion of paths from any positional arguments. "-" can be specified to read filenames from STDIN. ## --files-with-matches Flag. If specified, will only produce the filenames of the files in which the pattern was found. Defaults to `False`. ## --files-without-matches Flag. If specified, will only produce the filenames of the files in which the pattern was **not** found. Defaults to `False`. ## --filesize=condition If specified, indicates the `Callable` that should return True to include a file in the selection of files to be checked. The number of bytes of data in the file, will be passed as the only argument. See also `--is-empty`. ``` # show files that consist of at 30 bytes $ rak --find --filesize='* >= 30' ``` ## --find Flag. If specified, will **not** look at the contents of the selected paths, but instead consider the selected paths as lines in a virtual file. And as such will always only produce filenames. ## --only-first[=N] Indicate the **overall** number of matches to show. If specified without a value, will default to **1**. Defaults to **1000** if a human is watching, otherwise defaults to returning all possible matches. Can be used to tweak search results, before letting it loose to get all possible results. Special values that are allowed to produce all possible results are `∞` (aka `221E INFINITY`), `*` and `Inf`. ## --formula=[none] Only applicable if `--csv-per-line` has been specified. If specified, indicates the action to be taken when a field starts with an equal sign (indicating a formula of some kind in many spreadsheets). The following values are recognized: | type | action | | --- | --- | | none | take not action, just pass on | | die | throw an exception | | diag | report line and position where formula was found | | empty | replace the formula by an empty string | ## --frequencies Flag. If specified, will produce a frequency table of the matches with the most frequent match first. Default is `False`. See also `--unique`. Usually used in conjunction with `--matches-only` and/or `Callable` patterns returning something other than True/False/Nil/Empty. ## --gid=condition If specified, indicates the `Callable` that should return True to include a file in the selection of files to be checked. The numeric `gid` of the file will be passed as the only argument. Can also be specified as a single numeric argument. See also `
## dist_zef-lizmat-App-Rak.md ## Chunk 2 of 3 --group`. ``` # show files of which the numeric group id is greater than 20 $ rak --find --gid='* > 20' # show files of which the numeric group id is 20 $ rak --find --gid=20 ``` NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --group=condition If specified, indicates the `Callable` that should return True to include a file in the selection of files to be checked. The name of the group associated with the `gid` of the file will be passed as the only argument. Can also be specified as a list of comma separated names to (not) select on. To select all names **except** the listed named, prefix with a `!`. See also `--gid`. Requires the [P5getgrnam](https://raku.land/zef:lizmat/P5getgrnam) module to be installed. ``` # files of which the name associated with the user id starts with underscore $ rak --find --group='*.starts-with("_")' # show files of which the group is "staff" $ rak --find --group=staff # show files of which the group is NOT "staff" $ rak --find --group='!staff' ``` NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --group-matches Flag. Indicate whether matches of a file should be grouped together by mentioning the filename only once (instead of on every line). Defaults to `True` if a human is watching, else `False`. ## --hard-links=condition If specified, indicates the `Callable` that should return True to include a file in the selection of files to be checked. The number of hard-links to the file on the filesystem, will be passed as the only argument. ## --has-setgid Flag. If specified, will only select files that do have the SETGID bit set in their attributes. Use negation `--/has-setgid` to only select files that do **not** have the SETGID bit set. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --has-setuid Flag. If specified, will only select files that do have the SETUID bit set in their attributes. Use negation `--/has-setuid` to only select files that do **not** have the SETUID bit set. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --headers Only applicable when `--csv-per-line` is also specified. It defaults to "auto". It can have the following values: * --headers Boolean True, same as "auto" * --/headers Boolean False, assume comma separator and no header line, produce a list of column values for each line in the CSV file. * --headers=auto Automatically determine separator, first line is header with column names, produce a hash with values keyed to column names for each line in the CSV file. * --headers=skip Assume the first line is a header, but skip it. Produce a lust of column values for each line in the CSV file. * --headers=uc Same as "auto", but uppercase the column names found in the header line. * --headers=lc Same as "auto", but lowercase the column names found in the header line. * --headers='' Specifies a list of column names to associate with columns, in order. Assumes no header line is available. * --headers=':a, :b' Indicates a list of `Pair`s with column name mapping to use instead of the column names found in the header line of the CSV file. * --headers='code' Any Raku code that produces one of the above values. Also supports a `Map` or `Hash` instead of a list of `Pair`s. ``` # Use uppercase column names $ rak --csv-per-line --headers=uc '{.<FOO> if .<BAR> eq "foo"}' info.csv # Use alternate column names in order of columns $ rak --csv-per-line --headers='<a b>' '{.<a> if .<n> eq "foo"}' info.csv # Use alternate column names using mapping $ rak --csv-per-line --headers=':foo<a>, :bar<b>' '{.<a> if .<n> eq "foo"}' info.csv ``` ## --help[=area-of-interest] Show argument documentation, possibly extended by giving the area of interest, which are: * argument * code * content * debugging * examples * faq * filesystem * general * haystack * item * listing * option * pattern * philosophy * resource * result * special * string If no area of interest is given, then the overview will be shown. Any pattern specification will be used to search the help subjects, and only show the logical paragraphs with matches. ## --highlight Flag. Indicate whether the pattern should be highlighted in the line in which it was found. Defaults to `True` if a human is watching (aka STDOUT connected to a terminal), or `--highlight-before` or `highlight-after` are explicitely specified, or `False` otherwise. ## --highlight--after[=string] Indicate the string that should be used at the end of the pattern found in a line. Specifying implies `--highlight`ing implicitely. If `--highlight` or `--highlight-before` are explicitely specified, will default to whatever is specified with `--highlight-before`, or to the ANSI code to end **bold**. ## --highlight--before[=string] Indicate the string that should be used at the end of the pattern found in a line. Specifying implies `--highlight`ing implicitly. If `highlight` is explicitely specified, will default to the terminal code to start **bold**. ## --human Flag. Indicate that search results should be presented in a human readable manner. This means: filenames shown on a separate line, line numbers shown, and highlighting performed. Defaults to `True` if `STDOUT` is a TTY (aka, someone is actually watching the search results), otherwise defaults to `False`. ## --ignorecase Flag. If specified, indicates that any matching using a literal string or a regex, should be done case insensitively. Default is `False`. ## --ignoremark Flag. If specified, indicates that any matching using a literal string or a regex, should be done without consideration of any accents. Default is `False`. ## --inode=condition If specified, indicates the `Callable` that should return True to include a file in the selection of files to be checked. The inode number of the file on the filesystem, will be passed as the only argument. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --invert-match Flag. If specified, will negate the result of any match if it has a logical meaning: | given value | result | | --- | --- | | True | False | | False | True | | Nil | True | | Empty | True | | none of the above | just that | ## --is-empty Flag. If specified, will only select files that do not contain any data. Use negation `--/is-empty` to only select files that **do** contain data. Special case of `--filesize`. ## --is-executable Flag. If specified, will only select files that can be executed by the current user. Use negation `--/is-executable` to only select files that are **not** executable by the current user. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-group-executable Flag. If specified, will only select files that can be executed by members of the group of the owner. Use negation `--/is-group-executable` to only select files that are **not** executable by the members of the group of the owner. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-group-readable Flag. If specified, will only select files that can be read by members of the group of the owner. Use negation `--/is-group-readable` to only select files that are **not** readable by the members of the group of the owner. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-group-writable Flag. If specified, will only select files that can be written to by members of the group of the owner. Use negation `--/is-group-writable` to only select files that are **not** writable by the members of the group of the owner. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-moarvm Flag. If specified, will only select files that appear to be MoarVM bytecode files. Defaults to `False`. ## --is-owned-by-group Flag. If specified, will only select files that are owned by the group of the current user. Use negation `--/is-owned-by-group` to only select files that are **not** owned by the group of the current user. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-owned-by-user Flag. If specified, will only select files that are owned by current user. Use negation `--/is-owned-by-user` to only select files that are **not** owned by the current user. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-owner-executable Flag. If specified, will only select files that can be executed by the owner. Use negation `--/is-owner-executable` to only select files that are **not** executable by the owner. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-owner-readable Flag. If specified, will only select files that can be read by the owner. Use negation `--/is-owner-readable` to only select files that are **not** readable by the owner. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-owner-writable Flag. If specified, will only select files that can be written to by the owner. Use negation `--/is-owner-writable` to only select files that are **not** writable by the owner. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-pdf Flag. If specified, will only select files that appear to be PDF files. Defaults to `False`. ## --is-readable Flag. If specified, will only select files that can be read by the current user. Use negation `--/is-readable` to only select files that are **not** readable by the current user. ## --is-sticky Flag. If specified, will only select files that do have the STICKY bit set in their attributes. Use negation `--/is-sticky` to only select files that do **not** have the STICKY bit set. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-symbolic-link Flag. If specified, will only select files that are symbolic links. Use negation `--/is-symbolic-link` to only select files that are **not** symbolic links. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-text Flag. If specified, will only select files that appear to contain text (rather than binary data). Defaults to `True` if no other file filter has been specified, and `--find` is not specified either. Use negation `--/is-text` to only select files with binary data. Note: support for searching for binary data is not yet implemented, so `--/is-text` can only be used in conjunction with --find. ## --is-world-executable Flag. If specified, will only select files that can be executed by anybody. Use negation `--/is-group-executable` to only select files that are **not** executable by anybody. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-world-readable Flag. If specified, will only select files that can be read by anybody. Use negation `--/is-world-readable` to only select files that are **not** readable by anybody. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-world-writable Flag. If specified, will only select files that can be written to by anybody. Use negation `--/is-world-writable` to only select files that can **not** be written to by anybody. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --is-writable Flag. If specified, will only select files that can be written to by the current user. Use negation `--/is-writable` to only select files that can **not** be written to by the current user. ## --json-per-elem Flag. Only makes sense if the pattern is a `Callable`. If specified, indicates that each selected file will be interpreted as JSON, and if valid, will then produce all elements of the outermost data structure to the pattern for introspection. If the data structure is a hash, then key/value `Pair`s will be produced. If the Callable returns `True`, the stringification of the element will be produced. If the returned value is a string, that string will be produced. For example when searching the list of modules in the zef ecosystem (which consists of an array of hashes): ``` # Show all defined "auth" values of top elemens in JSON file $ rak '{ .<auth> // False }' META.json --json-per-elem ``` ## --json-per-file Flag. Only makes sense if the pattern is a `Callable`. If specified, indicates that each selected file will be interpreted as JSON, and if valid, will then be given to the pattern for introspection. If the Callable returns `True`, the filename will be produced. If anything else is returned, then the stringification of that object will be produced. For example: ``` # show the "auth" value from all JSON files $ rak '*<auth> // False' --json-per-file ``` ## --json-per-line Flag. Only makes sense if the pattern is a `Callable`. If specified, indicates that each line from the selected files will be interpreted as JSON, and if valid, will then be given to the pattern for introspection. If the Callable returns `True`, the filename and line number will be produced. If the returned value is anything else, then the stringification of that object will be be produced. For example: ``` # show the "auth" value from the JSON blob on each line $ rak '{ $_ with .<auth> }' --json-per-line ``` ## --keep-meta Flag. Only applicable if `--csv-per-line` has been specified. If specified, indicates that meta-information will be kept for each field, by presenting each field as a `CSV::Field|https://github.com/Tux/CSV/blob/master/doc/Text-CSV.md#csvfield` object rather than as a string. The most important methods that can be called on a `CSV::Field` object are: | method | meaning | | --- | --- | | is-quoted | field was quoted | | is-binary | field contains undecodable data | | is-utf8 | field contains decodable data beyond ASCII | | is-formula | field looks like it contains a spreadsheet formula | ## --list-custom-options Flag. If specified as the only option, will list all additional options previously saved with `--save`. ``` # show all of the custom options $ rak --list-custom-options fs: --'follow-symlinks' im: --ignorecase --ignoremark ``` ## --list-expanded-options Flag. If specified, will show all actual options being activated after having been recursively expanded, and then exit. Intended as a debugging aid if you have many custom options defined. ``` # show how custom option "--im" expands $ rak --im --list-expanded-options --ignorecase --ignoremark ``` ## --list-known-extensions Flag. If specified, will show all known extension groups and the extensions they represent. Intended as an informational aid. ``` # show the filename extensions that "rak" knows about $ rak --list-known-extensions #c: c h hdl #c++: cpp cxx hpp hxx #config: ini #cro: (none) crotmp #csv: (none) csv psv tsv #html: htm html css #js: js ts tsx #json: json #jsonl: jsonl #markdown: md markdown #perl: (none) pl pm t #python: py ipynb #r: (none) r R Rmd #raku: (none) raku rakumod rakutest rakudoc nqp t pm6 pl6 pod6 t6 #ruby: rb #text: (none) txt #wl: (none) wl m wlt mt nb #yaml: yaml yml ``` ## --matches-only Flag. Indicate whether only the matched pattern should be produced, rather than the line in which the pattern was found. Defaults to `False`. Frequently used in conjunction with `--per-file`. Will show separated by space if multiple matches are found on the same line. ## --max-matches-per-file[=N] Indicate the maximum number of matches that should be produced per file. If specified as a flag, will assume **1** for its value. By default, will produce **all** possible matches in a file. ## --mbc Flag. Indicates that a [`MoarVM::Bytecode` object should be produced for each MoarVM bytecode file, to be presented to the matcher. Only makes sense if the pattern is a `Callable`. Will also set the `is-moarvm` flag to only select MoarVM bytecode files, unless reading from STDIN. Requires the [`MoarVM::Bytecode`](https://raku.land/zef:lizmat/MoarVM::Bytecode) Raku module to be installed. ## --mbc-frames Flag. Indicates that the frames in a MoarVM bytecode file should be produced as a [`MoarVM::Bytecode::Frame`](https://raku.land/zef:lizmat/MoarVM::Bytecode#frame) to the matcher. Only makes sense if the pattern is a `Callable`. Will also set the `is-moarvm` flag to only select MoarVM bytecode files, unless reading from STDIN. Requires the [`MoarVM::Bytecode`](https://raku.land/zef:lizmat/MoarVM::Bytecode) Raku module to be installed. ## --mbc-strings Flag. Indicates that the strings in the string hap in a MoarVM bytecode file should be produced to the matcher. Will also set the `is-moarvm` flag to only select MoarVM bytecode files, unless reading from STDIN. Requires the [`MoarVM::Bytecode`](https://raku.land/zef:lizmat/MoarVM::Bytecode) Raku module to be installed. ## ---meta-modified=condition If specified, indicates the `Callable` that should return True to include a file in the selection of files to be checked. The modification time of meta information of the file (number of seconds since epoch, as a `Num` value) will be passed as the only argument. See "CHECKING TIMES ON FILES" for more information about features that can be used inside the `Callable`. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --mode=condition If specified, indicates the `Callable` that should return True to include a file in the selection of files to be checked. The full numeric mode value of the file on the filesystem, will be passed as the only argument. ``` # list files with sticky bit set $ rak --find --mode='{ $_ +& 0o1000 }' ``` NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --modifications Indicate whether modifications with `--modify-files` and `--rename-files` are allowed. Defaults to `True`, hence it will probably only be actually used in the negation case: `--no-modifications` or `--/modifications`. Intended to be used in cases where there is no complete control over the arguments being specified, e.g. when being used through a web or chat-bot interface. ## --modified=condition If specified, indicates the `Callable` that should return True to include a file in the selection of files to be checked. The modification time of the file (number of seconds since epoch, as a `Num` value) will be passed as the only argument. See "CHECKING TIMES ON FILES" for more information about features that can be used inside the `Callable`. ## --modify-files Flag. Only makes sense if the specified pattern is a `Callable`. Indicates whether the output of the pattern should be applied to the file in which it was found. Defaults to `False`. The `Callable` will be called for each file (in sorted order) and each line of the file, giving the line. By default, the line will be presented to the code **without** its line ending. You need to specify `--with-line-endings` if you want to have the line ending also. The `$*N` dynamic variable is available inside the `Callable` and is initialized to 0 (in case modifications require keeping numeric state between calls). It is then up to the `Callable` to return: ### False Remove this line from the file. NOTE: this means the exact `False` value. ### True Keep this line unchanged the file. NOTE: this means the exact `True` value. ### Nil Keep this line unchanged the file. NOTE: this means the exact `Nil` value. ### Empty Keep this line unchanged the file. NOTE: this means the exact `Empty` value. This is typically returned as the result of a failed condition. For example, only change the string "foo" into "bar" if the line starts with "#": ``` # replace "foo" by "bar" in all files $ rak '*.subst("foo","bar")' --modify-files # replace "foo" by "bar" in all comment lines $ rak '{ .subst("foo","bar") if .starts-with("#") }' --modify-files ``` ### any other value Inserts this value in the file instead of the given line. The value can either be a string, or a list of strings (which would add lines to the file). ## --module=Foo Indicate the Raku module that should be loaded. Only makes sense if the pattern is a `Callable`. ## --not=foo Specify **primary** pattern that should **not** match to produce a hit. ## --or=foo Specify **additional** pattern that should match to produce a hit. ## --ornot=foo Specify **additional** pattern that should **not** match to produce a hit. ## --output-dir=directory Specify the name of the directory to store the results in. For each group, a separate file will be created. Usually used in conjunction with `--classify` or `--categorize`, but can also be used for normal search results. In that case, the basename of a file with results, will be taken as the name of the file to create in that output directory. The directory must **not** exist beforehand. ## --output-file=filename Indicate the path of the file in which the result of the search should be placed. Defaults to `STDOUT`. ## --pager=name Indicate the name (and arguments) of a pager program to be used to page through the generated output. Defaults to the `RAK_PAGER` environment variable. If that isn't specified either, then no pager program will be run. ``` # use the "more" pager to page the output $ RAK_PAGER='more -r' rak foo # use the "less" pager to page the output $ rak foo --pager='less -r' ``` ## --paragraph-context Flag. Indicate all lines that are part of the same paragraph **around** any line that matches. Defaults to `False`. Paragraph boundaries are: * the start of the file * an empty line * the end of the file ## --passthru Flag. Indicate whether **all** lines from source should be shown always. Highlighting will still be performed, if so (implicitely) specified. ``` # watch a log file, and highlight a IP address 123.45.67.89 $ tail -f ~/access.log | rak --passthru 123.45.67.89 ``` ## --passthru-context Flag. Indicate whether **all** lines from source should be produced if at least one line matches. Highlighting will still be performed, if so (implicitely) specified. ## --paths=path1,path2 Indicates the path specification to be used instead of from any positional arguments. Multiple path specifications should be separated by comma's. ## --paths-from=filename Indicate the path of the file to read path specifications from instead of from any positional arguments. "-" can be specified to read path specifications from STDIN. ## --pattern=foo Alternative way to specify the pattern to search for. If (implicitly) specified, will assume the first positional parameter specified is actually a path specification, rather than a pattern. This allows the pattern to be saved with `--save`, and thus freeze a specific pattern as part of a custom option. ## --patterns-from=file Alternative way to specify one or more patterns to search for. Reads the indicated file and interprets each line as a pattern according to the rules (implicitly) set with the `--type` argument. If the file specification is `"-"`, then the patterns will be read from STDIN. ## --pdf-info Flag. Indicates that the meta-info of any PDF file should be produced as single hash to the matcher. Only makes sense if the pattern is a `Callable`. Will also set the `is-pdf` flag to only select PDF files, unless reading from STDIN. Requires the [`PDF::Extract`](https://raku.land/zef:librasteve/PDF::Extract) Raku module to be installed. ## --pdf-per-file Flag. Indicates that any PDF file text contents should be produced as single text to the matcher. Will also set the `is-pdf` flag to only select PDF files, unless reading from STDIN. Requires the [`PDF::Extract`](https://raku.land/zef:librasteve/PDF::Extract) Raku module to be installed. ## --pdf-per-line Flag. Indicates that any PDF file text contents should be produced as lines to the matcher. Will also set the `is-pdf` flag to only select PDF files, unless reading from STDIN. Requires the [`PDF::Extract`](https://raku.land/zef:librasteve/PDF::Extract) Raku module to be installed. ## --per-file[=code] Indicate whether matching should be done per file, rather than per line. If specified as a flag, will slurp a file with the indicated `--encoding` and present that to the matcher. Optionally takes a `Callable` specification: this will be given an `IO::Path` object of the file: whatever it produces will be presented to the matcher. Usually used in conjunction with `--matches-only` and/or `count-only`. ``` # look for foo in only the first 10 lines of each file $ rak foo --per-file='*.lines(:!chomp).head(10).join' ``` ## --per-line[=code] Indicate whether matching should be done per line. If specified as a flag, will read lines with the indicated `--encoding` and present each line to the matcher (which is actually the default if no action was specified).i Optionally takes a `Callable` specification: this will be given an `IO::Path` object of the file: that is then expected to produce lines that will be presented to the matcher. ``` # look for foo in only the last 10 lines of each file $ rak foo --per-line='*.lines.tail(10)' ``` ## --per-paragraph Indicate whether matching should be done per paragraph. It will read lines with the indicated `--encoding`, combine them into paragraphs and present each paragraph to the matcher, with the line number of the start of the paragraphs associated with it. ## --progress Flag. If specified, will produce a progress indicator on STDERR that indicates the number of files checked, number of lines checked and number of matches, updated 5 times per second. Defaults to `False`. ## --proximate=[N] Indicates whether matched lines should be grouped together that are within N lines of each other. This is useful for visually picking out matches that appear close to other matches. If specified as a flag, indicates a proximation of **1**. Defaults to <0> otherwise (indicating no proximation check should be performed). ## --quietly Flag. Only makes sense if the pattern is a `Callable`. If specified, will catch all **warnings** that are emitted when executing the pattern's `Callable`. Defaults to `False`. ## --quote=["] Only applicable if `--csv-per-line` has been specified. Indicates the character that should be used for quoting fields. Defaults to **double quote**. ## --rak Flag. Intended for debugging purposes only. When specified, will show the named arguments sent to the `rak` plumbing subroutine just before it isi being called. ## --rakudo-all Indicate that **all** the files recognized by the Rakudo cache (as generated by [`Rakudo::Cache`](https://raku.land/zef:lizmat/Rakudo::Cache)) should be searched. ## --rakudo-c Indicate that the files recognized as `C` programming language files by the Rakudo cache (as generated by [`Rakudo::Cache`](https://raku.land/zef:lizmat/Rakudo::Cache)) should be searched. ## --rakudo-doc Indicate that the files recognized as documentation files by the Rakudo cache (as generated by [`Rakudo::Cache`](https://raku.land/zef:lizmat/Rakudo::Cache)) should be searched. ## --rakudo-java Indicate that the files recognized as `Java` programming language files by the Rakudo cache (as generated by [`Rakudo::Cache`](https://raku.land/zef:lizmat/Rakudo::Cache)) should be searched. ## --rakudo-js Indicate that the files recognized as `Javascript` programming language files by the Rakudo cache (as generated by [`Rakudo::Cache`](https://raku.land/zef:lizmat/Rakudo::Cache)) should be searched. ## --rakudo-nqp Indicate that the files recognized as `NQP` related files by the Rakudo cache (as generated by [`Rakudo::Cache`](https://raku.land/zef:lizmat/Rakudo::Cache)) should be searched. ## --rakudo-perl Indicate that the files recognized as `Perl` programming language files by the Rakudo cache (as generated by [`Rakudo::Cache`](https://raku.land/zef:lizmat/Rakudo::Cache)) should be searched. ## --rakudo-raku Indicate that the files recognized as `Raku` Programming Language files by the Rakudo cache (as generated by [`Rakudo::Cache`](https://raku.land/zef:lizmat/Rakudo::Cache)) should be searched. ## --rakudo-shell Indicate that the files recognized as shell scripts / batch files by the Rakudo cache (as generated by [`Rakudo::Cache`](https://raku.land/zef:lizmat/Rakudo::Cache)) should be searched. ## --rakudo-test Indicate that the files recognized as test related files by the Rakudo cache (as generated by [`Rakudo::Cache`](https://raku.land/zef:lizmat/Rakudo::Cache)) should be searched. ## --rakudo-yaml Indicate that the files recognized as files containing YAML of some sort by the Rakudo cache (as generated by [`Rakudo::Cache`](https://raku.land/zef:lizmat/Rakudo::Cache)) should be searched. ## --recurse-unmatched-dir Flag. Indicate whether directories that didn't match the `--dir` specification, should be recursed into anyway. Will not produce files from such directories, but may recurse further if directories are encountered. Defaults to `False`. ## --recurse-symlinked-dir Flag. Indicate whether directories that are actually symbolic links, should be recursed into. Defaults to `False`. NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --rename-files Flag. Only makes sense if the specified pattern is a `Callable`. Feeds all selected files, sorted by absolute path, as `IO::Path` objects to the pattern, and uses the result (if different from the original) as the new name of the file. The `--dryrun` argument can be used to run through the whole process **except** doing actually any renaming. The `--verbose` argument can be used to get more verbose feedback on the operation. The `Callable` will be called for each line, giving the file as an `IO::Path` object. The `$*N` dynamic variable is available inside the `Callable` and is initialized to 0. It is then up to the `Callable` to return: ### False Don't change the name of the file NOTE: this means the exact `False` value. ### True Don't change the name of the file. NOTE: this means the exact `True` value. ### Nil Don't change the name of the file. NOTE: this means the exact `Nil` value. ### Empty Don't change the name of the file. NOTE: this means the exact `Empty` value. This is typically returned as the result of a failed condition. ### any other value Use this value as the new name of the file. It can either be a string or an `IO::Path` object. Only when the returned value is different from the given value, will a rename actually be attempted. To make this easier on the user, any `Str` returned, will be automatically converted to an `IO::Path` object before being compared using `eqv`. ``` # change the extension of all .t files to .rakutest $ rak '*.subst(/ \.t $/,".rakutest")' --rename-files # Rename files with 3 digits word bounded with an interval of 10 $ rak '*.subst(/ << \d ** 3 >> /, { ($*N += 10).fmt("%03d") })' --rename-files ``` Note that files that are under git revision control will be renamed using `git mv`: if that fails for any reason, a normal rename will be performed. ## --repository=dir Indicate the directory that should be searched for Raku module loading. Only makes sense if the pattern is executable code. ## --save=shortcut-name Save all options with the given name in the configuration file (`~/.rak-config.json`), and exit with a message that these options have been saved with the given name. This feature can used to both create shortcuts for specific (long) options, or just as a convenient way to combine often used options, or both. ``` # save options as "--im" $ rak --ignorecase --ignoremark --save=im Saved option '--im' as: --ignorecase --ignoremark # can use shortcut to --ignorecase --ignoremark $ rak foo --im # save options as "--rsd" $ rak --recurse-symlinked-dir --save=rsd Saved option '--rsd' as: --recurse-symlinked-dir # save as "--B" with a default of '---' $ rak --break='[---]' --save=B Saved option '--B' as: --break='[---]' # save as "--P" requiring a value $ rak --pattern=! --save=P Saved option '--P' as: --pattern='!' # remove shortcut "--foo" $ rak --save=foo Removed configuration for 'foo' ``` Any options can be accessed as if it is a standard option. Please note that no validity checking on the options is being performed at the moment of saving, as validity may depend on other options having been specified. One option can be marked as requiring a value to be specified (with "!") or have a default value (with "[default-value]"). To remove a saved set of options, use `--save`=foo as the only option to remove the "foo" set of options. ## --sep=, Only applicable if `--csv-per-line` has been specified. Indicates the character to indicate the field separator. Defaults to the **comma**. ## --show-blame Flag. Indicate whether to show `git blame` information for matching lines if possible, instead of just the line. Defaults to `False`. Requires that the [`Git::Blame::File`](https://raku.land/zef:lizmat/Git::Blame::File) module is installed. ## --show-item-number Flag. Indicate whether item numbers should be shown. Defaults to `True`. ## --show-filename Flag. Indicate whether filenames should be shown
## dist_zef-lizmat-App-Rak.md ## Chunk 3 of 3 . Defaults to `True`. ## --shell=invocation If specified, indicates the command(s) to be executed in a shell. Any `$_` in the invocation string will be replaced by the file being checked. The file will be included if the shell command(s) run to a successful conclusion. ## --silently[=out,err] Flag and option. Only applicable if the pattern is a `Callable`. Indicates whether any output from the `Callable` pattern should be caught. Defaults to `False`. If specified as a flag, will catch both STDOUT as well as STDERR output from the pattern's execution. When specified as an option, will accept:](https://raku.land/zef:lizmat/MoarVM::Bytecode) | flag(s) | action | | --- | --- | | out | only capture STDOUT | | err | only capture STDERR | | out,err | capture both STDIN as well as STDERR | | err,out | capture both STDIN as well as STDERR | ## --smartcase Flag. An intelligent version of `--ignorecase`. If the pattern does **not** contain any uppercase letters, it will act as if `--ignorecase` was specified. Otherwise it is ignored. ## --smartmark Flag. An intelligent version of `--ignoremark`. If the pattern does **not** contain any accented letters, it will act as if `--ignoremark` was specified. Otherwise it is ignored. ## --sourcery Flag. Mainly intended for Raku Programming Language core developers. If specified, indicates that the pattern should be interpreted as code specifying a simple call to a subroutine, or a simple call to a method, optionally with arguments. The search result will then contain the source locations of subroutine / method that is expected to be able to handle that call. Compatible with the `--edit`, `--vimgrep` and the implicit `per-line` option. ``` # edit the location(s) of the "say" sub handling a single string $ rak --sourcery 'say "foo"' --edit ``` Requires the [`sourcery`](https://raku.land/zef:lizmat/sourcery) module to be installed. ## --stats Flag. Also show statistics about the search operation after having shown the full search result. ## --stats-only Flag. **Only** show statistics about the search operation. See also `--count-only`. ## --strict Flag. Only applicable if `--csv-per-line` has been specified. If specified, then each line in the CSV file **must** have the same number of fields. Default is to allow different numbers of fields. ## --summary-if-larger-than=N Indicate the maximum size a line may have before it will be summarized. Defaults to `160` if `STDOUT` is a TTY (aka, someone is actually watching the search results), otherwise defaults to `Inf` effectively (indicating no summarization will ever occur). ## --type=string The `--type` argument indicates how any pattern, as specified on the commmand line, or from previously saved options, should be interpreted. If not specified specified, will assume `auto`. The following strings can be specified: ### auto If `--type=auto` is (implicitely) specified, will look for cues in a specified pattern to understand what functionality is requested. See the <pattern> for more information. ### regex If `--type=regex` is specified, then a pattern will be interpreted as a regex, as if it was surrounded by slashes. ### code If `--type=code` is specified, then a pattern will be interpreted as Raku source code, as if it was surrounded by curly braces. ### json-path If `--type=json-path` is specified, then a pattern will be interpreted as a `JSON path`. Only makes sense when used together with `--json-per-file`, `--json-per-line` or `--json-per-elem`. Requires the [`JSON::Path`](https://raku.land/cpan:JNTHN/JSON::Path) module to be installed. ### contains If `--type=contains` is specified, then a pattern will be interpreted as a literal string, while honouring any `--smartcase`, `--smartmark`, `--ignorecase` and `--ignoremark` specifications. ### words If `--type=words` is specified, then a pattern will be interpreted as a literal string that should be bounded by word boundares at both ends, while honouring any `--smartcase`, `--smartmark`, `--ignorecase` and `--ignoremark` specifications. ### starts-with If `--type=starts-with` is specified, then a pattern will be interpreted as a literal string that should occur at the **start** of a line, while honouring any `--smartcase`, `--smartmark`, `--ignorecase` and `--ignoremark` specifications. ### ends-with If `--type=ends-with` is specified, then a pattern will be interpreted as a literal string that should occur at the **end** of a line, while honouring any `--smartcase`, `--smartmark`, `--ignorecase` and `--ignoremark` specifications. ### equal If `--type=equal` is specified, then a pattern will be interpreted as a literal string that should be **equal** to the line, while honouring any `--smartcase`, `--smartmark`, `--ignorecase` and `--ignoremark` specifications. ## --trim Flag. Indicate whether lines that have the pattern, should have any whitespace at the start and/or end of the line removed. Defaults to `True` if no context for lines was specified, else defaults to `False`. ## --uid=condition If specified, indicates the `Callable` that should return `True` to include a file in the selection of files to be checked. The numeric `uid` of the file will be passed as the only argument. Can also be specified as a single numeric argument. See also `--user`. ``` # select files of which the numeric user id is greater than 500 $ rak --find --uid='* > 500' # select files of which the numeric user id is 501 $ rak --find --uid=501 ``` NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --under-version-control[=git] Indicate whether to only select files that are under some form of version control. If specified as a flag, will assume files that are under `git` version control. Can also specify the name of the version control system as the value: currently only **git** is supported. ## --unicode Flag. If specified, will search the unicode database for defined codepoints by name. Default is `False`. ## --unique Flag. If specified, will only produce unique lines of output. Default is `False`. See also `--frequencies`. ## --user=condition If specified, indicates the `Callable` that should return `True` to include a file in the selection of files to be checked. The user name associated with the `uid` of the file will be passed as the only argument. Can also be specified as a list of comma separated names to (not) select on. To select all names **except** the listed named, prefix with a `!`. See also `--uid`. Requires the [P5getpwnam](https://raku.land/zef:lizmat/P5getpwnam) module to be installed. ``` # files of which the name associated with the user id starts with underscore $ rak --find --user='*.starts-with("_")' # select files of which the owner is liz or wendy $ rak --find --user=liz,wendy # select files of which the owner is NOT liz or wendy $ rak --find --user='!liz,wendy' ``` NOTE: support of this feature depends on Raku supporting that feature on the current operating system. ## --version Flag. If the only argument, shows the name and version of the script, and the system it is running on. Additionally specify `--verbose` to see more information. ## --vimgrep Flag. If specified, will output search results in the format "filename:linenumber:column:line". This allows integration with the `:grep` action in vim-like editors. # CHECKING TIMES ON FILES The `--accessed`, `--created`, `--modified` and `--meta-modified` options expect `Callable` to perform the check to include a file in the search process. It is passed the **epoch** (number of seconds since 1 January 1970 UTC) value of the file being checked for the indicated option, and it should return `True` to include that file in any search. To facilitate checks, some extra features are activated for these `Callable`s, allowing you to more easily craft your conditions. ## Automatic conversion to epoch In Raku, the `.accessed`, `.created`, `.changed` and `.modified` methods on the `IO::Path` object return [`Instant`](https://docs.raku.org/type/Instant) objects, which are atomic time rather than epoch. Within these special `Callables`, these values are automatically converted to epoch values, to ease comparisons. ## Specifying some time ago Within these special `Callable`s, one can also indicate an epoch value in the past by using the `.ago` method in a specially formatted string. This string is formatted similarly to time specifications of the Unix `find` command: one of more digits followed by "s" for seconds, "m" for minutes, "h" for hours, "d" for days and "w" for weeks. "+" and "-" may also be used, but do not have any special meaning other than negating the value they apply to. ## On method naming For `rak` it was decided to name the option for checking the meta information of a file as `--meta-modified`. In Raku, the associated method on the `IO::Path` object is (probably for historical reasons) called `.changed`. To facilitate the creation of the `Callable`s for these options, one can use both `.meta-modified` as well as `.changed` as methods. ## Examples ``` # select all files that were modified later than an hour ago $ rak --find --modified='* > "1h".ago' # select all files that were created before 2.5 hours ago $ rak --find --created='* < "2h30m".ago' # select all files that were modified after "Changes" was created $ rak --find --modified='* > "Changes".IO.created' ``` # JSON PATH SUPPORT Supported JSON path syntax | expression | meaning | | --- | --- | | $ | root node | | .key | index hash key | | ['key'] | index hash key | | [2] | index array element | | [0,1] | index array slice | | [4:5] | index array range | | [:5] | index from the beginning | | [-3:] | index to the end | | .\* | index all elements | | [\*] | index all elements | | [?(expr)] | filter on Raku expression | | ..key | search all descendants for hash key | A query that is not rooted from $ or specified using .. will be evaluated from the document root (that is, same as an explicit $ at the start). #### Full Raku support The `jp:path` and `--type=json-path` syntax are actually syntactic sugar for calling a dedicated `jp` macro that takes an unquoted JSON path as its argument, and returns an instantiated `JP` object. This means that: ``` $ rak --json-per-file jp:foo $ rak --json-per-file --type=json-path foo ``` are a different way of saying: ``` $ rak --json-per-file '{ jp("path").Slip }' ``` using the "pattern is Raku code" syntax. The following methods can be called on the `JP` object: | method | selected | | --- | --- | | .value | The first selected value. | | .values | All selected values as a Seq. | | .paths | The paths of all selected values as a Seq. | | .paths-and-values | Interleaved selected paths and values. | Without listing all of the methods that can be called on the `JP` object, one should note that all efforts have been made to make the `JP` object act like a `Seq`. # AUTHOR Elizabeth Mattijsen [liz@raku.rocks](mailto:liz@raku.rocks) Source can be located at: <https://github.com/lizmat/App-Rak> . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2022, 2023, 2024, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-tbrowder-FontFactory-Type1.md [![Actions Status](https://github.com/tbrowder/FontFactory-Type1/actions/workflows/linux.yml/badge.svg)](https://github.com/tbrowder/FontFactory-Type1/actions) [![Actions Status](https://github.com/tbrowder/FontFactory-Type1/actions/workflows/macos.yml/badge.svg)](https://github.com/tbrowder/FontFactory-Type1/actions) [![Actions Status](https://github.com/tbrowder/FontFactory-Type1/actions/workflows/windows.yml/badge.svg)](https://github.com/tbrowder/FontFactory-Type1/actions) # NAME **FontFactory::Type1** - Provides the standard *Adobe PostScript Type 1* fonts in a friendly package for use with many *PDF::*\* modules. A `DocFont` object is a Type 1 font of a specific name and point size. It provides all the methods available in module `Font::AFM` plus some extra convenient methods (and aliases). All its methods provide outputs properly scaled for its font and point size. One can also use fonts *without* any specific size. # SYNOPSIS Find the fonts available in the current version along with their aliases: ``` $ ff1-showfonts # OUTPUT: Font family: 'Courier' (alias: 'c') Font family: 'Courier-Bold' (alias: 'ch') Font family: 'Courier-BoldOblique' (alias: 'cbo') Font family: 'Courier-Oblique' (alias: 'co') Font family: 'Helvetica' (alias: 'h') Font family: 'Helvetica-Bold' (alias: 'hb') Font family: 'Helvetica-BoldOblique' (alias: 'hbo') Font family: 'Helvetica-Oblique' (alias: 'ho') Font family: 'Symbol' (alias: 's') Font family: 'Times-Bold' (alias: 'tb') Font family: 'Times-BoldItalic' (alias: 'tbi') Font family: 'Times-Italic' (alias: 'ti') Font family: 'Times-Roman' (alias: 't') Font family: 'Zapfdingbats' (alias: 'z') ``` Get a copy of the factory for use in your program: ``` my $ff = FontFactory::Type1.new; ``` Define a `DocFont`. Use a name that indicates its face and size for easy use later. For fractional points use a 'd' for the decimal point: ``` my $t12d1 = $ff.get-font: 't12d1'; say "name: ", $t12d1.name; # OUTPUT: «name: Times-Roman␤» say "size: ", $t12d1.size; # OUTPUT: «size: 12.1␤» ``` Define another `DocFont`: ``` my $c10 = $ff.get-font: 'c'; say "name: ", $c10.name; # OUTPUT: «name: Courier␤» say "size: ", $c10.size; # OUTPUT: «size: 0␤» ``` As stated above, in addition to those attributes, all the attributes from `Font::AFM` are also available plus some added for convenience. For example: ``` # For typesetting, find the width of a kerned string in PostScript points (72/inch): my $text = "Some string of text to be typeset in a beautiful PDF document."; my $wk = $t12d1.stringwidth($text, :kern); say "kerned width: $wk"; # OUTPUT: «kerned width: 302.3064␤» ``` # DESCRIPTION **FontFactory::Type1** provides easy access to the Adobe standard Type 1 fonts (and their metrics) as used in PDF document creation using other Raku modules. See the accompanying [METHODS](METHODS.md) for details on the methods and their use in your own PDF document. # AUTHOR Tom Browder [tbrowder@acm.org](mailto:tbrowder@acm.org) # COPYRIGHT AND LICENSE © 2023-2025 Tom Browder This library is free software; you may redistribute it or modify it under the Artistic License 2.0.
## dist_github-antifessional-Log-ZMQ.md # Log::ZMQ ## SYNOPSIS Log::ZMQ is a Perl6 Logger using zeromq to log over tcp/ip ## Introduction A decoupled remote logger. The client sends log meesages from the application to a LogCatcher listening on a tcp port. The backend uses a publisher-subscriber pattern, suitable for debugging asynchronous apps (by sheer luck, the purpose of writing it) but not much else. A more general framework would require changing the pattern. Setup is minimal: A single application-wide call to Logging::instance with arguments, plus no-parameters call for each additinal place in the code that wants to hold its own logger. Enumerated arguments can be entered with colon notation and it is possible to set defaults and log with no extra arguments. A global .set-supress-level( :level) can turn all logging off. When suppressed, log calls incur only the cost of argument checking. Format is a choice of json, yaml and a raw format based on ZMQ frames. It can be extended on both sides with user-provided functions. On the backend, there is currently no distinction between adding parsers and adding handlers. The built-in parsers-handelrs all write the logged message in multiline to STDOUT (useful for debugging, not so much for monitoring.) #### Status In development. This is my learning process of perl6 and ZMQ. I have a lot to learn so use with care. #### Portability depends on Net::ZMQ:auth('github:gabrielash'); ## Example Code #### A (minimal) ``` my $l = Logging::instance( 'example' ).logger; $l.log( 'an important message'); my $l2 = Logging::instance.logger; $l2.log( 'another important message'); ``` #### B ( more elaborate ) ``` my $logger = Logging::instance('example', 'tcp://78.78.1.7:3301'\ , :default-level( :warning )\ , :domain-list( < database engine front-end nativecall > )\ , :format( :json ))\ .logger; $logger.log( 'a very important message', :critical, :front-end ); my $db-logger = Logging::instance.logger.domain( :database ); $db-logger.log( 'meh'); ``` #### C (the log catcher on the other side ) ``` # on the command line: log-catcher.pl --uri 'tcp://78.78.1.7:3301' --prefix example \ --level debug database front-end ``` ## Documentation #### Log::ZMQ::Logging The logging framework based on ZMQ. Usually a singleton summoned with ``` my $log-system = Logging::instance('prefix', ['tcp://127.127.8.17:8022', ... ]) ; ; only supply parameters the first time The default uri is 'tcp://127.0.0.1:3999' Attributes prefix; required default-level; (default = info) format; default yaml domain-list; default ('--') ;if left blank no domain is required below ``` Methods logger() ; returns a Logger set-supress-level(:level) ;silences logging globally unset-supress-level() add-formatter() ;see below set-format() ;must use this after adding a formatter #### Log::ZMQ::Logger The logger ``` Methods log( log-message, :level, :domain ) ; level is optional. ; domain is optional only if a domain list is not set ``` The logging uses a publisher socket. All protocols send 5 frames 1. prefix 2. domain 3. level 4. format [ zmq | yaml | json | ... ] 5. empty frame followed with frames that depend on the format. For zmq: 6. content 7. timestamp 8. target for yaml/json: 6. yaml/json formatted To add custom formatter, use instance.add-formatter. :(MsgBuilder :builder, :prefix, :timestamp, :level, :domain, :content --> MsgBuilder ) { ... your code here ... return $builder; } the builder should be returned unfinalized. then set the format: set-format('name'); #### Log::ZMQ::catcher handles the logging backend, listening to zmq messages. The wrapper script log-catcher.pl can be invoked from the cli. to see options: log-catcher.pl --help This is the body of the MAIN sub ``` my $c = $uri.defined ?? LogCatcher::instance(:$uri, :debug ) !! LogCatcher::instance( :$debug ); $c.set-level-filter( $level); $c.set-domains-filter(| @domains) if @domains; $c.run($prefix); ``` current implemention print the received messaged to stdout. other backends can be added with the following methods: * add-zmq-handler( &f:(:$content, :$timestamp, :$level, :$domain, :$prefix) ) * add-handler( Str $format, &f:(Str:D $content) ) ## LICENSE All files (unless noted otherwise) can be used, modified and redistributed under the terms of the Artistic License Version 2. Examples (in the documentation, in tests or distributed as separate files) can be considered public domain. ⓒ 2017 Gabriel Ash
## dist_zef-tbrowder-Date-YearDay.md [![Actions Status](https://github.com/tbrowder/Date-YearDay/workflows/test/badge.svg)](https://github.com/tbrowder/Date-YearDay/actions) # NAME Date::YearDay - Provides creation of a Raku Date object by year and day-of-year # SYNOPSIS ``` use Date::YearDay; my ($year, $day-of-year) = 2021, 42; my $d = Date::YearDay.new: :$year, :$day-of-year; say $d ~~ Date; # OUTPUT: «True␤» # alternatively: my $d2 = Date::YearDay.new: :$year, :doy($day-of-year); say $d2.Str; # OUTPUT: «2021-02-11␤» ``` # DESCRIPTION Class **Date::YearDay** is child class of a Raku *Date* object whose purpose is to provide *Date* instantiation by entering a year and day-of-year. As a child of the *Date* class it inherits all the *Date* class' methods without further action by the user. # AUTHOR Tom Browder [tbrowder@acm.org](mailto:tbrowder@acm.org) # COPYRIGHT AND LICENSE Copyright 2021 Tom Browder This library is free software; you may redistribute it or modify it under the Artistic License 2.0.
## sprintf.md sprintf Combined from primary sources listed below. # [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_routine_sprintf "direct link") See primary documentation [in context](/type/independent-routines#routine_sprintf) for **routine sprintf**. ```raku multi sprintf(Cool:D $format, *@args) ``` Returns a string according to a format as described below. The format used is the invocant (if called in method form) or the first argument (if called as a routine). ```raku sprintf( "%s the %d%s", "þor", 1, "st").put; # OUTPUT: «þor the 1st␤» sprintf( "%s is %s", "þor", "mighty").put; # OUTPUT: «þor is mighty␤» "%s's weight is %.2f %s".sprintf( "Mjölnir", 3.3392, "kg").put; # OUTPUT: «Mjölnir's weight is 3.34 kg␤» # OUTPUT: «Mjölnir's weight is 3.34 kg␤» ``` This function is mostly identical to the C library's `sprintf` and `printf` functions. The only difference between the two functions is that `sprintf` returns a string while the `printf` function writes to a filehandle. `sprintf` returns a [`Str`](/type/Str), not a literal. The `$format` is scanned for `%` characters. Any `%` introduces a format token. Directives guide the use (if any) of the arguments. When a directive other than `%` is used, it indicates how the next argument passed is to be formatted into the string to be created. *Parameter indexes* may also be used in the format tokens. They take the form `N$` and are explained in more detail below. The `$format` may be defined enclosed in single or double quotes. The double-quoted `$format` string is interpolated before being scanned and any embedded string whose interpolated value contains a `%` character will cause an exception. For example: ```raku my $prod = "Ab-%x-42"; my $cost = "30"; sprintf("Product $prod; cost: \$%d", $cost).put; # OUTPUT: «Your printf-style directives specify 2 arguments, but 1 argument was supplied␤» « in block <unit> at <unknown file> line 1␤» ``` When handling unknown input you should avoid using such syntax by putting all variables in the `*@args` array and have one `%` for each in `$format`. If you need to include a `$` symbol in the format string (even as a *parameter index*) either escape it or use the single-quoted form. For example, either of the following forms works without error: ```raku sprintf("2 x \$20 = \$%d", 2*20).put; # OUTPUT: «2 x $20 = $40␤» sprintf('2 x $20 = $%d', 2*20).put; # OUTPUT: «2 x $20 = $40␤» ``` In summary, unless you need something very special, you will have fewer unexpected problems by using the single-quoted format string and not using interpolated strings inside the format string. [[1]](#fn1) # [In Cool](#___top "go to top of document")[§](#(Cool)_method_sprintf "direct link") See primary documentation [in context](/type/Cool#method_sprintf) for **method sprintf**. ```raku method sprintf(*@args) ``` Returns a string according to a series of [format directives](/type/independent-routines#Directives) that are common in many languages; the object will be the format string, while the supplied arguments will be what's going to be formatted according to it. ```raku "% 6s".sprintf('Þor').say; # OUTPUT: « Þor␤» ```
## dist_cpan-MELEZHIK-Sparrowdo-Cpanm-GitHub.md # Sparrowdo::Cpanm::GitHub [![Build Status](https://travis-ci.org/melezhik/sparrowdo-cpanm-github.svg?branch=master)](https://travis-ci.org/melezhik/sparrowdo-cpanm-github) # Install ``` $ zef install Sparrowdo::Cpanm::GitHub ``` # SYNOPSIS [Sparrowdo](https://github.com/melezhik/sparrowdo) module to installs CPAN modules fetched from remote GitHub repositories. # Descritpion Installs CPAN modules taken from GitHub repositories and branches. # Usage ``` $ cat sparrowfile # install https://github.com/melezhik/outthentic # master branch module-run 'Cpanm::GitHub', %( user => "melezhik", # github user, required project => "outthentic", # GitHub project, required ); # install "realtime-stdout" branch module-run 'Cpanm::GitHub', %( user => "melezhik", # github user, required project => "outthentic", # GitHub project branch => "realtime-stdout" # Branch name; If not set master branch installed ); ``` # Limitation If need more precise control on CPAN modules installations consider [cpan-\*](https://github.com/melezhik/Sparrow6/blob/master/documentation/dsl.md#cpan-packages) functions come from Sparrow DSL. This is pretty straightforward install using system (root) installation. ## LICENSE All files (unless noted otherwise) can be used, modified and redistributed under the terms of the Artistic License Version 2. Examples (in the documentation, in tests or distributed as separate files) can be considered public domain. ⓒ2017 'Alexey Melezhik'
## dist_zef-FRITH-File-Metadata-Libextractor.md [![Actions Status](https://github.com/frithnanth/perl6-File-Metadata-Libextractor/workflows/test/badge.svg)](https://github.com/frithnanth/perl6-File-Metadata-Libextractor/actions) # NAME File::Metadata::Libextractor - Use libextractor to read file metadata # SYNOPSIS ``` use File::Metadata::Libextractor; #| This program extracts all the information about a file sub MAIN($file! where { .IO.f // die "file '$file' not found" }) { my File::Metadata::Libextractor $e .= new; my @info = $e.extract($file); for @info -> %record { for %record.kv -> $k, $v { say "$k: $v" } say '-' x 50; } } ``` # DESCRIPTION File::Metadata::Libextractor provides an OO interface to libextractor in order to query files' metadata. As the Libextractor site (<https://www.gnu.org/software/libextractor>) states, it is able to read information in the following file types: * HTML * MAN * PS * DVI * OLE2 (DOC, XLS, PPT) * OpenOffice (sxw) * StarOffice (sdw) * FLAC * MP3 (ID3v1 and ID3v2) * OGG * WAV * S3M (Scream Tracker 3) * XM (eXtended Module) * IT (Impulse Tracker) * NSF(E) (NES music) * SID (C64 music) * EXIV2 * JPEG * GIF * PNG * TIFF * DEB * RPM * TAR(.GZ) * LZH * LHA * RAR * ZIP * CAB * 7-ZIP * AR * MTREE * PAX * CPIO * ISO9660 * SHAR * RAW * XAR FLV * REAL * RIFF (AVI) * MPEG * QT * ASF Also, various additional MIME types are detected. ## new(Bool :$in-process?) Creates a **File::Metadata::Libextractor** object. libextractor interfaces to several libraries in order to extract the metadata. To work safely it starts sub-processes to perform the actual extraction work. This might cause problems in a concurrent envirnment with locks. A possible solution is to run the extraction process inside the program's own process. It's less secure, but it may avoid locking problems. The optional argument **$in-process** allows the execution of the extraction job in the parent's process. ## extract($file where .IO.f // fail "file '$file' not found" --> List) Reads all the possible information from an existing file, or fails if the file doesn't exist. The output **List** is actually a List of Hashes. Each hash has the following keys: * mime-type The file's mime-type * plugin-name The name of the plugin the library used to find out the information * plugin-type The plugin subtype used for the operation * plugin-format The format of the plugin's output * data-type The value returned by the plugin subtype The possible values for **plugin-format** are: * EXTRACTOR\_METAFORMAT\_UNKNOWN * EXTRACTOR\_METAFORMAT\_UTF8 * EXTRACTOR\_METAFORMAT\_BINARY * EXTRACTOR\_METAFORMAT\_C\_STRING The possible values for the **plugin-type** field are listed in File::Metadata::Libextractor::Constants, in the EXTRACTOR\_MetaType enum (231 values as for v3.1.6). # Prerequisites This module requires the libextractor library to be installed. It has been successfully tested on the following Linux distributions: * Debian 9 * Debian sid * Ubuntu 16.04 * Ubuntu 18.04 It doesn't work with the version of the library that comes with Ubuntu 14.04. ``` sudo apt-get install libextractor3 ``` This module looks for a library called libextractor.so.3 . # Installation To install it using zef (a module management tool): ``` $ zef install File::Metadata::Libextractor ``` # Testing To run the tests: ``` $ prove -e "raku -Ilib" ``` # AUTHOR Fernando Santagata [nando.santagata@gmail.com](mailto:nando.santagata@gmail.com) # COPYRIGHT AND LICENSE Copyright 2018 Fernando Santagata This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-dwarring-FontConfig.md [[Raku PDF Project]](https://pdf-raku.github.io) / [[FontConfig Module]](https://pdf-raku.github.io/FontConfig-raku/) [![Actions Status](https://github.com/pdf-raku/FontConfig-raku/workflows/test/badge.svg)](https://github.com/pdf-raku/FontConfig-raku/actions) # FontConfig-raku Raku interface to the FontConfig native library ## Synopsis ``` use FontConfig; use FontConfig::Pattern; use FontConfig::Match; # optional: fontconfig uses the default system configuration, by default INIT FontConfig.set-config-file: 'my-fonts.conf'; my FontConfig::Pattern $patt; $patt .= parse: 'Arial,sans:style<italic>'; # -- OR -- $patt .= new: :family<Arial sans>, :style<italic>; $patt.weight = 'bold'; say $patt.Str; # Arial,sans:style=italic:weight=205 my FontConfig::Match $match = $patt.match; say $match.file; say $match.format('%{file}'); # e.g. /usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf ``` ## Description This module provides Raku bindings to the FontConfig library for system-wide font configuration and access. At this stage, enough library bindings are implemented to enable FontConfig patterns to be parsed or built, and the best matching font to be located. ## Property Accessors The Raku FontConfig bindings provide automatic accessors for known properties ``` $patt.weight = 'bold'; say $patt.weight; ``` ## FontConfig Configuration By default, fontconfig uses system-wide font configuration files. Their location may depend on your particular distribution and system. There are several environment variables that can be set to define files and search paths, including: `FONTCONFIG_FILE` and `FONTCONFIG_PATH`. This may need to be set, prior to running your programs, to provide a custom configuration file, or if FontConfig is giving an error "Cannot load default config file". The FontConfig class has one method `set-config-file($path)` that can be called from the current process to set `FONTCONFIG_FILE`. This acts globally and should be called once, before using any other methods. ## Classes in this distribution * [FontConfig](https://pdf-raku.github.io/FontConfig-raku/FontConfig) - FontConfig base class for Patterns and Matches * [FontConfig::Pattern](https://pdf-raku.github.io/FontConfig-raku/FontConfig/Pattern) - FontConfig query Pattern * [FontConfig::Match](https://pdf-raku.github.io/FontConfig-raku/FontConfig/Match) - FontConfig matching font descriptor * [FontConfig::Match::Series](https://pdf-raku.github.io/FontConfig-raku/FontConfig/Match/Series) - Sorted series of FontConfig::Match matching objects * [FontConfig::Raw](https://pdf-raku.github.io/FontConfig-raku/FontConfig/Raw) - FontConfig native bindings ## Install This module requires a development version of fontconfig: * Debian/Ubuntu Linux: `sudo apt-get install libfontconfig1-dev` * Alpine/Linux: `doas apk add fontconfig-dev` * Mac OS X: `brew install fontconfig`
## dist_cpan-KJK-P6Repl-Helper.md [![Build Status](https://travis-ci.org/kjkuan/P6Repl-Helper.svg?branch=master)](https://travis-ci.org/kjkuan/P6Repl-Helper) # NAME P6Repl::Helper - Convenience functions to help with introspecting objects from Perl6 REPL. # SYNOPSIS ``` # Install it $ zef install P6Repl::Helper # Run the Perl6 REPL with it $ perl6 -M P6Repl::Helper # Or, load it from the REPL $ perl6 > use P6Repl::Helper; ``` # DESCRIPTION P6Repl::Helper provides functions to help you explore Perl6 packages (package/module/class/role/grammar) from the REPL. # EXAMPLES ``` # Show the GLOBAL package > our sub mysub { 123 }; ls GLOBAL # Show only names in the CORE module that have "str" in them > ls CORE, :name(/str/) # Show all s* subs and their multi candidates if any. > ls CORE, :name(/^s/), :long # You can also filter on the objects themselves. # E.g., show only CORE types(class, role, or grammar) # > ls CORE, :value(Class-ish) # Show only non-sub instances in CORE > ls CORE, :value({$^obj.DEFINITE && $^obj !~~ Sub}) # Show Str's methods that begins with 'ch'. 'll' is like 'ls' but with :long. > ll Str, :name(/^ch/) # By default only local methods are matched against; specify :all to match # against inherited methods as well. # > ll Str, :name(/fmt/), :all # Specifying :gather returns a Seq of Pairs > ls CORE, :name(/^sp/), :gather ==> { .value.&ls for $_ }() # Once you get a hold of a sub or a method, you can use &doc to open its # documentation in a browser. > doc &substr > ls CORE, :name(/^s/), :numbered > doc (ls CORE, :name(/^s/), :take(21)) ``` # AUTHOR Jack Kuan [kjkuan@gmail.com](mailto:kjkuan@gmail.com) # CONTRIBUTING This is my first Perl6 module, written mainly to learn Perl6; therefore, any corrections/suggestions or help is highly apprecicated! # COPYRIGHT AND LICENSE Copyright 2018 Jack Kuan This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## negatedpair.md class X::Syntax::NegatedPair Compilation error due to passing an argument to a negated colonpair ```raku class X::Syntax::NegatedPair does X::Syntax { } ``` Thrown if a colonpair illegally has a value, for example `:!a(1)`. This is an error because the `!` negation implies that the value is `False`. A typical error message from this class is *Argument not allowed on negated pair with key 'a'*. # [Methods](#class_X::Syntax::NegatedPair "go to top of document")[§](#Methods "direct link") ## [method key](#class_X::Syntax::NegatedPair "go to top of document")[§](#method_key "direct link") Returns the key of the pair that caused the error.
## dist_cpan-HOLLI-JSON-Pretty-Sorted.md [![Build Status](https://travis-ci.org/holli-holzer/raku-JSON-Pretty-Sorted.svg?branch=master)](https://travis-ci.org/holli-holzer/raku-JSON-Pretty-Sorted) # NAME JSON::Pretty::Sorted - JSON::Pretty, but with the ability to sort keys and data # SYNOPSIS ``` use JSON::Pretty::Sorted; # For brevity sub no-ws( $v ) { $v.subst( /\s/, '', :g ) } my %data = :c(1), :a(3), :b(2); # sort by key, '{"a":3,"b":2,"c":1}' say no-ws to-json %data, sorter => { $^a.key cmp $^b.key }; # sort by value, '{"a":3,"b":2,"c":1}' say no-ws to-json %data, sorter => { $^b.value cmp $^a.value } my %data = foo => [ 1, 2, 3 ], bar => [5, 6, 4], baz => [ 3.1, 8.1, 1.1 ]; # '{"bar":[6,5,4],"baz":[3.1,8.1,1.1],"foo":[3,2,1]}' say no-ws to-json %data, sorter => { $^a.isa( Pair ) ?? $^a.key cmp $^b.key !! $^a.isa( Int ) ?? $^b <=> $^a !! Same; }; # Same as above multi sub sorter( Pair $a, Pair $b ) { $a.key cmp $b.key } multi sub sorter( Int $a, Int $b ) { $b <=> $a } multi sub sorter( $a, $b ) { Same } say no-ws to-json( %data, :&sorter ); ``` # DESCRIPTION JSON::Pretty::Sorted is the same as [JSON::Pretty](https://github.com/FROGGS/p6-JSON-Pretty), but with the ability to sort the JSON output. # AUTHOR holli-holzer ([holli.holzer@gmail.com](mailto:holli.holzer@gmail.com)) # COPYRIGHT AND LICENSE This library is free software; you can redistribute it and/or modify it under the GPL-3 License.
## redo.md role CX::Redo Redo control exception ```raku role CX::Redo does X::Control { } ``` A [control exception](/language/exceptions#Control_exceptions) thrown when `redo` is called. # [Methods](#role_CX::Redo "go to top of document")[§](#Methods "direct link") ## [method message](#role_CX::Redo "go to top of document")[§](#method_message "direct link") ```raku method message() ``` Returns `'<redo control exception>'`.
## dist_github-melezhik-Sparrowdo-Cpm.md # SYNOPSIS Sparrowdo module to install CPAN modules using App::cpm - a fast CPAN module installer. # Install ``` $ panda install Sparrowdo::Cpm ``` # Usage ``` $ cat sparrowfile module_run 'Cpm', %( list => 'Moose DBI CGI', verbose => 1 ); ``` # Parameters ## list Should be space separated list of CPAN modules to install. ## user Sets user to runs a cpm client. By default user is not set. ## install-base Sets install base. By default install-base is not set. This is how user/install-base result in cpm install run: ``` +-----------+--------------+---------------------------------------------+ | user | install-base | cpm run | +-----------+--------------+---------------------------------------------+ | not set | not set | cpm install -g # global %INC install | | set | not set | cpm install # install into ./local | | not set | set | cpm install -L /install/base # into base | +-----------+--------------+---------------------------------------------+ ``` ## verbose Sets cpm client verbose mode on. # Author [Alexey Melezhik](mailto:melezhik@gmail.com) # See also * [SparrowDo](https://github.com/melezhik/sparrowdo) * [App::cpm](https://metacpan.org/pod/App::cpm)
## dist_github-salortiz-DBDish-ODBC.md # DBDish::ODBC ## Native library notes Requires ODBC library. If you believe you have a library installed but see error messages complaining that it is missing, try the `DBDISH_ODBC_LIB` environment variable.
## dist_github-jamesalbert-JSON-WebToken.md [![Build Status](https://travis-ci.org/jamesalbert/JSON-WebToken.svg?branch=master)](https://travis-ci.org/jamesalbert/JSON-WebToken) # NAME JSON::WebToken - JSON Web Token (JWT) implementation for Perl6 # INSTALL ``` panda update panda install JSON::WebToken ``` # SYNOPSIS ``` use Data::Dump; use JSON::WebToken; use Test; my $claims = { iss => 'joe', exp => 1300819380 }; my $secret = 'secret'; my $jwt = encode_jwt $claims, $secret; #, 'RS256'; say "encoded " ~ Dump($claims) ~ " to $jwt"; my $decoded = decode_jwt $jwt, $secret; say "decoded to " ~ Dump($decoded); is-deeply $decoded, $claims; done-testing; ``` # DESCRIPTION WARNING: This module is brand-spankin' new. It only supports one type of encryption/decryption (HS256). Contributors Welcome! JSON::WebToken is a JSON Web Token (JWT) implementation for Perl6 \*\*THIS MODULE IS ALPHA LEVEL INTERFACE. \*\* # METHODS ## encode($claims [, $secret, $algorithm, $extra\_headers ]) : String The default and currently only supported encryption algorithm is `HS256` and the synopsis above explains how to do it. Once we support RSA, you will be able to specify the algorithm by doing: ``` use JSON::WebToken; my $pricate_key_string = '...'; my $public_key_string = '...'; my $claims = { iss => 'joe', exp => 1300819380 }; my $jwt = encode-jwt($claims, $pricate_key_string, 'RS256'); # NOTE: not supported yet my $decoded = decode-jwt $jwt, $public_key_string; ``` If and when you use RS256, RS384 or RS512 algorithm, Crypt::OpenSSL::RSA is required. If you want to create a `Plaintext JWT` , should be specify `none` for the algorithm. ``` my $jwt = encode-jwt($claims, '', 'none'); ``` ## decode($jwt [, $secret, $verify\_signature, $accepted\_algorithms ]) : HASH This method decodes a hash from JWT string. ``` my $decoded = decode-jwt $jwt, $secret, 1, ['HS256']; ``` Any signing algorithm (except "none") is acceptable by default, so you should check it with $accepted\_algorithms parameter. ## add\_signing\_algorithm($algorithm, $class) This method adds a signing algorithm. ``` use JSON::WebToken; class Foo { method sign ($algorithm, $message, $key) { return 'H*'; # or whatever the heck your signature is } method verify ($algorithm, $message, $key, $signature) { $signature eq self.sign($algorithm, $message, $key); } } add_signing_algorithm Foo.new; ``` SEE ALSO JSON::WebToken::Crypt::HMAC or JSON::WebToken::Crypt::RSA . # FUNCTIONS ## encode\_jwt($claims [, $secret, $algorithm, $extra\_headers ]) : String Same as `encode()` method. ## decode\_jwt($jwt [, $secret, $verify\_signature, $accepted\_algorithms ]) : Hash Same as `decode()` method. # ERROR CODES JSON::WebToken::Exception will be thrown with following code. ## ERROR\_JWT\_INVALID\_PARAMETER When some method arguments are not valid. ## ERROR\_JWT\_MISSING\_SECRET When secret is required. (`alg != "none"` ) ## ERROR\_JWT\_INVALID\_SEGMENT\_COUNT When JWT segment count is not between 2 and 4. ## ERROR\_JWT\_INVALID\_SEGMENT\_ENCODING When each JWT segment is not encoded by base64url. ## ERROR\_JWT\_UNWANTED\_SIGNATURE When `alg == "none"` but signature segment found. ## ERROR\_JWT\_INVALID\_SIGNATURE When JWT signature is invalid. ## ERROR\_JWT\_NOT\_SUPPORTED\_SIGNING\_ALGORITHM When given signing algorithm is not supported. ## ERROR\_JWT\_UNACCEPTABLE\_ALGORITHM When given signing algorithm is not included in acceptable\_algorithms. # AUTHOR jamesalbert AKA jimmyjam5000ME (Millennium Edition) [jalbert1@uci.edu](mailto:jalbert1@uci.edu) Authors of Perl5 JSON::WebToken: xaicron [xaicron@cpan.orggt](mailto:xaicron@cpan.orggt) zentooo # COPYRIGHT Copyright 2016 - jamesalbert # LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. # SEE ALSO <http://tools.ietf.org/html/draft-ietf-oauth-json-web-token>
## dist_github-cjfields-BioPerl6.md [![Build Status](https://travis-ci.org/cjfields/bioperl6.svg?branch=master)](https://travis-ci.org/cjfields/bioperl6) # BioPerl 6 The experimental classes in this directory are test implementations for Perl 6. Most of these are similar to perl5-based BioPerl with simple Perl 6 translations. We intend on porting functionality when needed, but also addressing many of the problems faced with the perl5 BioPerl version, namely class/interface structure, overly complex class hierarchy, etc. So, keep in mind that nothing is set in stone yet and things may change under your feet. **Hic sunt dracones**. Also, just a note: this repository may eventually be moved under the BioPerl umbrella. If so, I'll leave stub repo here pointing to the correct location. # Participation If you have an itch to scratch and want to try it out, fork the code and hack away. Even better, *I can add you as a developer!* Drop me a note, I'm more than happy to have help. The more the better! # Targeting Currently, I target [Rakudo Perl 6](https://github.com/rakudo/rakudo) (specifically using the MoarVM backend) off the `nom` branch. We may switch at some point to a targeted Rakudo Star version for more stability, but since the latest branch code has seen dramatic improvements (as of Aug. 2014) we aim to stay consistent with that. Note, as of Dec. 25, 2015, Rakudo is now targeting the newly-released Perl 6 official specification (6.c), therefore syntax is expected to have stabilized and focus will be fixing bugs, improving performance, and working out corners of the specification that need further clarification. # Implemented * `Bio::PrimarySeq` - this includes required basic modules for transcription and translation. * `Bio::Range` - simple biological range operations (don't confuse this with the Perl 6 Range class) * `Bio::Root` - original base class for BioPerl, though this may be removed in favor of using Perl 6 standard exception handling (which is leagues better than p5) # Testing Basically, one can do this: ``` prove -e 'perl6' -r t ``` which will run all tests. **This will certainly fail at this stage!** Most current tests are ports from the original BioPerl distribution, and the current code is in various stages of updating. We anticipate this changing more over the next year. To run a single test: ``` prove -e 'perl6' t/Root.t ``` # Notes Perl 6 is a specification and thus can represent multiple implementations. More in the Perl 6 [synopses](http://design.perl6.org/). # Related * [Matt Oates](http://blog.mattoates.co.uk) has some nice Perl6 bioinformatics code implemented in the [BioInfo project](https://github.com/MattOates/BioInfo) that demonstrates some of the power of Perl6, including slangs and concurrency.
## dist_zef-guifa-Intl-LanguageTag.md # Intl::LanguageTag ## Usage ``` use Intl::LanguageTag; # ← Imports as 'LanguageTag' use Intl::LanguageTag::BCP-47; # ← Imports as 'LanguageTag::BCP-47' use Intl::LanguageTag::BCP-47 <enums>; # ← Include enums use Intl::LanguageTag::BCP-47 <utils>; # ← Include lookup-language-tags # and filter-language-tags subs # Create a new LanguageTag from a string LanguageTag.new: 'en-US'; ``` ## Which to `use` Most of the time, `use Intl::LanguageTag` is what you will want (the BCP-47 tag type is set as the default for a reason). Prefer `use Intl::LanguageTag::BCP-47` when interacting with other language tag types in the same scope to avoid a symbol collision. ## Features Everything is value typed! This means you can easily use them in sets, bags, and mixes and routines like `unique` will operate as you'd expect. Once you've created a language tag, you have the following simple methods to introspect it. * **`.language`** The language code. Introspections: *.well-formed, .valid, .preferred, .deprecated, .macrolanguage, .default-script*) * **`.script`** The script used, will be omitted if the same as the default script. Introspections: *.well-formed, .valid, .deprecated*) * **`.region`** The region code Introspections: *.well-formed, .valid, .deprecated, .preferred*) * **`.variants`** The variant codes. This object provides positional access to its subtags. Introspections: *.well-formed, .valid, .valid-for-tag, .deprecated, .prefixes*) * **`.extensions`** Any extensions. This object provides hashy access (currently recognizing `<t>` and `<u>`) * **`.private-use`** Any private use tags. This object provides positional access to its subtags. Each of the above will stringify into the exact code, but also has introspective methods. For instance, `.language.default-script` tells you what the default script for the language is. ## Canonicalization Language tags are canonicalized to the extent possible upon creation. This is done in accordance with BCP 47, RFC 6067, RFC 6497, and TR 35 and helps to guarantee value typing mechanics. Most likely, you may notice that a script will disappear. Less likely, if you use grandfathered tags, tags like `i-navajo` will be automatically converted to their preferred form (`nv`) when those exist. There are five grandfathered tags without preferred forms which will preserve the entire tag as the “language” (e.g. `i-default`), and issue a warning since those tags should not be used. Extended languages tags *are* preserved, and with on-demand and automatic conversion to preferred forms planned for a future release. ## Utility functions If you include `<utils>` in your use statement, you will have access to two subs to aid working with language tags. They are the following: * **`sub filter-language-tags(@source, $filter, :$basic = False)`** This performs a 'filter' operation. The source is a list of BCP47 objects, and the filter is also a BCP47. When in basic mode, all source tags that are identical to, or begin with tags identical to the filter are returned. * **`sub lookup-language-tags(@available, @preferred, $default)`** Performs a 'lookup' operation to return an optimally matching language tag. A common usage might be in an HTML server to receive the client's `@preferred` languages and compare them to the `@available` languages on the server. The `.head` is the best language to use (or use `:single` if you have no need for backup choices). If the names of these functions is too verbose, you can alias them easily by doing `my &filter = filter-language-tags`. ## Usage notes Major architectural changes were made between v0.10 and v0.11. Some functionality is not backwards compatible, however, I am not aware of any module making use of those previous features. The changes include how introspection and grandfathered tags work, removal of creation by anything other than a string, removal of enums, removal of `LanguageTagFilter` objects. ## Todo In likely order of completion: * Restore `enum` access * Better introspection of extensions U / T * Logical cloning with changes * Better validation (`.deprecated`, `.valid`, etc) * Extlang and grandfathered tag support (via automatic canonicalization) * Improve filtering by enabling wildcards in matches. * More exhaustive test files ## Version history * 0.12.4 * Updated to IANA subtag registry dated 2024-06-14 * 0.12.3 * Updated to IANA subtag registry dated 2023-03-22 * 0.12.2 * Fixed minor signature bug with `EmptyExtension` (found thanks to `Intl::Format::Number`'s `<u><nu>` usage) * Updated to IANA subtag registry dated 2023-02-14 * 0.12.1 * Fixed an issue with a potentially consumed sequence when accessing extensions * Updated to IANA subtag registry dated 2022-08-08 * Moved to zef ecosystem * 0.12.0 * Extensions and their subelements no longer prefix their type in `.Str` (technically not backwards compatible) for more intuitive use * Some canonicalization during creation (making `en-Latn-US-u-rg-us` yields `en-US`) * Smart introspection (`LanguageTag.new('en').script` yields `Latn`, as it's the specified default) * Updated to IANA subtag registry dated 2021-05-11 * 'Shortcuts' available for introspection to Unicode extensions T / U * API makes this available for modules creating custom extensions (although it's unlikely anyone will) * 0.11.0 * Internal code overhaul for better long-term maintenance * Added `LanguageTaggish` role * Tags are now value types * All tags automatically canonicalize upon creation. * 0.10.0 * Update to IANA subtag registry dated 2020-12-18 * Added a `COERCE(Str)` method for Raku's new coercion protocol. * **Final update** before near total reworking of the innards for better performance, code cleanliness/maintainability, etc. * 0.9.1 * Updated to IANA subtag registry dated 2020-06-10 * Temporarily removed `is DEPRECATED` from `LanguageTag::Script::type` until more extensive recoding can be done. * 0.9.0 * Preliminary Wildcard support * Updated to IANA subtag registry dated 2019-09-16 * Language and Region enums available under Language:: and Region:: namespaces * Preliminary semantic support for the T extension (U support still very early) * Preliminary creation of POD6 documentation (both inline and separate). * Particularly evident for the T extension * 0.8.5 * Lookups available (no wildcard support yet) * 0.8.3 * Added initial support for parsing -t and -u extensions. * Added initial support for grandfathered tags * Fixed bug on parsing variants when no region code was present * Laid groundwork for various validation and canonicalization options (not fully implemented yet) ## License All files (unless noted otherwise) can be used, modified and redistributed under the terms of the Artistic License Version 2. Examples (in the documentation, in tests or distributed as separate files) can be considered public domain. ### “Unless noted otherwise” The resources directory "cldr" contains the contents of the "bcp47" folder of the Unicode CLDR data. These files are copyrighted by Unicode, Inc., and are available and distributed in accordance with [their terms](http://www.unicode.org/copyright.html). The resources file “language-subtag-registry” comes from the [IANA](https://www.iana.org/assignments/language-subtag-registry). I do not currently distribute it because I am not aware of its exact license, but it will be automatically downloaded when running the parsing script. Its data is not needed for distribution, and so is gitignored
## dist_zef-hythm-content-storage-cli.md # Name content-storage-cli - CLI client to interact with [content-storage](https://github.com/hythm7/content-storage.git) # Installation ``` # using zef zef install content-storage-cli # or using Pakku pakku add content-storage-cli ``` Config file example: ``` > cat ~/.content-storage-cli/config.json { "storage": { "name": "my-storage", "api": { "uri": "https://content-storage.pakku.org/api/v1/", "page": 1, "limit": 20 } }, "verbose": true } # Please replace uri with the required storage api uri. ``` # Usage ``` content-storage-cli.raku distributions content-storage-cli.raku builds content-storage-cli.raku users content-storage-cli.raku my distributions content-storage-cli.raku my builds content-storage-cli.raku search distributions <name> content-storage-cli.raku search builds <name> content-storage-cli.raku search users <name> content-storage-cli.raku my user content-storage-cli.raku delete distribution <distribution> content-storage-cli.raku delete build <build> content-storage-cli.raku delete user <user> content-storage-cli.raku build log <build> content-storage-cli.raku update user <user> [--password=<Str>] content-storage-cli.raku update user <user> [--admin] content-storage-cli.raku update my password <password> content-storage-cli.raku download <identity> content-storage-cli.raku add <archive> content-storage-cli.raku login <username> <password> content-storage-cli.raku register <username> <password> [--firstname=<Str>] [--lastname=<Str>] [--email=<S content-storage-cli.raku logout ``` # Author Haytham Elganiny [elganiny.haytham@gmail.com](mailto:elganiny.haytham@gmail.com) # Copyright and License Copyright 2024 Haytham Elganiny This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## tables.md Pod6 tables Valid, invalid, and unexpected tables The official specification for Pod6 tables is located in the Documentation specification here: [Tables](https://raw.githubusercontent.com/perl6/specs/master/S26-documentation.pod). Although Pod6 specifications are not completely and properly handled yet, several projects are ongoing to correct the situation; one such project is ensuring the proper handling of Pod6 tables. As part of that effort, this document explains the current state of Pod6 tables by example: valid tables, invalid tables, and unexpected tables (i.e., valid tables that, because of sloppy construction, may result in something different than the user expects). # [Restrictions](#Pod6_tables "go to top of document")[§](#Restrictions "direct link") 1. The only valid column separators are either visible (' | ' or ' + ') (note at least one space is required before and after the visible column separators) or invisible [two or more contiguous whitespace (WS) characters (e.g., '  ')]. Column separators are not normally recognized as such at the left or right side of a table, but one on the right side may result in one or more empty cells depending upon the number of the cells in other rows. (Note that a pipe or plus character meant as part of cell data will result in an unintended extra column unless the character is escaped with a backslash, e.g., '\|' or '\+'.) 2. Mixing visible and invisible column separators in the same table is illegal. 3. The only valid row separator characters are '\_', '-', '+', ' ', '|', and '='. 4. Consecutive interior row-separator lines are illegal. 5. Leading and trailing row-separator lines generate a warning. 6. Formatting blocks in table cells are currently ignored and treated as plain text. HINT: During development, use of the environment variable `RAKUDO_POD6_TABLE_DEBUG` will show you how Rakudo interprets your Pod tables before they are passed to renderers such as `Pod::To::HTML`, `Pod::To::Text`, and `Pod::To::Markdown`. # [Best practices](#Pod6_tables "go to top of document")[§](#Best_practices "direct link") HINT: Not adhering to the following best practices may require more table processing due to additional looping over table rows. 1. Use of WS for column separators is fragile, and they should only be used for simple tables. The `Ugly Tables` section below illustrates the problem. 2. Align table columns and rows carefully. See the examples in later best practices. 3. Don't use visual borders on the table. 4. For tables with a heading and single- or multi-line content, use one or more contiguous equal signs ('=') as the row separator after the heading, and use one or more contiguous hyphens ('-') as the row separator in the content portion of the table. For example, * Heading and single- or multi-line content ```raku =begin table hdr col 0 | hdr col 1 ====================== row 0 | row 0 col 0 | col 1 ---------------------- row 1 | row 1 col 0 | col 1 ---------------------- =end table ``` * Heading and single-line content ```raku =begin table hdr col 0 | hdr col 1 ====================== row 0 col 0 | row 0 col 1 row 1 col 0 | row 1 col 1 =end table ``` 5. For tables with no header and multi-line content, use one or more contiguous hyphens ('-') as the row separator in the content portion of the table. For example, ```raku =begin table row 0 | row 0 col 0 | col 1 ---------------------- row 1 col 0 | row 1 col 1 =end table ``` 6. For tables with many rows and no multi-line content, using no row separators is fine. However, with one or more rows with multi-line content, it is easier to ensure proper results by using a row separator line (visible or invisible) between every content row. 7. Ensure intentionally empty cells have column separators, otherwise expect a warning about short rows being filled with empty cells. (Tables rows will always have the same number of cells as the row with the most cells. Short rows are padded on the right with empty cells and generate a warning.) 8. Adding a caption to a table is possible using the `=begin table` line as in this example: ```raku =begin table :caption<My Tasks> mow lawn take out trash =end table ``` Although not a good practice, currently there is in use an alternate method of defining a caption as shown in this example: ```raku =begin table :config{caption => "My Tasks"} mow lawn take out trash =end table ``` Note the alternative method of putting the caption in the `config` hash was necessary before the `:caption` method was implemented, but that method is now considered to be deprecated. The practice will generate a warning in the upcoming version `6.d`, and it will raise an exception in version `6.e`. # [Valid tables](#Pod6_tables "go to top of document")[§](#Valid_tables "direct link") Following are examples of valid tables (taken from the current [Specification Tests](https://github.com/Raku/roast)). ```raku =begin table The Shoveller Eddie Stevens King Arthur's singing shovel Blue Raja Geoffrey Smith Master of cutlery Mr Furious Roy Orson Ticking time bomb of fury The Bowler Carol Pinnsler Haunted bowling ball =end table ``` ```raku =table Constants 1 Variables 10 Subroutines 33 Everything else 57 ``` ```raku =for table mouse | mice horse | horses elephant | elephants ``` ```raku =table Animal | Legs | Eats ======================= Zebra + 4 + Cookies Human + 2 + Pizza Shark + 0 + Fish ``` ```raku =table Superhero | Secret | | Identity | Superpower ==============|=================|================================ The Shoveller | Eddie Stevens | King Arthur's singing shovel ``` ```raku =begin table Secret Superhero Identity Superpower ============= =============== =================== The Shoveller Eddie Stevens King Arthur's singing shovel Blue Raja Geoffrey Smith Master of cutlery Mr Furious Roy Orson Ticking time bomb of fury The Bowler Carol Pinnsler Haunted bowling ball =end table ``` ```raku =table X | O | ---+---+--- | X | O ---+---+--- | | X ``` ```raku =table X O =========== X O =========== X ``` ```raku =begin table foo bar =end table ``` # [Invalid tables](#Pod6_tables "go to top of document")[§](#Invalid_tables "direct link") Following are examples of invalid tables, and they should trigger an unhandled exception during parsing. * Mixed column separator types in the same row are not allowed: ```raku =begin table r0c0 + r0c1 | r0c3 =end table ``` * Mixed visual and whitespace column separator types in the same table are not allowed: ```raku =begin table r0c0 + r0c1 | r0c3 r1c0 r0c1 r0c3 =end table ``` * Two consecutive interior row separators are not allowed: ```raku =begin table r0c0 | r0c1 ============ ============ r1c0 | r1c1 =end table ``` # [Unexpected tables](#Pod6_tables "go to top of document")[§](#Unexpected_tables "direct link") Following are examples of valid tables that are probably intended to be two columns, but the columns are not aligned well so each will parse as a single-column table. * Unaligned columns with WS column separators: Notice the second row has the two words separated by only **one** WS character, while it takes at least **two** adjacent WS characters to define a column separation. **This is a valid table but will be parsed as a single-column table**. ```raku =begin table r0c0 r0c1 r1c0 r0c1 =end table ``` * Unaligned columns with visual column separators: Notice the second row has the two words separated by a visible character ('|') but the character is not recognized as a column separator because it doesn't have an adjacent WS character on both sides of it. Although this is a legal table, the result will not be what the user intended because the first row has two columns while the second row has only one column, and it will thus have an empty second column. ```raku =begin table r0c0 | r0c1 r1c0 |r0c1 =end table ```
## shape.md shape Combined from primary sources listed below. # [In Array](#___top "go to top of document")[§](#(Array)_method_shape "direct link") See primary documentation [in context](/type/Array#method_shape) for **method shape**. ```raku method shape() { (*,) } ``` Returns the shape of the array as a list. Example: ```raku my @foo[2;3] = ( < 1 2 3 >, < 4 5 6 > ); # Array with fixed dimensions say @foo.shape; # OUTPUT: «(2 3)␤» my @bar = ( < 1 2 3 >, < 4 5 6 > ); # Normal array (of arrays) say @bar.shape; # OUTPUT: «(*)␤» ```
## dist_cpan-MOZNION-Router-Boost.md [![Build Status](https://travis-ci.org/moznion/p6-Router-Boost.svg?branch=master)](https://travis-ci.org/moznion/p6-Router-Boost) # NAME Router::Boost - Routing engine for perl6 # SYNOPSIS ``` use Router::Boost; my $router = Router::Boost.new(); $router.add('/', 'dispatch_root'); $router.add('/entrylist', 'dispatch_entrylist'); $router.add('/:user', 'dispatch_user'); $router.add('/:user/{year}', 'dispatch_year'); $router.add('/:user/{year}/{month:\d ** 2}', 'dispatch_month'); $router.add('/download/*', 'dispatch_download'); my $dest = $router.match('/john/2015/10'); # => {:captured(${:month("10"), :user("john"), :year("2015")}), :stuff("dispatch_month")} my $dest = $router.match('/access/to/not/existed/path'); # => {} ``` # DESCRIPTION Router::Boost is a routing engine for perl6. This router pre-compiles a regex for each routes thus fast. This library is a perl6 port of [Router::Boom of perl5](https://metacpan.org/pod/Router::Boom). # METHODS ## `add(Router::Boost:D: Str $path, Any $stuff)` Add a new route. `$path` is the path string. `$stuff` is the destination path data. Any data is OK. ## `match(Router::Boost:D: Str $path)` Match the route. If matching is succeeded, this method returns hash like so; ``` { stuff => 'stuff', # matched stuff captured => {}, # captured values } ``` And if matching is failed, this method returns empty hash; # HOW TO WRITE A ROUTING RULE ## plain string ``` $router.add('/foo', { controller => 'Root', action => 'foo' }); ... $router.match('/foo'); # => {:captured(${}), :stuff(${:action("foo"), :controller("Root")})} ``` ## :name notation ``` $router.add('/wiki/:page', { controller => 'WikiPage', action => 'show' }); ... $router.match('/wiki/john'); # => {:captured(${:page("john")}), :stuff(${:action("show"), :controller("WikiPage")})} ``` ':name' notation matches `rx{(<-[/]>+)}`. You will get captured arguments by `name` key. ## '\*' notation ``` $router.add('/download/*', { controller => 'Download', action => 'file' }); ... $router.match('/download/path/to/file.xml'); # => {:captured(${"*" => "path/to/file.xml"}), :stuff(${:action("file"), :controller("Download")})} ``` '\*' notation matches `rx{(<-[/]>+)}`. You will get the captured argument as the special key: `*`. ## '{...}' notation ``` $router.add('/blog/{year}', { controller => 'Blog', action => 'yearly' }); ... $router.match('/blog/2010'); # => {:captured(${:year("2010")}), :stuff(${:action("yearly"), :controller("Blog")})} ``` '{...}' notation matches `rx{(<-[/]>+)}`, and it will be captured. ## '{...:<[0..9]>+}' notation ``` $router.add('/blog/{year:<[0..9]>+}/{month:<[0..9]> ** 2}', { controller => 'Blog', action => 'monthly' }); ... $router.match('/blog/2010/04'); # => {:captured(${:month("04"), :year("2010")}), :stuff(${:action("monthly"), :controller("Blog")})} ``` You can specify perl6 regular expressions in named captures. Note. You can't include normal capture in custom regular expression. i.e. You can't use `{year:(\d+)}` . But you can use `{year:[\d+]}` . # SEE ALSO [Router::Boom of perl5](https://metacpan.org/pod/Router::Boom) # COPYRIGHT AND LICENSE ``` Copyright 2015 moznion <moznion@gmail.com> This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. ``` And original perl5's Router::Boom is ``` Copyright (C) tokuhirom. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. ``` # AUTHOR moznion [moznion@gmail.com](mailto:moznion@gmail.com)
## dist_zef-grizzlysmit-App-fix.raku.md # App::Fix::term ## Table of Contents * [NAME](#name) * [AUTHOR](#author) * [VERSION](#version) * [TITLE](#title) * [SUBTITLE](#subtitle) * [COPYRIGHT](#copyright) * [Introduction](#introduction) * [Motivation](#motivation) * [Fix](#fix) # NAME App::fix # AUTHOR Francis Grizzly Smit ([grizzly@smit.id.au](mailto:grizzly@smit.id.au)) # VERSION v0.1.1 # TITLE App::fix # SUBTITLE A Raku program to fix borked (broken) terminals. # COPYRIGHT GPL V3.0+ [LICENSE](https://github.com/grizzlysmit/Usage-Utils/blob/main/LICENSE) [Top of Document](#table-of-contents) # Introduction This is a Raku program to fix broken (i.e. borked) terminals. ## Motivation Sometimes I exit a program nastily and I end up with a borked (broken) terminal fore example I **`^C`** out of raku command line repl and I can no longer see what I am typing. solution run fix i.e. fix.raku and everything just clears up. So put fix in your **`PATH`** and type **fix** and the borked terminal should come good. ### Fix ``` fix --help Usage: fix ``` ``` use Terminal::ANSI::OO :t; use Term::termios; multi sub MAIN( --> Int:D) { my $flags := Term::termios.new(:fd($*IN.native-descriptor)).getattr; $flags.set_lflags('ICANON'); $flags.set_lflags('ECHO'); $flags.setattr(:NOW); print t.show-cursor ~ t.restore-screen ~ t.clear-screen; exit 0; } ```
## dist_cpan-BDUGGAN-Grammar-PrettyErrors.md # Grammar::PrettyErrors [![Build Status](https://travis-ci.org/bduggan/p6-grammar-prettyerrors.svg?branch=master)](https://travis-ci.org/bduggan/p6-grammar-prettyerrors) Make grammars fail parsing with a pretty error instead of returning nil. ## SYNOPSIS Input: ``` use Grammar::PrettyErrors; grammar G does Grammar::PrettyErrors { rule TOP { 'orange'+ % ' ' } } # Handle the failure. G.parse('orange orange orange banana') orelse say "parse failed at line {.exception.line}"; # Don't handle it, an exception will be thrown: G.parse('orange orange orange banana'); ``` Output: ``` failed at line 1 --errors-- 1 │▶orange orange orange banana ^ Uh oh, something went wrong around line 1. Unable to parse TOP. ``` ## DESCRIPTION When the `Grammar::PrettyErrors` role is applied to a Grammar, it changes the behavior of a parse failure. Instead of returning `nil`, a failure is thrown. The exception object has information about the context of the failure, and a pretty error message that includes some context around the input text. It works by wrapping the `<ws>` token and keeping track of a highwater mark (the position), and the name of the most recent rule that was encountered. You can also use a token other than `<ws>` by sending a parameter to the role with the name of the token to use, e.g. ``` grammar G does Grammar::PrettyErrors["myws"] { ... token myws { ... } } ``` This technique is described by moritz in his excellent book [0] (see below). ## CLASSES, ROLES ### Grammar::PrettyErrors (Role) #### ATTRIBUTES * `quiet` -- Bool, default false: just save the error, don't throw it. * `colors` -- Bool, default true: make output colorful. * `error` -- a `X::Grammar::PrettyError` object (below). #### METHODS * `new` -- wraps the `<ws>` token as described above, it also takes additional named arguments (to set the ATTRIBUTEs above). ### X::Grammar::PrettyError (class) #### METHODS * `line` -- the line number at which the parse failed (starting at 1). Or 0 if no lines were parsed; * `column` -- the column at which the parse failed (starting at 1). Or 0 if no characters were parsed; * `lastrule` -- the last rule which was parsed. * `report` -- the text of a report including the above information, with a few lines before and after. (see SYNOPSIS) * `message` -- Same as `report`. ## EXAMPLES ``` grammar G does Grammar::PrettyErrors { ... } # Throw an exception with a message when a parse fails. G.parse('orange orange orange banana'); # Same thing G.new.parse('orange orange orange banana'); # Pass options to the constructor. Don't throw a failure. my $g = G.new(:quiet, :!colors); $g.parse('orange orange orange banana'); # Just print it ourselves. say .report with $g.error; # Use the failure to handle it without throwing it. G.parse('orange orange orange banana') orelse say "parse failed at line {.exception.line}"; ``` ## SEE ALSO * [0] [Parsing with Perl 6 Regexes and Grammars](https://www.apress.com/us/book/9781484232279) and the accompanying [code](https://github.com/Apress/perl-6-regexes-and-grammars/blob/master/chapter-11-error-reporting/03-high-water-mark.p6) * Grammar::ErrorReporting ## AUTHOR Brian Duggan