txt
stringlengths
93
37.3k
## chown.md class X::IO::Chown Error while trying to change file ownership ```raku class X::IO::Chown does X::IO is Exception { } ``` Error class for failed `chown` calls. A typical error message is 「text」 without highlighting ``` ``` Failed to change owner of '/home/other' to :137/666: Permission denied ``` ```
## dist_github-CurtTilmes-Redis-Async.md # Redis::Async - A high-performance client for Redis This module includes bindings for the [Eredis](https://github.com/EulerianTechnologies/eredis) client library for [Redis](https://redis.io). Eredis is a C client library built over Hiredis. It is lightweight, high performance, reentrant and thread-safe. ## INSTALLATION This module depends on the [Eredis](https://github.com/EulerianTechnologies/eredis) library, so it must be installed first. Then just use `zef` to install this package from the Perl 6 ecosystem: ``` zef install Redis::Async ``` ## Basic Usage ``` use Redis::Async; my $r = Redis::Async.new("localhost:6379"); $r.set('foo', 'bar'); say $r.get('foo'); # bar ``` ## Notes Case doesn't matter for commands `$r.GET` and `$r.get` are the same thing with a few exceptions: * `hgetall` returns a `Hash` * `info` returns a `Hash` * `keys` defaults to pattern '\*' -- Caution, this can take a very long time if you have a lot of keys! For production, `scan` may be a better option. * `subscribe` and `psubscribe` should be lower case. * `scan`, `sscan`, `hscan`, and `zscan` should be lower case. An `Instant` will be converted into epoch seconds. ``` $r.expireat('foo', now+5); # same as $r.expire('foo', 5) ``` See [redis.io](https://redis.io/commands) for the complete list of commands. Note carefully the version of your Redis server and if you are using an older version, which commands are valid. ## Timeouts You can set the Redis timeout with `$r.timeout($seconds)`. You can disable timeouts entirely with `$r.timeout(0)`. This is highly recommended if you use blocking read requests -- instead specify a timeout with the command. Timeouts should probably also be disabled for publish/subscribe. You can also set timeout on creation: ``` my $r = Redis::Async.new('localhost:6379', timeout => 0); ``` ## Multiple Redis servers You can configure multiple redundant (NOT clustered) Redis servers in several ways. List multiple servers on creation: ``` my $r = Redis::Async.new('server1:6379', 'server2:6379'); ``` Add additional servers: ``` $r.host-add('server3:6379'); ``` Or list servers in a configuration file, one line per host:port and add the file, alone, or as an option to `.new(host-file => 'my-hosts.conf')` ``` $r.host-file('my-hosts.conf'); ``` The first host provided becomes the "preferred" one. It will always reconnect to that one in case of a down/up event. You can set the number of retries on failure with `$r.retry($retries)` (defaults to 1) after which the client will fall back to the next server. You can also set retries with an option to new: ``` my $r = Redis::Async.new('localhost:6379', retries => 2); ``` ## Associative usage `Redis::Async` also does the `Associative` role: ``` $r<foo> = 'bar'; say $r<foo> if $r<foo>:exists; $r<foo>:delete; ``` ## Binary data Strings are encoded as utf8 by default, but you can also pass in Blobs of binary data. Some commands like `RESTORE` require this. Strings are also decoded as utf8 by default, you can request binary values with the `:bin` flag. It is highly recommended for `dump`. ``` say $r.get('foo', :bin); # Blob:0x<62 61 72> my $x = $r.dump('foo', :bin); $r<foo>:delete; $r.restore('foo', 0, $x); ``` ## Async writing If you use the :async option, the write calls will be queued and sent to the Redis server in the background and the call will return immediately. This can dramatically speed up multiple writes. You can wait for pending writes to complete with $r.write-wait. ``` for ^100 { $r.set("key:$_", $_, :async) } say "Pending writes: $r.write-pending()"; $r.write-wait; ``` ## Pipeline reads You can also issue multiple reads without waiting for the replies, then later read the replies. This will pipeline the requests more efficiently and speed up performance. ``` for ^100 { $r.get("key:$_", :pipeline) } for ^100 { say $r.value } ``` ## SCANing The SCAN commands have special lower case functions that return a `Redis::Cursor` object that has a `.next` method to get the next element. ``` my $cursor = $r.scan('key:*'); while $cursor.next -> $x { say "$x = $r{$x}"; } ``` The scan commands also just take the parameters themselves, not the 'MATCH' and 'COUNT' strings. ## Publish/Subscribe The `subscribe` and `psubscribe` commands return a `Redis::PubSub` object that can read messages with .message: ``` $r.timeout(0); my $sub = $r.subscribe('foo'); while $sub.message -> @m { if @m[0] eq 'message' { say "Received message @m[2] on channel @m[1]"; } last if @m[2] eq 'QUIT'; } ``` ## Multiple threads You can use a single `Redis::Async` object to issue requests from multiple threads simultaneously. Internally each thread will get its own communication channel so the requests won't get mixed up. You can't, therefore issue a pipelined read request in one thread and the corresponding `reply` request in a different thread. You can set the maximum number of readers with max-readers: ``` $r.max-readers(50); ``` Max readers will default to 16, so if you want to access Redis from more threads than that, increase it. As a convenience for Rakudo users, if you set the RAKUDO\_MAX\_THREADS environment variable, max-readers will be set to that number. You can also specify the max-readers option to new(): ``` $r = Redis::Async.new('localhost:6379', max-readers => 50); ``` ## `Redis::Objects` Perlish objects tied to Redis Objects *EXPERIMENTAL, not everything works yet* You can bind to a Redis List like this: ``` use Redis::Async; use Redis::Objects; my $redis = Redis::Async.new('localhost:6379'); my @list := Redis::List.new(:$redis, key => 'some-list-key'); @list.push(1,2,3); say @list[1]; # 2 .say for @list; ``` `push()` acts more like `append()` in that it flattens arrays since you can't really store objects in Redis (though maybe in the future this will serialize objects for you...) or a Redis Hash like this: ``` my %hash := Redis::Hash.new(:$redis, key => 'some-hash-key'); %hash<a> = 'something'; say %hash<a>; # something .say for %hash; # pairs say %hash.kv; say %hash.keys; say %hash.values; say %hash.elems; ``` ## Transactions TBD ## Clusters TBD # SEE ALSO There is another Perl6 Redis module [`Redis`](https://github.com/cofyc/perl6-redis) that uses a Perl 6 implementation of the protocol so it doesn't depend on external libraries like this module. If you don't need the performance, it may be easier to use. # LICENSE [Redis](https://redis.io), and the Redis logo are the trademarks of Salvatore Sanfilippo in the U.S. and other countries. [Eredis](https://github.com/EulerianTechnologies/eredis) is written and maintained by Guillaume Fougnies and released under the BSD license. This software is released under the NASA-1.3 license. See [NASA Open Source Agreement](../master/NASA_Open_Source_Agreement_1.3%20GSC-17829.pdf) Copyright © 2017 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. No copyright is claimed in the United States under Title 17, U.S.Code. All Other Rights Reserved.
## io.md IO Combined from primary sources listed below. # [In IO::Special](#___top "go to top of document")[§](#(IO::Special)_method_IO "direct link") See primary documentation [in context](/type/IO/Special#method_IO) for **method IO**. ```raku method IO(IO::Special:D: --> IO::Special) ``` Returns the invocant. ```raku say $*IN.path.IO.what; # OUTPUT: «<STDIN>␤» say $*IN.path.what; # OUTPUT: «<STDIN>␤» ``` # [In IO::Handle](#___top "go to top of document")[§](#(IO::Handle)_method_IO "direct link") See primary documentation [in context](/type/IO/Handle#method_IO) for **method IO**. ```raku method IO(IO::Handle:D:) ``` Alias for [`.path`](/type/IO/Handle#method_path) # [In IO::Notification::Change](#___top "go to top of document")[§](#(IO::Notification::Change)_method_IO "direct link") See primary documentation [in context](/type/IO/Notification/Change#method_IO) for **method IO**. Returns a handle of the file that's being watched. # [In Distribution::Resource](#___top "go to top of document")[§](#(Distribution::Resource)_method_IO "direct link") See primary documentation [in context](/type/Distribution/Resource#method_IO) for **method IO**. ```raku method IO() ``` Returns the corresponding resource as an [`IO::Path`](/type/IO/Path), which can effectively be used as such. # [In role Dateish](#___top "go to top of document")[§](#(role_Dateish)_method_IO "direct link") See primary documentation [in context](/type/Dateish#method_IO) for **method IO**. ```raku method IO(Dateish:D: --> IO::Path:D) ``` Returns an [`IO::Path`](/type/IO/Path) object representing the stringified value of the Dateish object: ```raku Date.today.IO.say; # OUTPUT: «"2016-10-03".IO␤» DateTime.now.IO.say; # OUTPUT: «"2016-10-03T11:14:47.977994-04:00".IO␤» ``` **PORTABILITY NOTE:** some operating systems (e.g. Windows) do not permit colons (`:`) in filenames, which would be present in [`IO::Path`](/type/IO/Path) created from a [`DateTime`](/type/DateTime) object. # [In IO::CatHandle](#___top "go to top of document")[§](#(IO::CatHandle)_method_IO "direct link") See primary documentation [in context](/type/IO/CatHandle#method_IO) for **method IO**. ```raku method IO(IO::CatHandle:D:) ``` Alias for [`.path`](/type/IO/CatHandle#method_path) # [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_IO "direct link") See primary documentation [in context](/type/IO/Path#method_IO) for **method IO**. ```raku method IO(IO::Path:D: --> IO::Path) ``` Returns the invocant. # [In IO::Pipe](#___top "go to top of document")[§](#(IO::Pipe)_method_IO "direct link") See primary documentation [in context](/type/IO/Pipe#method_IO) for **method IO**. ```raku method IO(IO::Pipe: --> IO::Path:U) ``` Returns an [`IO::Path`](/type/IO/Path) type object. # [In Cool](#___top "go to top of document")[§](#(Cool)_method_IO "direct link") See primary documentation [in context](/type/Cool#method_IO) for **method IO**. ```raku method IO(--> IO::Path:D) ``` Coerces the invocant to [`IO::Path`](/type/IO/Path). ```raku .say for '.'.IO.dir; # gives a directory listing ```
## required.md class X::Attribute::Required Compilation error due to not declaring an attribute with the `is required` trait ```raku class X::Attribute::NoPackage does X::MOP { } ``` Compile time error thrown when a required attribute is not assigned when creating an object. For example ```raku my class Uses-required { has $.req is required }; my $object = Uses-required.new() ``` Dies with 「text」 without highlighting ``` ``` OUTPUT: «(exit code 1) The attribute '$!req' is required, but you did not provide a value for it.␤» ``` ``` # [Methods](#class_X::Attribute::Required "go to top of document")[§](#Methods "direct link") ## [method name](#class_X::Attribute::Required "go to top of document")[§](#method_name "direct link") ```raku method name(--> Str:D) ``` Returns the name of the attribute. ## [method why](#class_X::Attribute::Required "go to top of document")[§](#method_why "direct link") ```raku method why(--> Str:D) ``` Returns the reason why that attribute is required, and it will be included in the message if provided. That reason is taken directly from the `is required` trait. ```raku my class Uses-required { has $.req is required("because yes") }; my $object = Uses-required.new(); │ # OUTPUT: # «(exit code 1) The attribute '$!req' is required because because yes,␤ # but you did not provide a value for it.␤» ```
## dist_zef-finanalyst-raku-pod-extraction.md ![github-tests-passing-badge](https://github.com/finanalyst/raku-pod-extraction/actions/workflows/test.yaml/badge.svg) # Extractor GUI > Mainly used to generate a README.md from .pm6, which contain POD6 ## Table of Contents [Dependencies](#dependencies) --- Run `Extractor` in the directory where the transformed files are needed. Select POD6 files (`.pod6`, `.pm6`, `.rakudoc`) by clicking on the FileChooser button at the top of the panel. The Output file name by default is the same as the basename of the input file, but can be changed. Select the output formats. Select `add github badge` to add a github badge at the beginning of the md file (typically README.md). The name of the module and the source url is taken from the META6.json file. An exception is generated if there is no META6.json file. Will also generate HTML files from POD6 using HTML2 (see ProcessPod documentation for information). HTML2 leaves css and favicon files in the directory with the html file. If a file was selected by mistake, uncheck the 'convert' box on the far left and it will not be processed. When the list is complete, click on **Convert**. The converted files will be shown, or the failure message. This tool is fairly primitive and it may not handle all error conditions. The tool is intended for generating md and html files in an adhoc manner. # Dependencies `Extractor` requires GTK::Simple. It is known that this is difficult to install on Windows. However, if the GTK library has already been installed on Windows, then GTK::Simple will load with no problem. Look at the GTK website for information about Windows installations of GTK. --- Rendered from README at 2022-10-30T09:24:27Z
## dist_cpan-JMERELO-Algorithm-Evolutionary-Simple.md [![Build Status](https://travis-ci.org/JJ/p6-algorithm-evolutionary-simple.svg?branch=master)](https://travis-ci.org/JJ/p6-algorithm-evolutionary-simple) # NAME Algorithm::Evolutionary::Simple - A simple evolutionary algorithm # SYNOPSIS ``` use Algorithm::Evolutionary::Simple; ``` # DESCRIPTION Algorithm::Evolutionary::Simple is a module for writing simple and quasi-canonical evolutionary algorithms in Perl 6. It uses binary representation, integer fitness (which is needed for the kind of data structure we are using) and a single fitness function. It is intended mainly for demo purposes, although it's been actually used in research. In the future, more versions will be available. It uses a fitness cache for storing and not reevaluating, so take care of memory bloat. # METHODS ## initialize( UInt :$size, UInt :$genome-length --> Array ) is export Creates the initial population of binary chromosomes with the indicated length; returns an array. ## random-chromosome( UInt $length --> List ) Generates a random chromosome of indicated length. Returns a `Seq` of `Bool`s ## max-ones( @chromosome --> Int ) Returns the number of trues (or ones) in the chromosome. ## leading-ones( @chromosome --> Int ) Returns the number of ones from the beginning of the chromosome. ## royal-road( @chromosome ) That's a bumpy road, returns 1 for each block of 4 which has the same true or false value. ## multi evaluate( :@population, :%fitness-of, :$evaluator, :$auto-t = False --> Mix ) is export Evaluates the chromosomes, storing values in the fitness cache. If `auto-t` is set to 'True', uses autothreading for faster operation (if needed). In absence of that parameter, defaults to sequential. ## sub evaluate-nocache( :@population, :$evaluator --> Mix ) Evaluates the population, returning a Mix, but does not use a cache. Intended mainly for concurrent operation. ## get-pool-roulette-wheel( Mix $population, UInt $need = $population.elems ) is export Returns `$need` elements with probability proportional to its *weight*, which is fitness in this case. ## mutation( @chromosome is copy --> Array ) Returns the chromosome with a random bit flipped. ## crossover ( @chromosome1 is copy, @chromosome2 is copy ) returns List Returns two chromosomes, with parts of it crossed over. Generally you will want to do crossover first, then mutation. ## produce-offspring( @pool, $size = @pool.elems --> Seq ) is export Produces offspring from an array that contains the reproductive pool; it returns a `Seq`. ## produce-offspring-no-mutation( @pool, $size = @pool.elems --> Seq ) is export Produces offspring from an array that contains the reproductive pool without using mutation; it returns a `Seq`. ## best-fitness( $population ) Returns the fitness of the first element. Mainly useful to check if the algorithm is finished. ## multi sub generation( :@population, :%fitness-of, :$evaluator, :$population-size = $population.elems, Bool :$auto-t --> Mix ) Single generation of an evolutionary algorithm. The initial `Mix` has to be evaluated before entering here using the `evaluate` function. Will use auto-threading if `$auto-t` is `True`. ## multi sub generation( :@population, :%fitness-of, :$evaluator, :$population-size = $population.elems, Bool :$no-mutation --> Mix ) Single generation of an evolutionary algorithm. The initial `Mix` has to be evaluated before entering here using the `evaluate` function. Will not use mutation if that variable is set to `True` ## sub generations-without-change( $generations, $population ) Returns `False` if the number of generations in `$generations` has not been reached without changing; it returns `True` otherwise. ## mix( $population1, $population2, $size --> Mix ) is export Mixes the two populations, returning a single one of the indicated size and with type Mix. ## sub pack-individual( @individual --> Int ) Packs the individual in a single `Int`. The invidual must be binary, and the maximum length is 64. ## sub unpack-individual( Int $packed, UInt $bits --> Array(Seq)) Unpacks the individual that has been packed previously using `pack-individual` ## sub pack-population( @population --> Buf) Packs a population, producing a buffer which can be sent to a channel or stored in a compact form. ## sub unpack-population( Buf $buffer, UInt $bits --> Array ) Unpacks the population that has been packed using `pack-population` ## multi sub frequencies( $population) `$population` can be an array or a Mix, in which case the keys are extracted. This returns the per-bit (or gene) frequency of one (or True) for the population. ## multi sub frequencies-best( $population, $proportion = 2) `$population` is a Mix, in which case the keys are extracted. This returns the per-bit (or gene) frequency of one (or True) for the population of the best part of the population; the size of the population will be divided by the $proportion variable. ## sub generate-by-frequencies( $population-size, @frequencies ) Generates a population of that size with every gene according to the indicated frequency. ## sub crossover-frequencies( @frequencies, @frequencies-prime --> Array ) Generates a new array with random elements of the two arrays that are used as arguments. # SEE ALSO There is a very interesting implementation of an evolutionary algorithm in Algorithm::Genetic. Check it out. This is also a port of [Algorithm::Evolutionary::Simple to Perl6](https://metacpan.org/release/Algorithm-Evolutionary-Simple), which has a few more goodies, but it's not simply a port, since most of the code is completely different. # AUTHOR JJ Merelo [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2018, 2019 JJ Merelo This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-jonathanstowe-Lumberjack-Application.md # Lumberjack::Application A web facility for the Lumberjack logging framework ![Build Status](https://github.com/jonathanstowe/Lumberjack-Application/workflows/CI/badge.svg) ## Synopsis ``` # In some shell start the lumberjack standalone application # on port 8898 and mirroring log messages to the console lumberjack-application --port=8898 --console ``` Meanwhile in some other application: ``` use Lumberjack; use Lumberjack::Dispatcher::Proxy; # Add the proxy dispatcher Lumberjack.dispatchers.append: Lumberjack::Dispatcher::Proxy.new(url => 'http://localhost:8898/log'); # Now all logging messages will be sent to the server application as well # as any other dispatchers that may be configured. The logs will be displayed # at a Websocket application that you can point your browser at. ``` Or you can arrange components as you see fit: ``` # This is almost identical to what Lumberjack::Application does use Lumberjack; use Lumberjack::Dispatcher::Supply; use Lumberjack::Application::PSGI; use Lumberjack::Application::WebSocket; use Lumberjack::Application::Index; use Crust::Builder; # The supply dispatcher is used to transfer the messages # between the lumberjack dispatch mechanism and the # connected websocket clients. my $supply = Lumberjack::Dispatcher::Supply.new; Lumberjack.dispatchers.append: $supply; # The application classes are PSGI applications in their own right my &ws-app = Lumberjack::Application::WebSocket.new(supply => $supply.Supply); my &log-app = Lumberjack::Application::PSGI.new; my &ind-app = Lumberjack::Application::Index.new(ws-url => 'socket'); # Use Crust::Builder to map the applications to locations on the server # you can of course any other mechanism that you choose. my &app = builder { mount '/socket', &ws-app; mount '/log', &log-app; mount '/', &ind-app; }; # Then pass &app to your P6SGI container. ``` ## Description This is actually more a collection of related modules than a single module. It comprises a [Lumberjack](https://github.com/jonathanstowe/Lumberjack) dispatcher that sends the logging messages encoded as JSON to a web server, A [P6SGI](https://github.com/zostay/P6SGI) application module that handles the JSON messages, deserialising them back to the appropriate objects and re-transmitting them to the local Lumberjack object, and a Websocket app module that will re-transmit the messages as JSON to one or more connected websockets. There are one or two convenience helpers to tie all this together. These components together can be combined in various ways to make for example, a log aggregator for a larger system, a web log monitoring tool, or simply perform logging to a service which is not on the local machine. This should probably be considered more as a proof of concept, experiment or demonstration than a polished application. Please feel free to take the parts you need and do what you want with them. ## Installation Assuming you have a working installation of Rakudo with "zef" then you can simply do: ``` zef install Lumberjack::Application ``` Or if you have a local copy of this distribution: ``` zef install . ``` Though I haven't tested it I can see no reason why this shouldn't work equally well with some similarly capable package manager that may come along in the future. ## Support This is quite experimental and depends on things that are themselves probably fairly experimental, but it it works and I hope you find it useful in some way, that said I'll be interested in enhancements, fixes and suggestions at [github](https://github.com/jonathanstowe/Lumberjack-Application/issues) ## Licence and Copyright This free software, please see the <LICENCE> file in the distribution directory. © Jonathan Stowe, 2016 - 2021
## dist_zef-lizmat-Object-Delayed.md [![Actions Status](https://github.com/lizmat/Object-Delayed/workflows/test/badge.svg)](https://github.com/lizmat/Object-Delayed/actions) # NAME Object::Delayed - export subs for lazy object creation # SYNOPSIS ``` use Object::Delayed; # imports "slack" and "catchup" # execute when value needed my $dbh = slack { DBIish.connect: ... } my $sth = slack { $dbh.prepare: 'select foo from bar' } # action if value was actually created LEAVE .disconnect with $dbh; # lazy default values for attributes in objects class Foo { has $.bar = slack { say "delayed init"; "bar" } } my $foo = Foo.new; say $foo.bar; # delayed init; bar # execute asynchronously, produce value when done my $prime1000 = catchup { (^Inf).grep( *.is-prime ).skip(999).head } # do other stuff while prime is calculated say $prime1000; # 7919 ``` # DESCRIPTION Provides a `slack` and a `catchup` subroutine that will perform actions when they are needed. # SUBROUTINES ## slack ``` # execute when value needed my $dbh = slack { DBIish.connect: ... } my $sth = slack { $dbh.prepare: 'select foo from bar' } ``` There are times when constructing an object is expensive but you are not sure yet you are going to need it. In that case it can be handy to delay the creation of the object. But then your code may become much more complicated. The `slack` subroutine allows you to transparently create an intermediate object that will perform the delayed creation of the original object when **any** method is called on it. This can also be used to serve as a lazy default value for a class attribute. To make it easier to check whether the actual object has been created, you can check for definedness or truthinesss of the object without actually creating the object. This can e.g. be used when wanting to disconnect a database handle upon exiting a scope, but only if an actual connection has been made (to prevent it from making the connection only to be able to disconnect it), e.g. by using a `LEAVE` phaser: ``` LEAVE .disconnect with $dbh; ``` ## catchup ``` # execute asynchronously, produce value when done my $prime1000 = catchup { (^Inf).grep( *.is-prime ).skip(999).head } # do other stuff while prime is calculated say $prime1000; # 7919 ``` The `catchup` subroutine allows you to transparently run code **asynchronously** that creates a result value. If the value is used in **any** way and the asychronous code has not finished yet, then it will wait until it is ready so that it can return the result. If it was already ready, then it will just give the value immediately. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Object::Delayed> . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2018, 2020, 2021, 2023 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-pierre-vigier-AttrX-Lazy.md # Perl6-AttrX::Lazy [![Build Status](https://travis-ci.org/pierre-vigier/Perl6-AttrX-Lazy.svg?branch=master)](https://travis-ci.org/pierre-vigier/Perl6-AttrX-Lazy) # NAME AttrX::Lazy # SYNOPSIS Provide a functionality similar to lazy in perl 5 with Moo # DESCRIPTION This module provides trait lazy. That trait will create a public accessor if attribute is private or replace the accessor if the attribute is public. A lazy attribute is read-onlu Lazy attribute with call a builder the first time to calculate the value of an attribute if not defined, and store the value. It's especially useful for property of a class that take a long time to compute, as they will be evaluated only on demand, and only once. An alternate way of doing a similat functionality would be to just create a public method with is cached trait, however, using lazy allow to give a value within the constructor, and never do the computation in that case ``` use AttrX::Lazy; class Sample has $.attribute is lazy; method !build_attribute() { #heavy calculation return $value; } } ``` is equivalent to ``` class Sample has $.attribute; method attribute() { unless $!attribute.defined { #heavy calculation $!attribute = $value; } $!attribute; } } ``` The builder method name can be changed like the following: ``` use AttrX::Lazy; class Sample has $.attribute is lazy( builder => 'my_custom_builder' ); method !my_custom_builder() { #heavy calculation return $value; } } ``` # NOTES Another approach to the same probleme here: <https://github.com/jonathanstowe/Attribute-Lazy> Hopefully, lazyness of attribute at one point will be integrated in perl6 core, and AttrX::Lazy will become useless # MISC To test the meta data of the modules, set environement variable PERL6\_TEST\_META to 1 On the Christmas version of perl, the module had no issue, but it's not working correctly anymore with precompilation as of today, waiting for a fix in rakudo, add no precompilation pragma # Author Pierre VIGIER # License Artistic License 2.0
## dist_zef-jforget-Date-Calendar-Gregorian.md # NAME Date::Calendar::Gregorian - Extending the core class 'Date' with strftime and conversions with other calendars # SYNOPSIS Here are two ways of printing the date 2020-04-05 in French. First, **without** Date::Calendar::Gregorian ``` use Date::Names; use Date::Calendar::Strftime; my Date $date .= new('2020-04-05'); my Date::Names $locale .= new(lang => 'fr'); my $day = $locale.dow($date.day-of-week); my $month = $locale.mon($date.month); $date does Date::Calendar::Strftime; say $date.strftime("$day %d $month %Y"); # --> dimanche 05 avril 2020 ``` Second, **with** Date::Calendar::Gregorian ``` use Date::Calendar::Gregorian; my Date::Calendar::Gregorian $date .= new('2020-04-05', locale => 'fr'); say $date.strftime("%A %d %B %Y"); # --> dimanche 05 avril 2020 ``` # INSTALLATION ``` zef install Date::Calendar::Gregorian ``` or ``` git clone https://github.com/jforget/raku-Date-Calendar-Gregorian.git cd raku-Date-Calendar-Gregorian zef install . ``` # DESCRIPTION Date::Calendar::Gregorian is a child class to the core class 'Date', to extend it with the string-generation method `strftime` and with the conversion methods `new-from-date` and `to-date`. # AUTHOR Jean Forget # COPYRIGHT AND LICENSE Copyright (c) 2020, 2021, 2024 Jean Forget, all rights reserved. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-lizmat-ValueType.md [![Actions Status](https://github.com/lizmat/ValueType/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/ValueType/actions) [![Actions Status](https://github.com/lizmat/ValueType/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/ValueType/actions) [![Actions Status](https://github.com/lizmat/ValueType/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/ValueType/actions) # NAME ValueType - A role to create Value Type classes # SYNOPSIS ``` use ValueType; class Point does ValueType { has $.x = 0; has $.y = 0; has $.distance is hidden-from-ValueType is built(False); method TWEAK() { $!distance = sqrt $!x² + $!y²; } } say Point.new.WHICH; # Point|Int|0|Int|0 say Point.new(x => 3, y => 4).distance; # 5 # fill a bag with random Points my $bag = bag (^1000).map: { Point.new: x => (-10..10).roll, y => (-10..10).roll } say $bag.elems; # less than 1000 ``` # DESCRIPTION The `ValueType` role mixes the logic of creating a proper [value type](https://docs.raku.org/language/glossary#Value_type) into a class. A class is considered to be a value type if the `.WHICH` method returns an object of the `ValueObjAt` class: that then indicates that objects that return the same `WHICH` value, are in fact identical and can be used interchangeably. This is specifically important when using set operators (such as `(elem)`, or `Set`s, `Bag`s or `Mix`es, or any other functionality that is based on the `===` operator functionality, such as `unique` and `squish`. The format of the value that is being returned by `WHICH` is only valid during a run of a process. So it should **not** be stored in any permanent medium. # EXCLUDING ATTRIBUTES Sometimes a class has an extra attribute that depends on the other attributes, but which cannot be set, and doesn't need to be included in the calculation of the `WHICH` value. Such attributes can be marked with the `is hidden-from-ValueType` attribute. # THEORY OF OPERATION At role composition time, each attribute will be checked for mutability. If any mutable attributes are found, then a compilation error will occur. Then, the first time the `WHICH` method (mixed in by this role) is called, it will check all of its attribute values for being a value type. If they all are, then it will construct a `ValueObjAt` object for its `WHICH` value, save it for future reference, and return it. If any of the attribute values are **not** a value type, then an exception will be thrown. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/ValueType> . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2020, 2021, 2024 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-antononcube-Math-Nearest.md # Math::Nearest Raku package for various algorithm for finding Nearest Neighbors (NNs) The implementation is tested for correctness against Mathematica's [`Nearest`](https://reference.wolfram.com/language/ref/Nearest.html). (See the resource files.) ### Features * Finds both top-k Nearest Neighbors (NNs). * Finds NNs within a ball with a given radius. * Can return distances, indexes, and labels for the found NNs. * The result shape is controlled with the option `:prop`. * Works with arrays of numbers, arrays of arrays of numbers, and arrays of pairs. * Utilizes distance functions from ["Math::DistanceFunctions"](https://github.com/antononcube/Raku-Math-DistanceFunctions). * Which can be specified by their string names, like, "bray-curtis" or "cosine-distance". * Allows custom distance functions to be used. * Currently has two algorithms (simple) Scan and K-Dimensional Tree (KDTree). --- ## Installation From Zef ecosystem: ``` zef install Math::Nearest ``` From GitHub: ``` zef install https://github.com/antononcube/Raku-Math-Nearest.git ``` --- ## Usage examples ### Setup ``` use Math::Nearest; use Data::TypeSystem; use Text::Plot; ``` ``` # (Any) ``` ### Set of points Make a random set of points: ``` my @points = ([(^100).rand, (^100).rand] xx 30).unique; deduce-type(@points); ``` ``` # Vector(Vector(Atom((Numeric)), 2), 30) ``` ### Create the K-dimensional tree object ``` my &finder = nearest(@points); say &finder; ``` ``` # Math::Nearest::Finder(Algorithm::KDimensionalTree(points => 30, distance-function => &euclidean-distance)) ``` ### Nearest k-neighbors Use as a search point one from the points set: ``` my @searchPoint = |@points.head; ``` ``` # [82.7997137400612 51.815911977937425] ``` Find `4` nearest neighbors: ``` my @res = &finder(@searchPoint, 4); .say for @res; ``` ``` # [82.7997137400612 51.815911977937425] # [76.74690048700612 45.30314548421236] # [93.76468756535048 53.45047592032191] # [71.62175684954694 55.56128771507127] ``` Instead of using the "finder" object as a callable (functor) we can use `nearest`: ``` .say for nearest(&finder, @searchPoint, count => 4) ``` ``` # [82.7997137400612 51.815911977937425] # [76.74690048700612 45.30314548421236] # [93.76468756535048 53.45047592032191] # [71.62175684954694 55.56128771507127] ``` Find nearest neighbors within a ball with radius `30`: ``` .say for &finder(@searchPoint, (Whatever, 30)) ``` ``` # [93.76468756535048 53.45047592032191] # [82.7997137400612 51.815911977937425] # [68.66354164361587 52.25273427733615] # [67.1439347976243 51.678609421192775] # [76.74690048700612 45.30314548421236] # [71.62175684954694 55.56128771507127] # [58.6565707908774 67.61014125155556] # [80.23300662613086 80.49154195793962] # [82.92996945428985 71.0086509061165] # [54.30669960433475 57.177447534448724] ``` ### Plot Plot the points, the found nearest neighbors, and the search point: ``` my @point-char = <* ⏺ ▲>; say <data nns search> Z=> @point-char; say text-list-plot( [@points, @res, [@searchPoint,]], :@point-char, x-limit => (0, 100), y-limit => (0, 100), width => 60, height => 20); ``` ``` # (data => * nns => ⏺ search => ▲) # ++----------+-----------+----------+-----------+----------++ # + * + 100.00 # | | # | * | # +* * * * * * + 80.00 # | * | # | * * | # | * | # + * + 60.00 # | * ** ⏺ ▲ ⏺ | # | ⏺ | # + * + 40.00 # |* * | # | | # | * | # + * + 20.00 # | * * | # | * * | # + + 0.00 # ++----------+-----------+----------+-----------+----------++ # 0.00 20.00 40.00 60.00 80.00 100.00 ``` --- ## TODO * TODO Implementation * TODO Implement the Octree nearest neighbors algorithm. * TODO Make the nearest methods work with strings * For example, using Hamming distance over a collection of words. * Requires using the distance function as a comparator for the splitting hyperplanes. * This means, any objects can be used as long as they provide a distance function. * TODO Documentation * DONE Basic usage examples with text plots * TODO More extensive documentation with a Jupyter notebook * Using "JavaScript::D3". * TODO Corresponding blog post * MAYBE Corresponding video --- ## References [AAp1] Anton Antonov, [Math::DistanceFunctions Raku package](https://github.com/antononcube/Raku-Math-DistanceFunctions), (2024), [GitHub/antononcube](https://github.com/antononcube). [AAp2] Anton Antonov, [Algorithm::KDimensionalTree Raku package](https://github.com/antononcube/Raku-Algorithm-KDimensionalTree), (2024), [GitHub/antononcube](https://github.com/antononcube). [AAp3] Anton Antonov, [Data::TypeSystem Raku package](https://github.com/antononcube/Raku-Data-TypeSystem), (2023), [GitHub/antononcube](https://github.com/antononcube). [AAp4] Anton Antonov, [Text::Plot Raku package](https://github.com/antononcube/Raku-Text-Plot), (2022), [GitHub/antononcube](https://github.com/antononcube).
## dist_cpan-MARTIMM-Config-DataLang-Refine.md # Configuration refinements [![Build Status](https://travis-ci.org/MARTIMM/config-datalang-refine.svg?branch=master)](https://travis-ci.org/MARTIMM/config-datalang-refine) [![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/MARTIMM/config-datalang-refine?branch=master&passingText=Windows%20-%20OK&failingText=Windows%20-%20FAIL&pendingText=Windows%20-%20pending&svg=true)](https://ci.appveyor.com/project/MARTIMM/config-datalang-refine/branch/master) [![License](http://martimm.github.io/label/License-label.svg)](http://www.perlfoundation.org/artistic_license_2_0) # Synopsis The following piece of code ``` use Config::DataLang::Refine; my Config::DataLang::Refine $c .= new(:config-name<myConfig.toml>); my Hash $hp1 = $c.refine(<options plugin1 test>); my Hash $hp2 = $c.refine(<options plugin2 deploy>); ``` With the following config file in **myConfig.toml** ``` [options] key1 = 'val1' [options.plugin1] key2 = 'val2' [options.plugin1.test] key1 = false key2 = 'val3' [options.plugin2.deploy] key3 = 'val3' ``` Will get you the following as if *$hp\** is set like ``` $hp1 = { key2 => 'val3'}; $hp2 = { key1 => 'val1', key3 => 'val3'}; ``` A better example might be from the MongoDB project to test several server setups, the config again in TOML format; ``` [mongod] journal = false fork = true smallfiles = true oplogSize = 128 logappend = true # Configuration for Server 1 [mongod.s1] logpath = './Sandbox/Server1/m.log' pidfilepath = './Sandbox/Server1/m.pid' dbpath = './Sandbox/Server1/m.data' port = 65010 [mongod.s1.replicate1] replSet = 'first_replicate' [mongod.s1.replicate2] replSet = 'second_replicate' [mongod.s1.authenticate] auth = true ``` Now, to get run options to start server 1 one does the following; ``` my Config::DataLang::Refine $c .= new(:config-name<mongoservers.toml>); my Array $opts = $c.refine-str( <mongod s1 replicate1>, :C-UNIX-OPTS-T2); # Output # --nojournal, --fork, --smallfiles, --oplogSize=128, --logappend, # --logpath='./Sandbox/Server1/m.log', --pidfilepath='./Sandbox/Server1/m.pid', # --dbpath='./Sandbox/Server1/m.data', --port=65010, --replSet=first_replicate ``` Easy to run the server now; ``` my Proc $proc = shell(('/usr/bin/mongod', |@$opts).join(' ')); ``` # Description The **Config::DataLang::Refine** class adds facilities to use a configuration file and gather the key value pairs by searching top down a list of keys thereby refining the resulting set of keys. Boolean values are used to add a key without a value when True or to cancel a previously found key out when False. # Documentation Look for documentation and other information at * [Config::DataLang::Refine](https://github.com/MARTIMM/config-datalang-refine/blob/master/doc/Refine.pdf) * [Release notes](https://github.com/MARTIMM/config-datalang-refine/blob/master/doc/CHANGES.md) * [Todo and Bugs](https://github.com/MARTIMM/config-datalang-refine/blob/master/doc/TODO.md)
## dist_zef-thundergnat-Lingua-EN-Numbers.md [![Actions Status](https://github.com/thundergnat/Lingua-EN-Numbers/actions/workflows/test.yml/badge.svg)](https://github.com/thundergnat/Lingua-EN-Numbers/actions) # NAME Lingua::EN::Numbers Various number-string conversion utility routines. Convert numbers to their cardinal or ordinal representation. Several other numeric string "prettifying" routines. # SYNOPSIS ``` use Lingua::EN::Numbers; # Integers say cardinal(42); # forty-two say cardinal('144'); # one hundred forty-four say cardinal(76541); # seventy-six thousand, five hundred forty-one # Rationals say cardinal(7/2); # three and one half say cardinal(7/2, :improper); # seven halves say cardinal(7/2, :im ); # seven halves say cardinal(15/4) # three and three quarters say cardinal(3.75) # three and three quarters say cardinal(15/4, :improper) # fifteen quarters say cardinal('3/16'); # three sixteenths # Years say cardinal-year(1800) # eighteen hundred say cardinal-year(1905) # nineteen oh-five say cardinal-year(2000) # two thousand say cardinal-year(2015) # twenty fifteen # cardinal vs. cardinal-year say cardinal(1776); # one thousand, seven hundred seventy-six say cardinal-year(1776) # seventeen seventy-six # Sometimes larger denominators make it difficult to discern where the # numerator ends and the denominator begins. Change the separator to # make it easier to tell. say cardinal(97873/10000000); # ninety seven thousand, eight hundred seventy-three ten millionths say cardinal(97873/10000000, :separator(' / ')); # ninety seven thousand, eight hundred seventy-three / ten millionths # If you want to use a certain denominator in the display and not reduce # fractions, specify a common denominator. say cardinal(15/1000); # three two hundredths say cardinal(15/1000, :denominator(1000)); # fifteen thousandths # or say cardinal(15/1000, denominator => 1000); # fifteen thousandths # or say cardinal(15/1000, :den(1000) ); # fifteen thousandths # Ordinals say ordinal(1); # first say ordinal(2); # second say ordinal(123); # one hundred twenty-third # Ordinal digit say ordinal-digit(22); # 22nd say ordinal-digit(1776); # 1776th say ordinal-digit(331 :u); # 331ˢᵗ say ordinal-digit(12343 :c); # 12,343rd # Use pretty-rat() to print rational strings as fractions rather than # as decimal numbers. Whole number fractions will be reduced to Ints. say pretty-rat(1.375); # 11/8 say pretty-rat(8/2); # 4 # no-commas flag # save state my $state = no-commas?; # disable commas no-commas; say cardinal(97873/10000000); # ninety seven thousand eight hundred seventy-three ten millionths # restore state no-commas($state); # Commas routine say comma( 5.0e9.Int ); # 5,000,000,000 say comma( -123456 ); # -123,456 say comma( 7832.00 ); # 7,832 say comma( '7832.00' ); # 7,832.00 # Super routine say super('32'); # ³² say super -47; # ⁻⁴⁷ ``` Or, import the short form routine names: ``` use Lingua::EN::Numbers :short; say card(42); # forty-two say card-y(2020) # twenty twenty say ord-n(42); # forty-second say ord-d(42); # 42nd say card(.875) # seven eights say prat(.875); # 7/8 ``` # DESCRIPTION Exports the Subs: * [cardinal( )](#cardinal) - short: card() * [cardinal-year( )](#cardinal-year) - short: card-y() * [ordinal( )](#ordinal) - short: ord-n() * [ordinal-digit( )](#ordinal-digit) - short: ord-d() * [comma( )](#comma) * [pretty-rat( )](#pretty-rat) - short: prat() * [super( )](#super) and Flag: * [no-commas](#no-commas) Short form routine names are only available if you specifically import them: `use Lingua::EN::Numbers :short;` ## cardinal( ) - short: card() Returns cardinal representations of integers following the American English, short scale convention. See: <https://en.wikipedia.org/wiki/Long_and_short_scales> ### cardinal( $number, :separator($str), :denominator($val), :improper ); * $number * value; required, any Real number (Rat, Int, or Num) * :separator or :sep * value; optional, separator between numerator and denominator, defaults to space. Ignored if a non Rat is passed in. * :denominator or :den * value; optional, integer denominator to use for representation, do not reduce to lowest terms. Ignored if a non Rat is passed in. * :improper or :im * flag; optional, do not regularize improper fractions. Ignored if a non Rat is passed in. Pass `cardinal()` a number or something that can be converted to one; returns its cardinal representation. Recognizes integer numbers from: -9999999999999999999999999999999999999999999999999999999999999999999999999999 99999999999999999999999999999999999999999999999999999999999999999999999999999 99999999999999999999999999999999999999999999999999999999999999999999999999999 9999999999999999999999999999999999999999999999999999999999999999999999999999 to 99999999999999999999999999999999999999999999999999999999999999999999999999999 99999999999999999999999999999999999999999999999999999999999999999999999999999 99999999999999999999999999999999999999999999999999999999999999999999999999999 999999999999999999999999999999999999999999999999999999999999999999999999999 Thats 306 9s, negative, through positive: nine hundred ninety-nine centillion, nine hundred ninety-nine novemnonagintillion, nine hundred ninety-nine octononagintillion, nine hundred ninety-nine septennonagintillion, nine hundred ninety-nine sexnonagintillion, nine hundred ninety-nine quinnonagintillion, nine hundred ninety-nine quattuornonagintillion, nine hundred ninety-nine trenonagintillion, nine hundred ninety-nine duononagintillion, nine hundred ninety-nine unnonagintillion, nine hundred ninety-nine nonagintillion, nine hundred ninety-nine novemoctogintillion, nine hundred ninety-nine octooctogintillion, nine hundred ninety-nine septenoctogintillion, nine hundred ninety-nine sexoctogintillion, nine hundred ninety-nine quinoctogintillion, nine hundred ninety-nine quattuoroctogintillion, nine hundred ninety-nine treoctogintillion, nine hundred ninety-nine duooctogintillion, nine hundred ninety-nine unoctogintillion, nine hundred ninety-nine octogintillion, nine hundred ninety-nine novemseptuagintillion, nine hundred ninety-nine octoseptuagintillion, nine hundred ninety-nine septenseptuagintillion, nine hundred ninety-nine sexseptuagintillion, nine hundred ninety-nine quinseptuagintillion, nine hundred ninety-nine quattuorseptuagintillion, nine hundred ninety-nine treseptuagintillion, nine hundred ninety-nine duoseptuagintillion, nine hundred ninety-nine unseptuagintillion, nine hundred ninety-nine septuagintillion, nine hundred ninety-nine novemsexagintillion, nine hundred ninety-nine octosexagintillion, nine hundred ninety-nine septensexagintillion, nine hundred ninety-nine sexsexagintillion, nine hundred ninety-nine quinsexagintillion, nine hundred ninety-nine quattuorsexagintillion, nine hundred ninety-nine tresexagintillion, nine hundred ninety-nine duosexagintillion, nine hundred ninety-nine unsexagintillion, nine hundred ninety-nine sexagintillion, nine hundred ninety-nine novemquinquagintillion, nine hundred ninety-nine octoquinquagintillion, nine hundred ninety-nine septenquinquagintillion, nine hundred ninety-nine sexquinquagintillion, nine hundred ninety-nine quinquinquagintillion, nine hundred ninety-nine quattuorquinquagintillion, nine hundred ninety-nine trequinquagintillion, nine hundred ninety-nine duoquinquagintillion, nine hundred ninety-nine unquinquagintillion, nine hundred ninety-nine quinquagintillion, nine hundred ninety-nine novemquadragintillion, nine hundred ninety-nine octoquadragintillion, nine hundred ninety-nine septenquadragintillion, nine hundred ninety-nine sexquadragintillion, nine hundred ninety-nine quinquadragintillion, nine hundred ninety-nine quattuorquadragintillion, nine hundred ninety-nine trequadragintillion, nine hundred ninety-nine duoquadragintillion, nine hundred ninety-nine unquadragintillion, nine hundred ninety-nine quadragintillion, nine hundred ninety-nine novemtrigintillion, nine hundred ninety-nine octotrigintillion, nine hundred ninety-nine septentrigintillion, nine hundred ninety-nine sextrigintillion, nine hundred ninety-nine quintrigintillion, nine hundred ninety-nine quattuortrigintillion, nine hundred ninety-nine tretrigintillion, nine hundred ninety-nine duotrigintillion, nine hundred ninety-nine untrigintillion, nine hundred ninety-nine trigintillion, nine hundred ninety-nine novemvigintillion, nine hundred ninety-nine octovigintillion, nine hundred ninety-nine septenvigintillion, nine hundred ninety-nine sexvigintillion, nine hundred ninety-nine quinvigintillion, nine hundred ninety-nine quattuorvigintillion, nine hundred ninety-nine trevigintillion, nine hundred ninety-nine duovigintillion, nine hundred ninety-nine unvigintillion, nine hundred ninety-nine vigintillion, nine hundred ninety-nine novemdecillion, nine hundred ninety-nine octodecillion, nine hundred ninety-nine septendecillion, nine hundred ninety-nine sexdecillion, nine hundred ninety-nine quindecillion, nine hundred ninety-nine quattuordecillion, nine hundred ninety-nine tredecillion, nine hundred ninety-nine duodecillion, nine hundred ninety-nine undecillion, nine hundred ninety-nine decillion, nine hundred ninety-nine nonillion, nine hundred ninety-nine octillion, nine hundred ninety-nine septillion, nine hundred ninety-nine sextillion, nine hundred ninety-nine quintillion, nine hundred ninety-nine quadrillion, nine hundred ninety-nine trillion, nine hundred ninety-nine billion, nine hundred ninety-nine million, nine hundred ninety-nine thousand, nine hundred ninety-nine Handles Rats limited to the integer limits for the numerator and denominator. When converting rational numbers, the word "and" is inserted between any whole number portion and the fractional portions of the number. If you have an "and" in the output, the input number had a fractional portion. By default, `cardinal()` reduces fractions to their lowest terms. If you want to specify the denominator used to display, pass in an integer to the :denominator option. It is probably best to specify a denominator that is a common divisor for the denominator. `cardinal()` will work with any integer denominator, and will scale the numerator to match, but will round off the numerator to the nearest integer after scaling, so some error will creep in if denominator is NOT a common divisor with the denominator. Recognizes Nums up to about 1.79e308. (2¹⁰²⁴ - 1) When converting Nums, reads out the enumerated digits for the mantissa and returns the ordinal exponent. E.G. `cardinal(2.712e7)` will return: ``` two point seven one two times ten to the seventh ``` If you want it to be treated like an integer or rational, coerce it to the appropriate type. `cardinal(2.712e7.Int)` to get: ``` twenty-seven million, one hundred twenty thousand ``` `cardinal(1.25e-3)` returns: ``` one point two five times ten to the negative third ``` `cardinal(1.25e-3.Rat)` returns: ``` one eight hundredth ``` ## cardinal-year( ) - short: card-y() Converts integers from 1 to 9999 to the common American English convention. ### cardinal-year( $year, :oh($str) ); * $year * value; must be an integer between 1 and 9999 or something that can be coerced to an integer between 1 and 9999. * :oh * value; optional, string to use for the "0" years after a millennium. Default 'oh-'. Change to ' ought-' or some other string if desired. Follows the common American English convention for years: ``` 2015 -> twenty fifteen. 1984 -> nineteen eighty-four. ``` Even millenniums are returned as thousands: ``` 2000 -> two thousand. ``` Even centuries are returned as hundreds: ``` 1900 -> nineteen hundred. ``` Years 1 .. 9 in each century are returned as ohs: ``` 2001 -> twenty oh-one. ``` Configurable with the :oh parameter. Default is 'oh-'. Change to 'ought-' if you prefer twenty ought-one, or something else if that is your preference. ## ordinal( ) - short: ord-n() Takes an integer or something that can be coerced to an integer and returns a string similar to the cardinal() routine except it is positional rather than valuation. E.G. 'first' rather than 'one', 'eleventh' rather than 'eleven'. ### ordinal( $integer ) * $integer * value; an integer or something that can be coerced to a sensible integer value. ## ordinal-digit( ) - short: ord-d() Takes an integer or something that can be coerced to an integer and returns the given numeric value with the appropriate suffix appended to the number. 1 -> 1st, 3 -> 3rd, 24 -> 24th etc. ### ordinal-digit( $integer, :u, :c ) * $integer * value; an integer or something that can be coerced to a sensible integer value. * :u * boolean; enable Unicode superscript ordinal suffixes (ˢᵗ, ⁿᵈ, ʳᵈ, ᵗʰ). Default false. * :c * boolean; add commas to the ordinal number. Default false. ## comma( ) Insert commas into a numeric string following the English convention. Groups of 3-orders-of-magnitude for whole numbers, fractional portions are unaffected. ### comma( $number ) * $number * value; an integer, rational, int-string, rat-string or numeric string. Will accept an Integer, Int-String, Rational, Rat-String or a numeric string that looks like an Integer or Rational. Any non-significant leading zeros are dropped. Non-significant trailing zeros are dropped for numeric rationals. If you want to retain non-significant trailing zeros in Rats, pass the argument as a string. ## pretty-rat() - short: prat() A "prettifying" routine to render rational numbers as a fraction. Rats that have a denominator of 1 will be rendered as integers. ### pretty-rat($number) * $number * value; Any real number. Integers and Nums will be passed along unchanged; Rats will be converted to a fractional representation. ## no-commas A global flag for the `cardinal()` and `ordinal()` routines that disables / enables returning commas between 3-order-of-magnitude groups. ## pretty-rat() - short: prat() A "prettifying" routine to render rational numbers as a fraction. Rats that have a denominator of 1 will be rendered as integers. ## super() A "prettifying" routine to render numbers as Unicode superscripts. Mostly for formatting output strings. Not convieniently usable for a variable exponent. ### super($number) * $number * value; Any real integer or integer string. Note that a numeric of -0 will be superscripted to ⁰ since Raku treats numeric -0 and 0 as equivalent. If it is important to have the negative sign show up, pass the value as a string "-0". Provides superscript versions of: +-0123456789()ei . Technically, super will work with any numeric, but Unicode does not offer a superscript decimal point, so it is of limited use for rationals and scientific notation. ## no-commas A global flag for the `cardinal()` and `ordinal()` routines that disables / enables returning commas between 3-order-of-magnitude groups. ### no-commas( $bool ) * $bool * A truthy / falsey value to enable / disable inserting commas into spelled out numeric strings. Takes a Boolean or any value that can be coerced to a Boolean as a flag to disable / enable inserting commas. Absence of a value is treated as True. E.G. ``` no-commas; ``` is the same as ``` no-commas(True); ``` to re-enable inserting commas: ``` no-commas(False); ``` Disabled (False) by default. May be enabled and disabled as desired, even within a single block; the flag is global though, not lexical. If you disable commas deep within a block, it will affect all `ordinal()` and `cardinal()` calls afterwords, even in a different scope. If your script is part of a larger application, you may want to query the `no-commas` state and restore it after any modification. Query the no-commas flag state with: ``` my $state = no-commas?; ``` Returns the current flag state as a Boolean: True - commas disabled, False - commas enabled. Does not modify the current state. Restore it with: ``` no-commas($state); ``` NOTE: the `comma()` routine and `no-commas` flag have nothing to do with each other, do not interact, and serve completely different purposes. --- # BUGS Doesn't handle complex numbers. Does some cursory error trapping and coercion but the foot cannon is still loaded. # AUTHOR Original Integer cardinal code by TimToady (Larry Wall). See: <http://rosettacode.org/wiki/Number_names#Raku> Other code by thundergnat (Steve Schulze). # LICENSE Licensed under The Artistic 2.0; see LICENSE.
## nfkc.md class NFKC Codepoint string in Normal Form KC (compatibility composed) ```raku class NFKC is Uni {} ``` A Codepoint string in Unicode Normalization Form KC. It is created by Compatibility Decomposition, followed by Canonical Composition. For more information on what this means, see [Unicode TR15](https://www.unicode.org/reports/tr15/). # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `NFKC` raku-type-graph NFKC NFKC Uni Uni NFKC->Uni Mu Mu Any Any Any->Mu Positional Positional Stringy Stringy Uni->Any Uni->Positional Uni->Stringy [Expand chart above](/assets/typegraphs/NFKC.svg)
## dist_cpan-MARTIMM-Gnome-GObject.md ![gtk logo](https://martimm.github.io/gnome-gtk3/content-docs/images/gtk-raku.png) # Gnome GObject - Data structures and utilities for C programs ![L](http://martimm.github.io/label/License-label.svg) 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. ## Documentation * [🔗 License document](http://www.perlfoundation.org/artistic_license_2_0) * [🔗 Release notes](https://github.com/MARTIMM/gnome-gobject/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/gnome-gtk3/issues). # Attribution * The developers of Raku of course and the writers of the documentation which helped me out every time again and again. * The builders of the GTK+ library and its documentation. * Other helpful modules for their insight and use.
## multi.md multi Combined from primary sources listed below. # [In Functions](#___top "go to top of document")[§](#(Functions)_multi_multi "direct link") See primary documentation [in context](/language/functions#Multi-dispatch) for **Multi-dispatch**. Raku allows for writing several routines with the same name but different signatures. When the routine is called by name, the runtime environment determines the proper *candidate* and invokes it. Each candidate is declared with the `multi` keyword. Dispatch happens depending on the parameter [arity](/type/Code#method_arity) (number), type and name; and under some circumstances the order of the multi declarations. Consider the following example: ```raku # version 1 multi happy-birthday( $name ) { say "Happy Birthday $name !"; } # version 2 multi happy-birthday( $name, $age ) { say "Happy {$age}th Birthday $name !"; } # version 3 multi happy-birthday( :$name, :$age, :$title = 'Mr' ) { say "Happy {$age}th Birthday $title $name !"; } # calls version 1 (arity) happy-birthday 'Larry'; # OUTPUT: «Happy Birthday Larry !␤» # calls version 2 (arity) happy-birthday 'Luca', 40; # OUTPUT: «Happy 40th Birthday Luca !␤» # calls version 3 # (named arguments win against arity) happy-birthday( age => '50', name => 'John' ); # OUTPUT: «Happy 50th Birthday Mr John !␤» # calls version 2 (arity) happy-birthday( 'Jack', 25 ); # OUTPUT: «Happy 25th Birthday Jack !␤» ``` The first two versions of the `happy-birthday` sub differs only in the arity (number of arguments), while the third version uses named arguments and is chosen only when named arguments are used, even if the arity is the same of another `multi` candidate. When two sub have the same arity, the type of the arguments drive the dispatch; when there are named arguments they drive the dispatch even when their type is the same as another candidate: ```raku multi happy-birthday( Str $name, Int $age ) { say "Happy {$age}th Birthday $name !"; } multi happy-birthday( Str $name, Str $title ) { say "Happy Birthday $title $name !"; } multi happy-birthday( Str :$name, Int :$age ) { say "Happy Birthday $name, you turned $age !"; } happy-birthday 'Luca', 40; # OUTPUT: «Happy 40th Birthday Luca !␤» happy-birthday 'Luca', 'Mr'; # OUTPUT: «Happy Birthday Mr Luca !␤» happy-birthday age => 40, name => 'Luca'; # OUTPUT: «Happy Birthday Luca, you turned 40 !␤» ``` Named parameters participate in the dispatch even if they are not provided in the call. Therefore a multi candidate with named parameters will be given precedence. For more information about type constraints see the documentation on [`Signature` literals](/language/signatures#Type_constraints). ```raku multi as-json(Bool $d) { $d ?? 'true' !! 'false'; } multi as-json(Real $d) { ~$d } multi as-json(@d) { sprintf '[%s]', @d.map(&as-json).join(', ') } say as-json( True ); # OUTPUT: «true␤» say as-json( 10.3 ); # OUTPUT: «10.3␤» say as-json( [ True, 10.3, False, 24 ] ); # OUTPUT: «[true, 10.3, false, 24]␤» ``` For some signature differences (notably when using a where clause or a subset) the order of definition of the multi methods or subs is used, evaluating each possibility in turn. See [multi resolution by order of definition](/language/functions#multi_resolution_by_order_of_definition) below for examples. `multi` without any specific routine type always defaults to a `sub`, but you can use it on methods as well. The candidates are all the multi methods of the object: ```raku class Congrats { multi method congratulate($reason, $name) { say "Hooray for your $reason, $name"; } } role BirthdayCongrats { multi method congratulate('birthday', $name) { say "Happy birthday, $name"; } multi method congratulate('birthday', $name, $age) { say "Happy {$age}th birthday, $name"; } } my $congrats = Congrats.new does BirthdayCongrats; $congrats.congratulate('promotion','Cindy'); # OUTPUT: «Hooray for your promotion, Cindy␤» $congrats.congratulate('birthday','Bob'); # OUTPUT: «Happy birthday, Bob␤» ``` Unlike `sub`, if you use named parameters with multi methods, the parameters must be required parameters to behave as expected. Please note that a non-multi sub or operator will hide multi candidates of the same name in any parent scope or child scope. The same is true for imported non-multi candidates. Multi-dispatch can also work on parameter traits, with routines with `is rw` parameters having a higher priority than those that do not: ```raku proto þoo (|) {*} multi þoo( $ðar is rw ) { $ðar = 42 } multi þoo( $ðar ) { $ðar + 42 } my $bar = 7; say þoo($bar); # OUTPUT: «42␤» ```
## dist_github-Skarsnik-Gumbo.md [![Build Status](https://travis-ci.org/Skarsnik/perl6-gumbo.svg?branch=master)](https://travis-ci.org/Skarsnik/perl6-gumbo) # Name Gumbo # Synopsis ``` use Gumbo; use LWP::Simple; my $xml = parse-html(LWP::Simple.get("www.google.com")); say $xml.lookfor(:TAG<title>); # Google; ``` # Description From the Gumbo (<https://github.com/google/gumbo-parser>) project page : Gumbo is an implementation of the HTML5 parsing algorithm implemented as a pure C99 library with no outside dependencies. It's designed to serve as a building block for other tools and libraries such as linters, validators, templating languages, and refactoring and analysis tools. This module is a binding to this library. It provide a `parse-html` routine that parse a given html string and return a `XML::Document` object. To access all the Gumbo library has to offer you probably want to look at the `Gumbo::Binding` module. # Installation Simply use zef. For the tests to pass, you need to install the Gumbo library (see your distribution documentation). If you installed the Gumbo library in your own location you can set the `PERL6_GUMBOLIB` environement variable with the path to the library file. `zef install Gumbo` or `PERL6_GUMBOLIB="/home/user/gumbo/libgumbo.so.1" zef install Gumbo` # Usage ## parse-html(Str $html) : XML::Document Parse a html string and retrurn a `XML::Document`. ## parse-html(Str $html, :$nowhitespace, \*%filters) : XML::Document This is the full signature of the `parse-html` routine. * nowhitespace Tell Gumbo to not include all extra whitespaces that can exist around tag, like intendation put in front of html tags * \*%filters The module offer some form of basic filtering if you want to restrict the `XML::Document` returned. You can only filter on elements (understand tags) and not content like the text of a `p` tag. It inspired by the `elements` method of the `XML::Element` class. The main purpore is to reduce time spent parsing uneccessary content and decrease the memory print of the `XML::Document`. IMPORTANT: the root will always be the html tag. * TAG Limits to elements with the given tag name * SINGLE If set only get the first match * attrib You can filter on one attribute name with his given value All the children of the element(s) matched are kept. Like if you search for all the links, you will get the eventuals additionals tags put around the text part. ## $gumbo\_last\_c\_parse\_duration && $gumbo\_last\_xml\_creation\_duration These two variables hold the time (`Duration`) spend in the two steps of the work parse-html does. ## PERL6\_GUMBOLIB Set this environment variable to specify where the module can find the gumbo library if it's not in the usual system library path. # Example ``` use Gumbo; my $html = q:to/END_HTML/; <html> <head> <title>Fancy</title> </head> <body> <p>It's fancy</p> <p class="fancier">It's fancier</p> </body> </html> END_HTML my $xmldoc = parse-html($html); say $xmldoc.root.elements(:TAG<p>, :RECURSE)[0][0].text; #It's fancy $xmldoc = parse-html($html, :TAG<p>, :SINGLE); say $xmldoc[0][0].text; #It's still fancy $xmldoc = parse-html($html, :TAG<p>, :class<fancier>, :SINGLE); say $xmldoc[0][0].text; # It's fancier ``` # Gumbo::Parser This module provide a Gumbo::Parser class that does the role defined by the `HTML::Parser` module. It also provide some additionnals attributes that contains various informations. It work exactly like the `parse-html` method with the same extra optionnals arguments. ``` use Gumbo::Parser; my $parser = Gumbo::Parser.new; my $xmldoc = $parser.parse($html); say $parser.c-parse-duration; say $parser.xml-creation-duration; say $parser.stats<xml-objects>; # the number of XML::* created (excluding the XML::Document) say $parser.stats<whitespaces>; # the number of Whitespaces elements (created or not) say $parser.stats<elements>; # the number of XML::Element (including root) ``` # See Also `XML`, `HTML::Parser::XML` # Copyright Sylvain "Skarsnik" Colinet [[email protected]](mailto:[email protected]) # License The modules provided by Gumbo are under the same licence as Rakudo, see the LICENCE file
## dist_cpan-PMQS-IO-Compress-Lzop.md ``` IO-Compress-Lzop Version 2.094 13 July 2020 Copyright (c) 2005-2020 Paul Marquess. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. DESCRIPTION ----------- This module provides a Perl interface to allow reading and writing of lzop files/buffers. PREREQUISITES ------------- Before you can build IO-Compress-Lzop you need to have the following installed on your system: * Perl 5.006 or better. * Compress::LZO * IO::Compress::Base BUILDING THE MODULE ------------------- Assuming you have met all the prerequisites, the module can now be built using this sequence of commands: perl Makefile.PL make make test INSTALLATION ------------ To install IO-Compress-Lzop, run the command below: make install TROUBLESHOOTING --------------- SUPPORT ------- General feedback/questions/bug reports should be sent to https://github.com/pmqs/IO-Compress-Lzop/issues (preferred) or https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress-Lzop. FEEDBACK -------- How to report a problem with IO-Compress-Lzop. To help me help you, I need all of the following information: 1. The Versions of everything relevant. This includes: a. The *complete* output from running this perl -V Do not edit the output in any way. Note, I want you to run "perl -V" and NOT "perl -v". If your perl does not understand the "-V" option it is too old. This module needs Perl version 5.004 or better. b. The version of IO-Compress-Lzop you have. If you have successfully installed IO-Compress-Lzop, this one-liner will tell you: perl -MIO::Compress::Lzop -e 'print qq[ver $IO::Compress::Lzop::VERSION\n]' If you are running windows use this perl -MIO::Compress::Lzop -e "print qq[ver $IO::Compress::Lzop::VERSION\n]" If you haven't installed IO-Compress-Lzop then search IO::Compress::Lzop.pm for a line like this: $VERSION = "2.094" ; 2. If you are having problems building IO-Compress-Lzop, send me a complete log of what happened. Start by unpacking the IO-Compress-Lzop module into a fresh directory and keep a log of all the steps [edit config.in, if necessary] perl Makefile.PL make make test TEST_VERBOSE=1 Paul Marquess ```
## dist_zef-raku-community-modules-Test-Output.md [![Actions Status](https://github.com/raku-community-modules/Test-Output/workflows/test/badge.svg)](https://github.com/raku-community-modules/Test-Output/actions) Test::Output - Test the output to STDOUT and STDERR your program generates # TABLE OF CONTENTS * [NAME](#name) * [SYNOPSIS](#synopsis) * [DESCRIPTION](#description) * [EXPORTED SUBROUTINES](#exported-subroutines) * [`is` Tests](#is-tests) * [`output-is`](#output-is) * [`stdout-is`](#stdout-is) * [`stderr-is`](#stderr-is) * [`like` Tests](#like-tests) * [`output-like`](#output-like) * [`stdout-like`](#stdout-like) * [`stderr-like`](#stderr-like) * [Output Capture](#output-capture) * [`output-from`](#output-from) * [`stdout-from`](#stdout-from) * [`stderr-from`](#stderr-from) * [REPOSITORY](#repository) * [BUGS](#bugs) * [AUTHOR](#author) * [LICENSE](#license) # SYNOPSIS ``` use v6.d; use Test; use Test::Output; my &test-code = sub { say 42; note 'warning!'; say "After warning"; }; # Test code's output using exact match ('is') output-is &test-code, "42\nwarning!\nAfter warning\n", 'testing output'; stdout-is &test-code, "42\nAfter warning\n", 'testing stdout'; stderr-is &test-code, "warning!\n", 'testing stderr'; # Test code's output using regex ('like') output-like &test-code, /42.+warning.+After/, 'testing output (regex)'; stdout-like &test-code, /42/, 'testing stdout (regex)'; stderr-like &test-code, /^ "warning!\n" $/, 'testing stderr (regex)'; # Just capture code's output and do whatever you want with it is output-from( &test-code ), "42\nwarning!\nAfter warning\n"; is stdout-from( &test-code ), "42\nAfter warning\n"; is stderr-from( &test-code ), "warning!\n"; ``` # DESCRIPTION This module allows you to capture the output (STDOUT/STDERR/BOTH) of a piece of code and evaluate it for some criteria. It needs version 6.d of the language, since it's following specs that were deployed for that version. If you need to go with 6.c, download 1.001001 from [here](https://github.com/raku-community-modules/Test-Output/releases) or via `git clone`+ ``` git checkout v1.001001 zef install . ``` # EXPORTED SUBROUTINES ## `is` Tests ### `output-is` ![](_chromatin/sub-signature.png) ``` sub output-is (&code, Str $expected, Str $desc? ); ``` ![](_chromatin/sub-usage-example.png) ``` output-is { say 42; note 43; say 44 }, "42\n43\n44\n", 'Merged output from STDOUT/STDERR looks fine!'; ``` Uses `is` function from `Test` module to test whether the combined STDERR/STDOUT output from a piece of code matches the given string. Takes an **optional** test description. --- ### `stdout-is` ![](_chromatin/sub-signature.png) ``` sub stdout-is (&code, Str $expected, Str $desc? ); ``` ![](_chromatin/sub-usage-example.png) ``` stdout-is { say 42; note 43; say 44 }, "42\n44\n", 'STDOUT looks fine!'; ``` Same as [`output-is`](#output-is), except tests STDOUT only. --- ### `stderr-is` ![](_chromatin/sub-signature.png) ``` sub stderr-is (&code, Str $expected, Str $desc? ); ``` ![](_chromatin/sub-usage-example.png) ``` stderr-is { say 42; note 43; say 44 }, "43\n", 'STDERR looks fine!'; ``` Same as [`output-is`](#output-is), except tests STDERR only. --- ## `like` Tests ### `output-like` ![](_chromatin/sub-signature.png) ``` sub output-like (&code, Regex $expected, Str $desc? ); ``` ![](_chromatin/sub-usage-example.png) ``` output-like { say 42; note 43; say 44 }, /42 .+ 43 .+ 44/, 'Merged output from STDOUT/STDERR matches the regex!'; ``` Uses `like` function from `Test` module to test whether the combined STDERR/STDOUT output from a piece of code matches the given `Regex`. Takes an **optional** test description. --- ### `stdout-like` ![](_chromatin/sub-signature.png) ``` sub stdout-like (&code, Regex $expected, Str $desc? ); ``` ![](_chromatin/sub-usage-example.png) ``` stdout-like { say 42; note 43; say 44 }, /42 \n 44/, 'STDOUT matches the regex!'; ``` Same as [`output-like`](#output-like), except tests STDOUT only. --- ### `stderr-like` ![](_chromatin/sub-signature.png) ``` sub stderr-like (&code, Regex $expected, Str $desc? ); ``` ![](_chromatin/sub-usage-example.png) ``` stderr-like { say 42; note 43; say 44 }, /^ 43\n $/, 'STDERR matches the regex!'; ``` Same as [`output-like`](#output-like), except tests STDERR only. --- ## Output Capture ### `output-from` ![](_chromatin/sub-signature.png) ``` sub output-from (&code) returns Str; ``` ![](_chromatin/sub-usage-example.png) ``` my $output = output-from { say 42; note 43; say 44 }; say "Captured $output from our program!"; is $output, "42\nwarning!\nAfter warning\n", 'captured merged STDOUT/STDERR look fine'; ``` Captures and returns merged STDOUT/STDERR output from the given piece of code. --- ### `stdout-from` ![](_chromatin/sub-signature.png) ``` sub stdout-from (&code) returns Str; ``` ![](_chromatin/sub-usage-example.png) ``` my $stdout = stdout-from { say 42; note 43; say 44 }; say "Captured $stdout from our program!"; is $stdout, "42\nAfter warning\n", 'captured STDOUT looks fine'; ``` Same as [`output-from`](#output-from), except captures STDOUT only. --- ### `stderr-from` ![](_chromatin/sub-signature.png) ``` sub stderr-from (&code) returns Str; ``` ![](_chromatin/sub-usage-example.png) ``` my $stderr = stderr-from { say 42; note 43; say 44 }; say "Captured $stderr from our program!"; is $stderr, "warning\n", 'captured STDERR looks fine'; ``` Same as [`output-from`](#output-from), except captures STDERR only. --- ### `test-output-verbosity` ![](_chromatin/sub-signature.png) ``` sub test-output-verbosity (Bool :$on, Bool :$off) returns Str; ``` ![](_chromatin/sub-usage-example.png) ``` # turn verbosity on test-output-verbosity(:on); my $output = output-from { do-something-interactive() }; # test output will now displayed during the test # turn verbosity off test-output-verbosity(:off); ``` Display the code's output while the test code is executed. This can be very useful for author tests that require you to enter input based on the output. --- # REPOSITORY Fork this module on GitHub: <https://github.com/raku-community-modules/Test-Output> # BUGS To report bugs or request features, please use <https://github.com/raku-community-modules/Test-Output/issues> # ORIGINAL AUTHOR Zoffix Znet (<http://zoffix.com/>) # LICENSE You can use and distribute this module under the terms of the The Artistic License 2.0. See the `LICENSE` file included in this distribution for complete details.
## dist_github-kmwallio-Text-TFIdf.md # Text::TFIdf Given a set of documents, generates [TF-IDF Vectors](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) for them. [![Build Status](https://travis-ci.org/kmwallio/p6-Text-TFIdf.svg?branch=master)](https://travis-ci.org/kmwallio/p6-Text-TFIdf) ## Installation ``` panda install Text::TFIdf ``` ## Usage ``` use Text::TFIdf; my %stop-words; my $doc-store = TFIdf.new(:trim(True), :stop-list(%stop-words)); $doc-store.add('perl is cool'); $doc-store.add('i like node'); $doc-store.add('java is okay'); $doc-store.add('perl and node are interesting meh about java'); sub results($id, $score) { say $id ~ " got " ~ $score; } $doc-store.tfids('node perl java', &results); ``` Output: ``` 0 got 0.858454714967854 1 got 0.858454714967854 2 got 0.858454714967854 3 got 2.17296349726238 ``` ## Acknowledgements * [Lingua::EN::Stem::Porter](https://github.com/johnspurr/Lingua-EN-Stem-Porter) * [NaturalNode](https://github.com/NaturalNode/natural) for heavy inspiration?
## dist_zef-dwarring-CSS.md [![Build Status](https://travis-ci.org/css-raku/CSS-raku.svg?branch=master)](https://travis-ci.org/css-raku/CSS-raku) [[Raku CSS Project]](https://css-raku.github.io) / [[CSS]](https://css-raku.github.io/CSS-raku) ## class CSS CSS Stylesheet processing ## Synopsis ``` use CSS; use CSS::Properties; use CSS::Units :px; # define 'px' postfix operator use CSS::TagSet::XHTML; use LibXML::Document; my $string = q:to<\_(ツ)_/>; <!DOCTYPE html> <html> <head> <style> @page :first { margin:4pt; } body {background-color: powderblue; font-size: 12pt} @media screen { h1:first-child {color: blue !important;} } @media print { h2 {color: green;} } p {color: red; font-family:'Para';} div {font-size: 10pt } @font-face { font-family:'Para'; src:url('/myfonts/para.otf'); } </style> </head> <body> <h1>This is a heading</h1> <h2>This is a sub-heading</h2> <h1>This is another heading</h1> <p>This is a paragraph.</p> <div style="color:green">This is a div</div> </body> </html> \_(ツ)_/ my LibXML::Document $doc .= parse: :$string, :html; # define a selection media my CSS::Media $media .= new: :type<screen>, :width(480px), :height(640px), :color; # Create a tag-set for XHTML specific loading of style-sheets and styling my CSS::TagSet::XHTML $tag-set .= new(); my CSS $css .= new: :$doc, :$tag-set, :$media, :inherit; # -- show some computed styles, based on CSS Selectors, media, inline styles and xhtml tags my CSS::Properties $body-props = $css.style('/html/body'); say $body-props.font-size; # 12pt say $body-props; # background-color:powderblue; display:block; font-size:12pt; margin:8px; unicode-bidi:embed; say $css.style('/html/body/h1[1]'); # color:blue; display:block; font-size:12pt; font-weight:bolder; margin-bottom:0.67em; margin-top:0.67em; unicode-bidi:embed; say $css.style('/html/body/div'); # color:green; display:block; font-size:10pt; unicode-bidi:embed; say $css.style($doc.first('/html/body/div')); # color:green; display:block; font-size:10pt; unicode-bidi:embed; # -- query first page properties (from @page rules) say $css.page-properties(:first); # margin:4pt; # -- find a font using @font-face declarations say .Str # font-family:'Para'; src:url('/myfonts/para.otf') with $css.font-sources('12pt Para').head; ``` ## Description [CSS](https://css-raku.github.io/CSS-raku) is a module for parsing style-sheets and applying them to HTML or XML documents. This module aims to be W3C compliant and complete, including: style-sheets, media specific and inline styling and the application of HTML specific styling (based on tags and attributes). ## Methods ### method new ``` method new( LibXML::Document :$doc!, # document to be styled. CSS::Stylesheet :$stylesheet!, # stylesheet to apply CSS::TagSet :$tag-set, # tag-specific styling CSS::Media :$media, # target media Bool :$inherit = True, # perform property inheritance :%include ( # External stylesheet loading: Bool :$imports = False, # - enable '@import' directives Bool :$links = False, # - load <link../> tags (XHTML) ), URI() :$base-url = $doc.URI, # base URL for imports and links ) returns CSS; ``` In particular, the `CSS::TagSet :$tag-set` options specifies a tag-specific styler; For example CSS::TagSet::XHTML. ### method style ``` multi method style(LibXML::Element:D $elem) returns CSS::Properties; multi method style(Str:D $xpath) returns CSS::Properties; ``` Computes a style for an individual element, or XPath to an element. ### method page-properties ``` method page-properties(Bool :$first, Bool :$right, Bool :$left, Str :$margin-box --> CSS::Properties) ``` Query and extract `@page` at rules. The `:first`, `:right` and `:left` flags can be used to select rules applicable to a given logical page. In addition, the `:margin-box` can be used to select a specific [Page Margin Box](https://www.w3.org/TR/css-page-3/#margin-boxes). For example given the at-rule `@page { margin:2cm; size:a4; @top-center { content: 'Page ' counter(page); } }`, the top-center page box properties can be selected with `$stylesheet.page(:margin-box<top-center>)`. ### method font-face ``` multi method font-face() returns Array[CSS::Font::Descriptor] multi method font-face($family) returns CSS::Font::Descriptor ``` * `font-face()` returns a list of all fonts declared with `@font-face` at-rules * `font-face($family)` returns font-properties for the given font-family; ### method prune ``` method prune(LibXML::Element $node? --> LibXML::Element) ``` Removes all XML nodes with CSS property `display:none;`, giving an approximate representation of a CSS rendering tree. For example, if an HTML document with an XHTML tag-set is pruned the `head` element will be removed because it has the property `display:none;`. Any other elements that have had `display:none;' applied to them via the tag-set, inline CSS, or CSS Selectors are also removed. By default, this method acts on the root element of the associated $.doc XML document. ### method font-sources ``` method font-sources(CSS::Font() $font) returns Array[CSS::Font::Resources::Source] ``` Returns a list of [CSS::Font::Resources::Source](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/Font/Resources/Source) objects for natching source fonts, based on `@font-face` rules and (as a fallback) the font's name and characterstics. ## Utility Scripts * `css-inliner.raku input.xml [output.xml] --style=file.css --prune --tags --type=html|pango|pdf --inherit` Apply internal or external style-sheets to per-element 'style' attributes ## See Also * [CSS::Stylesheet](https://css-raku.github.io/CSS-Stylesheet-raku/CSS/Stylesheet) - CSS Stylesheet representations * [CSS::Module](https://css-raku.github.io/CSS-Module-raku) - CSS Module module * [CSS::Properties](https://css-raku.github.io/CSS-Properties-raku/CSS/Properties) - CSS Properties module * [CSS::TagSet](https://css-raku.github.io/CSS-TagSet-raku/CSS/TagSet) - CSS tag-sets (XHTML, Pango, Tagged PDF) * [LibXML](https://css-raku.github.io/https://libxml-raku.github.io/LibXML-raku/) - LibXML Raku module * [DOM::Tiny](https://github.com/zostay/raku-DOM-Tiny) - A lightweight, self-contained DOM parser/manipulator ## Todo * Other At-Rule variants `@document`
## dist_zef-dwarring-CSS-Font-Resources.md [[Raku CSS Project]](https://css-raku.github.io) / [[CSS-Font-Resources]](https://css-raku.github.io/CSS-Font-Resources-raku) # CSS-Font-Resources-raku ## Description This is a light-weight font selector driven by CSS `@font-face` rules. It is integrated into the [CSS](https://css-raku.github.io) and [CSS::Stylesheet](https://css-raku.github.io/CSS-Stylesheet-raku) modules, but can also be used for stand-alone font resource loading. ## Classes in this distribution: * [CSS::Font::Resources](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/Font/Resources) - CSS Font Resources Manager * [CSS::Font::Resources::Source](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/Font/Resources/Source) - CSS Font Resources abstract source * [CSS::Font::Resources::Source::Local](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/Font/Resources/Source/Local) - CSS Font Resources `local` source * [CSS::Font::Resources::Source::Url](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/Font/Resources/Source/Url) - CSS Font Resources `url` source * [CSS::URI](https://css-raku.github.io/CSS-Font-Resources-raku/CSS/URI) - Lightweight object for fetchable URIs. ## Examples ## from CSS::Stylesheet ``` use CSS::Stylesheet; use CSS::Font::Resources; my CSS::Stylesheet $css .= parse: q:to<END>, :base-url<my/path/>; h1 {color:red} h2 {color:blue} @font-face { font-family: "DejaVu Sans"; src: url("fonts/DejaVuSans.ttf"); } @font-face { font-family: "DejaVu Sans"; src: url("fonts/DejaVuSans-Bold.ttf"); font-weight: bold; } @font-face { font-family: "DejaVu Sans"; src: url("fonts/DejaVuSans-Oblique.ttf"); font-style: oblique; } @font-face { font-family: "DejaVu Sans"; src: url("fonts/DejaVuSans-BoldOblique.ttf"); font-weight: bold; font-style: oblique; } END my $formats = 'opentype'|'truetype'; # accept first true-type or open-type font my $font = "bold 12pt times roman, serif"; my CSS::Font::Resources::Source @sources = $css.font-sources($font, :$formats); my Blob $font-buf = .IO with @sources.first; ``` ## stand-alone ``` use CSS::Font::Resources; use CSS::Font::Descriptor; my @decls = q:to<END>.split: /^^'---'$$/; font-family: "DejaVu Sans"; src: url("fonts/DejaVuSans.ttf"); --- font-family: serif; font-weight: bold; src: local(DejaVuSans-Bold); END my CSS::Font::Descriptor @font-face = @decls.map: -> $style {CSS::Font::Descriptor.new: :$font}; my $font = "bold 12pt times roman, serif"; my $formats = 'opentype'|'truetype'; # accept first true-type or open-type font my CSS::Font::Resources $font-selector .= new: :$font, :@font-face, :base-url</my/path/>, :$formats; # accept first true-type or open-type font my CSS::Font::Resources::Source @sources = $font-selector.sources; my Blob $font-buf = .Blob with @sources.first; ``` ## Methods ### new ``` method new( CSS::Font:D() :$font!, CSS::Font::Descriptor :@font-face, URI() $.base-url = './', :$formats = 'woff'|'woff2'|'truetype'|'opentype'|'embedded-opentype'|'postscript'|'svg'|'cff', --> CSS::Font::Resources ) ``` Returns a new font selector object for the given font and font-descriptor list. * `$base-url` is used to compute absolute URI's for relative font `src` urls. * `$formats` is used to filter fonts to a specific format, ### sources ``` multi method sources( CSS::Font::Resources:D: Bool :$fallback = True ) multi method sources( CSS::Font::Resources:U: :$font, :@font-face, :$base-url, :$formats, Bool :$fallback = True, ) ``` Returns a list of matching fonts of type CSS::Font::Resources::Source, ordered by preference. * `$fallback` return a system font source, if there are no matching font-descriptors. ## source ``` method source(|c --> CSS::Font::Resources::Source); ``` Returns the first matching source.
## shell.md shell Combined from primary sources listed below. # [In Proc](#___top "go to top of document")[§](#(Proc)_method_shell "direct link") See primary documentation [in context](/type/Proc#method_shell) for **method shell**. ```raku method shell($cmd, :$cwd = $*CWD, :$env --> Bool:D) ``` Runs the `Proc` object with the given command and environment which are passed through to the shell for parsing and execution. See [`shell`](/type/independent-routines#sub_shell) for an explanation of which shells are used by default in the most common operating systems. # [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_sub_shell "direct link") See primary documentation [in context](/type/independent-routines#sub_shell) for **sub shell**. ```raku multi shell($cmd, :$in = '-', :$out = '-', :$err = '-', Bool :$bin, Bool :$chomp = True, Bool :$merge, Str :$enc, Str:D :$nl = "\n", :$cwd = $*CWD, :$env) ``` Runs a command through the system shell, which defaults to `%*ENV<ComSpec> /c` in Windows, `/bin/sh -c` otherwise. All shell metacharacters are interpreted by the shell, including pipes, redirects, environment variable substitutions and so on. Shell escapes are a severe security concern and can cause confusion with unusual file names. Use [run](#sub_run) if you want to be safe. The return value is of [type Proc](/type/Proc). ```raku shell 'ls -lR | gzip -9 > ls-lR.gz'; ``` See [`Proc`](/type/Proc#method_shell) for more details, for example on how to capture output.
## dist_zef-bduggan-Terminal-UI.md [![Actions Status](https://github.com/bduggan/raku-terminal-ui/actions/workflows/linux.yml/badge.svg)](https://github.com/bduggan/raku-terminal-ui/actions/workflows/linux.yml) [![Actions Status](https://github.com/bduggan/raku-terminal-ui/actions/workflows/macos.yml/badge.svg)](https://github.com/bduggan/raku-terminal-ui/actions/workflows/macos.yml) ## Terminal::UI A framework for building terminal interfaces. ## Example Create a box in full screen with some text in it, wait for a key, then exit: ``` use Terminal::UI 'ui'; ui.setup(:1pane); ui.pane.put("Hello world."); ui.get-key; ui.shutdown; ╔══════════════╗ ║Hello world. ║ ║ ║ ╚══════════════╝ ``` ## Example 2 Make a screen split with a line in the middle, with scrollable text on the top and bottom, and a selected row in the top box. The arrow keys (or j,k) move the selected line up and down. Tab switches to the other box. ``` use Terminal::UI 'ui'; ui.setup(:2panes); ui.panes[0].put("$_") for 1..10; ui.panes[1].put("$_") for <hello world>; ui.interact; ui.shutdown; ╔══════════════╗ ║8 ║ <- selected in green, scrollable ║9 ║ ║10 ║ ╟──────────────╢ ║hello ║ <- selected in grey. ║world ║ ╚══════════════╝ ``` ## Example 3 Like example 2, but also -- pressing Enter in the top box will some text about add the currently selected row to the bottom box: ``` ui.setup(:2panes); ui.panes[0].put("$_") for 1..10; ui.panes[0].on: select => -> :$raw, :$meta { ui.panes[1].put("you chose $raw!") } ui.interact; ui.shutdown; ╔══════════════╗ ║8 ║ <- press Enter, and… ║9 ║ ║10 ║ ╟──────────────╢ ║you chose 8! ║ <- …this appears! ║ ║ ╚══════════════╝ ``` ## Features and design goals * Easy to quickly make a console interface with custom behavior, but practical defaults. * Scrolling with some optimization, such as using ANSI scroll region escape sequences. * Thread safe. Concurrency friendly. Unicode compatibile. * Dynamic geometry calculation, for smart handling of window resizing. ## More examples See the [eg](https://github.com/bduggan/raku-terminal-ui/blob/master/eg/) directory. ## See also <https://blog.matatu.org/terminal-ui> ## Description The best place for documentation is the [examples](https://github.com/bduggan/raku-terminal-ui/blob/master/eg/) directory. There is also reference documentation with links to the source code -- see [Terminal::UI](https://github.com/bduggan/raku-terminal-ui/blob/master/lib/Terminal/UI.md). Other classes with documentation are: * [Terminal::UI::Screen](https://github.com/bduggan/raku-terminal-ui/blob/master/lib/Terminal/UI/Screen.md) * [Terminal::UI::Frame](https://github.com/bduggan/raku-terminal-ui/blob/master/lib/Terminal/UI/Frame.md) * [Terminal::UI::Pane](https://github.com/bduggan/raku-terminal-ui/blob/master/lib/Terminal/UI/Pane.md) * [Terminal::UI::Style](https://github.com/bduggan/raku-terminal-ui/blob/master/lib/Terminal/UI/Style.md) * [Terminal::UI::Input](https://github.com/bduggan/raku-terminal-ui/blob/master/lib/Terminal/UI/Input.md) ## BUGS Probably! If you find some bugs, or just have something to say, feel free to contact the author. ## Author Brian Duggan (bduggan at matatu.org)
## dist_zef-jmaslak-TCP-LowLevel.md [![Build Status](https://travis-ci.org/jmaslak/Raku-TCP-LowLevel.svg?branch=master)](https://travis-ci.org/jmaslak/Raku-TCP-LowLevel) # NAME TCP::LowLevel - Raku bindings for NativeCall TCP on Linux w/ Non-NativeCall Fallback` # SYNOPSIS ## SERVER ``` use TCP::LowLevel; react { my $server = TCP::LowLevel.new; $server-tcp.listen; whenever $server-tcp.acceptor -> $conn { whenever $conn.Supply -> $msg { say "Received: $msg"; } } say "Listening on port: " ~ $server.socket-port.result; } ``` ## CLIENT ``` use TCP::LowLevel; react { my $client = TCP::LowLevel.new; my $conn = $client.connect('127.0.0.1', 12345).result; $conn.print("Hello!"); whenever $conn.Supply -> $msg{ say "Received: $msg"; } } ``` # DESCRIPTION On Linux, this module utilizes NativeCall to use the low level socket library in an asyncronous way. This allows enhanced functionality, such as the use of the MD5 authentication header option (see internet RFC 2385). When not using Linux, this module is essentially a factory for the built-in asyncronous network libraries, although functionality such as MD5 authentication headers is not available in this mode. # WARNING This module may experience some interface changes as I determine the best possible interface. I will however try to keep the existing public interface working as documented in this documentation. # ATTRIBUTES ## my-host ``` my $server = TCP::LowLevel.new(:my-host('127.0.0.1')); ``` This is the source IP used to create the socket. It defaults to 0.0.0.0, which represents all IPv4 addresses on the system. You can set this to `::` if your host supports IPv6, to allow listenig on both IPv4 and IPv6 addresses. Setting the value of this attribute is only supported at consturction time as an argument to the constructor. ## my-port ``` my $server = TCP::LowLevel.new(:my-port(55666)); ``` This is the source port used to create the socket. It defaults to 0, meaning to assign a random source port. This is usually set if you desire to create a listening socket on a static port number. Setting the value of this attribute is only supported at consturction time as an argument to the constructor. ## socket-port ``` my $port = $server.socket-port.result; ``` This contains a promise that is kept when the source port being actively used is known. This is useful when listening on a random port, to determine what port was selected. Note that this value will not necessaril be the same as the value of `my-port`, as `my-port` may be zero, while this will never return zero. This value is not settable by the user. ## sock This contains the socket object belonging to a current connection. It is not anticipated that this would be used directly. # METHODS ## listen ``` $server.listen; ``` This creates a listening socket on the address specified by `my-host` and the port specified by `my-port`. ## acceptor ``` whenever $server.acceptor -> $conn { … } ``` This, when executed on a listening socket (one which you previously had called `listen()` on) will create a supply of connections, with a new connection emitted for every new connection. ## connect ``` my $conn = $client.connect('127.0.0.1', 8888).result; ``` Creates a TCP connection to the destination address and port provided. This returns a promise that when kept will contain the actual connection object. ## close ``` $server.close; ``` Closes a listening socket. ## add-md5($host, $key) ``` my $server = TCP::LowLevel.new; $client-tcp.add-md5('127.0.0.1', $key); $server-tcp.listen; ``` On Linux systems, this module supports RFC 2385 MD5 TCP authentication, which is often used for BGP connections. It takes two parameters, the host that the MD5 key applies to and the actual key. This can be used on inbound or outbound connections. This will throw an exception if MD5 is not supported on the platform. ## supports-md5 ``` die("No MD5 support") unless TCP::LowLevel.supports-md5; ``` Returns `True` if MD5 authentication is supported on the platform, `False` otherwise. # USING CONNECTION OBJECTS The objects returned by the `acceptor` Supply or the `connect()` Promise may be Raku native objects or the wrapper around the Linux networking libraries. ## METHODS ### Supply(:$bin?) ``` whenever $conn.Supply(:bin) -> $msg { … } ``` This returns a supply that emits received messages. If `:bin` is `True`, the messages are returned as `buf8` objects, othrwise they are returned as `Str` objects. ### print($msg) ``` $conn.print("Hello world!\n"); ``` This sends a `Str` across the TCP session. ### write($msg) ``` $conn.write($msg) ``` This sends a `buf8` across the TCP session. # AUTHOR Joelle Maslak [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright © 2018-2022 Joelle Maslak This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-CIAvash-T.md # NAME T - An easy way of writing test assertions which output good test descriptions and error messages # DESCRIPTION T is a [Raku](https://www.raku-lang.ir/en/) module for writing test assertions which output good test descriptions and error messages. It provides the `t` keyword for writing test assertions which takes an expression of form `<got> <infix> <expected>`. Goals of the module: * Write less but more readable test code * Get a useful test description and failure message # SYNOPSIS ``` use T:auth<zef:CIAash>; t 4 == 4; =output ok 1 - 4 == 4 t $my_great_module.return('something') eq 'something'; =output ok 2 - $my_great_module.return('something') eq 'something' t $my_great_module.return('something else') eq 'something'; =output not ok 3 - $my_great_module.return('something else') eq 'something' # Failed test '$my_great_module.return('something else') eq 'something'' # at ... line ... # expected: "something" # matcher: 'infix:<eq>' # got: "something else" ``` # INSTALLATION You need to have [Raku](https://www.raku-lang.ir/en) and [zef](https://github.com/ugexe/zef), then run: ``` zef install --/test "T:auth<zef:CIAvash>" ``` or if you have cloned the repo: ``` zef install . ``` # TESTING ``` prove6 -I. -v ``` or: ``` prove -ve 'raku -I.' --ext rakutest ``` # REPOSITORY <https://codeberg.org/CIAvash/T/> # BUG <https://codeberg.org/CIAvash/T/issues> # AUTHOR Siavash Askari Nasr - <https://siavash.askari-nasr.com> # COPYRIGHT Copyright © 2022 Siavash Askari Nasr # LICENSE This file is part of T. T is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at yoption) any later version. T is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with T. If not, see <http://www.gnu.org/licenses/>.
## dist_zef-amano.kenji-File-Name-Editor.md # File::Name::Editor Rename files in any text editor that you like. Cyclic renames such as A to B, B to C, and C to A are possible. ## Programmatic Usage ``` use File::Name::Editor; my @files = ("file1", "file2", ...); my $editor = %*ENV<EDITOR>; edit-file-names(@files, $editor); ``` If there are problems, exceptions are thrown. Catch exceptions if necessary. ``` edit-file-names(@files, $editor, :overwrite); ``` allows `File::Name::Editor` to overwrite files not in `@files`. ## Command Line Usage ``` file-name-editor ``` prints how to use it. ## Installation You can install it with `zef`. ``` zef install File::Name::Editor ``` This installs file-name-editor in `~/.raku/bin` or some other place. If your linux distribution has it, you can install it with your distribution's package manager.
## dist_github-littlebenlittle-Stache.md # Stache > **nb**: This project currently has an unstable API! Minor version changes may break existing code. Stache is an extensible mustache-style templating engine. ## Basic Use Raku script: ``` use Stache; my $template = q:to/EOT/; say '> # This is some {{ lang }} code'; say '> {{ code }}'; say {{ code }}; EOT say Stache::render( $template, lang => 'Raku', code => '1 + 1', ); ``` Output: ``` say '> # This is some Raku code'; say '> 1 + 1'; say 1 + 1; ``` ## Structure Blocks ### With Blocks Raku script: ``` use Stache; my $template = q:to/EOT/; {{ with A }} name: {{ .name }} type: {{ .type }} {{ endwith }} EOT say Stache::render( $template, A => %( name => '楽', type => 'language', ), ); ``` Output: ``` name: 楽 type: language ``` ### For Blocks Raku script: ``` use Stache; my $template = q:to/EOT/; {{ for items }} shape: {{ .shape }} genus: {{ .holes }} {{ endfor }} EOT say Stache::render( $template, items => [ %( shape => 'sphere', holes => 0, ), %( shape => 'torus', holes => 1, ), ], ); ``` Output: ``` shape: sphere genus: 0 shape: torus genus: 1 ```
## dist_zef-masukomi-Prettier-Table.md # Name `Prettier::Table`, a simple Raku module to make it quick and easy to represent tabular data in visually appealing ASCII tables. By default it will generate tables using ASCII Box Drawing characters as show in the examples below. But you can also generate [GFM Markdown tables](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables), and MS Word Friendly tables by calling `$my_table.set-style('MARKDOWN')` or `$my_table.set-style('MSWORD-FRIENDLY')` Check out `demo.raku` to see this in action. This is a fork of [Luis F Uceta's Prettier::Table](https://gitlab.com/uzluisf/raku-pretty-table) which is itself a port of the [Kane Blueriver's PTable library for Python](https://github.com/kxxoling/PTable). # Synopsis **Example 1**: ``` use Prettier::Table; my $table = Prettier::Table.new: title => "Australian Cities", field-names => ["City name", "Area", "Population", "Annual Rainfall"], sort-by => 'Area', align => %('City name' => 'l'), ; given $table { .add-row: ["Adelaide", 1295, 1158259, 600.5 ]; .add-row: ["Brisbane", 5905, 1857594, 1146.4]; .add-row: ["Darwin", 112, 120900, 1714.7]; .add-row: ["Hobart", 1357, 205556, 619.5 ]; .add-row: ["Sydney", 2058, 4336374, 1214.8]; .add-row: ["Melbourne", 1566, 3806092, 646.9 ]; .add-row: ["Perth", 5386, 1554769, 869.4 ]; } say $table; ``` Output: ![actual rendering](https://github.com/masukomi/Prettier-Table/blob/images/images/australian_cities.png?raw=true) (GitHub displays the raw text incorrectly) ``` ┌─────────────────────────────────────────────────┐ │ Australian Cities │ ├───────────┬──────┬────────────┬─────────────────┤ │ City name │ Area │ Population │ Annual Rainfall │ ├───────────┼──────┼────────────┼─────────────────┤ │ Darwin │ 112 │ 120900 │ 1714.7 │ │ Adelaide │ 1295 │ 1158259 │ 600.5 │ │ Hobart │ 1357 │ 205556 │ 619.5 │ │ Melbourne │ 1566 │ 3806092 │ 646.9 │ │ Sydney │ 2058 │ 4336374 │ 1214.8 │ │ Perth │ 5386 │ 1554769 │ 869.4 │ │ Brisbane │ 5905 │ 1857594 │ 1146.4 │ └───────────┴──────┴────────────┴─────────────────┘ ``` **Example 2**: ``` use Prettier::Table; my $table = Prettier::Table.new; given $table { .add-column('Planet', ['Earth', 'Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']); .add-column('Position', [3, 1, 2, 4, 5, 6, 7, 8]) .add-column('Known Satellites', [1, 0, 0, 2, 79, 82, 27, 14]); .add-column('Orbital period (days)', [365.256, 87.969, 224.701, 686.971, 4332.59, 10_759.22, 30_688.5, 60_182.0]); .add-column('Surface gravity (m/s)', [9.806, 3.7, 8.87, 3.721, 24.79, 10.44, 8.69, 11.15]); } $table.title('Planets in the Solar System'); $table.align(%(:Planet<l>)); $table.float-format(%('Orbital period (days)' => '-10.3f', 'Surface gravity (m/s)' => '-5.3f')); $table.sort-by('Position'); # If you wish to change any of the characters used in the border # you could do something like this. # $table.junction-char('*'); put $table; ``` Output: ![actual rendering](https://github.com/masukomi/Prettier-Table/blob/images/images/planets_of_the_solar_system.png?raw=true) (GitHub displays the raw text incorrectly) ``` ┌────────────────────────────────────────────────────────────────────┐ │ Planets in the Solar System │ ├─────────┬──────────┬───────────────────────┬───────────────────────┤ │ Planet │ Position │ Orbital period (days) │ Surface gravity (m/s) │ ├─────────┼──────────┼───────────────────────┼───────────────────────┤ │ Earth │ 3 │ 365.256 │ 9.806 │ │ Mercury │ 1 │ 87.969 │ 3.7 │ │ Venus │ 2 │ 224.701 │ 8.87 │ │ Mars │ 4 │ 686.971 │ 3.721 │ │ Jupiter │ 5 │ 4332.59 │ 24.79 │ │ Saturn │ 6 │ 10759.22 │ 10.44 │ │ Uranus │ 7 │ 30688.5 │ 8.69 │ │ Neptune │ 8 │ 60182 │ 11.15 │ └─────────┴──────────┴───────────────────────┴───────────────────────┘ ``` # Installation Using zef: ``` zef install Prettier::Table ``` From source: ``` $ git clone $ cd raku-pretty-table $ zef install . ``` # Quickstart `Prettier::Table` supports two kinds of usage: ## As a module ``` use Prettier::Table; my $x = Prettier::Table.new; ``` Check out the attributes in `Prettier::Table` to see the full list of things that can be set / configured. Most notably the `*-char` attributes, used to control the look of the border. Additionally, the named parameters in the `get-string` method. ## AUTHORS * [Luis F Uceta's Prettier::Table](https://gitlab.com/uzluisf/raku-pretty-table) * [masukomi](https://masukomi.org) ## LICENSE MIT. See LICENSE file. # Methods ## Getter and Setter Methods **NOTE**: These methods's names are the same as their respective attributes. To set a specific attribute during the instantiation of a `Prettier::Table` object, use its method's name. For instance, to set `title`, `Prettier::Table.new(title => "Table's title")`. Thus, all methods listed here have an associated attribute that can be set during object construction. ### multi method field-names ``` multi method field-names() returns Array ``` Return a list of field names. ### multi method field-names ``` multi method field-names( @values ) returns Nil ``` Set a list of field names. ### multi method align ``` multi method align() returns Hash ``` Return how the alignment of fields is controlled. ### multi method align ``` multi method align( $val ) returns Nil ``` Set how the alignment of fields is controlled. Either an alignment string (l, c, or r) or a hash of field-to-alignment pairs. ### multi method valign ``` multi method valign() returns Hash ``` Return how the vertical alignment of fields is controlled. ### multi method valign ``` multi method valign( $val ) returns Nil ``` Set how the vertical alignment of fields is controlled. Either an alignment string (t, m, or b) or a hash of field-to-alignment pairs. ### multi method max-width ``` multi method max-width() returns Prettier::Table::Constrains::NonNeg ``` Return the maximum width of fields. ### multi method max-width ``` multi method max-width( $val where { ... } ) returns Nil ``` Set the maximum width of fields. ### multi method min-width ``` multi method min-width() returns Hash ``` Return the minimum width of fields. ### multi method min-width ``` multi method min-width( $val ) returns Nil ``` Set the minimum width of fields. ### multi method min-table-width ``` multi method min-table-width() returns Prettier::Table::Constrains::NonNeg ``` Return the minimum desired table width, in characters. ### multi method min-table-width ``` multi method min-table-width( $val where { ... } ) returns Mu ``` Set the minimum desired table width, in characters. ### multi method max-table-width ``` multi method max-table-width() returns Mu ``` Return the maximum desired table width, in characters. ### multi method max-table-width ``` multi method max-table-width( $val where { ... } ) returns Mu ``` Set the minimum desired table width, in characters. ### multi method fields ``` multi method fields() returns Array ``` Return the list of field names to include in displays. ### multi method fields ``` multi method fields( @values ) returns Mu ``` Return the list of field names to include in displays. ### multi method title ``` multi method title() returns Str ``` Return the table title (if existent). ### multi method title ``` multi method title( Str $val ) returns Mu ``` Set the table title. ### multi method start ``` multi method start() returns Prettier::Table::Constrains::NonNeg ``` Return the start index of the range of rows to print. ### multi method start ``` multi method start( $val where { ... } ) returns Mu ``` Set the start index of the range of rows to print. ### multi method end ``` multi method end() returns Mu ``` Return the end index of the range of rows to print. ### multi method end ``` multi method end( $val ) returns Mu ``` Set the end index of the range of rows to print. ### multi method sort-by ``` multi method sort-by() returns Mu ``` Return the name of field by which to sort rows. ### multi method sort-by ``` multi method sort-by( Str $val where { ... } ) returns Mu ``` Set the name of field by which to sort rows. ### multi method reverse-sort ``` multi method reverse-sort() returns Bool ``` Return the direction of sorting, ascending (False) vs descending (True). ### multi method reverse-sort ``` multi method reverse-sort( Bool $val ) returns Nil ``` Set the direction of sorting (ascending (False) vs descending (True). ### multi method sort-key ``` multi method sort-key() returns Callable ``` Return the sorting key function, applied to data points before sorting. ### multi method sort-key ``` multi method sort-key( &val ) returns Nil ``` Set the sorting key function, applied to data points before sorting. ### multi method header ``` multi method header() returns Bool ``` Return whether the table has a heading showing the field names. ### multi method header ``` multi method header( Bool $val ) returns Nil ``` Set whether the table has a heading showing the field names. ### multi method header-style ``` multi method header-style() returns Prettier::Table::Constrains::HeaderStyle ``` Return style to apply to field names in header ("cap", "title", "upper", or "lower"). ### multi method header-style ``` multi method header-style( $val where { ... } ) returns Mu ``` Set style to apply to field names in header ("cap", "title", "upper", or "lower"). ### multi method border ``` multi method border() returns Bool ``` Return whether a border is printed around table. ### multi method border ``` multi method border( Bool $val ) returns Mu ``` Set whether a border is printed around table. ### multi method hrules ``` multi method hrules() returns Prettier::Table::Constrains::HorizontalRule ``` Return how horizontal rules are printed after rows. ### multi method hrules ``` multi method hrules( $val where { ... } ) returns Mu ``` Set how horizontal rules are printed after rows. Allowed values: FRAME, ALL, HEADER, NONE ### multi method vrules ``` multi method vrules() returns Prettier::Table::Constrains::VerticalRule ``` Return how vertical rules are printed between columns. ### multi method vrules ``` multi method vrules( $val where { ... } ) returns Mu ``` Set how vertical rules are printed between columns. Allowed values: FRAME, ALL, NONE ### multi method int-format ``` multi method int-format() returns Mu ``` Return how the integer data is formatted. ### multi method int-format ``` multi method int-format( $val ) returns Nil ``` Set how the integer data is formatted. The value can either be a string or a hash of field-to-format pairs. ### multi method float-format ``` multi method float-format() returns Mu ``` Return how the integer data is formatted. ### multi method float-format ``` multi method float-format( $val ) returns Nil ``` Set how the integer data is formatted. The value can either be a string or a hash of field-to-format pairs. ### multi method padding-width ``` multi method padding-width() returns Prettier::Table::Constrains::NonNeg ``` Return the number of empty spaces between a column's edge and its content. ### multi method padding-width ``` multi method padding-width( $val where { ... } ) returns Nil ``` Set the number of empty spaces between a column's edge and its content. ### multi method left-padding-width ``` multi method left-padding-width() returns Prettier::Table::Constrains::NonNeg ``` Return the number of empty spaces between a column's left edge and its content. ### multi method left-padding-width ``` multi method left-padding-width( $val where { ... } ) returns Nil ``` Set the number of empty spaces between a column's left edge and its content. ### multi method right-padding-width ``` multi method right-padding-width() returns Prettier::Table::Constrains::NonNeg ``` Return the number of empty spaces between a column's right edge and its content. ### multi method right-padding-width ``` multi method right-padding-width( $val where { ... } ) returns Nil ``` Set the number of empty spaces between a column's right edge and its content. ### multi method vertical-char ``` multi method vertical-char() returns Prettier::Table::Constrains::Char ``` Return character used when printing table borders to draw vertical lines. ### multi method vertical-char ``` multi method vertical-char( $val where { ... } ) returns Nil ``` Set character used when printing table borders to draw vertical lines. ### multi method horizontal-char ``` multi method horizontal-char() returns Prettier::Table::Constrains::Char ``` Return character used when printing table borders to draw horizontal lines. ### multi method horizontal-char ``` multi method horizontal-char( $val where { ... } ) returns Nil ``` Set character used when printing table borders to draw horizontal lines. ### multi method junction-char ``` multi method junction-char() returns Prettier::Table::Constrains::Char ``` Return character used when printing table borders to draw mid-line junctions. ### multi method junction-char ``` multi method junction-char( $val where { ... } ) returns Nil ``` Set character used when printing table borders to draw mid-line junctions. ### multi method left-junction-char ``` multi method left-junction-char() returns Prettier::Table::Constrains::Char ``` Return character used when printing table borders to draw left-edge line junctions. ### multi method left-junction-char ``` multi method left-junction-char( $val where { ... } ) returns Nil ``` Set character used when printing table borders to draw left-edge line junctions. ### multi method right-junction-char ``` multi method right-junction-char() returns Prettier::Table::Constrains::Char ``` Return character used when printing table borders to draw right-edge line junctions. ### multi method right-junction-char ``` multi method right-junction-char( $val where { ... } ) returns Nil ``` Set character used when printing table borders to draw right-edge line junctions. ### multi method top-junction-char ``` multi method top-junction-char() returns Prettier::Table::Constrains::Char ``` Return character used when printing table borders to draw top edge mid-line junctions. ### multi method top-junction-char ``` multi method top-junction-char( $val where { ... } ) returns Nil ``` Set character used when printing table borders to draw top edge mid-line junctions. ### multi method bottom-junction-char ``` multi method bottom-junction-char() returns Prettier::Table::Constrains::Char ``` Return character used when printing table borders to draw bottom edge mid-line junctions. ### multi method bottom-junction-char ``` multi method bottom-junction-char( $val where { ... } ) returns Nil ``` Set character used when printing table borders to draw bottom edge mid-line junctions. ### multi method bottom-left-corner-char ``` multi method bottom-left-corner-char() returns Prettier::Table::Constrains::Char ``` Return character used when printing table borders to draw bottem edge left corners. ### multi method bottom-left-corner-char ``` multi method bottom-left-corner-char( $val where { ... } ) returns Nil ``` Set character used when printing table borders to draw bottom edge left corners. ### multi method bottom-right-corner-char ``` multi method bottom-right-corner-char() returns Prettier::Table::Constrains::Char ``` Return character used when printing table borders to draw bottom right corners. ### multi method bottom-right-corner-char ``` multi method bottom-right-corner-char( $val where { ... } ) returns Nil ``` Set character used when printing table borders to draw bottom right corners. ### multi method top-left-corner-char ``` multi method top-left-corner-char() returns Prettier::Table::Constrains::Char ``` Return character used when printing table borders to draw top left corners. ### multi method top-left-corner-char ``` multi method top-left-corner-char( $val where { ... } ) returns Nil ``` Set character used when printing table borders to top left corners. ### multi method top-right-corner-char ``` multi method top-right-corner-char() returns Prettier::Table::Constrains::Char ``` Return character used when printing table borders to top right corners. ### multi method top-right-corner-char ``` multi method top-right-corner-char( $val where { ... } ) returns Nil ``` Set character used when printing table borders to draw top right corners. ### multi method format ``` multi method format() returns Bool ``` Return whether or not HTML tables are formatted to match styling options. ### multi method format ``` multi method format( Bool $val ) returns Nil ``` Set whether or not HTML tables are formatted to match styling options. ### multi method print-empty ``` multi method print-empty() returns Bool ``` Return whether or not empty tables produce a header and frame or just an empty string. ### multi method print-empty ``` multi method print-empty( Bool $val ) returns Nil ``` Set whether or not empty tables produce a header and frame or just an empty string. ### multi method old-sort-slice ``` multi method old-sort-slice() returns Bool ``` Return whether to slice rows before sorting in the "old style". ### multi method old-sort-slice ``` multi method old-sort-slice( Bool $val ) returns Nil ``` Return whether to slice rows before sorting in the "old style". ## Style of Table ### multi method set-style ``` multi method set-style( TableStyle $style ) returns Nil ``` Set the style to be used for the table. Allowed values: DEFAULT: Show header and border, hrules and vrules are FRAME and ALL respectively, paddings are 1, ASCII Box Drawing characters used for borders. MSWORD-FRIENDLY: Show header and border, hrules is NONE, paddings are 1, and vert. char is | MARKDOWN: GitHub Flavored Markdown table. - Removes title, only hrule below column headers, paddings are 1, and vert. char is | PLAIN-COLUMNS: Show header and hide border, hrules is NONE, padding is 1, left padding is 0, and right padding is 8 RANDOM: random style ### method set-default-style ``` method set-default-style() returns Nil ``` Single character string used to draw vertical lines. Single character string used to draw horizontal lines. Single character string used to draw line junctions. ### method set-markdown-style ``` method set-markdown-style() returns Nil ``` modifies border characters to produce markdown output ## Data Input Methods ### method add-row ``` method add-row( @row ) returns Nil ``` Add a row to the table. ## class Mu $ Row of data, should be a list with as many elements as the table has fields. ### method del-row ``` method del-row( Int $row-index ) returns Nil ``` Delete a row from the table. ## class Mu $ Index of the row to delete (0-based index). ### method add-column ``` method add-column( Str $fieldname, @column, $align where { ... } = "c", $valign where { ... } = "m" ) returns Nil ``` Add a column to the table. ## class Mu $ Name of the field to contain the new column of data. ## class Mu $ Column of data, should be a list with as many elements as the table has rows. ## class Mu $ Desired alignment for this column - "l" (left), "c" (center), and "r" (right). ## class Mu $ Desired vertical alignment for new columns - "t" (top), "m" (middle), and "b" (bottom). ### method clear-rows ``` method clear-rows() returns Nil ``` Delete all rows from the table but keep the current field names. ### method clear ``` method clear() returns Nil ``` Delete all rows and field names from the table, maintaining nothing but styling options. ## Plain Text String methods ### method get-string ``` method get-string( Str :$title = Str, :$start where { ... } = Prettier::Table::Constrains::NonNeg, :$end where { ... } = Prettier::Table::Constrains::NonNeg, :@fields, Bool :$header = Bool, Bool :$border = Bool, :$hrules where { ... } = Prettier::Table::Constrains::HorizontalRule, :$vrules where { ... } = Prettier::Table::Constrains::VerticalRule, Str :$int-format = Str, Str :$float-format = Str, :$padding-width where { ... } = Prettier::Table::Constrains::NonNeg, :$left-padding-width where { ... } = Prettier::Table::Constrains::NonNeg, :$right-padding-width where { ... } = Prettier::Table::Constrains::NonNeg, :$vertical-char where { ... } = Prettier::Table::Constrains::Char, :$horizontal-char where { ... } = Prettier::Table::Constrains::Char, :$junction-char where { ... } = Prettier::Table::Constrains::Char, :$left-junction-char where { ... } = Prettier::Table::Constrains::Char, :$right-junction-char where { ... } = Prettier::Table::Constrains::Char, :$top-junction-char where { ... } = Prettier::Table::Constrains::Char, :$bottom-junction-char where { ... } = Prettier::Table::Constrains::Char, :$bottom-left-corner-char where { ... } = Prettier::Table::Constrains::Char, :$bottom-right-corner-char where { ... } = Prettier::Table::Constrains::Char, :$top-left-corner-char where { ... } = Prettier::Table::Constrains::Char, :$top-right-corner-char where { ... } = Prettier::Table::Constrains::Char, Str :$sort-by = Str, :&sort-key, Bool :$reverse-sort = Bool, Bool :$old-sort-slice = Bool, Bool :$print-empty = Bool ) returns Str ``` Return string representation of table in current state. ## class Mu $ See method title ## class Mu $ See method start ## class Mu $ See method end ## class Mu $ See method fields ## class Mu $ See method header ## class Mu $ See method border ## class Mu $ See method hrules ## class Mu $ See method vrules ## class Mu $ See method int-format ## class Mu $ See method float-format ## class Mu $ See method padding-width ## class Mu $ See method left-padding-width ## class Mu $ See method right-padding-width ## class Mu $ See method vertical-char ## class Mu $ See method horizontal-char ## class Mu $ See method junction-char ## class Mu $ See method junction-char ## class Mu $ See method right-junction-char ## class Mu $ See method top-junction-char ## class Mu $ See method bottom-junction-char ## class Mu $ See method bottom-left-corner-char ## class Mu $ See method bottom-right-corner-char ## class Mu $ See method top-left-corner-char ## class Mu $ See method top-right-corner-char ## class Mu $ See method sort-by ## class Mu $ See method sort-key ## class Mu $ See method reverse-sort ## class Mu $ see method old-sort-slice ## class Mu $ See method print-empty ## Miscellaneous Methods ### method row-count ``` method row-count() returns Int ``` Return the number of rows. ### method col-count ``` method col-count() returns Int ``` Return the number of columns. ### method slice ``` method slice( *@indices ) returns Prettier::Table ``` Return a sliced-off new Prettier::Table. The indices must between 0 and the table's number of rows (exclusive). Alternatively, the postcircumfix operator [] can be used.
## channel.md class Channel Thread-safe queue for sending values from producers to consumers ```raku class Channel {} ``` A `Channel` is a thread-safe queue that helps you to send a series of objects from one or more producers to one or more consumers. Each object will arrive at only one such consumer, selected by the scheduler. If there is only one consumer and one producer, the order of objects is guaranteed to be preserved. Sending on a `Channel` is non-blocking. ```raku my $c = Channel.new; await (^10).map: { start { my $r = rand; sleep $r; $c.send($r); } } $c.close; say $c.list; ``` Further examples can be found in the [concurrency page](/language/concurrency#Channels) # [Methods](#class_Channel "go to top of document")[§](#Methods "direct link") ## [method send](#class_Channel "go to top of document")[§](#method_send "direct link") ```raku method send(Channel:D: \item) ``` Enqueues an item into the `Channel`. Throws an exception of type [`X::Channel::SendOnClosed`](/type/X/Channel/SendOnClosed) if the `Channel` has been closed already. This call will **not** block waiting for a consumer to take the object. There is no set limit on the number of items that may be queued, so care should be taken to prevent runaway queueing. ```raku my $c = Channel.new; $c.send(1); $c.send([2, 3, 4, 5]); $c.close; say $c.list; # OUTPUT: «(1 [2 3 4 5])␤» ``` ## [method receive](#class_Channel "go to top of document")[§](#method_receive "direct link") ```raku method receive(Channel:D:) ``` Receives and removes an item from the `Channel`. It blocks if no item is present, waiting for a `send` from another thread. Throws an exception of type [`X::Channel::ReceiveOnClosed`](/type/X/Channel/ReceiveOnClosed) if the `Channel` has been closed, and the last item has been removed already, or if `close` is called while `receive` is waiting for an item to arrive. If the `Channel` has been marked as erratic with method `fail`, and the last item has been removed, throws the argument that was given to `fail` as an exception. See method `poll` for a non-blocking version that won't throw exceptions. ```raku my $c = Channel.new; $c.send(1); say $c.receive; # OUTPUT: «1␤» ``` ## [method poll](#class_Channel "go to top of document")[§](#method_poll "direct link") ```raku method poll(Channel:D:) ``` Receives and removes an item from the `Channel`. If no item is present, returns [`Nil`](/type/Nil) instead of waiting. ```raku my $c = Channel.new; Promise.in(2).then: { $c.close; } ^10 .map({ $c.send($_); }); loop { if $c.poll -> $item { $item.say }; if $c.closed { last }; sleep 0.1; } ``` See method `receive` for a blocking version that properly responds to `Channel` closing and failure. ## [method close](#class_Channel "go to top of document")[§](#method_close "direct link") ```raku method close(Channel:D:) ``` Close the `Channel`, normally. This makes subsequent `send` calls die with [`X::Channel::SendOnClosed`](/type/X/Channel/SendOnClosed). Subsequent calls of `.receive` may still drain any remaining items that were previously sent, but if the queue is empty, will throw an [`X::Channel::ReceiveOnClosed`](/type/X/Channel/ReceiveOnClosed) exception. Since you can produce a [`Seq`](/type/Seq) from a `Channel` by contextualizing to array with `@()` or by calling the `.list` method, these methods will not terminate until the `Channel` has been closed. A [whenever](/language/concurrency#whenever)-block will also terminate properly on a closed `Channel`. ```raku my $c = Channel.new; $c.close; $c.send(1); CATCH { default { put .^name, ': ', .Str } }; # OUTPUT: «X::Channel::SendOnClosed: Cannot send a message on a closed channel␤» ``` Please note that any exception thrown may prevent `.close` from being called, this may hang the receiving thread. Use a [LEAVE](/language/phasers#LEAVE) phaser to enforce the `.close` call in this case. ## [method list](#class_Channel "go to top of document")[§](#method_list "direct link") ```raku method list(Channel:D:) ``` Returns a list based on the [`Seq`](/type/Seq) which will iterate items in the queue and remove each item from it as it iterates. This can only terminate once the `close` method has been called. ```raku my $c = Channel.new; $c.send(1); $c.send(2); $c.close; say $c.list; # OUTPUT: «(1 2)␤» ``` ## [method closed](#class_Channel "go to top of document")[§](#method_closed "direct link") ```raku method closed(Channel:D: --> Promise:D) ``` Returns a promise that will be kept once the `Channel` is closed by a call to method `close`. ```raku my $c = Channel.new; $c.closed.then({ say "It's closed!" }); $c.close; sleep 1; ``` ## [method fail](#class_Channel "go to top of document")[§](#method_fail "direct link") ```raku method fail(Channel:D: $error) ``` Closes the `Channel` (that is, makes subsequent `send` calls die), and enqueues the error to be thrown as the final element in the `Channel`. Method `receive` will throw that error as an exception. Does nothing if the `Channel` has already been closed or `.fail` has already been called on it. ```raku my $c = Channel.new; $c.fail("Bad error happens!"); $c.receive; CATCH { default { put .^name, ': ', .Str } }; # OUTPUT: «X::AdHoc: Bad error happens!␤» ``` ## [method Capture](#class_Channel "go to top of document")[§](#method_Capture "direct link") ```raku method Capture(Channel:D: --> Capture:D) ``` Equivalent to calling [`.List.Capture`](/type/List#method_Capture) on the invocant. ## [method Supply](#class_Channel "go to top of document")[§](#method_Supply "direct link") ```raku method Supply(Channel:D:) ``` This returns an `on-demand` [`Supply`](/type/Supply) that emits a value for every value received on the `Channel`. `done` will be called on the [`Supply`](/type/Supply) when the `Channel` is closed. ```raku my $c = Channel.new; my Supply $s1 = $c.Supply; my Supply $s2 = $c.Supply; $s1.tap(-> $v { say "First $v" }); $s2.tap(-> $v { say "Second $v" }); ^10 .map({ $c.send($_) }); sleep 1; ``` Multiple calls to this method produce multiple instances of Supply, which compete over the values from the `Channel`. ## [sub await](#class_Channel "go to top of document")[§](#sub_await "direct link") ```raku multi await(Channel:D) multi await(*@) ``` Waits until all of one or more `Channel`s has a value available, and returns those values (it calls `.receive` on the `Channel`). Also works with [`Promise`](/type/Promise)s. ```raku my $c = Channel.new; Promise.in(1).then({$c.send(1)}); say await $c; ``` Since 6.d, it no longer blocks a thread while waiting. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Channel` raku-type-graph Channel Channel Any Any Channel->Any Mu Mu Any->Mu [Expand chart above](/assets/typegraphs/Channel.svg)
## dist_zef-jjmerelo-Digest-HMAC.md # Raku-Digest-HMAC Fork from [@retupmoca's original](https://github.com/retupmoca/P6-Digest-HMAC) fixing some installation errors. ## Example Usage ``` use Digest::HMAC; use Digest; my Buf $hmac = hmac($key, $data, &md5); my Str $hmac = hmac-hex($key, $data, &md5); ``` ## Functions * `sub hmac-hex($key, $data, Callable &hash, $blocksize = 64 --> Str)` Returns the hex stringified output of hmac. * `sub hmac($key, $data, Callable &hash, $blocksize = 64 --> Buf)` Computes the HMAC of the passed information. `$key` and `$data` can either be Str or Blob objects; if they are Str they will be encoded as ascii. `&hash` needs to be a hash function that takes and returns a Blob or Buf. If it operates on or returns a Str, it will not work. (The md5, sha1, sha256 functions from Digest work well, as in the example above) `$blocksize` is the block size of the hash function. 64 is the default, and is correct for at least md5, sha1, sha256. ## See also Since version 0.28, [`Digest`](https://raku.land/zef:grondilu/Digest) also implements the HMAC algorithm, along with many others. You can use that one for a more complete range of digest methods.
## dist_zef-coke-rakudoc.md [![Build Status](https://travis-ci.com/Raku/rakudoc.svg?branch=master)](https://travis-ci.com/Raku/rakudoc) # NAME rakudoc - A tool for reading Raku documentation # SYNOPSIS ``` rakudoc [-d|--doc-sources=<Directories>] [-D|--no-default-docs] <query> rakudoc -b|--build-index [-d|--doc-sources=<Directories>] [-D|--no-default-docs] rakudoc -V|--version rakudoc -h|--help <ARGUMENTS> <query> Example: 'Map', 'IO::Path.add', '.add' -d|--doc-sources=<Directories> Additional directories to search for documentation -D|--no-default-docs Use only directories in --doc / $RAKUDOC -b|--build-index Index all documents found in doc source directories ``` # DESCRIPTION The `rakudoc` command displays Raku documentation for language features and installed modules. # ENVIRONMENT * `RAKUDOC` — Comma-separated list of doc directories (e.g., `../doc/doc,./t/test-doc`); ignored if `--doc-sources` option is given * `RAKUDOC_DATA` — Path to directory where Rakudoc stores cache and index data * `RAKUDOC_PAGER` — Pager program (default: `$PAGER`) # LICENSE Rakudoc is Copyright (C) 2019–2021, by Joel Schüller, Tim Siegel and others. It is free software; you can redistribute it and/or modify it under the terms of the [Artistic License 2.0](https://www.perlfoundation.org/artistic-license-20.html).
## dist_cpan-VRURG-Cro-RPC-JSON.md # NAME `Cro::RPC::JSON` - convenience shortcut for JSON-RPC 2.0 # SYNOPSIS ``` use Cro::HTTP::Server; use Cro::HTTP::Router; use Cro::RPC::JSON; class JRPC-Actor is export { method foo ( Int :$a, Str :$b ) is json-rpc { return "$b and $a"; } proto method bar (|) is json-rpc { * } multi method bar ( Str :$a! ) { "single named Str param" } multi method bar ( Int $i, Num $n, Str $s ) { "Int, Num, Str positionals" } multi method bar ( *%options ) { [ "slurpy hash:", %options ] } method non-json (|) { "I won't be called!" } } sub routes is export { route { post -> "api" { my $actor = JRPC-Actor.new; json-rpc $actor; } post -> "api2" { json-rpc -> Cro::RPC::JSON::Request $jrpc-req { { to-user => "a string", num => pi } } } } } ``` # DESCRIPTION This module provides a convenience shortcut for handling JSON-RPC requests by exporting `json-rpc` function to be used inside a [Cro::HTTP::Router](https://cro.services/docs/reference/cro-http-router) `post` handler. The function takes one argument which could either be a [`Code`](https://docs.perl6.org/type/Code.html) object or an instantiated class. When code object is used: ``` json-rpc -> $jrpc-request { ... } sub jrpc-handler ( Cro::RPC::JSON::Request $jrpc-request ) { ... } json-rpc -> &jrpc-handler; ``` it is supplied with parsed JSON-RPC request (`Cro::RPC::JSON::Request`). When a class instance is used a JSON-RPC call is mapped on a class method with the same name as in RPC request. The class method must have `is json-rpc` trait applied (see [SYNOPSIS](#SYNOPSIS) example). Methods without the trait are not considered part of JSON-RPC API and calling such method would return -32601 error code back to the caller. The class implementing the API is called *JSON-RPC actor class* or just *actor*. If the only parameter of a JSON-RPC method has `Cro::RPC::JSON::Request` type then the method will receive the JSON-RPC request object as parameter. Otherwise `params` object of JSON-RPC request is used and matched against actor class method signature. If `params` is an object then it is considered a set of named parameters. If it's an array then all params are passed as positionals. For example: ``` params => { a => 1, b => "aa" } ``` will match to ``` method foo ( Int :$a, Str :$b ) { ... } ``` Whereas ``` params => [ 1, "aa" ] ``` will match to ``` method foo( Int $a, Str $b ) { ... } ``` If parameters fail to match to the method signature then -32601 error would be returned. To handle various set of parameters one could use either slurpy parameters or `multi` methods. In second case the `is json-rpc` trait must be applied to method's `proto` declaration. **NOTE** that `multi` method cannot have the request object as a parameter. This is due to possible ambiguity in a situation when there is a match to one `multi` candidate by parameters and by the request object to another. # SEE ALSO [Cro](https://cro.services) # AUTHOR Vadim Belman [[email protected]](mailto:[email protected]) # LICENSE Artistic License 2.0 See the LICENSE file in this distribution.
## dist_cpan-MORITZ-Math-Model.md `Math::Model` lets you write mathematical and physical models in an easy and natural way. Please see <https://perlgeek.de/blog-en/perl-6/physical-modelling.html> for a longer description and tutorial. This module may be used under the terms of the [Artistic License 2.0](https://opensource.org/licenses/Artistic-2.0). Its accompanying tests and examples are public domain, as defined by the [CC0 1.0 Universal (CC0 1.0) Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/).
## dist_cpan-TIMOTIMO-App-MoarVM-ConfprogCompiler.md [![Build Status](https://travis-ci.org/timo/App-MoarVM-ConfprogCompiler.svg?branch=master)](https://travis-ci.org/timo/App-MoarVM-ConfprogCompiler) # NAME App::MoarVM::ConfprogCompiler - Compiler for MoarVM's confprog subsystem # SYNOPSIS ``` use App::MoarVM::ConfprogCompiler; ConfprogCompiler.compile($sourcecode); ``` ``` confprog-compile -e="version = 1; entry profiler_static: profile = choice(1, 2, 3, 4); log = "hello";' -o=example.mvmconfprog perl6 --confprog=example.mvmconfprog --profile -e '.say for (^100_000).grep(*.is-prime).tail(5)' ``` # DESCRIPTION `App::MoarVM::ConfprogCompiler` will parse a domain-specific language for defining the behavior of specific pluggable moarvm subsystems, such as the instrumented or heapsnapshot profiler. A commandline utility named `confprog-compile` is provided that takes a program as a filename or a literal string and outputs a hexdump (compatible with xxd -r) or to an output file passed on the commandline. # AUTHOR Timo Paulssen [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2019 Timo Paulssen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## chrs.md chrs Combined from primary sources listed below. # [In Nil](#___top "go to top of document")[§](#(Nil)_method_chrs "direct link") See primary documentation [in context](/type/Nil#method_chrs) for **method chrs**. Will return `\0`, and also throw a warning. # [In Cool](#___top "go to top of document")[§](#(Cool)_routine_chrs "direct link") See primary documentation [in context](/type/Cool#routine_chrs) for **routine chrs**. ```raku sub chrs(*@codepoints --> Str:D) method chrs() ``` Coerces the invocant (or in the sub form, the argument list) to a list of integers, and returns the string created by interpreting each integer as a Unicode codepoint, and joining the characters. ```raku say <67 97 109 101 108 105 97>.chrs; # OUTPUT: «Camelia␤» ``` This is the list-input version of [chr](/routine/chr). The inverse operation is [ords](/routine/ords).
## -item-assignment-.md = (item assignment) Combined from primary sources listed below. # [In Operators](#___top "go to top of document")[§](#(Operators)_infix_=_(item_assignment) "direct link") See primary documentation [in context](/language/operators#infix_=_(item_assignment)) for **infix = (item assignment)**. ```raku sub infix:<=>(Mu $a is rw, Mu $b) ``` Called the *item assignment operator*. It copies the value of the right-hand side into the Scalar container on the left-hand side. The item assignment operator should be distinguished from the [list assignment operator](#infix_=_(list_assignment)), which uses the same operator symbol `=` but has a lower precedence. The context of the left-hand side of the `=` symbol determines whether it is parsed as item assignment or list assignment. See the section on [item and list assignment](/language/variables#Item_and_list_assignment) for a comparative discussion of the two assignment types.
## earlier.md earlier Combined from primary sources listed below. # [In role Dateish](#___top "go to top of document")[§](#(role_Dateish)_method_earlier "direct link") See primary documentation [in context](/type/Dateish#method_earlier) for **method earlier**. ```raku multi method earlier(Dateish:D: *%unit) multi method earlier(Dateish:D: @pairs) ``` Returns an object based on the current one, but with a date delta towards the past applied. Unless the given unit is `second` or `seconds`, the given value will be converted to an [`Int`](/type/Int). See [`.later`](/type/Dateish#method_later) for usage. It will generally be used through classes that implement this role, [`Date`](/type/Date) or [`DateTime`](/type/DateTime) ```raku my $d = Date.new('2015-02-27'); say $d.earlier(month => 5).earlier(:2days); # OUTPUT: «2014-09-25␤» my $d = DateTime.new(date => Date.new('2015-02-27')); say $d.earlier(month => 1).earlier(:2days); # OUTPUT: «2015-01-25T00:00:00Z␤» ``` If the resultant time has value `60` for seconds, yet no leap second actually exists for that time, seconds will be set to `59`: ```raku say DateTime.new('2008-12-31T23:59:60Z').earlier: :1day; # OUTPUT: «2008-12-30T23:59:59Z␤» ``` Negative offsets are allowed, though [later](/routine/later) is more idiomatic for that. If you need to use more than one unit, you will need to build them into a [`List`](/type/List) of [`Pair`](/type/Pair)s to use the second form of the method: ```raku say Date.new('2021-03-31').earlier( ( year => 3, month => 2, day => 8 ) ); # OUTPUT: «2018-01-23␤» ``` This feature was introduced in release 2021.02 of the Rakudo compiler.
## dist_zef-bduggan-Map-DeckGL.md [![Actions Status](https://github.com/bduggan/raku-map-deckgl/actions/workflows/linux.yml/badge.svg)](https://github.com/bduggan/raku-map-deckgl/actions/workflows/linux.yml) [![Actions Status](https://github.com/bduggan/raku-map-deckgl/actions/workflows/macos.yml/badge.svg)](https://github.com/bduggan/raku-map-deckgl/actions/workflows/macos.yml) # NAME Map::DeckGL - Generate maps using deck.gl # SYNOPSIS Put some text on a map: ``` use Map::DeckGL; my $deck = Map::DeckGL.new: initialViewState => zoom => 10; $deck.add-text: 40.7128, -74.0060, "Hello, World!"; my @boroughs = [ 40.6782, -73.9442, 'Brooklyn', [255, 0, 0], 40.7831, -73.9712, 'Manhattan', [100, 200, 155], 40.7282, -73.7949, 'Queens', [0, 255, 0], 40.8448, -73.8648, 'Bronx', [255, 255, 0], 40.5795, -74.1502, 'Staten Island', [255, 0, 255], ]; for @boroughs -> $lat, $lng, $name, $color { $deck.add-text: $lat, $lng, $name, color => $color, size => 10, backgroundColor => $color, sizeScale => 0.4, backgroundPadding => [10, 5, 10, 5], getBorderColor => [0, 0, 0], getBorderWidth => 2; } $deck.show; ``` ![img](https://github.com/user-attachments/assets/76a771cd-2337-4858-bfc0-0dca80a0d783) Put some some icons and geojson on a map: ``` use Map::DeckGL; my $map = Map::DeckGL.new: initialViewState => %( :pitch(75), :zoom(17) ); my %geojson = type => 'FeatureCollection', features => [ { type => 'Feature', geometry => { type => 'Polygon', coordinates => [ [ [-73.986454, 40.757722], [-73.986454, 40.758146], [-73.986129, 40.758146], [-73.986129, 40.757722], [-73.986454, 40.757722], ], ], }, }, ]; $map.add-geojson: %geojson, getFillColor => [19, 126, 109, 255], getLineColor => [126, 19, 109, 255]; $map.add-icon: 40.757722, -73.986454, getSize => f => 100; $map.add-text: 40.757722, -73.986454, 'times square', backgroundColor => [255, 255, 255, 100], getBorderColor => [0, 0, 0], getBorderWidth => 2; $map.show; ``` ![img](https://github.com/user-attachments/assets/cf7e5dfd-288e-4865-9ee6-d3dcdea62a9c) # DESCRIPTION This module provides an interface to generate HTML and Javascript to render a map using the deck.gl javascript library. After creating a `Map::DeckGL` object, you can add layers to it using `add-geojson`, `add-icon`, and `add-text` methods. This adds respectively, a GeoJsonLayer, an IconLayer, and a TextLayer. The `render` method will return the HTML and Javascript to render the map. Alternatively, layers can be generated directly by using classes which correspond to the DeckGL classes, and added via the `add-layer` method. # EXPORTS If an argument is given to the module, a new `Map::DeckGL` object is created and returned with that name. e.g. ``` use Map::DeckGL 'deck'; deck.add-text: 40.7128, -74.0060, "Hello, World! ``` is equivalent to ``` use Map::DeckGL; my $deck = Map::DeckGL.new; $deck.add-text: 40.7128, -74.0060, "Hello, World! ``` # METHODS ## method add-geojson ``` $map.add-geojson: %geojson, getFillColor => [255,0,0,128], getLineColor => [0,255,0,255]; ``` Add a GeoJsonLayer to the map. The first argument is a hash representing the GeoJson data. The remaining arguments are options to the GeoJsonLayer constructor. They correspond to the properties of the javascript object which can be found in the deck.gl documentation: <https://deck.gl/docs/api-reference/layers/geojson-layer> ## method add-icon ``` $map.add-icon: 40.757722, -73.986454; $map.add-icon: lat => 40.757722, lon => -73.986454; $map.add-icon: lat => 40.757722, lon => -73.986454, iconAtlas => 'https://example.com/icon-atlas.png'; ``` Add an IconLayer to the map. The first two arguments are the latitude and longitude of the icon. The remaining arguments are options to the IconLayer constructor. They correspond to the properties of the javascript object which can be found in the deck.gl documentation: <https://deck.gl/docs/api-reference/layers/icon-layer> ## method add-text ``` $map.add-text: 40.757722, -73.986454, 'times square'; $map.add-text: lat => 40.757722, lon => -73.986454, text => 'times square'; $deck.add-text: 40.6782, -73.9442, "Brooklyn", color => [255, 0, 0], size => 10, backgroundColor => [0, 128, 0], sizeScale => 0.4, backgroundPadding => [10, 5, 10, 5], getBorderColor => [0, 0, 0], getBorderWidth => 2; ``` Add a TextLayer to the map. The first two arguments are the latitude and longitude of the text. The remaining arguments are options to the TextLayer constructor. They correspond to the properties of the javascript object which can be found in the deck.gl documentation: <https://deck.gl/docs/api-reference/layers/text-layer> ## method add-layer ``` my $layer = Map::DeckGL::IconLayer.new: getPosition => [40.757722, -73.986454]; $map.add-layer($layer); ``` Add a layer to the map. The argument should be an object of a class which corresponds to a deck.gl layer. ## method render ``` spurt 'out.html', $map.render; ``` Return the HTML and Javascript to render the map. ## method write ``` $map.write; ``` Write the HTML and Javascript to a file. The default filename is 'map-deck-gl-tmp.html'. Returns true if the file was created, false if it already existed. ## method show ``` $map.show; ``` Write the HTML and Javascript to a file, and open it in a browser. # ATTRIBUTES ## output-path Where to write the file when calling `write`. Defaults to 'map-deck-gl-tmp.html'. ## mapStyle Defaults to 'https://basemaps.cartocdn.com/gl/positron-nolabels-gl-style/style.json' ## initialViewState Override the calculated view state. This is a hash with keys `longitude`, `latitude`, `zoom`, `pitch`, and `bearing`. If this is omitted, the bounds are calculated from the layers. Any options here will override the calculated values. ## fit-bounds-opts ``` my $map = Map::DeckGL.new(fit-bounds-opts => { padding => 100 }); ``` Options to pass to the `fitBounds` method. See the deck.gl documentation for details. # SEE ALSO The deck.gl documentation: <https://deck.gl>. Also please check out the examples in the eg/ directory of this distribution, as well as `Map::DeckGL::Layers` for a comprehensive list of available layers and their attributes. # AUTHOR Brian Duggan
## dist_zef-lizmat-allow-no.md [![Actions Status](https://github.com/lizmat/allow-no/actions/workflows/test.yml/badge.svg)](https://github.com/lizmat/allow-no/actions) # NAME allow-no - provide %\*SUB-MAIN-OPTS for older Rakudos # SYNOPSIS ``` use allow-no; sub MAIN(:$foo, :$bar) { # calling script with --foo, --no-bar say $foo; # True say $bar; # False } ``` # DESCRIPTION The `allow-no` module provides functionality that has been provided by Rakudo 2022.08 and higher: it allows command line parameters to indicate a `False` flag to be specified as `--no-foo` as well as the standard allowed `--/foo` or `--foo-False`. Using this module will run an INIT block that will perform the necessary transformation on `@*ARGS`. No further action or configuration is needed. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/allow-no> . 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 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## withoutobject.md class X::Syntax::Self::WithoutObject Compilation error due to invoking `self` in an ineligible scope ```raku class X::Syntax::Self::WithoutObject does X::Syntax { } ``` Syntax error thrown when `self` is referenced in a place where no invocant is available. For example ```raku self; ``` outside a class or role declaration dies with 「text」 without highlighting ``` ``` ===SORRY!=== 'self' used where no object is available ``` ```
## dist_cpan-KAIEPI-Data-Record.md ![Build Status](https://github.com/Kaiepi/ra-Data-Record/actions/workflows/test.yml/badge.svg) # NAME Data::Record - Record types! # SYNOPSIS ``` use Data::Record; # Data::Record introduces record types for maps, lists, and tuples: my constant Schema = {@ name => Str:D, items => [@ <@ Int:D, Str:D @> @] @} :name('Schema'); # With the type we just made, we can typecheck data structures to ensure they # match it: my %valid = name => 'Kaiepi', items => [(1, 'Item 1'), (2, 'Item 2')]; my %invalid = name => 'Mrofnet', items => [], constructor => 'Thanks, JavaScript.'; say %valid ~~ Schema; # OUTPUT: True say %invalid ~~ Schema; # OUTPUT: False # ...but typechecking this way is inefficient, and is always done eagerly! # Using the (<<), (>>), (<>), and (><) operators provided, data can be coerced # to our record type by various means: %valid := %valid (><) Schema; %invalid := %invalid (<<) Schema; say %invalid; # OUTPUT: {items => [], name => Mrofnet} # For the most part, coerced data can be used the same way as the original # data, with the bonus of extra typechecking: { CATCH { default { say .^name } } %invalid<items>.push: (3, 'Item 3'); # OK! %invalid<items>.push: "OOPSIE WOOPSIE OwO"; # OUTPUT: X::Data::Record::TypeCheck } # Finally, to restore the data's original typing, simply call the unrecord # method on it: my %now-valid := %invalid.unrecord; say %now-valid.^name; # OUTPUT: Hash say %now-valid<items>.^name; # OUTPUT: Array say %now-valid<items>[0].^name; # OUTPUT: List ``` # DESCRIPTION `Data::Record` is a library that adds support for record types to Raku. Operators for creating record types for maps, lists, and tuples are included. Data structures can then be coerced to these record types using the coercion operators provided, some of which will sanitize them, all of which allow for efficient typechecking for common operations you can do with them. For documentation on how this library can be used, refer to the [wiki](https://github.com/Kaiepi/p6-Data-Record/wiki/). # AUTHOR Ben Davies (Kaiepi) # COPYRIGHT AND LICENSE Copyright 2020 Ben Davies This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## grammar-tutorial.md Grammar tutorial An introduction to grammars # [Before we start](#Grammar_tutorial "go to top of document")[§](#Before_we_start "direct link") ## [Why grammars?](#Grammar_tutorial "go to top of document")[§](#Why_grammars? "direct link") Grammars parse strings and return data structures from those strings. Grammars can be used to prepare a program for execution, to determine if a program can run at all (if it's a valid program), to break down a web page into constituent parts, or to identify the different parts of a sentence, among other things. ## [When would I use grammars?](#Grammar_tutorial "go to top of document")[§](#When_would_I_use_grammars? "direct link") If you have strings to tame or interpret, grammars provide the tools to do the job. The string could be a file that you're looking to break into sections; perhaps a protocol, like SMTP, where you need to specify which "commands" come after what user-supplied data; maybe you're designing your own domain specific language. Grammars can help. ## [The broad concept of grammars](#Grammar_tutorial "go to top of document")[§](#The_broad_concept_of_grammars "direct link") Regular expressions ([Regexes](/language/regexes)) work well for finding patterns in strings. However, for some tasks, like finding multiple patterns at once, or combining patterns, or testing for patterns that may surround strings regular expressions, alone, are not enough. When working with HTML, you could define a grammar to recognize HTML tags, both the opening and closing elements, and the text in between. You could then organize these elements into data structures, such as arrays or hashes. # [Getting more technical](#Grammar_tutorial "go to top of document")[§](#Getting_more_technical "direct link") ## [The conceptual overview](#Grammar_tutorial "go to top of document")[§](#The_conceptual_overview "direct link") Grammars are a special kind of class. You declare and define a grammar exactly as you would any other class, except that you use the *grammar* keyword instead of *class*. ```raku grammar G { ... } ``` As such classes, grammars are made up of methods that define a regex, a token, or a rule. These are all varieties of different types of match methods. Once you have a grammar defined, you call it and pass in a string for parsing. ```raku my $matchObject = G.parse($string); ``` Now, you may be wondering, if I have all these regexes defined that just return their results, how does that help with parsing strings that may be ahead or backwards in another string, or things that need to be combined from many of those regexes... And that's where grammar actions come in. For every "method" you match in your grammar, you get an action you can use to act on that match. You also get an overarching action that you can use to tie together all your matches and to build a data structure. This overarching method is called `TOP` by default. ## [The technical overview](#Grammar_tutorial "go to top of document")[§](#The_technical_overview "direct link") As already mentioned, grammars are declared using the *grammar* keyword and its "methods" are declared with *regex*, or *token*, or *rule*. * Regex methods are slow but thorough, they will look back in the string and really try. * Token methods are faster than regex methods and ignore whitespace. Token methods don't backtrack; they give up after the first possible match. * Rule methods are the same as token methods except whitespace is not ignored. When a method (regex, token or rule) matches in the grammar, the string matched is put into a [match object](/type/Match) and keyed with the same name as the method. ```raku grammar G { token TOP { <thingy> .* } token thingy { 'clever_text_keyword' } } ``` If you were to use `my $match = G.parse($string)` and your string started with 'clever\_text\_keyword', you would get a match object back that contained 'clever\_text\_keyword' keyed by the name of `<thingy>` in your match object. For instance: ```raku grammar G { token TOP { <thingy> .* } token thingy { 'Þor' } } my $match = G.parse("Þor is mighty"); say $match.raku; # OUTPUT: «Match.new(made => Any, pos => 13, orig => "Þor is mighty",...» say $/.raku; # OUTPUT: «Match.new(made => Any, pos => 13, orig => "Þor is mighty",...» say $/<thingy>.raku; # OUTPUT: «Match.new(made => Any, pos => 3, orig => "Þor is mighty", hash => Map.new(()), list => (), from => 0)␤» ``` The two first output lines show that `$match` contains a [`Match`](/type/Match) object with the results of the parsing; but those results are also assigned to the [match variable `$/`](/syntax/$$SOLIDUS). Either match object can be keyed, as indicated above, by `thingy` to return the match for that particular `token`. The `TOP` method (whether regex, token, or rule) is the overarching pattern that must match everything (by default). If the parsed string doesn't match the TOP regex, your returned match object will be empty ([`Nil`](/type/Nil)). As you can see above, in `TOP`, the `<thingy>` token is mentioned. The `<thingy>` is defined on the next line. That means that `'clever_text_keyword'` **must** be the first thing in the string, or the grammar parse will fail and we'll get an empty match. This is great for recognizing a malformed string that should be discarded. # [Learning by example - a REST contrivance](#Grammar_tutorial "go to top of document")[§](#Learning_by_example_-_a_REST_contrivance "direct link") Let's suppose we'd like to parse a URI into the component parts that make up a RESTful request. We want the URIs to work like this: * The first part of the URI will be the "subject", like a part, or a product, or a person. * The second part of the URI will be the "command", the standard CRUD functions (create, retrieve, update, or delete). * The third part of the URI will be arbitrary data, perhaps the specific ID we'll be working with or a long list of data separated by "/"'s. * When we get a URI, we'll want 1-3 above to be placed into a data structure that we can easily work with (and later enhance). So, if we have "/product/update/7/notify", we would want our grammar to give us a match object that has a `subject` of "product", a `command` of "update", and `data` of "7/notify". We'll start by defining a grammar class and some match methods for the subject, command, and data. We'll use the token declarator since we don't care about whitespace. ```raku grammar REST { token subject { \w+ } token command { \w+ } token data { .* } } ``` So far, this REST grammar says we want a subject that will be just *word* characters, a command that will be just *word* characters, and data that will be everything else left in the string. Next, we'll want to arrange these matching tokens within the larger context of the URI. That's what the TOP method allows us to do. We'll add the TOP method and place the names of our tokens within it, together with the rest of the patterns that makes up the overall pattern. Note how we're building a larger regex from our named regexes. ```raku grammar REST { token TOP { '/' <subject> '/' <command> '/' <data> } token subject { \w+ } token command { \w+ } token data { .* } } ``` With this code, we can already get the three parts of our RESTful request: ```raku my $match = REST.parse('/product/update/7/notify'); say $match; # OUTPUT: «「/product/update/7/notify」␤ # subject => 「product」 # command => 「update」 # data => 「7/notify」» ``` The data can be accessed directly by using `$match<subject>` or `$match<command>` or `$match<data>` to return the values parsed. They each contain match objects that you can work further with, such as coercing into a string ( `$match<command>.Str` ). ## [Adding some flexibility](#Grammar_tutorial "go to top of document")[§](#Adding_some_flexibility "direct link") So far, the grammar will handle retrieves, deletes and updates. However, a *create* command doesn't have the third part (the *data* portion). This means the grammar will fail to match if we try to parse a create URI. To avoid this, we need to make that last *data* position match optional, along with the '/' preceding it. This is accomplished by adding a question mark to the grouped '/' and *data* components of the TOP token, to indicate their optional nature, just like a normal regex. So, now we have: ```raku grammar REST { token TOP { '/' <subject> '/' <command> [ '/' <data> ]? } token subject { \w+ } token command { \w+ } token data { .* } } my $m = REST.parse('/product/create'); say $m<subject>, $m<command>; # OUTPUT: «「product」「create」␤» ``` Next, assume that the URIs will be entered manually by a user and that the user might accidentally put spaces between the '/'s. If we wanted to accommodate for this, we could replace the '/'s in TOP with a token that allowed for spaces. ```raku grammar REST { token TOP { <slash><subject><slash><command>[<slash><data>]? } token subject { \w+ } token command { \w+ } token data { .* } token slash { \s* '/' \s* } } my $m = REST.parse('/ product / update /7 /notify'); say $m; # OUTPUT: «「/ product / update /7 /notify」␤ # slash => 「/ 」 # subject => 「product」 # slash => 「 / 」 # command => 「update」 # slash => 「 /」 # data => 「7 /notify」» ``` We're getting some extra junk in the match object now, with those slashes. There are techniques to clean that up that we'll get to later. ## [Inheriting from a grammar](#Grammar_tutorial "go to top of document")[§](#Inheriting_from_a_grammar "direct link") Since grammars are classes, they behave, OOP-wise, in the same way as any other class; specifically, they can inherit from base classes that include some tokens or rules, this way: ```raku grammar Letters { token letters { \w+ } } grammar Quote-Quotes { token quote { "\"" | "`" | "'" } } grammar Quote-Other { token quote { "|" | "/" | "¡" } } grammar Quoted-Quotes is Letters is Quote-Quotes { token TOP { ^ <quoted> $} token quoted { <quote>? <letters> <quote>? } } grammar Quoted-Other is Letters is Quote-Other { token TOP { ^ <quoted> $} token quoted { <quote>? <letters> <quote>? } } my $quoted = q{"enhanced"}; my $parsed = Quoted-Quotes.parse($quoted); say $parsed; # OUTPUT: #「"enhanced"」 # quote => 「"」 # letters => 「enhanced」 #quote => 「"」 $quoted = "|barred|"; $parsed = Quoted-Other.parse($quoted); say $parsed; # OUTPUT: #|barred|」 #quote => 「|」 #letters => 「barred」 #quote => 「|」 ``` This example uses multiple inheritance to compose two different grammars by varying the rules that correspond to `quotes`. In this case, besides, we are rather using composition than inheritance, so we could use Roles instead of inheritance. ```raku role Letters { token letters { \w+ } } role Quote-Quotes { token quote { "\"" | "`" | "'" } } role Quote-Other { token quote { "|" | "/" | "¡" } } grammar Quoted-Quotes does Letters does Quote-Quotes { token TOP { ^ <quoted> $} token quoted { <quote>? <letters> <quote>? } } grammar Quoted-Other does Letters does Quote-Other { token TOP { ^ <quoted> $} token quoted { <quote>? <letters> <quote>? } } ``` Will output exactly the same as the code above. Symptomatic of the difference between Classes and Roles, a conflict like defining `token quote` twice using Role composition will result in an error: ```raku grammar Quoted-Quotes does Letters does Quote-Quotes does Quote-Other { ... } # OUTPUT: ... Error while compiling ... Method 'quote' must be resolved ... ``` ## [Adding some constraints](#Grammar_tutorial "go to top of document")[§](#Adding_some_constraints "direct link") We want our RESTful grammar to allow for CRUD operations only. Anything else we want to fail to parse. That means our "command" above should have one of four values: create, retrieve, update or delete. There are several ways to accomplish this. For example, you could change the command method: ```raku token command { \w+ } # …becomes… token command { 'create'|'retrieve'|'update'|'delete' } ``` For a URI to parse successfully, the second part of the string between '/'s must be one of those CRUD values, otherwise the parsing fails. Exactly what we want. There's another technique that provides greater flexibility and improved readability when options grow large: *proto-regexes*. To utilize these proto-regexes (multimethods, in fact) to limit ourselves to the valid CRUD options, we'll replace `token command` with the following: ```raku proto token command {*} token command:sym<create> { <sym> } token command:sym<retrieve> { <sym> } token command:sym<update> { <sym> } token command:sym<delete> { <sym> } ``` The `sym` keyword is used to create the various proto-regex options. Each option is named (e.g., `sym<update>`), and for that option's use, a special `<sym>` token is auto-generated with the same name. The `<sym>` token, as well as other user-defined tokens, may be used in the proto-regex option block to define the specific *match condition*. Regex tokens are compiled forms and, once defined, cannot subsequently be modified by adverb actions (e.g., `:i`). Therefore, as it's auto-generated, the special `<sym>` token is useful only where an exact match of the option name is required. If, for one of the proto-regex options, a match condition occurs, then the whole proto's search terminates. The matching data, in the form of a match object, is assigned to the parent proto token. If the special `<sym>` token was employed and formed all or part of the actual match, then it's preserved as a sub-level in the match object, otherwise it's absent. Using proto-regex like this gives us a lot of flexibility. For example, instead of returning `<sym>`, which in this case is the entire string that was matched, we could instead enter our own string, or do other funny stuff. We could do the same with the `token subject` method and limit it also to only parsing correctly on valid subjects (like 'part' or 'people', etc.). ## [Putting our RESTful grammar together](#Grammar_tutorial "go to top of document")[§](#Putting_our_RESTful_grammar_together "direct link") This is what we have for processing our RESTful URIs, so far: ```raku grammar REST { token TOP { <slash><subject><slash><command>[<slash><data>]? } proto token command {*} token command:sym<create> { <sym> } token command:sym<retrieve> { <sym> } token command:sym<update> { <sym> } token command:sym<delete> { <sym> } token subject { \w+ } token data { .* } token slash { \s* '/' \s* } } ``` Let's look at various URIs and see how they work with our grammar. ```raku my @uris = ['/product/update/7/notify', '/product/create', '/item/delete/4']; for @uris -> $uri { my $m = REST.parse($uri); say "Sub: $m<subject> Cmd: $m<command> Dat: $m<data>"; } # OUTPUT: «Sub: product Cmd: update Dat: 7/notify␤ # Sub: product Cmd: create Dat: ␤ # Sub: item Cmd: delete Dat: 4␤» ``` Note that since `<data>` matches nothing on the second string, `$m<data>` will be [`Nil`](/type/Nil), then using it in string context in the `say` function warns. With just this part of a grammar, we're getting almost everything we're looking for. The URIs get parsed and we get a data structure with the data. The *data* token returns the entire end of the URI as one string. The 4 is fine. However from the '7/notify', we only want the 7. To get just the 7, we'll use another feature of grammar classes: *actions*. # [Grammar actions](#Grammar_tutorial "go to top of document")[§](#Grammar_actions "direct link") Grammar actions are used within grammar classes to do things with matches. Actions are defined in their own classes, distinct from grammar classes. You can think of grammar actions as a kind of plug-in expansion module for grammars. A lot of the time you'll be happy using grammars all by their own. But when you need to further process some of those strings, you can plug in the Actions expansion module. To work with actions, you use a named parameter called `actions` which should contain an instance of your actions class. With the code above, if our actions class called REST-actions, we would parse the URI string like this: ```raku my $matchObject = REST.parse($uri, actions => REST-actions.new); # …or if you prefer… my $matchObject = REST.parse($uri, :actions(REST-actions.new)); ``` If you *name your action methods with the same name as your grammar methods* (tokens, regexes, rules), then when your grammar methods match, your action method with the same name will get called automatically. The method will also be passed the corresponding match object (represented by the `$/` variable). Let's turn to an example. ## [Grammars by example with actions](#Grammar_tutorial "go to top of document")[§](#Grammars_by_example_with_actions "direct link") Here we are back to our grammar. ```raku grammar REST { token TOP { <slash><subject><slash><command>[<slash><data>]? } proto token command {*} token command:sym<create> { <sym> } token command:sym<retrieve> { <sym> } token command:sym<update> { <sym> } token command:sym<delete> { <sym> } token subject { \w+ } token data { .* } token slash { \s* '/' \s* } } ``` Recall that we want to further process the data token "7/notify", to get the 7. To do this, we'll create an action class that has a method with the same name as the named token. In this case, our token is named `data` so our method is also named `data`. ```raku class REST-actions { method data($/) { $/.split('/') } } ``` Now when we pass the URI string through the grammar, the *data token match* will be passed to the *REST-actions' data method*. The action method will split the string by the '/' character and the first element of the returned list will be the ID number (7 in the case of "7/notify"). But not really; there's a little more. ## [Keeping grammars with actions tidy with `make` and `made`](#Grammar_tutorial "go to top of document")[§](#Keeping_grammars_with_actions_tidy_with_make_and_made "direct link") If the grammar calls the action above on data, the data method will be called, but nothing will show up in the big `TOP` grammar match result returned to our program. In order to make the action results show up, we need to call [make](/routine/make) on that result. The result can be many things, including strings, array or hash structures. You can imagine that the `make` places the result in a special contained area for a grammar. Everything that we `make` can be accessed later by [made](/routine/made). So instead of the REST-actions class above, we should write: ```raku class REST-actions { method data($/) { make $/.split('/') } } ``` When we add `make` to the match split (which returns a list), the action will return a data structure to the grammar that will be stored separately from the `data` token of the original grammar. This way, we can work with both if we need to. If we want to access just the ID of 7 from that long URI, we access the first element of the list returned from the `data` action that we `made`: ```raku my $uri = '/product/update/7/notify'; my $match = REST.parse($uri, actions => REST-actions.new); say $match<data>.made[0]; # OUTPUT: «7␤» say $match<command>.Str; # OUTPUT: «update␤» ``` Here we call `made` on data, because we want the result of the action that we `made` (with `make`) to get the split array. That's lovely! But, wouldn't it be lovelier if we could `make` a friendlier data structure that contained all of the stuff we want, rather than having to coerce types and remember arrays? Just like Grammar's `TOP`, which matches the entire string, actions have a TOP method as well. We can `make` all of the individual match components, like `data` or `subject` or `command`, and then we can place them in a data structure that we will `make` in TOP. When we return the final match object, we can then access this data structure. To do this, we add the method `TOP` to the action class and `make` whatever data structure we like from the component pieces. So, our action class becomes: ```raku class REST-actions { method TOP ($/) { make { subject => $<subject>.Str, command => $<command>.Str, data => $<data>.made } } method data($/) { make $/.split('/') } } ``` Here in the `TOP` method, the `subject` remains the same as the subject we matched in the grammar. Also, `command` returns the valid `<sym>` that was matched (create, update, retrieve, or delete). We coerce each into `.Str`, as well, since we don't need the full match object. We want to make sure to use the `made` method on the `$<data>` object, since we want to access the split one that we `made` with `make` in our action, rather than the proper `$<data>` object. After we `make` something in the `TOP` method of a grammar action, we can then access all the custom values by calling the `made` method on the grammar result object. The code now becomes ```raku my $uri = '/product/update/7/notify'; my $match = REST.parse($uri, actions => REST-actions.new); my $rest = $match.made; say $rest<data>[0]; # OUTPUT: «7␤» say $rest<command>; # OUTPUT: «update␤» say $rest<subject>; # OUTPUT: «product␤» ``` If the complete return match object is not needed, you could return only the made data from your action's `TOP`. ```raku my $uri = '/product/update/7/notify'; my $rest = REST.parse($uri, actions => REST-actions.new).made; say $rest<data>[0]; # OUTPUT: «7␤» say $rest<command>; # OUTPUT: «update␤» say $rest<subject>; # OUTPUT: «product␤» ``` Oh, did we forget to get rid of that ugly array element number? Hmm. Let's make something new in the grammar's custom return in `TOP`... how about we call it `subject-id` and have it set to element 0 of `<data>`. ```raku class REST-actions { method TOP ($/) { make { subject => $<subject>.Str, command => $<command>.Str, data => $<data>.made, subject-id => $<data>.made[0] } } method data($/) { make $/.split('/') } } ``` Now we can do this instead: ```raku my $uri = '/product/update/7/notify'; my $rest = REST.parse($uri, actions => REST-actions.new).made; say $rest<command>; # OUTPUT: «update␤» say $rest<subject>; # OUTPUT: «product␤» say $rest<subject-id>; # OUTPUT: «7␤» ``` Here's the final code: ```raku grammar REST { token TOP { <slash><subject><slash><command>[<slash><data>]? } proto token command {*} token command:sym<create> { <sym> } token command:sym<retrieve> { <sym> } token command:sym<update> { <sym> } token command:sym<delete> { <sym> } token subject { \w+ } token data { .* } token slash { \s* '/' \s* } } class REST-actions { method TOP ($/) { make { subject => $<subject>.Str, command => $<command>.Str, data => $<data>.made, subject-id => $<data>.made[0] } } method data($/) { make $/.split('/') } } ``` ## [Add actions directly](#Grammar_tutorial "go to top of document")[§](#Add_actions_directly "direct link") Above we see how to associate grammars with action objects and perform actions on the match object. However, when we want to deal with the match object, that isn't the only way. See the example below: ```raku grammar G { rule TOP { <function-define> } rule function-define { 'sub' <identifier> { say "func " ~ $<identifier>.made; make $<identifier>.made; } '(' <parameter> ')' '{' '}' { say "end " ~ $/.made; } } token identifier { \w+ { make ~$/; } } token parameter { \w+ { say "param " ~ $/; } } } G.parse('sub f ( a ) { }'); # OUTPUT: «func f␤param a␤end f␤» ``` This example is a reduced portion of a parser. Let's focus more on the feature it shows. First, we can add actions inside the grammar itself, and such actions are performed once the control flow of the regex arrives at them. Note that action object's method will always be performed after the whole regex item matched. Second, it shows what `make` really does, which is no more than a sugar of `$/.made = ...`. And this trick introduces a way to pass messages from within a regex item. Hopefully this has helped introduce you to the grammars in Raku and shown you how grammars and grammar action classes work together. For more information, check out the more advanced [Raku Grammar Guide](/language/grammars). For more grammar debugging, see [Grammar::Debugger](https://github.com/jnthn/grammar-debugger). This provides breakpoints and color-coded MATCH and FAIL output for each of your grammar tokens.
## dist_zef-raku-community-modules-PrettyDump.md [![Actions Status](https://github.com/raku-community-modules/PrettyDump/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/PrettyDump/actions) [![Actions Status](https://github.com/raku-community-modules/PrettyDump/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/PrettyDump/actions) [![Actions Status](https://github.com/raku-community-modules/PrettyDump/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/PrettyDump/actions) # NAME PrettyDump - represent a Raku data structure in a human readable way # SYNOPSIS Use it in the OO fashion: ``` use PrettyDump; my $pretty = PrettyDump.new: :after-opening-brace; my $raku = { a => 1 }; say $pretty.dump: $raku; # '{:a(1)}' ``` Or, use its subroutine: ``` use PrettyDump; my $ds = { a => 1 }; say pretty-dump( $ds ); # setting named arguments say pretty-dump( $ds, :indent<\t>); ``` Or, a shorter shortcut that dumps and outputs to standard output: ``` use PrettyDump; my $ds = { a => 1 }; pd $ds; ``` # DESCRIPTION This module creates nicely formatted representations of your data structure for your viewing pleasure. It does not create valid Raku code and is not a serialization tool. When `.dump` encounters an object in your data structure, it first checks for a `.PrettyDump` method. It that exists, it uses it to stringify that object. Otherwise, `.dump` looks for internal methods. So far, this module handles these types internally: * List * Array * Pair * Map * Hash * Match ## Custom dump methods If you define a `.PrettyDump` method in your class, `.dump` will call that when it encounters an object in that class. The first argument to `.PrettyDump` is the dumper object, so you have access to some things in that class: ``` class Butterfly { has $.genus; has $.species; method PrettyDump ( PrettyDump $pretty, Int:D :$depth = 0 ) { "_{$.genus} {$.species}_"; } } ``` The second argument is the level of indentation so far. If you want to dump other objects that your object contains, you should call `.dump` again and pass it the value of `$depth+1` as it's second argument: ``` class Butterfly { has $.genus; has $.species; has $.some-other-object; method PrettyDump ( PrettyDump $pretty, Int:D :$depth = 0 ) { "_{$.genus} {$.species}_" ~ $pretty.dump: $some-other-object, $depth + 1; } } ``` You can add a `PrettyDump` method to an object with `but role`: ``` use PrettyDump; my $pretty = PrettyDump.new; my Int $a = 137; put $pretty.dump: $a; my $b = $a but role { method PrettyDump ( PrettyDump:D $pretty, Int:D :$depth = 0 ) { "({self.^name}) {self}"; } } put $pretty.dump: $b; ``` This outputs: ``` 137 (Int+{<anon|140644552324304>}) 137 ``` ## Per-object dump handlers You can add custom handlers to your `PrettyDump` object. Once added, the object will try to use a handler first. This means that you can override builtin methods. ``` $pretty = PrettyDump.new: ... ; $pretty.add-handler: "SomeTypeNameStr", $code-thingy; ``` The code signature for `$code-thingy` must be: ``` (PrettyDump $pretty, $ds, Int:D :$depth = 0 --> Str) ``` Once you are done with the per-object handler, you can remove it: ``` $pretty.remove-handler: "SomeTypeNameStr"; ``` This allows you to temporarily override a builtin method. You might want to mute a particular object, for instance. You can completely ignore a type as if it's not even there. It's a wrapper around g that supplies the code for you. ``` $pretty.ignore-type: SomeType; ``` This works by returning a `Str` type object instead of a defined string. If the type you want to exclude is at the top of the data structure, you'll get back a type object. But why are you dumpng something you want to ignore? ## Formatting and Configuration You can set some tidy-like settings to control how `.dump` will present the data stucture: * debug Output debugging info to watch the module walk the data structure. * indent The default is a tab. * intra-group-spacing The spacing inserted inside (empty) `${}` and `$[]` constructs. The default is the empty string. * pre-item-spacing The spacing inserted just after the opening brace or bracket of non-empty `${}` and `$[]` constructs. The default is a newline. * post-item-spacing The spacing inserted just before the close brace or bracket of non-empty `${}` and `$[]` constructs. The default is a newline. * pre-separator-spacing The spacing inserted just before the comma separator of non-empty `${}` and `$[]` constructs. The default is the empty string. * post-separator-spacing The spacing inserted just after the comma separator of non-empty `${}` and `$[]` constructs. Defaults to a newline. # AUTHORS * brian d foy * Raku Community This module started as `Pretty::Printer` from Jeff Goff. Parts of this module were supported by a grant from TPRF. # COPYRIGHT Copyright © 2017-2021, brian d foy Copyright © 2024 Raku Community # LICENSE This module is available under the Artistic License 2.0. A copy of this license should have come with this distribution in the LICENSE file.
## dist_github-ramiroencinas-Package-Updates.md # Package::Updates [![Build Status](https://travis-ci.org/ramiroencinas/perl6-Package-Updates.svg?branch=master)](https://travis-ci.org/ramiroencinas/perl6-Package-Updates) Provides a hash including package updates from the most popular package managers. ## Package managers supported: * apt * pacman * yum * Windows Update ## Getting the updates: The updates we get through the subroutine get-updates() that returns a hash. Each element of this hash includes: * key: Packet name. * value with the current packet version installed. * value with the new packet version available to install. ## Windows Update considerations: * The updates from Windows Update is done using the Powershell script `get-updates.ps1`. This Powershell script `must be located` in the same directory as the script that call the Package::Updates module. * The returned hash only provides the name of the package (the hash key) that has a new version available. ## Permisions considerations: The script that call this module must be run by a user with administrative or root privileges. ## Installing the module: ``` with zef: zef update zef install Package::Updates with Panda: panda update panda install Package::Updates ``` ## Example Usage: ``` use v6; use Package::Updates; my %updates = get-updates(); for %updates.sort(*.key)>>.kv -> ($name, $data) { say "Packet name: $name Current: $data<current> New: $data<new>"; } ```
## dist_cpan-MOZNION-Stream-Buffered.md [![Build Status](https://travis-ci.org/moznion/p6-Stream-Buffered.svg?branch=master)](https://travis-ci.org/moznion/p6-Stream-Buffered) # NAME Stream::Buffered - Temporary buffer to save bytes # SYNOPSIS ``` use Stream::Buffered; my $buf = Stream::Buffered.new($length); $buf.print("foo"); my Int $size = $buf.size; my IO::Handle $io = $buf.rewind; ``` # DESCRIPTION Stream::Buffered is a buffer class to store arbitrary length of byte strings and then get a seekable IO::Handle once everything is buffered. It uses Blob and temporary file to save the buffer depending on the length of the size. This library is a perl6 port of [perl5's Stream::Buffered](https://metacpan.org/pod/Stream::Buffered). # METHODS ## `new(Int $length, Int $maxMemoryBufferSize = 1024 * 1024) returns Stream::Buffered` Creates instance. When you specify negative value as `$maxMemoryBufferSize`, Stream::Buffered always uses Blob as buffer. Or when you specify 0 as `$maxMemoryBufferSize`, Stream::Buffered always uses temporary file as buffer. If you pass 0 to the first argument, Stream::Buffered decides what kind of buffer type (Blob or temp file) to use automatically. ## `print(Stream::Buffered:D: *@text) returns Bool` Append text to buffer. ## `size(Stream::Buffered:D:) returns Int` Return the size of buffer. ## `rewind(Stream::Buffered:D:) returns IO::Handle` Seek to the head of buffer and return buffer. # SEE ALSO * [perl5's Stream::Buffered](https://metacpan.org/pod/Stream::Buffered) # AUTHOR moznion [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE ``` Copyright 2015 moznion This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. ``` And original perl5's Stream::Buffered is ``` The following copyright notice applies to all the files provided in this distribution, including binary files, unless explicitly noted otherwise. Copyright 2009-2011 Tatsuhiko Miyagawa This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. ```
## dist_zef-FCO-Trie.md [![Build Status](https://travis-ci.org/FCO/Trie.svg?branch=master)](https://travis-ci.org/FCO/Trie) # Trie A pure perl6 implementation of the trie data structure. ## SYNOPSIS ``` use Trie; my Trie $t .= new; $t.insert: $_ for <ability able about above accept according account>; $t.insert: "agent", {complex => "data"}; say $t.get-all: "ab"; # (ability able about above) say $t.get-all: "abov"; # (above) say $t.get-single: "abov"; # "above" # $t.get-single: "ab"; # dies say $t.get-single: "agent"; # {complex => "data"} $t<all> = 1; $t<allow> = 2; say $t<all>; # (1 2) say $t[0]; # ability say $t[0 .. 3]; # (ability able about above) say $t.find-substring: "cc"; # (accept according account) say $t.find-fuzzy: "ao"; # set(2 about above according account) ``` ## DESCRIPTION Trie is a pure perl6 implementation of the trie data structure. ## AUTHOR Fernando Correa de Oliveira [[email protected]](mailto:[email protected]) ## COPYRIGHT AND LICENSE Copyright 2018 Fernando Correa de Oliveira This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-Marcool04-Script-Hash.md # NAME Script::Hash - A module to export a md5 hash of program name and arguments # SYNOPSIS ``` use Script::Hash; say "$script-hash" # output, example: 5067EEFF4999C7B5B4F593DD3521B9 ``` # DESCRIPTION `Script::Hash` exports a single varibale, `$script-hash`, that can be used to access an md5 hash of the program name (`$*PROGRAM-NAME`) and the arguments (`@*ARGS`), stripped to 100 characters (to account for utf8 multi-codepoint chars, and the md5 implementation limit of 128 codepoints). # USE CASE Why would you ever need such a simplistic and strange module? `Script::Hash` was designed for use in a module that requires a temporary directory that is keyed to the specific invocation of that module's binary. Basically, when one runs: `raku script.raku option1 option2` it creates a directory and uses it to store temporary files, based on the `$script-hash` variable provided by this module. Then, whenever `raku script.raku option1 option2` is run again (same arguments) the same temporary folder is used. When one calls `raku script.raku option3 option4 option5` on the other hand, then the `$script-hash` variable differs, and a new temporary directory is created. Not sure it can be used in any more cases than this… If you have any, let me know! # AUTHOR Mark Collins [tera\[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2020 Mark Collins This work is free. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See the COPYING file for more details.
## slip.md Slip Combined from primary sources listed below. # [In Any](#___top "go to top of document")[§](#(Any)_method_Slip "direct link") See primary documentation [in context](/type/Any#method_Slip) for **method Slip**. ```raku method Slip(--> Slip:D) is nodal ``` Coerces the invocant to [`Slip`](/type/Slip). # [In Array](#___top "go to top of document")[§](#(Array)_method_Slip "direct link") See primary documentation [in context](/type/Array#method_Slip) for **method Slip**. ```raku multi method Slip(Array:D: --> Slip:D) ``` Converts the array to a [`Slip`](/type/Slip), filling the holes with the type value the `Array` has been defined with. ```raku my Int @array= [0]; @array[3]=3; say @array.Slip; # OUTPUT: «(0 (Int) (Int) 3)␤» ``` # [In IterationBuffer](#___top "go to top of document")[§](#(IterationBuffer)_method_Slip "direct link") See primary documentation [in context](/type/IterationBuffer#method_Slip) for **method Slip**. ```raku method Slip(IterationBuffer:D: --> Slip:D) ``` Coerces the `IterationBuffer` to a [`Slip`](/type/Slip).
## dist_zef-tbrowder-Date-Event.md [![Actions Status](https://github.com/tbrowder/Date-Event/actions/workflows/linux.yml/badge.svg)](https://github.com/tbrowder/Date-Event/actions) [![Actions Status](https://github.com/tbrowder/Date-Event/actions/workflows/macos.yml/badge.svg)](https://github.com/tbrowder/Date-Event/actions) [![Actions Status](https://github.com/tbrowder/Date-Event/actions/workflows/windows.yml/badge.svg)](https://github.com/tbrowder/Date-Event/actions) # NAME **Date::Event** - Provides a class suitable for use with calendars or any program using the Raku `Date` type # SYNOPSIS ``` use Date::Event; my $date = Date.new: :year(2024), :month(12), :day(31); # Enter an Etype with a known enum EType name: my $e = Date::Event.new: :$date, :Etype<Birthday>; # Enter an Etype with a known enum EType number my $e2 = Date::Event.new: :$date, :name<Easter>,:Etype(12); # Liturgy # Smart match on the enum attribute if $e2.Etype ~~ Liturgy { say $e2.name; # OUTPUT: «Easter␤» } ``` # DESCRIPTION **Date::Event** is a class that provides basic attributes to describe an event occurring on a particular `Date`. It is suitable for multiple instances on a `Date` and is currently defined as follows: ``` unit class Date::Event; enum EType is export ( Unknown => 0, Birth => 1, Christening => 2, Baptism => 3, BarMitzvah => 4, BatMitzvah => 5, Graduation => 6, Wedding => 7, Anniversary => 8, Retirement => 9, Death => 10, Birthday => 11, Liturgy => 12, Holiday => 100, Astro => 150, Other => 200, ); has Str $.set-id = ""; has Str $.id = ""; has Str $.name; = ""; has Str $.short-name = ""; has $.Etype = 0; has Date $.date; has Date $.date-observed; has Str $.notes = ""; has Bool $.is-calculated = False; # For use with Date::Utils: has UInt $.nth-value; has UInt $.nth-dow; has UInt $.nth-month-number; # Attributes for Astro events: has Numeric $.lat where { -90 <= $_ <= 90 }; has Numeric $.lon where { -180 <= $_ <= 180 }; has DateTime $.time; submethod TWEAK { $!Etype = self.etype($!Etype) } multi method etype(Str $v? --> UInt) { my %m = EType.enums; if $v.defined { return %m{$v} } else { return %m{self.Etype} } } multi method etype(UInt $v? --> EType) { if $v.defined { return EType($v) } else { return EType(self.Etype) } } method lat(Numeric $v?) { if $v.defined { $!lat = $v } else { return $!lat } } method lon(Numeric $v?) { if $v.defined { $!lon = $v } else { return $!lon } } # A default event is normally set on a certain date. Many holidays # are an exception in that they are calculated based on one or more # date criteria or conversion from another calendar (e.g., from Jewish # to Gregorian). } #= Enable the user to change the attribute #= during development method is-calculated(Bool $v?) { if $v.defined { $!is-calculated = $v } else { return $!is-calculated } } ``` Published modules showing similar use are 'Holidays::US:Federal' and 'Holidays::Miscellaneous'. They include special databases that use the 'Date::Event' class to provide a common interface (API) for working with dates. Those modules are being integrated into the next version of published module 'Calendar'. # AUTHOR Tom Browder [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE © 2023-2024 Tom Browder This library is free software; you may redistribute it or modify it under the Artistic License 2.0.
## dist_zef-jmaslak-App-Tasks.md # POD # NAME `task.pl6` - Perl 6 task management application # SYNOPSIS ``` task.pl6 new # Add a new task task.pl6 list # List existing tasks task.pl6 <num> # Show information about a task task.pl6 note <num> # Add notes to a task task.pl6 close <num> # Close a task ``` # DESCRIPTION This program provides basic to-do list management. The project was initially created by its author, Joelle Maslak, to solve her particular task tracking needs. However, it's likely to be useful to others as well. # CAVEATS This is not yet production-ready code. It runs, and I believe the bugs are reasonably managable, and it meets the author's current needs. However, it was never written with the intent of meeting anyone else's needs! This code highly depends upon a terminal capable of interepreting the Xterminal color codes. Editing notes requires the `nano` editor to be installed. The `less` pager is also used. The author has not yet documented the main classes used by this program. That said, suggestions are more then welcome! # GOALS / PHILOSOPHY The goals for this project, which may be changed by the author when she realizes they get in the way of something more important, are: * Maintain data in plain-text format * Each task is represented by a unique file * Simplicity for basic tasks * Somewhat scriptable front-end * Work inside a Unix shell account * Track pending work on a task (notes) # YOU'RE STILL HERE! Congrats! Now for the usage! # USAGE ## ENVIRONMENT ### `%ENV<TASKDIR>` This enviornmental variable determines where the task database (files) reside. Open tasks are in this directory, while closed tasks are moved to the `done/` directory under this directory. The default, if the environmental variable is not set, is `%ENV<HOME>/.task` if the `HOME` environmental variable is set. If the `HOME` environmental variable is not set, it it will be `.task` under the user's current working directory. ## CONFIGURATION Optional, a configuration file can be installed in the user's home directory. If a file named `.task.yaml` is located there, it is parsed as described in the App::Tasks::Config documentation. ## COMMANDS ### No command line options ``` task.pl ``` When `task.pl` is executed without any options, it enters an interactive mode. The author rarely uses this mode, preerring command line options instead. ### new ``` task.pl6 new task.pl6 new <title> task.pl6 --expire-today new task.pl6 --expire-today new <title> task.pl6 --maturity-date=2099-12-31 new task.pl6 --tag=foo new ``` Create a new task. If a title is passed on the command line (as a single argument, so quotes may be needed if you have a multi-word title), it is simply created with an empty body. If a title is not provided, an interactive dialog with the user asks for the title, and, optionally a more detailed set of notes. If the `--expire-today` option is provided, the new task will have an expiration date of today. See [expire](#expire) for more details. This is not compatibile with the `--maturity-date` option. If the `--maturity-date` option is provided, this sets the maturity date for the task. See [set-maturity](#set-maturity) for more information. If the `--tag` option is provided, this sets a tag on the task. See [add-tag](#add-tag) for more information. ### list ``` task.pl6 list task.pl6 list <max-items> task.pl6 --show-immature list task.pl6 --show-immature list <max-items> task.pl6 --all list task.pl6 --tag=foo list ``` Display a list of active tasks. Normally, only non-immature tasks are shown. If the `--show-immature` or the `--all` option is provided, immature tasks are also shown. The `--all` option additional shows all tasks that have a frequency that would normally prevent them from being shown today (see the section on `set-frequency` for more information. If the `--tag` option is provided, this lists only tasks with a matching tag. See [add-tag](#add-tag) for more information. Normally, tasks that include any tag that is listed in the `ignore-tags` section of the config file (if it exists) are not displayed. However, they will be displayed if `--all` is specified or if the `--tag` option includes one of the tags associated with the task. Optionally, an integer specifying the maximum number of items to display can be provided. ### show ``` task.pl6 <task-number> task.pl6 show <task-number> ``` Display a task's details. This uses the `less` pager if needed. All notes will be displayed with the task. ### monitor ``` task.pl6 monitor task.pl6 --show-immature monitor task.pl6 --all monitor ``` Displays an updating list of tasks that auto-refreshes. It displays as many tasks as will fit on the screen. The `--show-immature`, `--all`, and `--tag` options function as they do for `list`. ### note ``` task.pl6 note <task-number> ``` Adds a note to a task. The note is appended to the task. Notes are visible via the [show](#show) command. You must have done a [list](#list) in the current window before you can make notes, in case the task numbers have changed. ### close ``` task.pl6 close <task-number> ``` Closes a task (moves it from the You must have done a [list](#list) in the current window before you can make notes, in case the task numbers have changed. This will automatically execute a `#coalesce`. Thus task numbers will change after using this. You must have done a [list](#list) in the current window before you can make notes, in case the task numbers have changed. ### retitle ``` task.pl6 retitle <task-number> ``` Change the title on a task. You must have done a [list](#list) in the current window before you can make notes, in case the task numbers have changed. ### move ``` task.pl6 move <task-number> <new-number> ``` Moves a task from it's current position to a new position (as seen by the list command). This will automatically execute a `#coalesce`. Thus task numbers will change after using this. You must have done a [list](#list) in the current window before you can make notes, in case the task numbers have changed. ### set-expire ``` task.pl6 set-expire <task-number> ``` Set an expiration date. This is the last day that the task is considered valid. This is used for tasks that don't make sense after a given date. For instance, if you add a task to buy a Christmas turkey, if you don't actually do that task before Christmas, it's likely not relevant after Christmas. Thus, you might set an expiration date of December 25th. At that point, it will be pruned by the [expire](#expire) command. You must have done a [list](#list) in the current window before you can make notes, in case the task numbers have changed. ### expire ``` task.pl6 expire ``` This closes any open tasks with an expiration date prior to the current date. It is suitable to run via crontab daily. This will automatically execute a `#coalesce`. Thus task numbers will change after using this. You must have done a [list](#list) in the current window before you can make notes, in case the task numbers have changed. ### set-frequency ``` task.pl6 set-frequency <task-number> ``` This sets the "display frequency" of the task. Tasks with a frequency set will display only on one day out of `N` number of days. The `N` is the frequency value, with higher values representing less frequent display of the task. So, for instance, a frequency of `7` would indicate that the task should only be displayed once per week. The first day the task will be displayed will be betwen now and `N-1` days from now. It will then display every `N` days. The idea is that with a large task list with lots of low priority tasks, it low priority tasks can be assigned a frequency that causes the normal `list` to display only a subset of them, so as to not overwhelm. ### set-maturity ``` task.pl6 set-maturity <task-number> ``` Sets the maturity date. Before the maturity date, a task will not be displayed with the [list](#list) or [monitor](#monitor) commands before the maturity date (unless the `--show-immature` option is also provided to the [list](#list) or [monitor](#monitor) commands). ### add-tag ``` task.pl6 add-tag <task-number> <tag> ``` Sets a tag (a string with no whitespace) for a given task number. Tags can be used to filter tasks with [list](#list). They are also displayed in task lists. ### remove-tag ``` task.pl6 remove-tag <task-number> <tag> ``` Removes a tag (a string with no whitespace) for a given task number. ### coalesce ``` task.pl6 coalesce ``` Coalesces task numbers, so that the first task becomes task number 1, and any gaps are filled in, moving tasks as required. This is needed if tasks are deleted outside of the `task.pl6` program. This will automatically execute a `#coalesce`. Thus task numbers will change after using this. You must have done a [list](#list) in the current window before you can make notes, in case the task numbers have changed. ### trello-sync If a c section of the config file is created, which looks something like the following, sync with Trello: ``` trello: api-key: abcdef0123456789 token: 9876543210fedcba tasks: Board1: List1: tag1 ``` In this case, the API key and token are created as a Trello power-up (you must do that for your own sync to work). This specifies that cards in Board1's list, "List1", will be syncronized and given a tag of "tag1" in `App::Tasks`. Note this is a one-way sync (it creates tasks from Trello that can't be edited, and those tasks are deleted when the associated Trello card is deleted/moved and the sync is re-run. ## OPTIONS ### --expire-today This option is used along with the [new](#new) command to create a task that will expire today (see the [expire](#expire) option for more details). ### --show-immature Show all open tasks. Normally, tasks that are "immature" (see the L# command) are not displayed by the [monitor](#monitor) or [list](#list) commands. This option changes that behavior. ### --maturity-date=YYYY-MM-DD Sets the maturity date for the [new](#new) command when creating a task. Not valid with the `--expire-today` option. This will be the first day the task shows up in basic `task list` output. # AUTHOR Joelle Maslak `[email protected]` # LEGAL Licensed under the same terms as Perl 6. Copyright © 2018-2022 by Joelle Maslak
## dist_cpan-CTILMES-Native-Exec.md # NAME Native::Exec -- NativeCall bindings for Unix exec\*() calls # SYNOPSIS ``` use Native::Exec; # Default searches PATH for executable exec 'echo', 'hi'; # Specify :nopath to avoid PATH searching exec :nopath, '/bin/echo', 'hi'; # Override ENV entirely by passing in named params exec 'env', HOME => '/my/home', PATH => '/bin:/usr/bin'; ``` # DESCRIPTION Very basic wrapper around NativeCall bindings for the Unix `execv`(), `execve`(), `execvp`(), and `execvpe`() Unix calls. `exec` defaults to the 'p' variants that search your PATH for the specified executable. If you include the `:nopath` option, it will use the non 'p' variants and avoid the PATH search. You can also include a '/' in your specified executable and that will also avoid the PATH search within the `exec*` routines. Including any named parameters OTHER THAN `:nopath` will build a new environment for the `exec`ed program, replacing the existing environment entirely, using the 'e' variants. # EXCEPTIONS `exec` does NOT return. On success, the `exec`ed program will replace your Perl 6 program entirely. If there are any errors, such as not finding the specified program, it will throw `X::Native::Exec` with the native error code. You can access the native error code with `.errno`, and the native error message with `.message`. ``` exec 'non-existant'; CATCH { when X::Native::Exec { say "Native Error Code: ", .errno; say "Native Error Message: ", .message; } } ``` # NOTE The `exec`\* family are Unix specific, and are unlikely to work on other architectures.
## dist_cpan-HOLLI-Color-Names.md # NAME Color::Names - A comprehensive? list of named colors # SYNOPSIS ``` use Color::Names; # a hash of normalized color names associated # with rgb values and a pretty name say Color.Names.color-data("X11"); # you can mix sets, the later one wins in case of # name clashes say Color.Names.color-data("X11", "XKCD"); use Color::Names::X11; say Color::Names::X11.color-data{'Aqua'}; # --> { rgb => [0x00, 0xff, 0xff], name => 'Aqua' } use Color::Data::CSS3 :colors; say COLORS{'red'}; # --> { rgb => [0xff, 0x00, 0x00], name => Red' } ``` # DESCRIPTION You can choose from (currently) three color sets: X11, CSS3 and the [xkcd](https://xkcd.com/) set from the [xkcd color survey](https://xkcd.com/color/rgb/). The X11 and CSS3 sets are basically [identical](https://en.wikipedia.org/wiki/X11_color_names), except for 4 colors. If you know about other lists of name/color pairs in use, please let me know. # AUTHOR ``` Markus «Holli» Holzer ``` # COPYRIGHT AND LICENSE Copyright © Markus Holzer ( [[email protected]](mailto:[email protected]) ) License <GPLv3|: [The GNU General Public License](https://www.gnu.org/licenses/gpl-3.0.txt), Version 3, 29 June 2007 This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.
## dist_zef-leont-Path-Finder.md [![Actions Status](https://github.com/Leont/path-finder/workflows/test/badge.svg)](https://github.com/Leont/path-finder/actions) # SYNOPSIS ``` use Path::Finder; my $finder = Path::Finder.file.skip-vcs.ext(/pm6?/).size(* > 10_000); # iterator interface for $finder.in('.') -> $file { ... } # functional interface for find(:file, :skip-vcs, :ext(/pm6?/), :size(* > 10_000)) -> $file { ... } ``` # DESCRIPTION This module iterates over files and directories to identify ones matching a user-defined set of rules. The object-oriented API is based heavily on perl5's `Path::Iterator::Rule`. A `Path::Finder` object is a collection of rules (match criteria) with methods to add additional criteria. Options that control directory traversal are given as arguments to the method that generates an iterator. Here is a summary of features for comparison to other file finding modules: * provides many "helper" methods for specifying rules * offers (lazy) list interface * custom rules implemented with roles * breadth-first (default) or pre- or post-order depth-first searching * follows symlinks (by default, but can be disabled) * directories visited only once (no infinite loop; can be disabled) * doesn't chdir during operation * provides an API for extensions # USAGE There are two interfaces: an object oriented one, and a functional one. Path::Finder objects are immutable. All methods except `in` return a new object combining the existing rules with the additional rules provided. When using the `find` function, all methods described below (except `in`) are allowed as named arguments, as well as all arguments to `in`. This is usually the easiest way to use Path::Finder, even if it allows for slightly less control over ordering of the constraints. There is also a `finder` function that returns a Path::Finder object. ## Matching and iteration ### `CALL-ME` / `in` ``` for $finder(@dirs, |%options) -> $file { ... } ``` Creates a sequence of results. This sequence is "lazy" -- results are not pre-computed. It takes as arguments a list of directories to search and named arguments as control options. Valid options include: * `order` -- Controls order of results. Valid values are `BreadthFirst` (breadth-first search), `PreOrder` (pre-order, depth-first search), `PostOrder` (post-order, depth-first search). The default is `PreOrder`. * `follow-symlinks` - Follow directory symlinks when true. Default is `True`. * `report-symlinks` - Includes symlinks in results when true. Default is equal to `follow-symlinks`. * `loop-safe` - Prevents visiting the same directory more than once when true. Default is `True`. * `relative` - Return matching items relative to the search directory. Default is `False`. * `sorted` - Whether entries in a directory are sorted before processing. Default is `True`. * `keep-going` - Whether or not the search should continue when an error is encountered (typically an unreadable directory). Defaults to `True`. * `quiet` - Whether printing non-fatal errors to `$*ERR` is repressed. Defaults to `False`. * `invert` - This will invert which files are matched and which files are not * `as` - The type of values that will be returned. Valid values are `IO::Path` (the default) and `Str`. Filesystem loops might exist from either hard or soft links. The `loop-safe` option prevents infinite loops, but adds some overhead by making `stat` calls. Because directories are visited only once when `loop-safe` is true, matches could come from a symlinked directory before the real directory depending on the search order. To get only the real files, turn off `follow-symlinks`. You can have symlinks included in results, but not descend into symlink directories if you turn off `follow-symlinks`, but turn on `report-symlinks`. Turning `loop-safe` off and leaving `follow-symlinks` on avoids `stat` calls and will be fastest, but with the risk of an infinite loop and repeated files. The default is slow, but safe. If the search directories are absolute and the `relative` option is true, files returned will be relative to the search directory. Note that if the search directories are not mutually exclusive (whether containing subdirectories like `@*INC` or symbolic links), files found could be returned relative to different initial search directories based on `order`, `follow-symlinks` or `loop-safe`. ## Logic operations `Path::Finder` provides three logic operations for adding rules to the object. Rules may be either a subroutine reference with specific semantics or another `Path::Finder` object. ### `and` ``` $finder.and($finder2) ; $finder.and(-> $item, *% { $item ~~ :rwx }); $finder.and(@more-rules); find(:and(@more-rules)); ``` This creates a new rule combining the curent one and the arguments. E.g. "old rule AND new1 AND new2 AND ...". ### `or` ``` $finder.or( Path::Finder.name("foo*"), Path::Finder.name("bar*"), -> $item, *% { $item ~~ :rwx }, ); ``` This creates a new rule combining the curent one and the arguments. E.g. "old rule OR new1 OR new2 OR ...". ### `none` ``` $finder.none( -> $item, *% { $item ~~ :rwx } ); ``` This creates a new rule combining the current one and one or more alternatives and adds them as a negative constraint to the current rule. E.g. "old rule AND NOT ( new1 AND new2 AND ...)". Returns the object to allow method chaining. ### `not` ``` $finder.not(); ``` This creates a new rule negating the whole original rule. Returns the object to allow method chaining. ### `skip` ``` $finder.skip( $finder.new.dir.not-writeable, $finder.new.dir.name("foo"), ); ``` Takes one or more alternatives and will prune a directory if any of the criteria match or if any of the rules already indicate the directory should be pruned. Pruning means the directory will not be returned by the iterator and will not be searched. For files, it is equivalent to `$finder.none(@rules)` . Returns the object to allow method chaining. This method should be called as early as possible in the rule chain. See `skip-dir` below for further explanation and an example. # RULE METHODS Rule methods are helpers that add constraints. Internally, they generate a closure to accomplish the desired logic and add it to the rule object with the `and` method. Rule methods return the object to allow for method chaining. Generally speaking there are two kinds of rule methods: the ones that take a value to smartmatch some property against (e.g. `name`), and ones that take a boolean (defaulting to `True`) to check a boolean value against (e.g. `readable`). ## File name rules ### `name` ``` $finder.name("foo.txt"); find(:name<foo.txt>); ``` The `name` method takes a pattern and creates a rule that is true if it matches the **basename** of the file or directory path. Patterns may be anything that can smartmatch a string. If it's a string it will be interpreted as a glob pattern. ### `path` ``` $finder.path( "foo/*.txt" ); find(:path<foo/*.txt>); ``` The `path` method takes a pattern and creates a rule that is true if it matches the path of the file or directory. Patterns may be anything that can smartmatch a string. If it's a string it will be interpreted as a glob pattern. ### `relpath` ``` $finder.relpath( "foo/bar.txt" ); find(:relpath<foo/bar.txt>); $finder.relpath( any(rx/foo/, "bar.*")); find(:relpath(any(rx/foo/, "bar.*")) ``` The `relpath` method takes a pattern and creates a rule that is true if it matches the path of the file or directory relative to its basedir. Patterns may be anything that can smartmatch a string. If it's a string it will be interpreted as a glob pattern. ### `io` ``` $finder.path(:f|:d); find(:path(:f|:d); ``` The `io` method takes a pattern and creates a rule that is true if it matches the `IO` of the file or directory. This is mainly useful for combining filetype tests. ### `ext` The `ext` method takes a pattern and creates a rule that is true if it matches the extension of path. Patterns may be anything that can smartmatch a string. ### `skip-dir` ``` $finder.skip-dir( $pattern ); ``` The `skip-dir` method skips directories that match a pattern. Directories that match will not be returned from the iterator and will be excluded from further search. **This includes the starting directories.** If that isn't what you want, see `skip-subdir` instead. **Note:** this rule should be specified early so that it has a chance to operate before a logical shortcut. E.g. ``` $finder.skip-dir(".git").file; # OK $finder.file.skip-dir(".git"); # Won't work ``` In the latter case, when a ".git" directory is seen, the `file` rule shortcuts the rule before the `skip-dir` rule has a chance to act. ### `skip-subdir` ``` $finder.skip-subdir( @patterns ); ``` This works just like `skip-dir`, except that the starting directories (depth 0) are not skipped and may be returned from the iterator unless excluded by other rules. ## File test rules Most of the `:X` style filetest are available as boolean rules: ### `readable` This checks if the entry is readable ### `writable` This checks if the entry is writable ### `executable` This checks if the entry is executable ### `file` This checks if the entry is a file ### `directory` This checks if the entry is a directory ### `symlink` This checks if the entry is a symlink ### `special` This checks if the entry is anything but a file, directory or symlink. ### `exists` This checks if the entry exists ### `empty` This checks if the entry is empty For example: ``` $finder.file.empty; ``` Two composites are also available: ### `read-writable` This checks if the entry is readable and writable ### `read-write-executable` This checks if the entry is readable, writable and executable ### `dangling` ``` $finder.dangling; ``` The `dangling` rule method matches dangling symlinks. It's equivalent to ``` $finder.symlink.exists(False) ``` The timestamps methods take a single argument in a form that can smartmatch an `Instant`. ### `accessed` Compares the access time ### `modified` Compares the modification time ### `changed` Compares the (inode) change time For example: ``` # hour old $finder.modified(* < now - 60 * 60); ``` It also supports the following integer based matching rules: ### `size` This compares the size of the entry ### `mode` This compares the mode of the entry ### `device` This compares the device of the entry. This may not be available everywhere. ### `device-type` This compares the device ID of the entry (when its a special file). This may not be available everywhere. ### `inode` This compares the inode of the entry. This may not be available everywhere. ### `nlinks` This compares the link count of the entry. This may not be available everywhere. ### `uid` This compares the user identifier of the entry. ### `gid` This compares the group identifier of the entry. ### `blocks` This compares the number of blocks in the entry. ### `blocksize` This compares the blocksize of the entry. For example: ``` $finder.size(* > 10240) ``` ## Depth rules ``` $finder.depth(3..5); ``` The `depth` rule method take a single range argument and limits the paths returned to a minimum or maximum depth (respectively) from the starting search directory, or an integer representing a specific depth. A depth of 0 means the starting directory itself. A depth of 1 means its children. (This is similar to the Unix `find` utility.) ## Version control file rules ``` # Skip all known VCS files $finder.skip-vcs; ``` Skips files and/or prunes directories related to a version control system. Just like `skip-dir`, these rules should be specified early to get the correct behavior. ## File content rules ### `contents` ``` $finder.contents(rx/BEGIN .* END/); ``` The `contents` rule takes a list of regular expressions and returns files that match one of the expressions. The expressions are applied to the file's contents as a single string. For large files, this is likely to take significant time and memory. Files are assumed to be encoded in UTF-8, but alternative encodings can be passed as a named argument: ``` $finder.contents(rx/BEGIN .* END/xs, :enc<latin1>); ``` ### `lines` ``` $finder.lines(rx:i/^new/); ``` The `line` rule takes a list of regular expressions and returns files with at least one line that matches one of the expressions. Files are assumed to be encoded in UTF-8, but alternative Perl IO layers can be passed like in `contents` ### `no-lines` ``` $finder.no-lines(rx:i/^new/); ``` The `line` rule takes a list of regular expressions and returns files with no lines that matches one of the expressions. Files are assumed to be encoded in UTF-8, but alternative Perl IO layers can be passed like in `contents` ### `shebang` ``` $finder.shebang(rx/#!.*\bperl\b/); ``` The `shebang` rule takes a value and checks it against the first line of a file. The default checks for `rx/^#!/`. ## Other rules # EXTENDING ## Custom rule subroutines Rules are implemented as (usually anonymous) subroutine callbacks that return a value indicating whether or not the rule matches. These callbacks are called with three arguments. The only positional argument is a path. ``` $finder.and( sub ($item, *%args) { $item ~~ :r & :w & :x } ); ``` The named arguments contain more information for such a check For example, the `depth` key is used to support minimum and maximum depth checks. The custom rule subroutine must return one of four values: * `True` -- indicates the constraint is satisfied * `False` -- indicates the constraint is not satisfied * `PruneExclusive` -- indicate the constraint is satisfied, and prune if it's a directory * `PruneInclusive` -- indicate the constraint is not satisfied, and prune if it's a directory Here is an example. This is equivalent to the "depth" rule method with a depth of `0..3`: ``` $finder.and( sub ($path, :$depth, *%) { return $depth < 3 ?? True !! PruneExclusive; } ); ``` Files and directories and directories up to depth 3 will be returned and directories will be searched. Files of depth 3 will be returned. Directories of depth 3 will be returned, but their contents will not be added to the search. Once a directory is flagged to be pruned, it will be pruned regardless of subsequent rules. ``` $finder.depth(0..3).name(rx/foo/); ``` This will return files or directories with "foo" in the name, but all directories at depth 3 will be pruned, regardless of whether they match the name rule. Generally, if you want to do directory pruning, you are encouraged to use the `skip` method instead of writing your own logic using `PruneExclusive` and `PruneInclusive`. # PERFORMANCE By default, `Path::Finder` iterator options are "slow but safe". They ensure uniqueness, return files in sorted order, and throw nice error messages if something goes wrong. If you want speed over safety, set these options: ``` :!loop-safe, :!sorted, :order(PreOrder) ``` Depending on the file structure being searched, `:order(PreOrder)` may or may not be a good choice. If you have lots of nested directories and all the files at the bottom, a depth first search might do less work or use less memory, particularly if the search will be halted early (e.g. finding the first N matches.) Rules will shortcut on failure, so be sure to put rules likely to fail early in a rule chain. Consider: ``` $f1 = Path::Finder.new.name(rx/foo/).file; $f2 = Path::Finder.new.file.name(rx/foo/); ``` If there are lots of files, but only a few containing "foo", then `$f1` above will be faster. Rules are implemented as code references, so long chains have some overhead. Consider testing with a custom coderef that combines several tests into one. Consider: ``` $f3 = Path::Finder.new.read-write-executable; $f4 = Path::Finder.new.readable.writeable.executable; ``` Rule `$f3` above will be much faster, not only because it stacks the file tests, but because it requires to only check a single rule. When using the `find` function, `Path::Finder` will try to sort the arguments automatically in such a way that cheap checks and skipping checks are done first.
## dist_zef-dwarring-HarfBuzz-Shaper-Cairo.md [[Raku HarfBuzz Project]](https://harfbuzz-raku.github.io) / [[HarfBuzz-Shaper-Cairo Module]](https://harfbuzz-raku.github.io/HarfBuzz-Shaper-Cairo-raku) ## class HarfBuzz::Shaper::Cairo HarfBuzz / Cairo shaping integration ## Synopsis ``` use HarfBuzz::Shaper::Cairo :&cairo-glyphs; use HarfBuzz::Shaper; use Cairo; my Cairo::Glyphs $glyphs; my $file = 't/fonts/NimbusRoman-Regular.otf'; my $text = 'Hell€!'; # -- functional interface -- my HarfBuzz::Shaper $shaper .= new: :font{:$file}, :buf{:$text}; $glyphs = cairo-glyphs($shaper); # -- OO interface -- my HarfBuzz::Shaper::Cairo $shaper2 .= new: :font{:$file}, :buf{:$text}; $glyphs = $shaper2.cairo-glyphs; # -- FreeType integration -- use Font::FreeType; use Font::FreeType::Face; use Harfbuzz::Shaper::Cairo::Font; my Font::FreeType::Face $ft-face = Font::FreeType.face: $file; my Harfbuzz::Shaper::Cairo::Font $font .= new: :$file; my HarfBuzz::Shaper::Cairo $shaper3 .= $font.shaper: {:$text}; $glyphs = $shaper3.cairo-glyphs; ``` ### Description This module compiles a set of shaped glyphs into a Cairo::Glyphs object; suitable for use by the Cairo::Context `show_glyphs()` and `glyph_path()` methods. This module also includes the [HarfBuzz::Font::Cairo](https://harfbuzz-raku.github.io/HarfBuzz-Shaper-Cairo-raku/HarfBuzz/Font/Cairo) class. Please see the `examples/` folder, for a full working example. ## Methods ### method cairo-glyphs ``` method cairo-glyphs( Numeric :x($x0) = 0e0, Numeric :y($y0) = 0e0, |c ) returns Cairo::Glyphs ``` Return a set of Cairo compatible shaped glyphs The returned object is typically passed to either the Cairo::Context show\_glyphs() or glyph\_path() methods
## dist_zef-lancew-Scientist.md # DESCRIPTION Raku module inspired by <https://github.com/github/scientist> ( <http://githubengineering.com/scientist/> ) See also: <https://github.com/MadcapJake/Test-Lab> For a different take on the same idea. [![test](https://github.com/lancew/ScientistP6/actions/workflows/test.yml/badge.svg)](https://github.com/lancew/ScientistP6/actions/workflows/test.yml) # SYNOPSIS ``` flowchart LR raku[$exp.run] -->|execute| use(Control Code) --> compare(Compare Result) raku -->|execute| try(Candidate Code) --> compare(Compare Result) use --> return[Return Result] compare -->|publish| Metrics ``` ``` use Scientist; my $experiment = Scientist.new( experiment => 'Tree', try => sub {return 99}, use => sub {return 10}, ); my $answer = $experiment.run; say "The number ten is $answer"; warn 'There was a mismatch between control and candidate' if $test.result{'mismatched'}; ``` # Introduction This module is inspired by the Scientist ruby code released by GitHub under the MIT license in 2015/2016. In February 2016 I started writing the Perl5 module to bring similar ideas to Perl. Later I started this module to apply same ideas in Raku. Please get involved in this module; contact [[email protected]](mailto:[email protected]) with ideas, suggestions; support, etc. This code is also released under the MIT license to match the original Ruby implementation. # Methods / Attributes ## context() Provide contextual information for the experiment; will be returned in the result set. Should be a hashref ## enabled(|) DEFAULT : TRUE Boolean switch to enable or disable the experiment. If disabled the experiment will only return the control code (use) result. The candidate code (try) will NOT be executed. The results set will not be populated. ## experiment() Simply the name of the experiment included in the result set. ## publish Publish is a method called by ->run(). Scientist is design so that you create your own personalised My::Scientist module and extend publish to do what you want/need. For example push timing and mismathc information to Statsd. ## use() Control code to be included in the experiment. This code will be executed and returned when the experiment is run. NB: This code is run and returned even if experiment enabed=false. ## run() This method executes the control (use) code and if experiment enabled will also run the candidate (try) code. The control and candidate code is run in random order. ## try() Candidate code to be included in the experiment. This code will be executed and discarded when the experiment is run. # Extending Publish To automate reporting of experiement results, you will want to write your own .publish() method. Publish is called by .run(). A typical example would be to push timing information to Statsd or a database. ``` use Scientist; class MyScientist is Scientist { has $.test_value is rw; method publish { # Do Stuff... } } my $experiment = MyScientist.new( experiment => 'Tree', enabled => True, try => sub {return 99}, use => sub {return 88}, ); ``` # AUTHOR Lance Wicks [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE This software is Copyright (c) 2016 by Lance Wicks. This is free software, licensed under: The MIT (X11) License The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # SEE ALSO <http://www.infoq.com/news/2016/02/github-scientist-refactoring> <http://githubengineering.com/scientist/> <https://news.ycombinator.com/item?id=11104781> <https://github.com/ziyasal/scientist.js> <http://tech-blog.cv-library.co.uk/2016/03/03/introducing-scientist/>
## dist_zef-tbrowder-File-file.md [![Actions Status](https://github.com/tbrowder/File-file/actions/workflows/linux.yml/badge.svg)](https://github.com/tbrowder/File-file/actions) [![Actions Status](https://github.com/tbrowder/File-file/actions/workflows/macos.yml/badge.svg)](https://github.com/tbrowder/File-file/actions) [![Actions Status](https://github.com/tbrowder/File-file/actions/workflows/windows.yml/badge.svg)](https://github.com/tbrowder/File-file/actions) # NAME **File::file** - Provides a Raku wrapper for the system 'file' command # SYNOPSIS ``` use File::file; my $o = File::file.new; say $o.file: ".."; # OUTPUT: «..: directory␤» ``` # DESCRIPTION **File::file** is a convenience wrapper around the system 'file' command. # AUTHOR Tom Browder [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE © 2023 Tom Browder This library is free software; you may redistribute it or modify it under the Artistic License 2.0.
## dist_cpan-AKIYM-JSON-Hjson.md [![Build Status](https://travis-ci.org/akiym/JSON-Hjson.svg?branch=master)](https://travis-ci.org/akiym/JSON-Hjson) # NAME JSON::Hjson - Human JSON (Hjson) deserializer # SYNOPSIS ``` use JSON::Hjson; my $text = q:to'...'; { // specify delay in // seconds delay: 1 message: wake up! } ... say from-hjson($text).raku; ``` # DESCRIPTION JSON::Hjson implements Human JSON (Hjson) in Raku grammar. # SEE ALSO JSON::Tiny <https://hjson.org/rfc.html> # AUTHOR Takumi Akiyama [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2016 Takumi Akiyama This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-raku-community-modules-GlotIO.md [![Actions Status](https://github.com/raku-community-modules/GlotIO/workflows/test/badge.svg)](https://github.com/raku-community-modules/GlotIO/actions) # NAME GlotIO - use glot.io API via Raku # SYNOPSIS ``` use GlotIO; my GlotIO $glot .= new: :key<89xxxx9f-a3ec-4445-9f14-6xxxe6ff3846>; say $glot.languages; ``` # TABLE OF CONTENTS * [NAME](#name) * [SYNOPSIS](#synopsis) * [DESCRIPTION](#description) * [KEY](#key) * [METHODS](#methods) * [`.new`](#new) * [`.languages`](#languages) * [`.versions`](#versions) * [`.run`](#run) * [`.stdout`](#stdout) * [`.stderr`](#stderr) * [`.list`](#list) * [`.create`](#create) * [`.get`](#get) * [`.update`](#update) * [`.delete`](#delete) * [REPOSITORY](#repository) * [BUGS](#bugs) * [AUTHOR](#author) * [LICENSE](#license) # DESCRIPTION This module lets you use API provided [glot.io](http://glot.io) which is a pastebin that also lets you execute code in a number of languages. # KEY Some parts of the API require you register at glot.io and [obtain an API key](https://glot.io/api) # METHODS ## `.new` ``` my GlotIO $glot .= new: :key<89xxxx9f-a3ec-4445-9f14-6xxxe6ff3846>; ``` Constructs and returns a new `GlotIO` object. Takes one **optional** argument: `key`, which is [the API key](https://glot.io/api). Methods that require the key are marked as such. ## `.languages` ``` say "Glot.io supports $_" for $glot.languages; ``` Returns a list of languages supported by GlotIO. ## `.versions` ``` say "Glot.io supports $_ version of Raku" for $glot.versions: 'raku'; ``` Returns a list of supported versions for a language that must be supplied as the mandatory positional argument. List of valid language names can be obtained via `.languages` method. Using an invalid language will `fail` as an HTTP 404 error. ## `.run` ``` say $glot.run: 'raku', 'say "Hello, World!"'; say $glot.run: 'raku', [ 'main.raku' => 'use lib "."; use Foo; doit;', 'Foo.rakumod' => 'unit module Foo; sub doit is export { say "42" }', ]; say $glot.run: 'python', 'print "Hello, World!"', :ver<2>; ``` Requests code to run on Glot. The first positional argument specifies the language to use (see `.languages` method). Second argument can either be an `Str` of code to run or an `Array` of `Pair`s. If the array is specified, the key of each `Pair` specifies the filename and the value specifies the code for that file. The first file in the array will be executed by Glot, while the rest are supporting files, such as modules loaded by the first file. The optional named argument `ver` can be used to specify the version of the language to use. See `.versions` method. Returns a `Hash` with three keys: `stdout`, `stderr` which specify the output streams received from the program and `error` that seems to contain an error code, if the program doesn't successfully exit. If an incorrect language or version are specified, will `fail` with an HTTP 404 error. ## `.stdout` ``` say $glot.stdout: 'raku', 'say "Hello, World!"'; ``` A shortcut for calling `.run` (takes same arguments) and returning just the `stdout` key. Will `fail` with the entire `Hash` returned from `.run` if the program errors out. ## `.stderr` ``` say $glot.stderr: 'raku', 'note "Hello, World!"'; ``` A shortcut for calling `.run` (takes same arguments) and returning just the `stderr` key. Will `fail` with the entire `Hash` returned from `.run` if the program errors out. ## `.list` ``` say $glot.list<content>[0..3]; say $glot.list: :3page, :50per-page, :mine; ``` Fetches a list of metadata for snippets. Takes optional named arguments: * `page` positive integer starting at and defaulting to 1. Specifies the page to display * `per-page` positive integer stating the maximum number of items to return per page. Defaults to `100`. Maximum value is `100`. * `mine` boolean specifying whether public or your own snippets should be listed. Defaults to `False`. Requires `key` argument to `.new` to be provided if set to `True`. Returns a `Hash` in the following format: ``` { first => 1, last => 20, next => 5, prev => 3, content => [ { created => "2016-04-09T17:52:19Z", files_hash => "2afa1f37cc0bc7d033e4b3a049659792f5caac6d", id => "edltstt3n0", language => "cpp", modified => "2016-04-09T17:52:19Z", owner => "anonymous", public => Bool::True, title => "Untitled", url => "https://snippets.glot.io/snippets/edltstt3n0", }, ... ] } ``` The `first`, `last`, `next`, `prev` keys indicate the corresponding page number. All 4 will NOT be present at all times. The `content` key is a list of hashes, each representing metadata for a snipet. Attempting to fetch a page that doesn't exist will `fail` with an HTTP 404 error. ## `.create` ``` say $glot.create: 'perl6', 'say "Hello, World!"'; say $glot.create: 'perl6', [ 'main.p6' => 'use lib "."; use Foo; say "Hello, World!"', 'Foo.pm6' => 'unit module Foo;', ], 'Module import example', :mine; ``` Creates a new snippet. Takes: a valid language (see `.languages` method), either a `Str` of code or an array of `filename => code` pairs, and an optional title of the snippet as positional arguments. An optional `Bool` `mine` named argument, which defaults to `False` can be set to `True` to specify your snippet should not be public. API Key (see `.key` in `.new`) must be specified for this option to succeed. Returns a hash with metadata for the newly created snippet: ``` { created => "2016-04-10T17:42:20Z".Str, files => [ { content => "say \"Hello, World!\"".Str, name => "main".Str, }, ], files_hash => "6ed47f09569b36dc8d83b6af82026e5f86e3967e".Str, id => "edmx7tewwu".Str, language => "perl6".Str, modified => "2016-04-10T17:42:20Z".Str, owner => "c490baa3-1ecb-42f5-8742-216abbb97f8d".Str, public => Bool::False.Bool, title => "Untitled".Str, url => "https://snippets.glot.io/snippets/edmx7tewwu".Str, } ``` ## `.get` ``` say $glot.get: 'edmxttmtd5'; ``` Fetches a snippet. Takes one mandatory argument: the ID of the snippet to fetch. Returns a hash with the snippet details: ``` { created => "2016-04-10T18:04:30Z".Str, files => [ { content => "use lib \".\"; use Foo; say \"Hello, World!\"".Str, name => "main.raku".Str, }, { content => "unit module Foo;".Str, name => "Foo.rakumod".Str, }, ], files_hash => "8042cf6813f1772e63c8afd0a556004ad9591ce2".Str, id => "edmxttmtd5".Str, language => "raku".Str, modified => "2016-04-10T18:04:30Z".Str, owner => "c490baa3-1ecb-42f5-8742-216abbb97f8d".Str, public => Bool::True.Bool, title => "Module import example".Str, url => "https://snippets.glot.io/snippets/edmxttmtd5".Str, } ``` ## `.update` ``` say $glot.update: 'snippet-id', 'perl6', 'say "Hello, World!"'; # Or say $glot.update: 'snippet-id', 'perl6', [ 'main.p6' => 'use lib "."; use Foo; say "Hello, World!"', 'Foo.pm6' => 'unit module Foo;', ], 'Module import example'; # Or my $snippet = $glot.get: 'edmxttmtd5'; $snippet<title> = 'New title'; $glot.update: $snippet; ``` Updates an existing snippet. Requires the use of API key (see `.key` in constructor). As positional arguments, takes snippet ID to update, the language of the snippet, snippet code, and snippet title. The title is optional and will be set to `Untitled` by default. Snippet code can be provided as a single string of code or as an array of `Pair`s, where the key is the filename and the value is the code for the file. In addition, `.update` can also take a `Hash`. This form is useful when you already have a snippet `Hash` from `.create` or `.get` methods and simply wish to modify it. The required keys in the hash are `id`, `title`, `language`, and `files`, where the first three are strings and `files` is an array of Hashes, with each hash having keys `name` and `content` representing the filename of a file and its code. Returns a `Hash` with the updated snippet data: ``` { created => "2016-04-10T18:04:30Z".Str, files => [ { content => "use lib \".\"; use Foo; say \"Hello, World!\"".Str, name => "main.p6".Str, }, { content => "unit module Foo;".Str, name => "Foo.pm6".Str, }, ], files_hash => "8042cf6813f1772e63c8afd0a556004ad9591ce2".Str, id => "edmxttmtd5".Str, language => "perl6".Str, modified => "2016-04-13T00:05:02Z".Str, owner => "c490baa3-1ecb-42f5-8742-216abbb97f8d".Str, public => Bool::False.Bool, title => "New title".Str, url => "https://snippets.glot.io/snippets/edmxttmtd5".Str, } ``` ## `.delete` ``` $glot.delete: 'snippet-id'; ``` Deletes a snippet. Requires the use of API key (see `.key` in constructor). Takes one positional argument: the ID of the snippet to delete. On success, returns `True`. Attempting to delete a non-existant snippet will `fail` with an HTTP 404 error. --- # REPOSITORY Fork this module on GitHub: <https://github.com/raku-community-modules/GlotIO> # BUGS To report bugs or request features, please use <https://github.com/raku-community-modules/GlotIO/issues> # AUTHOR Zoffix Znet (<http://zoffix.com/>) # LICENSE You can use and distribute this module under the terms of the The Artistic License 2.0. See the `LICENSE` file included in this distribution for complete details.
## dist_github-khalidelboray-Text-Slugify.md [![Build Status](https://travis-ci.org/khalidelboray/raku-text-slugify.svg?branch=master)](https://travis-ci.org/khalidelboray/raku-text-slugify) # NAME `Text::Slugify` - create a URL slug from text. # SYNOPSIS ``` use Text::Slugify; my $txt; $txt = "This is a test ---"; slugify $txt; #=> «this-is-a-test» $txt = 'C\'est déjà l\'été.'; slugify $txt; #= «c-est-deja-l-ete» $txt = 'jaja---lol-méméméoo--a'; slugify $txt, :max-length(9); #=> «jaja-lol» ``` For more examples, have a look at the test file (`t/basic.t6`). # DESCRIPTION `Text::Slugify` is a module to slugify text. It takes a piece of text, removes punctuation, spaces and other unwanted characters to produce a string suitable for use in a URL. # INSTALLATION ## Using zef: ``` zef update && zef install Text::Slugify ``` ## From source: ``` git clone https://github.com/khalidelboray/raku-text-slugify.git cd raku-text-slugify && zef install . ``` # SUBROUTINES The module exports the following subroutines: #### `slugify` ``` sub slugify( Str:D $text is copy, # Text to be slugified. Int:D :$max-length = 0, # Output string length. :$separator = "-", # Separator between words. :$regex-pattern = Nil, # Regex pattern for allowed characters in output text. :@stopwords = [], # Words to be discounted from output text. :@replacements = [], # List of replacement rule pairs e.g. ['|'=>'or', '%'=>'percent'] Bool:D :$entities = True, Bool:D :$decimal = True, Bool:D :$hexadecimal = True, Bool:D :$word-boundary = False, Bool:D :$lowercase = True, # Set case sensitivity by setting it to False. Bool:D :$save-order = False, # If True and max-length > 0 return whole words in the initial order. ) ``` #### `smart-truncate` ``` sub smart-truncate( Str:D $string is rw, # String to be modified. Int:D :$max-length = 0, # Output string length. Bool:D :$word-boundary = False, Str:D :$separator = " ", # Separator between words. Bool:D :$save-order = False, # Output text's word order same as input. ) ``` **NOTE**: To import the subroutine `smart-truncate` or `strip` alongside `slugify` into your code, use `use Text::Slugify :ALL`. # CREDIT-REFERENCE This module is mostly based on [Python Slugify](https://github.com/un33k/python-slugify). This is my fork of <https://gitlab.com/uzluisf/raku-text-slugify>
## dist_zef-andinus-taurus.md ``` ━━━━━━━━━━━━━━━━━━━━━━━━━ TAURUS Taurus parses Call logs Andinus ━━━━━━━━━━━━━━━━━━━━━━━━━ Table of Contents ───────────────── Demo Installation Documentation News ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Website Source GitHub (mirror) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Demo ════ This was recorded with `asciinema'. [https://asciinema.org/a/431154.png] ⁃ Taurus v0.1.1: ⁃ alt-link (download): [https://asciinema.org/a/431154.png] Installation ════════════ Taurus is released to `fez', you can get it from there or install it from source. In any case, `zef' is required to install the distribution. You can run Taurus without `zef'. Just run `raku -Ilib bin/taurus' from within the source directory. Release ─────── 1. Run `zef install taurus'. Taurus should be installed, try running `taurus --version' to confirm. From Source ─────────── You can either download the release archive generated by cgit/GitHub or clone the project if you have `git' installed. Without `git' ╌╌╌╌╌╌╌╌╌╌╌╌╌ 1. Download the release: • • 2. Extract the file. 3. Run `zef install .' in source directory. With `git' ╌╌╌╌╌╌╌╌╌╌ All commits will be signed by my [PGP Key]. ┌──── │ # Clone the project. │ git clone https://git.tilde.institute/andinus/taurus │ cd taurus │ │ # Install taurus. │ zef install . └──── [PGP Key] Documentation ═════════════ Taurus parses Call logs exported by [OpenContacts]. Get the application from F-Droid and export the call logs by selecting /More/, then /Export call log/ from the three dot menu on top right. [OpenContacts] Implementation ────────────── It parses the exported log file line by line, stores them & presents an interface. Options ─────── log ╌╌╌ Exported log file. digits ╌╌╌╌╌╌ Number of significant digits in phone numbers. Default is set to 10. If the number of digits is less than significant digits then the number is discarded, if it's more then the initial extra digits are discarded (Country Code, etc.). News ════ v0.1.1 - 2021-08-19 ─────────────────── ⁃ Better format for timestamps. ⁃ Add Yearly Records. ⁃ Add Monthly Records. v0.1.0 - 2021-08-15 ─────────────────── Initial Implementation. ⁃ Present overall stats. ⁃ Displays contact specific stats. ⁃ Outgoing ⁃ Incoming ⁃ Total Call Time ⁃ Declined ⁃ They Declined ⁃ Missed Calls ```
## dist_zef-lizmat-InterceptAllMethods.md [![Actions Status](https://github.com/lizmat/InterceptAllMethods/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/InterceptAllMethods/actions) [![Actions Status](https://github.com/lizmat/InterceptAllMethods/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/InterceptAllMethods/actions) [![Actions Status](https://github.com/lizmat/InterceptAllMethods/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/InterceptAllMethods/actions) # NAME InterceptAllMethods - export ClassHOW to intercept all method calls # SYNOPSIS ``` use InterceptAllMethods; class FooBar { method ^find_method(Mu $obj, Str $name) { return -> | { say "calling $name" } } } ``` # DESCRIPTION Change the ClassHOW of the compilation unit so that you can create a class that has a `^find_method` that will be called for **any** method call to that class. This method should then return a `Callable` that will called as if it were the method. This allows one to implement one's own caching methods, or not have any caching method at all. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/InterceptAllMethods> . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2018, 2021, 2023, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## find-method.md find\_method Combined from primary sources listed below. # [In role Metamodel::MROBasedMethodDispatch](#___top "go to top of document")[§](#(role_Metamodel::MROBasedMethodDispatch)_method_find_method "direct link") See primary documentation [in context](/type/Metamodel/MROBasedMethodDispatch#method_find_method) for **method find method**. ```raku method find_method($obj, $name, :$no_fallback, *%adverbs) ``` Given a method name, it returns the method object of that name which is closest in the method resolution order (MRO). If no method can be found, it returns a VM-specific sentinel value (typically a low-level NULL value) that can be tested for with a test for [definedness](/routine/defined): ```raku for <uppercase uc> { Str.^find_method: $^meth andthen .("foo").say orelse "method `$meth` not found".say } # OUTPUT: # method `uppercase` not found # FOO ``` If `:no_fallback` is supplied, fallback methods are not considered. # [In Metamodel::DefiniteHOW](#___top "go to top of document")[§](#(Metamodel::DefiniteHOW)_method_find_method "direct link") See primary documentation [in context](/type/Metamodel/DefiniteHOW#method_find_method) for **method find method**. ```raku method find_method($definite_type, $name) ``` Looks up a method on the base type of a definite type.
## control.md role X::Control Role for control exceptions ```raku role X::Control is Exception { } ``` This role turns an exception into a [control exception](/language/exceptions#Control_exceptions), such as [`CX::Next`](/type/CX/Next) or [`CX::Take`](/type/CX/Take). It has got no code other than the definition. Since Rakudo 2019.03, `throw`ing an object that mixes in this role `X::Control` can raise a control exception which is caught by the [CONTROL phaser](/language/phasers#CONTROL) instead of [CATCH](/language/phasers#CATCH). This allows to define custom control exceptions. For example, the custom `CX::Vaya` control exception we define below: ```raku class CX::Vaya does X::Control { has $.message } sub ea { CONTROL { default { say "Controlled { .^name }: { .message }" } } CX::Vaya.new( message => "I messed up!" ).throw; } ea; # OUTPUT: «Controlled CX::Vaya: I messed up!␤» ```
## dist_cpan-FRITH-Math-Libgsl-Complex.md [![Build Status](https://travis-ci.org/frithnanth/raku-Math-Libgsl-Complex.svg?branch=master)](https://travis-ci.org/frithnanth/raku-Math-Libgsl-Complex) # NAME Math::Libgsl::Raw::Complex - An interface to libgsl, the Gnu Scientific Library - complex numbers. # SYNOPSIS ``` use Math::Libgsl::Raw::Complex :ALL; ``` # DESCRIPTION Math::Libgsl::Raw::Complex provides an interface to libgsl's implementation of complex numbers. This package provides the low-level interface to the C library (Raw). Math::Libgsl::Complex will not be implemented, because Raku's Complex datatype works just fine. Its Raw counterpart, Math::Libgsl::Raw::Complex, is present because it's needed by other modules that rely on the GSL implementation of complex numbers. # C Library Documentation For more details on libgsl see <https://www.gnu.org/software/gsl/>. The excellent C Library manual is available here <https://www.gnu.org/software/gsl/doc/html/index.html>, or here <https://www.gnu.org/software/gsl/doc/latex/gsl-ref.pdf> in PDF format. # Prerequisites This module requires the libgsl library to be installed. Please follow the instructions below based on your platform: ## Debian Linux ``` sudo apt install libgsl23 libgsl-dev libgslcblas0 ``` That command will install libgslcblas0 as well, since it's used by the GSL. ## Ubuntu 18.04 libgsl23 and libgslcblas0 have a missing symbol on Ubuntu 18.04. I solved the issue installing the Debian Buster version of those three libraries: * <http://http.us.debian.org/debian/pool/main/g/gsl/libgslcblas0_2.5+dfsg-6_amd64.deb> * <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl23_2.5+dfsg-6_amd64.deb> * <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl-dev_2.5+dfsg-6_amd64.deb> # Installation To install it using zef (a module management tool): ``` $ zef install Math::Libgsl::Complex ``` # AUTHOR Fernando Santagata [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2020 Fernando Santagata This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-JJMERELO-Pod-Load_1.md [![Build Status](https://travis-ci.com/JJ/p6-pod-load.svg?branch=master)](https://travis-ci.com/JJ/p6-pod-load) [![Build status](https://ci.appveyor.com/api/projects/status/lq9rqjq6hljdfqw4?svg=true)](https://ci.appveyor.com/project/JJ/p6-pod-load) # NAME Pod::Load - Loads and compiles the Pod documentation of an external file # SYNOPSIS ``` use Pod::Load; # Read a file handle. my $pod = load("file-with.pod6".IO); say $pod.raku; # Process it as a Pod # Or use simply the file name my @pod = load("file-with.pod6"); say .raku for @pod; # Or a string @pod = load("=begin pod\nThis could be a comment with C<code>\n=end pod"); # Or ditch the scaffolding and use the string directly: @pod = load-pod("This could be a comment with C<code>"); ``` # DESCRIPTION Pod::Load is a module with a simple task: obtain the documentation of an external file in a standard, straighworward way. Its mechanism is inspired by [`Pod::To::BigPage`](https://github.com/perl6/perl6-pod-to-bigpage), from where the code to use the cache is taken from. ### multi sub load ``` multi sub load( Str $string ) returns Mu ``` Loads a string, returns a Pod. ### multi sub load ``` multi sub load( Str $file where { ... } ) returns Mu ``` If it's an actual filename, loads a file and returns the pod ### multi sub load ``` multi sub load( IO::Path $io ) returns Mu ``` Loads a IO::Path, returns a Pod. ## INSTALL Do the usual: ``` zef install . ``` to install this if you've made any modification. # INSTRUCTIONS This is mainly a reminder to myself, although it can help you if you create a distribution just like this one. Write: ``` export VERSION=0.x.x ``` And ``` make dist ``` To create a tar file ready for CPAN. # AUTHOR JJ Merelo [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2020 JJ Merelo This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-lizmat-Unicode.md [![Actions Status](https://github.com/lizmat/Unicode/actions/workflows/test.yml/badge.svg)](https://github.com/lizmat/Unicode/actions) # NAME Unicode - provide information about Unicode versions # SYNOPSIS ``` use Unicode; ``` # DESCRIPTION The `Unicode` class provided information about the (current) Unicode version supported. It was introduced in Rakudo release 2023.02. It is provided here to allow the functionality to be used with older versions of Rakudo. If Rakudo already supplies a `Unicode` class, then loading this module will effectively be a no-op. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Unicode> . 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 2023 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-jjatria-Timer-Stopwatch.md ## NAME Timer::Stopwatch - Schedule and reset repeated time measurements ## SYNOPSIS ``` use Timer::Stopwatch; my $irregular-supply = Supply.interval(1).grep: { Bool.pick } my $timer = Timer::Stopwatch.new; react { whenever $irregular-supply { note "{ now.DateTime.hh-mm-ss }: Received an irregular event"; # Wait up to 2 seconds for the next event $timer.reset: 2; } whenever $timer { note "It's been { .round } seconds since the last event"; $timer.stop; } whenever Promise.in: 20 { note 'Stopping after 20 seconds'; $timer.stop; } whenever $timer.Promise { note "Timer was stopped. We're done"; done; } } # OUTPUT: # 20:33:39: Received an irregular event # 20:33:40: Received an irregular event # 20:33:42: Received an irregular event # It's been 2 seconds since the last event # Timer was stopped. We're done ``` ## DESCRIPTION Timer::Stopwatch is a resettable, stoppable wrapper around a Supply that can be used to mark multiple moments in time. ## METHODS ### in ``` method in( Numeric $in ) returns Timer::Stopwatch ``` Creates a new Stopwatch with a timer that will trigger in the given amount of seconds, unless it is reset or stopped before that. ### tick ``` method tick() returns Duration ``` Emits the duration since creation time (or the last `reset`) to the Supply. Returns the emitted Duration. ### reset ``` method reset( Numeric $in? ) returns Bool ``` Reset sets the start time for the stopwatch to the current time. If called with a numeric argument, it also sets a timer to expire after the given duration. It returns True if the call interrupted a pending timer, and False if no timer had been set, or if it had already expired, or if the stopwatch had already been stopped. ### stop ``` method stop() returns Bool ``` Stop marks this stopwatch as done. Once a stopwatch has been stopped, most of its actions are finished, and new stopwatch should be created. Internally, it stops any pending timers and closes the supply. It returns True if the call interrupted a pending timer, and False if no timer had been set, or if it had already expired, or if the stopwatch had already been stopped. ### Duration ``` method Duration() returns Duration ``` Returns the amount of time elapsed since the start (or the last reset) as a Duration. ### Promise ``` method Promise() returns Promise ``` Returns a Promise that will be kept when the Stopwatch is stopped. When kept, it will hold the Duration elapsed since the time the Stopwatch was created, or since the last call to `reset`. ### Supply ``` method Supply() returns Supply ``` Returns a live Supply that will receive timer events ## AUTHOR José Joaquín Atria [[email protected]](mailto:[email protected]) ## COPYRIGHT AND LICENSE Copyright 2021 José Joaquín Atria This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-andinus-fornax.md ``` ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ FORNAX Collection of tools to visualize Path Finding Algorithms Andinus ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Table of Contents ───────────────── 1. Demo 2. Usage 3. Installation .. 1. Release .. 2. From Source 4. Documentation .. 1. Options .. 2. Fornax Format .. 3. Project Structure 5. Bugs 6. News .. 1. v0.2.0 - 2021-11-25 .. 2. v0.1.1 - 2021-11-16 .. 3. v0.1.0 - 2021-11-03 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Website Source GitHub (mirror) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ This collection includes: • `fornax': Program that parses /Fornax Format/ and outputs video solution. • Algorithms: Various algorithms solved in several programming languages. Writings: • Fornax: Generating 4.8 million frames: 1 Demo ══════ Solution for DFS-60, generated on 2021-11-16 (click to play): [https://andinus.unfla.me/resources/projects/fornax/2021-11-16-DFS-60-00000436.png] • Mirror: • Solution for /DFS-71/, generated on /2021-11-18/: Fornax v0.1.0: • Solution for /DFS-33/, generated on /2021-11-03/: • DFS-51-incomplete (upto 187,628 frames; 120 fps): • DFS-51-incomplete (upto 4,000 frames; 120 fps): [https://andinus.unfla.me/resources/projects/fornax/2021-11-16-DFS-60-00000436.png] 2 Usage ═══════ ┌──── │ # Solve the maze. │ raku algorithms/raku/DFS.raku resources/input/06 > /tmp/solution.fornax │ │ # Visualize the solution. │ raku -Ilib bin/fornax /tmp/solution.fornax └──── 3 Installation ══════════════ `fornax' is written in Raku, it can be installed with `zef'. You can also run it without `zef', just run `raku -Ilib bin/fornax' from within the source directory. • *Note*: `Cairo' module & `ffmpeg' program is required. 3.1 Release ─────────── 1. Run `zef install 'fornax:auth'' Fornax should be installed, try running `fornax --version' to confirm. • Solving programs / solutions are not included in the distribution, get them from this repository. 3.2 From Source ─────────────── You can either download the release archive generated by cgit/GitHub or clone the project if you have `git' installed. 3.2.1 Without `git' ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ 1. Download the release: • • 2. Extract the file. 3. Run `zef install .' in source directory. 3.2.2 With `git' ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ All commits by /Andinus/ will be signed by this [PGP Key]. ┌──── │ # Clone the project. │ git clone https://git.tilde.institute/andinus/fornax │ cd fornax │ │ # Install fornax. │ zef install . └──── [PGP Key] 4 Documentation ═══════════════ Fornax parses /Fornax format/, generates a `PNG' for each iteration which is later converted to a slideshow with `ffmpeg'. • Solved paths are highlighted if the iteration is preceded by `|'. • Illegal paths are highlighted if the iteration is preceded by `!'. 4.1 Options ─────────── • `input': This takes solved input file in the /Fornax/ format. • `fps': Frame rate for the video solution. • `skip-video': Skip generating the video solution. • `batch': Number of iterations to process at once. 4.2 Fornax Format ───────────────── Fornax format defines 2 formats: • Maze (input) • Solution (output) 4.2.1 Grids ╌╌╌╌╌╌╌╌╌╌╌ A grid is printed for every iteration. Grids are composed of cells. ━━━━━━━━━━━━━━━━━━━━━━━━━━ Cell Symbol ────────────────────────── Path `.' Blocked `#' Start `^' Destination `$' ────────────────────────── Visited `-' Current Path `~' Current Position `@' ━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.2.2 Maze (input) ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ Maze input must be in this format: ┌──── │ ...rows └──── It is upto the program to infer the number of rows & columns from the input file or it ask the user. 4.2.3 Solution (output) ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ Fornax solution format is an intermediate output file generated after solving the maze. Algorithms must output the solution in this format: ┌──── │ rows: cols: │ │ ...iterations └──── `...iterations' is to be replaced by the resulting grid in each iteration that is to be included in the final video. Since the number of rows and columns is known, the whole grid should be printed in a single line. • Every iteration should be separated by a newline. • If the iteration cells is not equal to `rows * columns' or `(rows * columns) + 1' then it may be ignored by the program that parses the file. • Solved iteration can be preceded by `|' character. • Iteration that tries to walk on a blocked path can be preceded by `!' character. • First iteration is assumed to be the maze. 4.3 Project Structure ───────────────────── • Algorithms are located in `algorithms/' directory, sub-directory needs to be created for programming languages which will hold the actual source. • Sample solutions can be found in `resources/solutions/' directory. • *Note*: Some solutions might output illegal moves (like walking over blocked path), this error is only in visualization, the solution is correct. This has been fixed in commit `8cef86f0eb8b46b0ed2d7c37fa216890300249f6'. 5 Bugs ══════ • If the number of iterations are greater than an 8 digit number then the slideshow might be incorrect. • `/tmp' is assumed to exist. • Might panic with: `MoarVM oops: MVM_str_hash_entry_size called with a stale hashtable pointer'. This has been fixed: . 6 News ══════ 6.1 v0.2.0 - 2021-11-25 ─────────────────────── ⁃ Add demo videos. ⁃ Add more solutions. ⁃ Implement BFS in Java. ⁃ Implement DFS in Raku. ⁃ Add basic tests. 6.2 v0.1.1 - 2021-11-16 ─────────────────────── ⁃ Add option to skip generating slideshow. ⁃ Use random directory to store solutions. ⁃ Process iterations in parallel. ⁃ Wait 4s on solution frame. ⁃ Add incomplete BFS program. ⁃ Add demo videos. ⁃ Upgrade to latest Fornax Format. ⁃ Add more solutions. 6.3 v0.1.0 - 2021-11-03 ─────────────────────── ⁃ Initial implementation: • Includes DFS solver in Java and a tool to visualize the solution. ```
## dist_zef-tony-o-HTML-Parser-XML.md # Perl 6: HTML::Parser::XML; This module will read HTML and attempt to build an XML::Document (<https://github.com/supernovus/exemel/#xmldocument-xmlnode>) ## Features: * Automatically closes certain tags if certain other tags are encountered * Parses dirty HTML fairly well (AFAIK), submit a bug if it doesn't * Perl6 Magicness ## Status: Bugs/feature requests Maintenance mode ### Usage: ``` my $html = LWP::Simple.get('http://some-non-https-site.com/'); my $parser = HTML::Parser::XML.new; $parser.parse($html); $parser.xmldoc; # XML::Document ``` > or ``` my $html = LWP::Simple.get('http://some-non-https-site.com/'); my $parser = HTML::Parser::XML.new; my $xmldoc = $parser.parse($html); ``` Contact me, tony-o on irc.freenode #perl6 (tony-o) License: Artistic 2.0
## dist_zef-tbrowder-Timezones-US.md [![Actions Status](https://github.com/tbrowder/Timezones-US/actions/workflows/linux.yml/badge.svg)](https://github.com/tbrowder/Timezones-US/actions) [![Actions Status](https://github.com/tbrowder/Timezones-US/actions/workflows/macos.yml/badge.svg)](https://github.com/tbrowder/Timezones-US/actions) [![Actions Status](https://github.com/tbrowder/Timezones-US/actions/workflows/windows.yml/badge.svg)](https://github.com/tbrowder/Timezones-US/actions) # NAME **Timezones::US** - Provides US time zone data and subroutines for use with modules 'DateTime::US' and 'LocalTime' # SYNOPSIS ``` use Timezones::US; ``` # DESCRIPTION Raku module **Timezones::US** provides constant US time zone data (currently valid through the year 2030) to be used by related date and time dynamic modules. The following table shows the time zones included: US Time Zones | Name | Symbol | UTC offset (hrs) | | --- | --- | --- | | Atlantic | AST | -4, | | Eastern | EST | -5 | | Central | CST | -6 | | Mountain | MST | -7 | | Pacific | PST | -8 | | Alaska | AKST | -9 | | Hawaii-Aleutian | HAST | -10 | | Samoa | WST | -11 | | Chamorro | CHST | +10 | ### Exported constants The following constants are automatically exported into the using environment: * `SEC-PER-HOUR` Seconds per hour: 3600 * `@tz` A list of time zones (lower-case symbols) * `%tzones` A hash of all US time zone abbreviations keyed by their symbols (lower-case) with values of names and UTC offsets * `%dst-exceptions` A hash of US time zone abbreviations keyed by their symbols (lower-case) with values of states or regions and details of Daylight Saving exceptions (**CAUTION**: this an incomplete list at the moment) * `%utc-offsets` A hash of US time zone abbreviations keyed by their symbols (lower-case) with value of their UTC offset in hours * `%offsets-utc` A hash of US time zone offsets keyed by their hours with value of their symbols (lower-case) ### Exported subroutines The following subroutines are automatically exported into the using environment: * **begin-dst**($year --> DateTime) {...} Return the time when DST (Daylight Saving Time) begins. * **end-dst**($year --> DateTime) {...} Return the time when DST ends. * **is-dst**(DateTime :$localtime! --> Bool) {...} Return True if the local time is DST, otherwise return False. * **is-dst**(:$year!, :$month, :$day, :$hour, :$minute, :$second --> Bool) {...} Return True if the local time is DST, otherwise return False. * **show-us-data**(--> Str) {...} List the time zone and DST data being used. Note some of these routines are now duplicated in module `DateTime::US`, but those are (1) perpetual and (2) return `Date` objects instead of `DateTime` objects which are preferred for use by the author's module `Calendar`. As well, this module was designed to be completely standalone. If the user requires "perpetual" DST dates for all all years affected under current US federal law, please use the routines in `DateTime::US`. # AUTHOR Tom Browder [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE © 2022-2024 Tom Browder This library is free software; you may redistribute it or modify it under the Artistic License 2.0.
## range.md class Range Interval of ordered values ```raku class Range is Cool does Iterable does Positional {} ``` Ranges serve two main purposes: to generate lists of consecutive numbers or strings, and to act as a matcher to check if a number or string is within a certain range. Ranges are constructed using one of the four possible range operators, which consist of two dots, and optionally a caret which indicates that the endpoint marked with it is excluded from the range. ```raku 1 .. 5; # 1 <= $x <= 5 1^.. 5; # 1 < $x <= 5 1 ..^5; # 1 <= $x < 5 1^..^5; # 1 < $x < 5 ``` The caret is also a prefix operator for constructing numeric ranges starting from zero: ```raku my $x = 10; say ^$x; # same as 0 ..^ $x.Numeric ``` Iterating a range (or calling the `list` method) uses the same semantics as the `++` prefix and postfix operators, i.e., it calls the `succ` method on the start point, and then the generated elements. Ranges always go from small to larger elements; if the start point is bigger than the end point, the range is considered empty. ```raku for 1..5 { .say }; # OUTPUT: «1␤2␤3␤4␤5␤» say ('a' ^..^ 'f').list; # OUTPUT: «(b c d e)␤» say 5 ~~ ^5; # OUTPUT: «False␤» say 4.5 ~~ 0..^5; # OUTPUT: «True␤» say (1.1..5).list; # OUTPUT: «(1.1 2.1 3.1 4.1)␤» ``` Use the [`...`](/language/operators#infix_...) sequence operator to produce lists of elements that go from larger to smaller values, or to use offsets other than increment-by-1 and other complex cases. Use `∞` or `*` (Whatever) to indicate an end point to be open-ended. ```raku for 1..* { .say }; # start from 1, continue until stopped for 1..∞ { .say }; # the same ``` Beware that a [`WhateverCode`](/type/WhateverCode) end point, instead of a plain Whatever, will go through the range operator and create another WhateverCode which returns a Range: ```raku # A Whatever produces the 1..Inf range say (1..*).^name; # OUTPUT: «Range␤» say (1..*); # OUTPUT: «1..Inf␤» # Upper end point is now a WhateverCode say (1..*+20).^name; # OUTPUT: «{ ... }␤» say (1..*+20).WHAT; # OUTPUT: «(WhateverCode)␤» say (1..*+20).(22); # OUTPUT: «1..42␤» ``` Ranges implement [`Positional`](/type/Positional) interface, so its elements can be accessed using an index. In a case when the index given is bigger than the Range object's size, [`Nil`](/type/Nil) object will be returned. The access works for lazy Range objects as well. ```raku say (1..5)[1]; # OUTPUT: «2␤» say (1..5)[10]; # OUTPUT: «Nil␤» say (1..*)[10]; # OUTPUT: «11␤» ``` ## [Ranges in subscripts](#class_Range "go to top of document")[§](#Ranges_in_subscripts "direct link") A Range can be used in a subscript to get a range of values. Please note that assigning a Range to a scalar container turns the Range into an item. Use binding, @-sigiled containers or a slip to get what you mean. ```raku my @numbers = <4 8 15 16 23 42>; my $range := 0..2; .say for @numbers[$range]; # OUTPUT: «4␤8␤15␤» my @range = 0..2; .say for @numbers[@range]; # OUTPUT: «4␤8␤15␤» ``` ## [Shifting and scaling intervals](#class_Range "go to top of document")[§](#Shifting_and_scaling_intervals "direct link") It is possible to shift or scale the interval of a range: ```raku say (1..10) + 1; # OUTPUT: «2..11␤» say (1..10) - 1; # OUTPUT: «0..9␤» say (1..10) * 2; # OUTPUT: «2..20␤» say (1..10) / 2; # OUTPUT: «0.5..5.0␤» ``` ## [Matching against Ranges](#class_Range "go to top of document")[§](#Matching_against_Ranges "direct link") You can use [smartmatch](/routine/~~) to match against Ranges. ```raku say 3 ~~ 1..12; # OUTPUT: «True␤» say 2..3 ~~ 1..12; # OUTPUT: «True␤» ``` *In Rakudo only*, you can use the `in-range` method for matching against a range, which in fact is equivalent to smartmatch except it will throw an exception when out of range, instead of returning `False`: ```raku say ('א'..'ת').in-range('ע'); # OUTPUT: «True␤» ``` However, if it is not included in the range: ```raku say ('א'..'ת').in-range('p', "Letter 'p'"); # OUTPUT: «(exit code 1) Letter 'p' out of range. Is: "p", should be in "א".."ת"␤ ``` The second parameter to `in-range` is the optional message that will be printed with the exception. It will print `Value` by default. # [Methods](#class_Range "go to top of document")[§](#Methods "direct link") ## [method ACCEPTS](#class_Range "go to top of document")[§](#method_ACCEPTS "direct link") ```raku multi method ACCEPTS(Range:D: Mu \topic) multi method ACCEPTS(Range:D: Range \topic) multi method ACCEPTS(Range:D: Cool:D \got) multi method ACCEPTS(Range:D: Complex:D \got) ``` Indicates if the `Range` contains (overlaps with) another `Range`. As an example: ```raku my $p = Range.new( 3, 5 ); my $r = Range.new( 1, 10 ); say $p.ACCEPTS( $r ); # OUTPUT: «False␤» say $r.ACCEPTS( $p ); # OUTPUT: «True␤» say $r ~~ $p; # OUTPUT: «False␤» (same as $p.ACCEPTS( $r ) say $p ~~ $r; # OUTPUT: «True␤» (same as $r.ACCEPTS( $p ) ``` An infinite `Range` always contains any other `Range`, therefore: ```raku say 1..10 ~~ -∞..∞; # OUTPUT: «True␤» say 1..10 ~~ -∞^..^∞; # OUTPUT: «True␤» ``` Similarly, a `Range` with open boundaries often includes other ranges: ```raku say 1..2 ~~ *..10; # OUTPUT: «True␤» say 2..5 ~~ 1..*; # OUTPUT: «True␤» ``` It is also possible to use non-numeric ranges, for instance string based ones: ```raku say 'a'..'j' ~~ 'b'..'c'; # OUTPUT: «False␤» say 'b'..'c' ~~ 'a'..'j'; # OUTPUT: «True␤» say 'raku' ~~ -∞^..^∞; # OUTPUT: «True␤» say 'raku' ~~ -∞..∞; # OUTPUT: «True␤» say 'raku' ~~ 1..*; # OUTPUT: «True␤» ``` When smartmatching a `Range` of integers with a [`Cool`](/type/Cool) (string) the `ACCEPTS` methods exploits the [before](/routine/before) and [after](/routine/after) operators in order to check that the [`Cool`](/type/Cool) value is overlapping the range: ```raku say 1..10 ~~ '5'; # OUTPUT: «False␤» say '5' before 1; # OUTPUT: «False␤» say '5' after 10; # OUTPUT: «True␤» say '5' ~~ *..10; # OUTPUT: «False␤» ``` In the above example, since the `'5'` string is *after* the `10` integer value, the `Range` does not overlap with the specified value. When matching with a [`Mu`](/type/Mu) instance (i.e., a generic instance), the [cmp](/routine/cmp) operator is used. ## [method min](#class_Range "go to top of document")[§](#method_min "direct link") ```raku method min(Range:D:) ``` Returns the start point of the range. ```raku say (1..5).min; # OUTPUT: «1␤» say (1^..^5).min; # OUTPUT: «1␤» ``` ## [method excludes-min](#class_Range "go to top of document")[§](#method_excludes-min "direct link") ```raku method excludes-min(Range:D: --> Bool:D) ``` Returns `True` if the start point is excluded from the range, and `False` otherwise. ```raku say (1..5).excludes-min; # OUTPUT: «False␤» say (1^..^5).excludes-min; # OUTPUT: «True␤» ``` ## [method max](#class_Range "go to top of document")[§](#method_max "direct link") ```raku method max(Range:D:) ``` Returns the end point of the range. ```raku say (1..5).max; # OUTPUT: «5␤» say (1^..^5).max; # OUTPUT: «5␤» ``` ## [method excludes-max](#class_Range "go to top of document")[§](#method_excludes-max "direct link") ```raku method excludes-max(Range:D: --> Bool:D) ``` Returns `True` if the end point is excluded from the range, and `False` otherwise. ```raku say (1..5).excludes-max; # OUTPUT: «False␤» say (1^..^5).excludes-max; # OUTPUT: «True␤» ``` ## [method bounds](#class_Range "go to top of document")[§](#method_bounds "direct link") ```raku method bounds() ``` Returns a list consisting of the start and end point. ```raku say (1..5).bounds; # OUTPUT: «(1 5)␤» say (1^..^5).bounds; # OUTPUT: «(1 5)␤» ``` ## [method infinite](#class_Range "go to top of document")[§](#method_infinite "direct link") ```raku method infinite(Range:D: --> Bool:D) ``` Returns `True` if either end point was declared with `∞` or `*`. ```raku say (1..5).infinite; # OUTPUT: «False␤» say (1..*).infinite; # OUTPUT: «True␤» ``` ## [method is-int](#class_Range "go to top of document")[§](#method_is-int "direct link") ```raku method is-int(Range:D: --> Bool:D) ``` Returns `True` if both end points are [`Int`](/type/Int) values. ```raku say ('a'..'d').is-int; # OUTPUT: «False␤» say (1..^5).is-int; # OUTPUT: «True␤» say (1.1..5.5).is-int; # OUTPUT: «False␤» ``` ## [method int-bounds](#class_Range "go to top of document")[§](#method_int-bounds "direct link") ```raku proto method int-bounds(|) multi method int-bounds() multi method int-bounds($from is rw, $to is rw --> Bool:D) ``` If the `Range` is an integer range (as indicated by [is-int](/routine/is-int)), then this method returns a list with the first and last value it will iterate over (taking into account [excludes-min](/routine/excludes-min) and [excludes-max](/routine/excludes-max)). Returns a [`Failure`](/type/Failure) if it is not an integer range. ```raku say (2..5).int-bounds; # OUTPUT: «(2 5)␤» say (2..^5).int-bounds; # OUTPUT: «(2 4)␤» ``` If called with (writable) arguments, these will take the values of the higher and lower bound and returns whether integer bounds could be determined from the `Range`: ```raku if (3..5).int-bounds( my $min, my $max) { say "$min, $max" ; # OUTPUT: «3, 5␤» } else { say "Could not determine integer bounds"; } ``` ## [method minmax](#class_Range "go to top of document")[§](#method_minmax "direct link") ```raku multi method minmax(Range:D: --> List:D) ``` If the `Range` is an integer range (as indicated by [is-int](/routine/is-int)), then this method returns a list with the first and last value it will iterate over (taking into account [excludes-min](/routine/excludes-min) and [excludes-max](/routine/excludes-max)). If the range is not an integer range, the method will return a two element list containing the start and end point of the range unless either of [excludes-min](/routine/excludes-min) or [excludes-max](/routine/excludes-max) are `True` in which case a [`Failure`](/type/Failure) is returned. ```raku my $r1 = (1..5); my $r2 = (1^..5); say $r1.is-int, ', ', $r2.is-int; # OUTPUT: «True, True␤» say $r1.excludes-min, ', ', $r2.excludes-min; # OUTPUT: «False, True␤» say $r1.minmax, ', ', $r2.minmax; # OUTPUT: «(1 5), (2 5)␤» my $r3 = (1.1..5.2); my $r4 = (1.1..^5.2); say $r3.is-int, ', ', $r4.is-int; # OUTPUT: «False, False␤» say $r3.excludes-max, ', ', $r4.excludes-max; # OUTPUT: «False, True␤» say $r3.minmax; # OUTPUT: «(1.1 5.2)␤» say $r4.minmax; CATCH { default { put .^name, ': ', .Str } }; # OUTPUT: «X::AdHoc: Cannot return minmax on Range with excluded ends␤» ``` ## [method elems](#class_Range "go to top of document")[§](#method_elems "direct link") ```raku method elems(Range:D: --> Numeric:D) ``` Returns the number of elements in the range, e.g. when being iterated over, or when used as a [`List`](/type/List). Returns 0 if the start point is larger than the end point, including when the start point was specified as `∞`. Fails when the Range is lazy, including when the end point was specified as `∞` or either end point was specified as `*`. ```raku say (1..5).elems; # OUTPUT: «5␤» say (1^..^5).elems; # OUTPUT: «3␤» ``` ## [method list](#class_Range "go to top of document")[§](#method_list "direct link") ```raku multi method list(Range:D:) ``` Generates the list of elements that the range represents. ```raku say (1..5).list; # OUTPUT: «(1 2 3 4 5)␤» say (1^..^5).list; # OUTPUT: «(2 3 4)␤» ``` ## [method flat](#class_Range "go to top of document")[§](#method_flat "direct link") ```raku method flat(Range:D:) ``` Generates a [`Seq`](/type/Seq) containing the elements that the range represents. ## [method pick](#class_Range "go to top of document")[§](#method_pick "direct link") ```raku multi method pick(Range:D: --> Any:D) multi method pick(Range:D: $number --> Seq:D) ``` Performs the same function as `Range.list.pick`, but attempts to optimize by not actually generating the list if it is not necessary. ## [method roll](#class_Range "go to top of document")[§](#method_roll "direct link") ```raku multi method roll(Range:D: --> Any:D) multi method roll(Range:D: $number --> Seq:D) ``` Performs the same function as `Range.list.roll`, but attempts to optimize by not actually generating the list if it is not necessary. ## [method sum](#class_Range "go to top of document")[§](#method_sum "direct link") ```raku multi method sum(Range:D:) ``` Returns the sum of all elements in the Range. Throws [`X::Str::Numeric`](/type/X/Str/Numeric) if an element can not be coerced into Numeric. ```raku (1..10).sum # 55 ``` ## [method reverse](#class_Range "go to top of document")[§](#method_reverse "direct link") ```raku method reverse(Range:D: --> Seq:D) ``` Returns a [`Seq`](/type/Seq) where all elements that the `Range` represents have been reversed. Note that reversing an infinite `Range` won't produce any meaningful results. ```raku say (1^..5).reverse; # OUTPUT: «(5 4 3 2)␤» say ('a'..'d').reverse; # OUTPUT: «(d c b a)␤» say (1..∞).reverse; # OUTPUT: «(Inf Inf Inf ...)␤» ``` ## [method Capture](#class_Range "go to top of document")[§](#method_Capture "direct link") ```raku method Capture(Range:D: --> Capture:D) ``` Returns a [`Capture`](/type/Capture) with values of [`.min`](/type/Range#method_min) [`.max`](/type/Range#method_max), [`.excludes-min`](/type/Range#method_excludes-min), [`.excludes-max`](/type/Range#method_excludes-max), [`.infinite`](/type/Range#method_infinite), and [`.is-int`](/type/Range#method_is-int) as named arguments. ## [method rand](#class_Range "go to top of document")[§](#method_rand "direct link") ```raku method rand(Range:D --> Num:D) ``` Returns a pseudo-random value belonging to the range. ```raku say (1^..5).rand; # OUTPUT: «1.02405550417031␤» say (0.1..0.3).rand; # OUTPUT: «0.2130353370062␤» ``` ## [method EXISTS-POS](#class_Range "go to top of document")[§](#method_EXISTS-POS "direct link") ```raku multi method EXISTS-POS(Range:D: int \pos) multi method EXISTS-POS(Range:D: Int \pos) ``` Returns `True` if `pos` is greater than or equal to zero and lower than `self.elems`. Returns `False` otherwise. ```raku say (6..10).EXISTS-POS(2); # OUTPUT: «True␤» say (6..10).EXISTS-POS(7); # OUTPUT: «False␤» ``` ## [method AT-POS](#class_Range "go to top of document")[§](#method_AT-POS "direct link") ```raku multi method AT-POS(Range:D: int \pos) multi method AT-POS(Range:D: int:D \pos) ``` Checks if the [`Int`](/type/Int) position exists and in that case returns the element in that position. ```raku say (1..4).AT-POS(2) # OUTPUT: «3␤» ``` ## [method raku](#class_Range "go to top of document")[§](#method_raku "direct link") ```raku multi method raku(Range:D:) ``` Returns an implementation-specific string that produces an [equivalent](/routine/eqv) object when given to [EVAL](/routine/EVAL). ```raku say (1..2).raku # OUTPUT: «1..2␤» ``` ## [method fmt](#class_Range "go to top of document")[§](#method_fmt "direct link") ```raku method fmt(|c) ``` Returns a string where `min` and `max` in the `Range` have been formatted according to `|c`. For more information about parameters, see [List.fmt](/type/List#method_fmt). ```raku say (1..2).fmt("Element: %d", ",") # OUTPUT: «Element: 1,Element: 2␤» ``` ## [method WHICH](#class_Range "go to top of document")[§](#method_WHICH "direct link") ```raku multi method WHICH (Range:D:) ``` This returns a string that identifies the object. The string is composed by the type of the instance (`Range`) and the `min` and `max` attributes: ```raku say (1..2).WHICH # OUTPUT: «Range|1..2␤» ``` ## [sub infix:<+>](#class_Range "go to top of document")[§](#sub_infix:<+> "direct link") ```raku multi infix:<+>(Range:D \r, Real:D \v) multi infix:<+>(Real:D \v, Range:D \r) ``` Takes a [`Real`](/type/Real) and adds that number to both boundaries of the `Range` object. Be careful with the use of parenthesis. ```raku say (1..2) + 2; # OUTPUT: «3..4␤» say 1..2 + 2; # OUTPUT: «1..4␤» ``` ## [sub infix:<->](#class_Range "go to top of document")[§](#sub_infix:<-> "direct link") ```raku multi infix:<->(Range:D \r, Real:D \v) ``` Takes a [`Real`](/type/Real) and subtract that number to both boundaries of the `Range` object. Be careful with the use of parenthesis. ```raku say (1..2) - 1; # OUTPUT: «0..1␤» say 1..2 - 1; # OUTPUT: «1..1␤» ``` ## [sub infix:<\*>](#class_Range "go to top of document")[§](#sub_infix:<*> "direct link") ```raku multi infix:<*>(Range:D \r, Real:D \v) multi infix:<*>(Real:D \v, Range:D \r) ``` Takes a [`Real`](/type/Real) and multiply both boundaries of the `Range` object by that number. ```raku say (1..2) * 2; # OUTPUT: «2..4␤» ``` ## [sub infix:</>](#class_Range "go to top of document")[§](#sub_infix:</> "direct link") ```raku multi infix:</>(Range:D \r, Real:D \v) ``` Takes a [`Real`](/type/Real) and divide both boundaries of the `Range` object by that number. ```raku say (2..4) / 2; # OUTPUT: «1..2␤» ``` ## [sub infix:<cmp>](#class_Range "go to top of document")[§](#sub_infix:<cmp> "direct link") ```raku multi infix:<cmp>(Range:D \a, Range:D \b --> Order:D) multi infix:<cmp>(Num(Real) \a, Range:D \b --> Order:D) multi infix:<cmp>(Range:D \a, Num(Real) \b --> Order:D) multi infix:<cmp>(Positional \a, Range:D \b --> Order:D) multi infix:<cmp>(Range:D \a, Positional \b --> Order:D) ``` Compares two `Range` objects. A [`Real`](/type/Real) operand will be considered as both the starting point and the ending point of a `Range` to be compared with the other operand. A [`Positional`](/type/Positional) operand will be compared with the list returned by the [`.list` method](/type/Range#method_list) applied to the other operand. See [`List infix:<cmp>`](/type/List#infix_cmp) ```raku say (1..2) cmp (1..2); # OUTPUT: «Same␤» say (1..2) cmp (1..3); # OUTPUT: «Less␤» say (1..4) cmp (1..3); # OUTPUT: «More␤» say (1..2) cmp 3; # OUTPUT: «Less␤» say (1..2) cmp [1,2]; # OUTPUT: «Same␤» ``` # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Range` raku-type-graph Range Range Cool Cool Range->Cool Positional Positional Range->Positional Iterable Iterable Range->Iterable Mu Mu Any Any Any->Mu Cool->Any [Expand chart above](/assets/typegraphs/Range.svg)
## dist_zef-raku-community-modules-Net-LibIDN2.md [![Actions Status](https://github.com/raku-community-modules/Net-LibIDN2/workflows/test/badge.svg)](https://github.com/raku-community-modules/Net-LibIDN2/actions) # NAME Net::LibIDN2 - Raku bindings for GNU LibIDN2 # SYNOPSIS ``` use Net::LibIDN2; my $idn = Net::LibIDN2.new; my Int $code; my $ulabel = "m\xFC\xDFli"; my $alabel = $idn.lookup_u8($ulabel, IDN2_NFC_INPUT, $code); say "$alabel $code"; # xn--mli-5ka8l 0 my $result = $idn.register_u8($ulabel, $alabel, IDN2_NFC_INPUT, $code); say "$result $code"; # xn--mli-5ka8l 0 say $idn.strerror($code); # success say $idn.strerror_name($code); # IDN2_OK ``` # DESCRIPTION Net::LibIDN2 is a Raku wrapper for the GNU LibIDN2 library. Using this module requires a native LibIDN2 dependency. Here's how to install it for your OS: * Windows Clone <https://gitlab.com/libidn/libidn2> and follow the install instructions in the README. Don't forget to add the path to the installed LibIDN2 to your PATH environment variable! * OS X $ brew install libidn2 * Ubuntu/Debian $ sudo apt-get install libidn2 * OpenSUSE $ sudo zypper install libidn2 * Fedora $ sudo yum install libidn2 * Arch/Manjaro $ sudo pacman -S libidn2 * FreeBSD # pkg install libidn2 or ``` # cd /usr/ports/devel/libidn2 # make config # make # make install ``` * OpenBSD $ doas pkg\_add libidn2 or ``` $ cd /usr/ports/devel/libidn2 $ doas make $ doas make install ``` * NetBSD # pkgin install libidn2 or ``` # cd /usr/pkgsrc/devel/libidn2 # make # make install ``` # METHODS * **Net::LibIDN2.check\_version**(--> Version) * **Net::LibIDN2.check\_version**(Str *$version* --> Version) * **Net::LibIDN2.check\_version**(Version *$version* --> Version) Compares `$version` against the version of LibIDN2 installed and returns either an empty string if `$version` is greater than the version installed, or `IDN2_VERSION` otherwise. * **Net::LibIDN2.strerror**(Int *$errno* --> Str) Returns the error represented by `$errno` in human readable form. * **Net::LibIDN2.strerror\_name**(Int *$errno* --> Str) Returns the internal error name of `$errno`. * **Net::LibIDN2.to\_ascii\_8z**(Str *$input* --> Str) * **Net::LibIDN2.to\_ascii\_8z**(Str *$input*, Int *$flags* --> Str) * **Net::LibIDN2.to\_ascii\_8z**(Str *$input*, Int *$flags*, Int *$code* is rw --> Str) Converts a UTF8 encoded string `$input` to ASCII and returns the output. `$code`, if provided, is assigned to `IDN2_OK` on success, or another error code otherwise. Requires LibIDN2 v2.0.0 or greater. * **Net::LibIDN2.to\_unicode\_8z8z**(Str *$input* --> Str) * **Net::LibIDN2.to\_unicode\_8z8z**(Str *$input*, Int *$flags* --> Str) * **Net::LibIDN2.to\_unicode\_8z8z**(Str *$input*, Int *$flags*, Int *$code* is rw --> Str) Converts an ACE encoded domain name `$input` to UTF8 and returns the output. `$code`, if provided, is assigned to `IDN2_OK` on success, or another error code otherwise. Requires LibIDN v2.0.0 or greater. * **Net::LibIDN2.lookup\_u8**(Str *$input* --> Str) * **Net::LibIDN2.lookup\_u8**(Str *$input*, Int *$flags* --> Str) * **Net::LibIDN2.lookup\_u8**(Str *$input*, Int *$flags*, Int *$code* is rw --> Str) Performs an IDNA2008 lookup string conversion on `$input`. See RFC 5891, section 5. `$input` must be a UTF8 encoded string in NFC form if no `IDN2_NFC_INPUT` flag is passed. * **Net::LibIDN2.register\_u8**(Str *$uinput*, Str *$ainput* --> Str) * **Net::LibIDN2.register\_u8**(Str *$uinput*, Str *$ainput*, Int *$flags* --> Str) * **Net::LibIDN2.register\_u8**(Str *$uinput*, Str *$ainput*, Int *$flags*, Int *$code* is rw --> Str) Performs an IDNA2008 register string conversion on `$uinput` and `$ainput`. See RFC 5891, section 4. `$uinput` must be a UTF8 encoded string in NFC form if no `IDN2_NFC_INPUT` flag is passed. `$ainput` must be an ACE encoded string. # CONSTANTS * Int **IDN2\_LABEL\_MAX\_LENGTH** The maximum label length. * Int **IDN2\_DOMAIN\_MAX\_LENGTH** The maximum domain name length. ## VERSIONING * Str **IDN2\_VERSION** The version of LibIDN2 installed. * Int **IDN2\_VERSION\_NUMBER** The version of LibIDN2 installed represented as a 32 bit integer. The first pair of bits represents the major version, the second represents the minor version, and the last 4 represent the patch version. * Int **IDN2\_VERSION\_MAJOR** The major version of LibIDN2 installed. * Int **IDN2\_VERSION\_MINOR** The minor version of LidIDN2 installed. * Int **IDN2\_VERSION\_PATCH** The patch version of LibIDN2 installed. ## FLAGS * Int **IDN2\_NFC\_INPUT** Normalize the input string using the NFC format. * Int **IDN2\_ALABEL\_ROUNDTRIP** Perform optional IDNA2008 lookup roundtrip check. * Int **IDN2\_TRANSITIONAL** Perform Unicode TR46 transitional processing. * Int **IDN2\_NONTRANSITIONAL** Perform Unicode TR46 non-transitional processing. ## ERRORS * Int **IDN2\_OK** Success. * Int **IDN2\_MALLOC** Memory allocation failure. * Int **IDN2\_NO\_CODESET** Failed to determine a string's encoding. * Int **IDN2\_ICONV\_FAIL** Failed to transcode a string to UTF8. * Int **IDN2\_ENCODING\_ERROR** Unicode data encoding error. * Int **IDN2\_NFC** Failed to normalize a string. * Int **IDN2\_PUNYCODE\_BAD\_INPUT** Invalid input to Punycode. * Int **IDN2\_PUNYCODE\_BIG\_OUTPUT** Punycode output buffer is too small. * Int **IDN2\_PUNYCODE\_OVERFLOW** Punycode conversion would overflow. * Int **IDN2\_TOO\_BIG\_DOMAIN** Domain is larger than `IDN2_DOMAIN_MAX_LENGTH`. * Int **IDN2\_TOO\_BIG\_LABEL** Label is larger than `IDN2_LABEL_MAX_LENGTH`. * Int **IDN2\_INVALID\_ALABEL** Invalid A-label. * Int **IDN2\_UALABEL\_MISMATCH** Given U-label and A-label do not match. * Int **IDN2\_INVALID\_FLAGS** Invalid combination of flags. * Int **IDN2\_NOT\_NFC** String is not normalized in NFC format. * Int **IDN2\_2HYPHEN** String has forbidden two hyphens. * Int **IDN2\_HYPHEN\_STARTEND** String has forbidden start/end hyphen. * Int **IDN2\_LEADING\_COMBINING** String has forbidden leading combining character. * Int **IDN2\_DISALLOWED** String has disallowed character. * Int **IDN2\_CONTEXTJ** String has forbidden context-j character. * Int **IDN2\_CONTEXTJ\_NO\_RULE** String has context-j character without any rull. * Int **IDN2\_CONTEXTO** String has forbidden context-o character. * Int **IDN2\_CONTEXTO\_NO\_RULE** String has context-o character without any rull. * Int **IDN2\_UNASSIGNED** String has forbidden unassigned character. * Int **IDN2\_BIDI** String has forbidden bi-directional properties. * Int **IDN2\_DOT\_IN\_LABEL** Label has forbidden dot (TR46). * Int **IDN2\_INVALID\_TRANSITIONAL** Label has a character forbidden in transitional mode (TR46). * Int **IDN2\_INVALID\_NONTRANSITIONAL** Label has a character forbidden in non-transitional mode (TR46). # AUTHOR Ben Davies (kaiepi) # COPYRIGHT AND LICENSE Copyright 2017 Ben Davies This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## absolute.md absolute Combined from primary sources listed below. # [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_absolute "direct link") See primary documentation [in context](/type/IO/Path#method_absolute) for **method absolute**. ```raku multi method absolute(IO::Path:D: --> Str) multi method absolute(IO::Path:D: $base --> Str) ``` Returns a new [`Str`](/type/Str) object that is an absolute path. If the invocant is not already an absolute path, it is first made absolute using `$base` as base, if it is provided, or the `.CWD` attribute the object was created with if it is not.
## line.md line Combined from primary sources listed below. # [In Backtrace::Frame](#___top "go to top of document")[§](#(Backtrace::Frame)_method_line "direct link") See primary documentation [in context](/type/Backtrace/Frame#method_line) for **method line**. ```raku method line(Backtrace::Frame:D --> Int) ``` Returns the line number (line numbers start counting from 1). ```raku my $bt = Backtrace.new; my $btf = $bt[0]; say $btf.line; ``` # [In role X::Comp](#___top "go to top of document")[§](#(role_X::Comp)_method_line "direct link") See primary documentation [in context](/type/X/Comp#method_line) for **method line**. The line number in which the compilation error occurred. # [In Label](#___top "go to top of document")[§](#(Label)_method_line "direct link") See primary documentation [in context](/type/Label#method_line) for **method line**. Returns the line where the label has been defined. # [In Code](#___top "go to top of document")[§](#(Code)_method_line "direct link") See primary documentation [in context](/type/Code#method_line) for **method line**. ```raku method line(Code:D: --> Int:D) ``` Returns the line number in the source code at which the code object's declaration begins. ```raku say &infix:<+>.line; # OUTPUT: «208␤» ``` If the code object was generated automatically (and thus *not* declared in the source code), then `line` returns the line on which the enclosing scope's declaration begins. For example, when called on an [automatically generated accessor method](/language/objects#Attributes) produced by the `has $.name` syntax, `line` returns the line on which the method's class's declaration begins. For example, if you have the following source file: ```raku class Food { # Line 1 has $.ingredients; # Line 2 # Line 3 method eat {}; # Line 4 } # Line 5 ``` Then the `line` method would give you the following output: ```raku say Food.^lookup('eat').line; # OUTPUT: «4␤» say Food.^lookup('ingredients').line; # OUTPUT: «1␤» ``` # [In CallFrame](#___top "go to top of document")[§](#(CallFrame)_method_line "direct link") See primary documentation [in context](/type/CallFrame#method_line) for **method line**. ```raku method line() ``` This is a shortcut for looking up the `line` annotation. For example, the following two calls are identical. ```raku say callframe(1).line; say callframe(1).annotations<line>; ```
## dist_github-cbk-API-USNavalObservatory.md # perl6-API-USNavalObservatory [Build Status](https://travis-ci.org/cbk/API-USNavalObservatory) ## SYNOPSIS This module is a simple **Perl 6** interface to the U.S. Naval Observatory, Astronomical Applications API v2.2.0 which can be found at <http://aa.usno.navy.mil/data/docs/api.php> You may choose to use an 8 character alphanumeric identifier in your forms or scripts. This API has a default of **"P6mod"** which is registered with the U.S. Naval Observatory as the default ID of this API. The 'AA' ID is used internally by the U.S. Naval Observatory and thus can not be used. It is recommended that you override the default `apiID` You may use any other identifier you want for `apiID`. Information about the ID and how to register your own can be found **[here](https://aa.usno.navy.mil/data/docs/api.php#id)**. #### Example: the following example creates a new **API::NavalObservatory** object called $webAgent and sets the apiID to 'MyID'. ``` my $webAgent = API::USNavalObservatory.new( apiID => "MyID" ); ``` ## Returns * For services which return text, you will receive an JSON formatted blob of text. * For services which produce a image, this API will save the .PNG file in the current working directory. (Overwriting any existing file with the same name.) ## Methods There are currently 9 methods which are used to interact with this API. The API uses UTC time for all time based calls. When crafting your method calls add the `.utc` method on the DateTime object to convert a local time to UTC. Below is a list of the current methods in this module: * Day and Night Across the Earth, Cylindrical Projection: `.cylindrical()` * Day and Night Across the Earth, Spherical Projection: `.spherical()` * Apparent Disk of the Solar System Object: `.apparentDisk()` * Phases of the Moon: `.moonPhase()` * Complete Sun and Moon Data for One Day: `.oneDayData()` * Sidereal Time: `.siderealTime()` * Solar Eclipse Calculator: `.solarEclipses()` * Religious Observances: `.observances()` * Earth Seasons and Apsides: `.seasons()` ### Day and Night Across the Earth - Cylindrical Projection Generates a cylindrical map of the Earth (similar to a Mercator projection) with daytime and nighttime areas appropriately shaded. #### Examples: The following example shows a request using a date only. ``` say $webAgent.cylindrical( :dateObj( Date.today ) ); ``` This example shows a request that uses both date and time. ``` say $webAgent.cylindrical( :dateTimeObj( DateTime.now ) ); ``` #### Return: This method returns a .png image in the current working directory. * NOTE: This will overwrite any file with the same name in the CWD. ### Day and Night Across the Earth - Spherical Projections Creates a .png image view of the Earth with daytime and nighttime areas shaded appropriately. The image generated is of the apparent disk you would see if you were in a spacecraft looking back at Earth. This method takes two named pramaters: `dateTimeObj` which is a DateTime object and view which is a View subset. * The value for `view` can be any one of the following: **moon, sun, north, south, east, west, rise, and set.** #### Example: ``` say $webAgent.spherical( :dateTimeObj( DateTime.now ), :view("sun") ); ``` #### Return: This method returns a .png image in the current working directory. * NOTE: This will overwrite any file with the same name in the CWD. ### Apparent Disk of a Solar System Object Produces an apparent disk of a solar system object oriented as if you were viewing it through a high-powered telescope. #### Example: ``` say $webAgent.apparentDisk( :dateTimeObj( DateTime.now ), :body('moon') ); ``` #### Return: This method returns a png image in the current working directory. ### Phases of the Moon Returns the dates and times of a list of primary moon phases. This method has two signatures: * One where a valid year is provided, and returns ALL moon phase data for that year. This is a un-named pramater. * One that has will take a `Date` object and a unsigned integer for the number of phases to include in the results. #### Examples: The following example shows a request for a given date and number of phases. ``` say $webAgent.moonPhase( :dateObj( Date.today() ), :numP( 5 ) ); ``` The following example shows a request for a given year. ``` say $webAgent.moonPhase( 2019 ); ``` #### Return: This method returns a JSON formatted text blob. ### Complete Sun and Moon Data for One Day Returns the rise, set, and transit times for the Sun and the Moon on the requested date at the specified location. #### Examples: The following example shows a request using date, coordinates, and time zone. ``` say $webAgent.oneDayData( :dateObj( Date.today() ), :coords( "41.98N, 12.48E" ), :tz(-6) ); ``` The following example shows a request using date amd location. ``` say $webAgent.oneDayData( :dateObj( Date.today()), :loc("San Diego, CA") ); ``` #### Return: This method returns a JSON formatted text blob. ### Sidereal Time Provides the greenwich mean and apparent sidereal time, local mean and apparent sidereal time, and the Equation of the Equinoxes for a given date & time. #### Examples: The following example shows a request using a location string. ``` say $webAgent.siderealTime( :dateTimeObj(DateTime.new( year => 2019, month => 2, day => 2, hour => 2, minute => 2, second => 1,)), :loc("Denver,CO"), :reps(90), :intvMag(5), :intvUnit('minutes') ); ``` The following example shows a request using coordinates. ``` say $webAgent.siderealTime( :dateTimeObj( DateTime.new( year => 2019, month => 2, day => 2, hour => 2, minute => 2, second => 1,)), :coords("41.98N, 12.48E"), :reps(90), :intvMag(5), :intvUnit('minutes') ); ``` #### Return: This method returns a JSON formatted text blob. ### Solar Eclipse Calculator This data service provides local circumstances for solar eclipses, and also provides a means for determining dates and types of eclipses in a given year. #### Examples: The following example shows a request using a U.S. based location (San Francisco CA) for the current day. * NOTE: Currently this module utilizes the URI::Encode, uri\_encode method. Including a comma **,** in the string that is passed to uri\_encode seams to produce a malformed URL which fails when passed to the API. Use a space instead of a comma for now. ``` say $webAgent.solarEclipses( :loc("San Francisco CA"), :dateObj( Date.today() ), :height(50), :format("json") ); ``` The following example shows a request using lat and long. ``` say $webAgent.solarEclipses( :coords("46.67N, 1.48E" ), :dateObj( Date.today() ), :height(50), :format("json") ); ``` The following example shows a request providing only the year in the range of 1800 to 2050. ``` say $webAgent.solarEclipses( 2019 ); ``` #### Return: All these method signatures return an JSON formatted text blob. ### Selected Religious Observances Single method to handle all three calender types; `christan, jewish, islamic` * For Christan calender, use years between 1583 and 9999. * For Jewish calender, use years between 360 and 9999. * For Islamic calender, use years between 622 and 9999. #### Example: ``` say $webAgent.observances( :year(2019), :cal('christian') ); ``` #### Return: This method returns a JSON formatted text blob. ### Julian Date Converter This data service converts dates between the Julian/Gregorian calendar and Julian date. Data will be provided for the years 4713 B.C. through A.D. 9999, or Julian dates of 0 through 5373484.5. To use the `.julianDate` method, you must provide a valid `DateTime` object and a valid Era OR an unsigned integer. This method returns a JSON text blob of the request converted into ether a Julian or calendar date. #### Examples: ``` say $webAgent.julianDate( 2457892.312674 ); ``` ``` say $webAgent.julianDate( :dateTimeObj(DateTime.now), :era('AD') ); ``` #### Return: Both of these methods returns an JSON formatted text blob. ### Earth's Seasons and Apsides #### Example: ``` say $webAgent.seasons( :year(2019), :tz(-6), :dst(False) ); ``` #### Return: This method returns a JSON formatted text blob. ## Sample code * The following example makes a new object and overrides the default apiID. Then calls the solarEclipses method with the year 2019 to find all eclipses for 2019. ``` use v6; use API::USNavalObservatory; my $webAgent = API::NavalObservatory.new( apiID => "MyID" ); my $output = $webAgent.solarEclipses( 2019 ); say $output; ``` OUTPUT: ``` { "error" : false, "year" : 2019, "apiversion" : "2.2.0", "eclipses_in_year" : [ { "event" : "Partial Solar Eclipse of 6 January 2019", "day" : 6, "year" : 2019, "month" : 1 }, { "event" : "Total Solar Eclipse of 2 July 2019", "month" : 7, "year" : 2019, "day" : 2 }, { "event" : "Annular Solar Eclipse of 26 December 2019", "month" : 12, "year" : 2019, "day" : 26 } ] } ``` ## AUTHOR * Michael, cbk on #perl6, <https://github.com/cbk/>
## dist_github-pierre-vigier-AttrX-PrivateAccessor.md # Perl6-AttrX::PrivateAccessor [![Build Status](https://travis-ci.org/pierre-vigier/Perl6-AttrX-PrivateAccessor.svg?branch=master)](https://travis-ci.org/pierre-vigier/Perl6-AttrX-PrivateAccessor) # NAME AttrX::PrivateAccessor # SYNOPSIS Provide private accessor for private attribute, provide only read accessor, see NOTES for the reason # DESCRIPTION This module provides trait private-accessible (providing-private-accessor was too long), which will create a private accessor for a private attribute, in read only, no modification possible It allows from within a class to access another instance of the same class' private attributes ``` use AttrX::PrivateAccessor; class Sample has $!attribute is private-accessible; } ``` is equivalent to ``` class Sample has $!attribute; method !attribute() { return $!attribute; } } ``` The private accessor method by default will have the name of the attribute, but can be customized, as an argument to the trait ``` use AttrX::PrivateAccessor; class Sample has $!attribute is private-accessible('accessor'); } ``` THe private method will then be ``` method !accessor() { $!attribute } ``` A use case for having private read accessor could be, let's see that we have class who store a chareacteristic under an interanl format, that should not be visible from the outside. To check if two instances of that class are equal, we have to compare that internal value, we would have a method like that ``` class Foo { has $!characteristic is private-accessible; ... method equal( Foo:D: Foo:D $other ) { return $!characteristic == $other!characteristic; } } ``` Without the trai, we can't know the value in the other instance # NOTES This module create private accessor in read-only mode. Even if really useful sometimes, accessing private attributes of another instance of the same class is starting to violate encapsulation. Giving permission to modify private attributes of another instance seemed a bit to much, if it is really needed, i guess it would really be some specific case, where writing a dedicated private method with comments seems more adequate. However, if one day that behavior has to be implemented, it could be done through a parameter of the trait, like ``` has $!attribute is private-accessible( :rw ) ``` # MISC To test the meta data of the modules, set environement variable PERL6\_TEST\_META to 1
## dist_cpan-MELEZHIK-Sparrowdo-VSTS-YAML-Solution.md # Sparrowdo::VSTS::YAML:Solution Sparrowdo module to generate VSTS yaml steps to build solution files. ``` $ cat sparrowfile module_run "VSTS::YAML::Solution", %( build-dir => "cicd/build", vs-version => '15.0', # visual studio version, default value display-name => "Build app.sln", # optional solution => "app.sln", # path to solution file, default is "**\*.sln" platform => "x86", configuration => "debug", restore-solution => "app.sln", # path to NugetRestore solution file skip-nuget-install => True, # don't install nuget cli test-assemblies => True, # run tests, default value is False publish-symbols => False, # publish symbols, this is default value ); $ sparrowdo --local_mode --no_sudo ``` # Parameters ## vs-version Visual studio version ## solution Path to solution file ## platform Build platform ## configuration Build configuration ## restore-solution Path to solution file for `nuget restore` command ## skip-nuget-restore Don't run `nuget restore` command ## skip-nuget-install Don't install nuget ## test-assemblies Run tests ## publish-symbols Publish symbols # Author Alexey Melezhik
## dist_cpan-MARTIMM-Pod-Render.md # Rendering of pod documents [![Travis Build Status](https://travis-ci.org/MARTIMM/pod-render.svg?branch=master)](https://travis-ci.org/MARTIMM/pod-render) [![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/MARTIMM/pod-render?branch=master&passingText=Windows%20-%20OK&failingText=Windows%20-%20FAIL&pendingText=Windows%20-%20pending&svg=true)](https://ci.appveyor.com/project/MARTIMM/pod-render/branch/master) [![License](http://martimm.github.io/label/License-label.svg)](http://www.perlfoundation.org/artistic_license_2_0) ## Synopsis ``` pod-render --html lib/Your/Module.pm6 ``` ## Documentation The pdf output is generated with the program `prince`. You can find the downdload page [here](https://www.princexml.com/download/). ### Program and library * [pod-render.pl6 html](https://nbviewer.jupyter.org/github/MARTIMM/pod-render/blob/master/doc/pod-render.html) * [Pod::Render html](https://nbviewer.jupyter.org/github/MARTIMM/pod-render/blob/master/doc/Render.html) ### Other examples of the same documents * [pod-render.pl6 pdf](https://nbviewer.jupyter.org/github/MARTIMM/pod-render/blob/master/doc/pod-render.pdf) * [pod-render.pl6 md](https://github.com/MARTIMM/pod-render/blob/master/doc/pod-render.md) * [Pod::Render pdf](https://nbviewer.jupyter.org/github/MARTIMM/pod-render/blob/master/doc/Render.pdf) * [Pod::Render md](https://github.com/MARTIMM/pod-render/blob/master/doc/Render.md) ### Release notes * [Release notes](https://github.com/MARTIMM/pod-render/blob/master/doc/CHANGES.md) ## Installing `zef install Pod::Render` ## Versions of PERL, MOARVM This project is tested with latest Rakudo built on MoarVM implementing Perl v6. ## Dependency on external programs When generating pdf files, the program uses **[prince](https://www.princexml.com/download/)** to get the work done. Please also read the [end user license agreement](https://www.princexml.com/license/) before generating prince. ## Authors `© Marcel Timmerman (MARTIMM on github)` ## Attribution * `Pod::To::HTML` * Camelia™ (butterfly) is © 2009 by Larry Wall
## multiple.md class X::Phaser::Multiple Compilation error due to multiple phasers of the same type ```raku class X::Phaser::Multiple does X::Comp { } ``` Thrown when multiple phasers of the same type occur in a block, but only one is allowed (for example `CATCH` or `CONTROL`). For example ```raku CATCH { }; CATCH { } ``` dies with 「text」 without highlighting ``` ``` ===SORRY!=== Only one CATCH block is allowed ``` ``` # [Methods](#class_X::Phaser::Multiple "go to top of document")[§](#Methods "direct link") ## [method block](#class_X::Phaser::Multiple "go to top of document")[§](#method_block "direct link") Returns the name of the phaser that occurred more than once.
## dist_zef-lizmat-Bits.md [![Actions Status](https://github.com/lizmat/Bits/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Bits/actions) [![Actions Status](https://github.com/lizmat/Bits/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Bits/actions) [![Actions Status](https://github.com/lizmat/Bits/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/Bits/actions) # NAME Bits - provide bit related functions for arbitrarily large integers # SYNOPSIS ``` use Bits; # exports "bit", "bits", "bitcnt", "bitswap" say bit(8, 3); # 1000 -> True say bit(7, 3); # 0111 -> False say bits(8); # 1000 -> (3,).Seq say bits(7); # 0111 -> (0,1,2).Seq say bitcnt(8); # 1000 -> 1 say bitcnt(7); # 0111 -> 3 say bitswap(1); # 0001 -> 1110 say bitswap(-1); # 1111 -> 0000 ``` # DESCRIPTION This module exports a number of function to handle significant bits in arbitrarily large integer values, aka bitmaps. If the specified value is zero or positive, then the on-bits will be considered significant. If the specified value is negative, then the off-bits in the value will be considered significant. # SUBROUTINES ## bit ``` sub bit(Int:D value, UInt:D bit --> Bool:D) ``` Takes an integer value and a bit number and returns whether that bit is significant (1 for positive values, 0 for negative values). ## bits ``` sub bits(Int:D value --> Seq:D) ``` Takes an integer value and returns a `Seq`uence of the bit numbers that are significant in the value. For negative values, these are the bits that are 0. ## bitcnt ``` sub bitcnt(Int:D value --> Int:D) ``` Takes an integer value and returns the number of significant bits that are set in the value. For negative values, this is the number of bits that are 0. ## bitswap ``` sub bitswap(Int:D value --> Int:D) ``` Takes an integer value and returns an integer value with all of the 1-bits turned to 0-bits and vice-versa. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Bits> . 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 2019, 2020, 2021, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-sirrobert-Class-Utils.md ## Class::Utils ### role Has Some of the core classes don't run through `bless` during object creation (apparently for efficiency reasons). This means that if you define a class that inherits from Array, for example, you can't define properties for the class using the normal `has` route. The `Has` role addresses this by importing a new `new` that takes advantage of bless. #### Usage The following code breaks. If you try to access `$.foo` below, you get an undefined `Any` value instead of `'bar'`. ``` class MySet is Array { has $.foo = 'bar'; } say MySet.new.foo; # Any() ``` Fix this with `does Has` from `Class::Utils`: ``` use Class::Utils; class MySet is Array does Has { has $.foo = 'bar'; } say MySet.new.foo; # bar ```
## dist_github-azawawi-LibZip.md # LibZip [![Build Status](https://travis-ci.org/azawawi/perl6-libzip.svg?branch=master)](https://travis-ci.org/azawawi/perl6-libzip) [![Build status](https://ci.appveyor.com/api/projects/status/github/azawawi/perl6-libzip?svg=true)](https://ci.appveyor.com/project/azawawi/perl6-libzip/branch/master) LibZip provides Perl 6 bindings for libzip This is an experimental module at the moment. ## Example ``` use v6; use lib 'lib'; use LibZip; # Remove the old one (just in case) my $zip-file-name = "test.zip"; $zip-file-name.IO.unlink; # Create a new LibZip instance my $archive = LibZip.new; # Create a new zip file $archive.open($zip-file-name); # Add file to zip archive $archive.add-file("README.md"); # Add file to zip archive my $lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; my Blob $blob = $lorem.encode("UTF-8"); $archive.add-blob("lorem.txt", $blob); # Close the zip archive $archive.close; ``` ## Author Ahmad M. Zawawi, azawawi on #perl6, <https://github.com/azawawi/> ## License [MIT License](LICENSE)
## dist_cpan-MOZNION-IO-Blob.md [![Build Status](https://travis-ci.org/moznion/p6-IO-Blob.svg?branch=master)](https://travis-ci.org/moznion/p6-IO-Blob) # NAME IO::Blob - IO:: interface for reading/writing a Blob # SYNOPSIS ``` use v6; use IO::Blob; my $data = "foo\nbar\n"; my IO::Blob $io = IO::Blob.new($data.encode); $io.get; # => "foo\n" $io.print('buz'); $io.seek(0); # rewind $io.slurp-rest; # => "foo\nbar\nbuz" ``` # DESCRIPTION `IO::` interface for reading/writing a Blob. This class inherited from IO::Handle. The IO::Blob class implements objects which behave just like IO::Handle objects, except that you may use them to write to (or read from) Blobs. This module is inspired by IO::Scalar of perl5. # METHODS ## new(Blob $data = Buf.new) Make a instance. This method is equivalent to `open`. ``` my $io = IO::Blob.new("foo\nbar\n".encode); ``` ## open(Blob $data = Buf.new) Make a instance. This method is equivalent to `new`. ``` my $io = IO::Blob.open("foo\nbar\n".encode); ``` ## new(Str $str) Make a instance. This method is equivalent to `open`. ``` my $io = IO::Blob.new("foo\nbar\n"); ``` ## open(Str $str) Make a instance. This method is equivalent to `new`. ``` my $io = IO::Blob.open("foo\nbar\n"); ``` ## get(IO::Blob:D:) Reads a single line from the Blob. ``` my $io = IO::Blob.open("foo\nbar\n".encode); $io.get; # => "foo\n" ``` ## getc(IO::Blob:D:) Read a single character from the Blob. ``` my $io = IO::Blob.open("foo\nbar\n".encode); $io.getc; # => "f\n" ``` ## lines(IO::Blob:D: $limit = Inf) Return a lazy list of the Blob's lines read via `get`, limited to `$limit` lines. ``` my $io = IO::Blob.open("foo\nbar\n".encode); for $io.lines -> $line { $line; # 1st: "foo\n", 2nd: "bar\n" } ``` ## word(IO::Blob:D:) Read a single word (separated on whitespace) from the Blob. ``` my $io = IO::Blob.open("foo bar\tbuz\nqux".encode); $io.word; # => "foo " ``` ## words(IO::Blob:D: $count = Inf) Return a lazy list of the Blob's words (separated on whitespace) read via `word`, limited to `$count` words. ``` my $io = IO::Blob.open("foo bar\tbuz\nqux".encode); for $io.words -> $word { $word; # 1st: "foo ", 2nd: "bar\t", 3rd: "buz\n", 4th: "qux" } ``` ## print(IO::Blob:D: \*@text) returns Bool Text writing; writes the given `@text` to the Blob. ## say(IO::Blob:D: \*@text) returns Bool Text writing; similar to print, but add a newline to end of the `@text`. ## read(IO::Blob:D: Int(Cool:D) $bytes) Binary reading; reads and returns `$bytes` bytes from the Blob. ## write(IO::Blob:D: Blob:D $buf) Binary writing; writes $buf to the Blob. ## seek(IO::Blob:D: int $offset, SeekType:D $whence = SeekFromBeginning) Move the pointer (that is the position at which any subsequent read or write operations will begin,) to the byte position specified by `$offset` relative to the location specified by `$whence` which may be one of: * SeekFromBeginning The beginning of the file. * SeekFromCurrent The current position in the file. * SeekFromEnd The end of the file. ## tell(IO::Blob:D:) returns Int Returns the current position of the pointer in bytes. ## ins(IO::Blob:D:) returns Int Returns the number of lines read from the file. ## slurp-rest(IO::Blob:D: :$bin!) returns Buf Return the remaining content of the Blob from the current position (which may have been set by previous reads or by seek.) If the adverb `:bin` is provided a Buf will be returned. ## slurp-rest(IO::Blob:D: :$enc = 'utf8') returns Str Return the remaining content of the Blob from the current position (which may have been set by previous reads or by seek.) Return will be a Str with the optional encoding `:enc`. ## eof(IO::Blob:D:) Returns Bool::True if the read operations have exhausted the content of the Blob; ## close(IO::Blob:D:) Will close a previously opened Blob. ## is-closed(IO::Blob:D:) Returns Bool::True if the Blob is closed. ## data(IO::Blob:D:) Returns the current Blob. # SEE ALSO [IO::Scalar of perl5](https://metacpan.org/pod/IO::Scalar) # AUTHOR moznion [[email protected]](mailto:[email protected]) # CONTRIBUTORS * mattn * shoichikaji # LICENSE Copyright 2015 moznion [[email protected]](mailto:[email protected]) This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-SCIMON-Test-HTTP-Server.md [![Build Status](https://travis-ci.org/Scimon/p6-Test-HTTP-Server.svg?branch=master)](https://travis-ci.org/Scimon/p6-Test-HTTP-Server) # NAME Test::HTTP::Server - Simple to use wrapper around HTTP::Server::Async designed for tests # SYNOPSIS ``` use Test::HTTP::Server; # Simple usage # $path is a folder with a selection of test files including index.html my $test-server = Test::HTTP::Server.new( :dir($path) ); # method-to-test expects a web host and will make a GET request to host/index.html ok method-to-test( :host( "http://localhost:{$test-server.port}" ) ), "This is a test"; # Other tests on the results here. my @events = $test-server.events; is @events.elems, 1, "One request made"; is @events[0].path, '/index.html', "Expected path called"; is @events[0].method, 'GET', "Expected method used"; is @events[0].code, 200, "Expected response code"; $test-server.clear-events; ``` # DESCRIPTION Test::HTTP::Server is a wrapper around HTTP::Server::Async designed to allow for simple Mock testing of web services. The constructor accepts a 'dir' and an optional 'port' parameter. The server will server up any files that exist in 'dir' on the given port (if not port is given then one will be assigned, the '.port' method can be accessed to find what port is being used). All requests are logged in a basic even log allowing for testing. If you make multiple async requests to the server the ordering of the events list cannot be assured and tests should be written based on this. If a file doesn't exist then the server will return a 404. Currently the server returns all files as 'text/plain' except files with the following extensions : * `html` => `text/html` * `png` => `image/png` * `jpg` => `image/jpeg` * `jpeg` => `image/jpeg` * `gif` => `image/gif` * `js` => `application/javascript` * `json` => `application/json` * `css` => `text/css` * `xml` => `application/xml` ## CONFIG You can include a file called `config.yml` in the file which allows for additional control over the responses. The following keys are available : ### mime Hash representation of extension and mime type header allows adding additional less common mime types. ### paths Hash where keys are paths to match (including leading `/`), values are hashes with the currently allowed keys : #### returns A list of commands to specify the return result, currently valid values. * Any 3 digit code => returns that HTTP status. * "file" => returns the file at the given path. * "loop" => goes to the top of the list and processes that Each time a request is made to the given path the next response in the list will be given. If the end of the list is reached then this result will be returned from then on. ## METHODS ### events Returns the list of event objects giving the events registered to the server. Note if async requests are being made the order of events cannot be assured. Events objects have the following attributes : * `path` Path of the request * `method` Method of the request * `code` HTTP code of the response ### clear-events Clear the event list allowing the server to be reused in further tests. Calling this method will also reset all the indexes on 'returns' in the config files. Further requests will start from the first registered response. ### mime-types Returns a hash of mime-types registered with the server including any added in `config.yml` file. ## TODO This is a very basic version of the server in order to allow other development to be worked on. Planned is to allow a config.yml file to exist in the top level directory. If the file exists it will allow you control different paths and their responses. This is intended to allow the system to replicate errors to allow for error testing. # AUTHOR Simon Proctor [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2018 Simon Proctor This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-tbrowder-LocalTime.md [![Actions Status](https://github.com/tbrowder/LocalTime/actions/workflows/linux.yml/badge.svg)](https://github.com/tbrowder/LocalTime/actions) [![Actions Status](https://github.com/tbrowder/LocalTime/actions/workflows/macos.yml/badge.svg)](https://github.com/tbrowder/LocalTime/actions) [![Actions Status](https://github.com/tbrowder/LocalTime/actions/workflows/windows.yml/badge.svg)](https://github.com/tbrowder/LocalTime/actions) # NAME **LocalTime** - A wrapper of class **DateTime** with varied formatters depending on time zone entry # SYNOPSIS ``` use LocalTime; ``` # DESCRIPTION **LocalTime** is a wrapper class holding an instance of the Raku **DateTime** class. It was created to either add a local timezone (TZ) abbreviation to a time string or show either none or other TZ information depending on the use (or non-use) of the named variable `:tz-abbrev`. Following are the formatting effects of the various input conditions: ### class DateTime * The default format for `DateTime`: ``` $ say DateTime.new: :2024year; 2024-01-01T00:00:00Z ``` ### class LocalTime * The default format for `LocalTime` with no time zone entry: ``` $ say LocalTime.new(:2024year); 2024-01-01T00:00:00 # <== note no trailing 'Z' ``` * The default format for `LocalTime` with 'CST' entered: ``` $ say LocalTime.new(:2024year, :tz-abbrev<CST>); 2024-01-01T00:00:00 CST ``` * The format for `LocalTime` with a non-US TZ abbreviation entered: ``` $ say LocalTime.new(:2024year, :tz-abbrev<XYT>); 2024-01-01T00:00:00 XYT ``` * The format for `LocalTime` with an empty `:tz-abbrev` named argument entered: ``` $ say LocalTime.new(:2024year, :tz-abbrev); 2024-01-01T00:00:00 Local Time (UTC -6 hrs) ``` Note for US TZ entries the user can enter either '\*st' or '\*dt' (case insensitive) and the correct form will be used for the time of year. This module is used to good effect in module `DateTime::US` to get the desired time zone abbreviation in its `.to-localtime` method. Currently only US abbreviations are in the 'use'd **Timezones::US** database, but a future modification will add others (perhaps in other languages also). PRs are welcome! # AUTHOR Tom Browder [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE © 2022-2024 Tom Browder This library is free software; you may redistribute or modify it under the Artistic License 2.0.
## dist_zef-tbrowder-Calendar.md [![Actions Status](https://github.com/tbrowder/Calendar/actions/workflows/linux.yml/badge.svg)](https://github.com/tbrowder/Calendar/actions) [![Actions Status](https://github.com/tbrowder/Calendar/actions/workflows/macos.yml/badge.svg)](https://github.com/tbrowder/Calendar/actions) # NAME **Calendar** - Provides class data for producing calendars **Calendar** is a Work in Progress (WIP). Please file an issue if there are any features you want added. Bug reports (issues) are always welcome. Useful features now working: * Produce text calendar output to stdout, **in one of 13 languages**, identical to the `cal` program found on Linux hosts. * Calendar output can be for months less than one year. * Show an example events CSV file for upcoming personalization of PDF wall calendars. # SYNOPSIS ``` use Calendar; ``` # DESCRIPTION **Calendar** Provides class data for producing calendars. It includes a Raku program to provide a personalized calendar: `make-cal`. Note that calendars may be printed in other languages than English. Through use of the author's public module **Date::Names**, the user can select the ISO two-letter language code and enter it in the `make-cal` program. Those codes are repeated here for reference: ### Table 1. Language ISO codes (lower-case) | Language | ISO code | | --- | --- | | Dutch | nl | | English | en | | French | fr | | German | de | | Indonesian | id | | Italian | it | | Norwegian (Bokmål) | nb | | Norwegian (Nynorsk) | nn | | Polish | pl | | Romanian | ro | | Russian | ru | | Spanish | es | | Ukranian | uk | See the **docs/WIP.rakudoc** for more information on planned features. ## Program `make-cal` Execute the program, without arguments, to see details of its current capabilities. # AUTHOR Tom Browder [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE © 2020-2023 Tom Browder This library is free software; you may redistribute it or modify it under the Artistic License 2.0.
## dist_cpan-UZLUISF-Podviewer.md # TITLE Podviewer `podviewer` is a simple GUI application written in Raku Perl 6 for previewing (Perl 6) Pod files. It requires [Zenity](https://help.gnome.org/users/zenity/), which in turn requires GTK3 and WebKit engine. # USAGE Viewing a Pod file with slightly-modified Github Markdown CSS: ``` $ podviewer sample.pod6 ``` Viewing a Pod file with provided CSS: ``` $ podviewer -css=path/to/css sample.pod6 ``` Run **`podviewer -h`** for the usage message. # INSTALLATION If you have [`zef`](https://github.com/ugexe/zef) installed, simply run `zef install podviewer`. Alternatively, download or clone the repository (`git clone https://gitlab.com/uzluisf/podviewer.git`). Then, `zef install ./podviewer`. # AUTHOR Luis F. Uceta
## dist_github-CurtTilmes-Math-Primesieve.md # Math::Primesieve Raku bindings for [primesieve](http://primesieve.org/). primesieve generates primes using a highly optimized [sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) implementation. It counts the primes below 10¹⁰ in just 0.45 seconds on an Intel Core i7-6700 CPU (4 x 3.4GHz). primesieve can generate primes and [prime k-tuplets](http://en.wikipedia.org/wiki/Prime_k-tuple) up to 2⁶⁴. # USAGE ``` use Math::Primesieve; my $p = Math::Primesieve.new; say "Using libprimesieve version $p.version()"; say $p.primes(100); # Primes under 100 say $p.primes(100, 200); # Primes between 100 and 200 say $p.n-primes(20); # First 20 primes say $p.n-primes(10, 1000); # 10 primes over 1000 say $p.nth-prime(10); # nth-prime say $p[10]; # Can also just subscript for nth-prime say $p.nth-prime(100, 1000); # 100th prime over 1000 say $p.count(10**9); # Count primes under 10^9 $p.print(10); # Print primes under 10 say $p.count(10**8, 10**9); # Count primes between 10^8 and 10^9 $p.print(10, 20); # Print primes between 10 and 20 ``` Pass options :twins, :triplets, :quadruplets, :quintuplets, :sextuplets to `count` or `print` for prime k-tuplets. # Iterator ``` my $iterator = Math::Primesieve::iterator.new; say $iterator.next for ^10; # Print first 10 primes; $iterator.skipto(1000); # skip to a specific start (can also # specify stop_hint) say $iterator.next for ^10; # Print 10 primes over 1000 say $iterator.prev for ^10; # Previous primes my $it = Math::Primesieve::iterator.new(1000); # Can start at a num ``` # INSTALLATION First install the [primesieve](https://github.com/kimwalisch/primesieve) library. For Ubuntu linux, just run: ``` sudo apt install libprimesieve-dev ``` Then install this module in the normal way with zef. ``` zef install Math::Primesieve ```
## dist_cpan-LEMBARK-FindBin.md # SYNOPSIS ``` # export Bin() and Script() by default. use FindBin; my $dir_from = Bin(); # $dir_from is an IO object my $script_base = Script(); # $script_base is a string. # explicitly export only Bin() or Script(). use FindBin :Bin; use FindBin :Script; # set verbose or resolve to True by default in the current # lexical scope. # # caller can examine constants # MY::_FindBin-verbose-def # MY::_FindBin-resolve-def # to determine the default. # # verbose output is sent to stderr via "note" with a # leading '#'. use FindBin :verbose; use FindBin :resolve; use FindBin ( :verbose :resolve ); # request the bin path with symlinks resolved # regardless of the default at use time. # Bin will have symlinks along the path resolved, # Script will return the basename of any resolved # symlink. my $resolved = Bin( :resolve ); # determine if the current executable is running # from a symlinked path. stringy compare of the # IO objects does the right thing. my $dir = Bin( :!resolve ); my $abs = Bin( :resolve ); $dir ne $abs and say "There is a symlink in path '$dir'"; # make every subsequent call to Bin() default to # Bin( :resolve ) # within the current lexical scope. use FindBin :resolve; # messages might be useful for dealing with # stray symlinks in filesystem. my $dir_from = Bin( :verbose ); # make every subsequent call to Bin() default to Bin(:verbose) # within the current lexical scope. use FindBin :verbose; ``` # DESCRIPTION This module is used to locate the currently running Raku program and the diretory it is running from. Command-line use of raku -, raku -e or interactive use of the REPL will cause `Script()` to return `"-"`, `"-e"`, or `"interactive"` and `Bin()` to return `$*CWD`. Otherwise `Script()` will return the basename of the running program and `Bin()` will return the name of the directory where the program was run from (taken from `$*PROGRAM` when Bin is called). ## Notes: * Bin returns *absolute* paths. The IO returned by Bin will allways be an absolute (i.e., rooted) path via `.absolute` or or `.resolve`. In most cases the *absolute* path is more useful: people created the symlinks for a reason; resolve is mainly useful for code performing validation or analysis of things like dangling links. * Bin returns an *IO object* The stringy path can be extracted calling `~Bin()` or `Bin.Str`. ## Arguments to `Bin()` & `Script()`: * *:resolve* Causes `Bin()` to return the bin value after resolving symliks with `.resolve` instead of `.absolute`. * *:verbose* Turns on verbose reporting (to STDERR) for debugging purposes, including the path used, resolve status, and returned value. ## Defaults via `use FindBin` The defaults for both arguments can be set in the current lexical context by passing the options to `use FindBin` statement. For example: ``` # make Bin() default to Bin(:resolve) use FindBin :Bin, :resolve; # alternatively, make Bin() default to Bin(:resolve, :verbose) use FindBin :Bin, :resolve, :verbose; ``` Note that explicitly passing a `:!resolve` or `:!verbose` to `Bin()` will override these defaults: ``` use FindBin :verbose; my $dir = Bin( :!verbose ); # runs without logging ``` ## Tests use symlinks To see examples of using :resolve with symlinks look at the test `t/10-symlink.t`. # SEE ALSO * Raku variables `$*PROGRAM`, `$*PROGRAM-NAME`: <https://docs.raku.org/language/variables#index-entry-%24%2APROGRAM> Class which implements the dirname, basename, and absolute methods use to determine the absolute path returned by `Bin()`. ``` https://docs.raku.org/type/IO ``` * IO *absolute* vs. *resolve* <https://docs.raku.org/routine/absolute> <https://docs.raku.org/routine/resolve> * <https://metacpan.org/search?size=20&q=gbarr> Imitation really is the sincerest form of flattery. Kindly take a moment to notice how many thing that made sense and just plain worked were contributed to Perl by Graham Barr. Then flatter him: produce something that works equally well in Raku. # AUTHOR Steven Lembark [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2018-2020 Steven Lembark This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0 or any later version.
## dist_cpan-JNTHN-JSON-Path.md # JSON::Path [Build Status](https://travis-ci.org/jnthn/json-path) The [JSONPath query language](https://goessner.net/articles/JsonPath/) was designed for indexing into JSON documents. It plays the same role as XPath does for XML documents. This module implements `JSON::Path`. However, it is not restricted to working on JSON input. In fact, it will happily work over any data structure made up of arrays and hashes. ## Synopsis ``` # Example data. my $data = { kitchen => { drawers => [ { knife => '🔪' }, { glass => '🍷' }, { knife => '🗡️' }, ] } }; # A query my $jp = JSON::Path.new('$.kitchen.drawers[*].knife'); # The first result dd $jp.value($data); # "🔪" # All results. dd $jp.values($data); # ("🔪", "🗡️").Seq # All paths where the results were found. dd $jp.paths($data); # ("\$.kitchen.drawers[0].knife", # "\$.kitchen.drawers[2].knife").Seq # Interleaved paths and values. dd $jp.paths-and-values($data); # ("\$.kitchen.drawers[0].knife", "🔪", # "\$.kitchen.drawers[2].knife", "🗡️").Seq ``` ## Query Syntax Summary The following syntax is supported: ``` $ 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 (Perl 6) 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).
## dist_zef-yabobay-sublist.md # sublist a sublist is when one list is found verbatim inside another list. ## sublist::index determines whether a list is a sublist of another. if it can, it returns the location where it was found. otherwise, returns `Nil`. ``` use sublist; say sublist::index(<d e f>, <a b c d e f g>); # should print 3 ``` enjoy!!! ## sublist::indices finds all sublist indexes and returns a list of them. returns `Nil` if none are found. ``` use sublist; # ↓ should print 3 and 7 .say for sublist::indices(<d e f>, <a b c d e f and d e f g>); ```
## say.md say Combined from primary sources listed below. # [In IO::Handle](#___top "go to top of document")[§](#(IO::Handle)_method_say "direct link") See primary documentation [in context](/type/IO/Handle#method_say) for **method say**. ```raku multi method say(IO::Handle:D: **@text --> True) ``` This method is identical to [put](/type/IO/Handle#method_put) except that it stringifies its arguments by calling [`.gist`](/routine/gist) instead of [`.Str`](/routine/Str). 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 = open 'path/to/file', :w; $fh.say(Complex.new(3, 4)); # OUTPUT: «3+4i␤» $fh.close; ``` # [In Proc::Async](#___top "go to top of document")[§](#(Proc::Async)_method_say "direct link") See primary documentation [in context](/type/Proc/Async#method_say) for **method say**. ```raku method say(Proc::Async:D: $output, :$scheduler = $*SCHEDULER) ``` Calls method `gist` on the `$output`, adds a newline, encodes it as UTF-8, and sends it 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 say, otherwise an [`X::Proc::Async::MustBeStarted`](/type/X/Proc/Async/MustBeStarted) exception is thrown. # [In Mu](#___top "go to top of document")[§](#(Mu)_method_say "direct link") See primary documentation [in context](/type/Mu#method_say) for **method say**. ```raku multi method say() ``` Will [`say`](/type/IO/Handle#method_say) to [standard output](/language/variables#index-entry-$*OUT). ```raku say 42; # OUTPUT: «42␤» ``` What `say` actually does is, thus, deferred to the actual subclass. In [most cases](/routine/say) it calls [`.gist`](/routine/gist) on the object, returning a compact string representation. In non-sink context, `say` will always return `True`. ```raku say (1,[1,2],"foo",Mu).map: so *.say ; # OUTPUT: «1␤[1 2]␤foo␤(Mu)␤(True True True True)␤» ``` However, this behavior is just conventional and you shouldn't trust it for your code. It's useful, however, to explain certain behaviors. `say` is first printing out in `*.say`, but the outermost `say` is printing the `True` values returned by the `so` operation. # [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_sub_say "direct link") See primary documentation [in context](/type/independent-routines#sub_say) for **sub say**. ```raku multi say(**@args --> True) ``` Prints the "gist" of given objects; it will always invoke `.gist` in the case the object is a subclass of [`Str`](/type/Str). Same as [`put`](/type/independent-routines#sub_put), except it uses [`.gist`](/routine/gist) method to obtain string representation of the object; as in the case of `put`, it will also autothread for [`Junction`](/type/Junction)s. **NOTE:** the [`.gist`](/routine/gist) method of some objects, such as [Lists](/type/List#method_gist), returns only **partial** information about the object (hence the "gist"). If you mean to print textual information, you most likely want to use [`put`](/type/independent-routines#sub_put) instead. ```raku say Range; # OUTPUT: «(Range)␤» say class Foo {}; # OUTPUT: «(Foo)␤» say 'I ♥ Raku'; # OUTPUT: «I ♥ Raku␤» say 1..Inf; # OUTPUT: «1..Inf␤» ```
## documenting.md role Metamodel::Documenting Metarole for documenting types. ```raku role Metamodel::Documenting { } ``` *Warning*: this role is part of the Rakudo implementation, and is not a part of the language specification. Type declarations may include declarator blocks (`#|` and `#=`), which allow you to set the type's documentation. This can then be accessed through the `WHY` method on objects of that type: ```raku #|[Documented is an example class for Metamodel::Documenting's documentation.] class Documented { } #=[Take a look at my WHY!] say Documented.WHY; # OUTPUT: # Documented is an example class for Metamodel::Documenting's documentation. # Take a look at my WHY! ``` `Metamodel::Documenting` is what implements this behavior for types. This example can be rewritten to use its methods explicitly like so: ```raku BEGIN { our Mu constant Documented = Metamodel::ClassHOW.new_type: :name<Documented>; Documented.HOW.compose: Documented; Documented.HOW.set_why: do { my Pod::Block::Declarator:D $pod .= new; $pod._add_leading: "Documented is an example class for Metamodel::Documenting's documentation."; $pod._add_trailing: "Take a look at my WHY!"; $pod }; } say Documented.HOW.WHY; # OUTPUT: # Documented is an example class for Metamodel::Documenting's documentation. # Take a look at my WHY! ``` It typically isn't necessary to handle documentation for types directly through their HOW like this, as `Metamodel::Documenting`'s methods are exposed through [`Mu`](/type/Mu) via its `WHY` and `set_why` methods, which are usable on types in most cases. # [Methods](#role_Metamodel::Documenting "go to top of document")[§](#Methods "direct link") ## [method set\_why](#role_Metamodel::Documenting "go to top of document")[§](#method_set_why "direct link") ```raku method set_why($why) ``` Sets the documentation for a type to `$why`. ## [method WHY](#role_Metamodel::Documenting "go to top of document")[§](#method_WHY "direct link") ```raku method WHY() ``` Returns the documentation for a type.
## dist_zef-massa-App-ShowPath.md [![Actions Status](https://github.com/massa/App-ShowPath/actions/workflows/linux.yml/badge.svg)](https://github.com/massa/App-ShowPath/actions) [![Actions Status](https://github.com/massa/App-ShowPath/actions/workflows/macos.yml/badge.svg)](https://github.com/massa/App-ShowPath/actions) # NAME App::ShowPath - show the contents of the environment variable $PATH, in a browseable table form # SYNOPSIS ``` $ showpath ``` # DESCRIPTION App::ShowPath is a simple script to show the contents of $PATH via Term::TablePrint; # AUTHOR Humberto Massa `[email protected]` # COPYRIGHT AND LICENSE Copyright © 2024 Humberto Massa This library is free software; you can redistribute it and/or modify it under either the Artistic License 2.0 or the LGPL v3.0, at your convenience.
## dist_cpan-PMQS-Bundle-IO-Compress-Bzip2.md ``` Bundle-IO-Compress-Bzip2 Version 2.017 28 March 2009 Copyright (c) 2008-2009 Paul Marquess. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. DESCRIPTION ----------- This module is for use with the CPAN or CPANPLUS shells to install IO-Compress-Bzip2 and all its dependencies. Paul Marquess ```
## dist_zef-lizmat-App-Ecosystems.md [![Actions Status](https://github.com/lizmat/App-Ecosystems/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/App-Ecosystems/actions) [![Actions Status](https://github.com/lizmat/App-Ecosystems/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/App-Ecosystems/actions) [![Actions Status](https://github.com/lizmat/App-Ecosystems/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/App-Ecosystems/actions) # NAME App::Ecosystems - Interactive Ecosystem Inspector # SYNOPSIS ``` $ ecosystems Ecosystem: Raku Ecosystem Archive ('rea' 12069 identities) Updated: 2024-12-04T09:32:33 Period: 2011-05-10 - 2024-12-03 rea > % ecosystems --ecosystem=zef Ecosystem: Zef (Fez) Ecosystem Content Storage ('zef' 5002 identities) Updated: 2024-12-03T19:42:25 rea > ``` # DESCRIPTION App::Ecosystems provides an interactive shell for interrogating and inspecting the Raku module ecosystem, providing an interactive interface to the API provided by the [`Ecosystem`](https://raku.land/zef:lizmat/Ecosystem) module. This shell is both provided as an exported `ecosystems` subroutine, as well as a command-line script called `ecosystems`. # COMMANDS These are the available commands in alphabetical order. Note that if `Linenoise` or `Terminal::LineEditor` is used as the underlying interface, tab completion will be available for all of these commands. Also note that each command may be shortened to a unique root: so just entering "a" would be ambiguous, but "ap" would give you the "api" functionality. ## authors ``` rea > authors Found 600 unique author names rea > authors liz Authors matching 'liz' ---------------------------------------------------------------------- Elizabeth Mattijsen (230x) ``` Search authors related information (the information in the meta tags "author" and "authors"). ## catch ``` rea > catch Exception catching is: ON rea > catch off Exception catching set to OFF ``` Show whether exceptions will be caught or not, or change that setting. By default any exceptions during execution will be caught and only a one-line message of the error will be shown. By default it is **ON**. Switching it to **OFF** will cause an exception to show a complete backtrace and exit the program, which may be desirable during debugging and/or error reporting. ## default-api ``` rea > default-api Default api is: 'Any' rea > default-api 1 Default api set to '1' ``` Show or set the default "api" value to be used in ecosystem searches. ## default-auth ``` rea > default-auth Default authority is: 'Any' rea > default-auth zef:raku-community-modules Default authority set to 'zef:raku-community-modules' ``` Show or set the default "auth" value to be used in ecosystem searches. ## default-from ``` rea > default-from Default from is: 'Any' rea > default-from NQP Default from set to 'NQP' ``` Show or set the default "from" value to be used in ecosystem searches. ## default-ver ``` rea > default-ver Default version is: 'Any' rea > default-ver 0.0.3+ Default version set to '0.0.3+' ``` Show or set the default "ver" value to be used in ecosystem searches. ## dependencies ``` rea > dependencies Map::Match Dependencies of Map::Match:ver<0.0.5>:auth<zef:lizmat> Add 'verbose' for recursive depencies ---------------------------------------------------------------------- Hash::Agnostic:ver<0.0.16>:auth<zef:lizmat> Map::Agnostic:ver<0.0.10>:auth<zef:lizmat> ``` Show the dependencies of a given distribution name. If the distribution name is not fully qualified with `auth`, `ver` and `api`, then the most recent version will be assumed. ``` rea > dependencies Map::Match :ver<0.0.1> Dependencies of Map::Match:ver<0.0.1>:auth<zef:lizmat> Add 'verbose' for recursive depencies ---------------------------------------------------------------------- Hash::Agnostic:ver<0.0.10>:auth<zef:lizmat> Map::Agnostic:ver<0.0.6>:auth<zef:lizmat> ``` You can also specify a version if you'd like to see the dependency information of that version of the distribution. ## distros ``` rea > distros Agnostic Distributions that match 'Agnostic' Add 'verbose' to also see their frequency ---------------------------------------------------------------------- Array::Agnostic Hash::Agnostic List::Agnostic Map::Agnostic ``` Show the names of the distributions with the given search term. For now any distribution name that contains the given string, will be included. The search term may be expressed as a regular expression. ## ecosystem ``` rea > ecosystem Using the Raku Ecosystem Archive rea > ecosystem fez Ecosystem: Zef (Fez) Ecosystem Content Storage ('zef' 4996 identities) Updated: 2024-12-02T19:35:46 ``` Show or set the ecosystem to be used in ecosystem searches. Note that the currently used ecosystem is also shown in the prompt. ## editor ``` rea > editor LineEditor ``` Show the name of the underlying editor that is being used. Note that only `Linenoise` and `LineEditor` allow tab-completions. ## exit ``` rea > exit $ ``` Exit and save any history. ## help ``` rea > help Available commands: ---------------------------------------------------------------------- api authority catch dependencies distros ecosystem editor exit from help identities meta quit reverse-dependencies river unresolvable unversioned use-targets verbose version ``` Show available commands if used without additional argument. If a command is specified as an additional argument, show any in-depth information about that command. ## identities ``` rea > identities SSH::LibSSH Most recent version of identities that match 'SSH::LibSSH' Add 'verbose' to see all identities ---------------------------------------------------------------------- SSH::LibSSH:ver<0.9.2>:auth<zef:raku-community-modules> SSH::LibSSH::Tunnel:ver<0.0.9>:auth<zef:massa> ``` Show the most recent versions of the identities that match the given search term, either as distribution name or `use` target. The search term may be expressed as a regular expression. ## meta ``` rea > meta actions Meta information of actions:ver<0.0.2>:auth<zef:lizmat> Resolved from: actions ---------------------------------------------------------------------- { "auth": "zef:lizmat", "authors": [ "Elizabeth Mattijsen" ], "description": "Introduce \"actions\" keyword", "dist": "actions:ver<0.0.2>:auth<zef:lizmat>", "license": "Artistic-2.0", "name": "actions", "perl": "6.d", "provides": { "actions": "lib/actions.rakumod" }, "release-date": "2024-09-23", "source-url": "https://raw.githubusercontent.com/raku/REA/main/archive/A/actions/actions%3Aver%3C0.0.2%3E%3Aauth%3Czef%3Alizmat%3E.tar.gz", "tags": [ "GRAMMAR", "ACTIONS" ], "version": "0.0.2" } ``` Show the meta information of the given distribution name as it was found in the currently active ecosystem. Note that this may be subtly different from the contents of the META6.json file becomes an ecosystem may have added fields and/or have updated fields for that particular ecosystem (such as "source-url"). ## quit ``` rea > quit $ ``` Exit and save any history. ## release-dates ``` rea > release-dates 2023 Found 332 dates matching '2023' with 1358 releases rea > release-dates 2024-12-11 verbose Found 1 dates matching '2024-12-11' with 2 releases -------------------------------------------------------------------------------- 2 recent identities on 2024-12-11: -------------------------------------------------------------------------------- Graph:ver<0.0.25>:auth<zef:antononcube> JavaScript::D3:ver<0.2.28>:auth<zef:antononcube>:api<1> ``` Show the dates and optionally the releases on those dates (as found in the "release-date" field in the META6.json). Note that this field is only provided by the Raku Ecosystem Archive so far. ## unresolvable Current semantics are less than useful. Please ignore until fixed. ## reverse-dependencies ``` rea > reverse-dependencies Ecosystem Reverse dependencies of Ecosystem ---------------------------------------------------------------------- App::Ecosystems CLI::Ecosystem ``` Show the distribution names that have a dependency on the given identity. ## river ``` rea > river Top 3 distributions and number of dependees Add 'verbose' to also see the actual dependees JSON::Fast (398) File::Directory::Tree (249) MIME::Base64 (233) ``` Show the N distributions (defaults to **3**) that have the most reverse dependencies (aka: are most "up-stream"). ## tags ``` rea > tags Found 1790 unique tags rea > tags conc Tags matching 'conc' ---------------------------------------------------------------------- CONCURRENCY CONCURRENT (8x) ``` Search tag related information (the information in the meta tag "tags"). ## unresolvable Current semantics are less than useful. Please ignore until fixed. ## unversioned ``` rea > unversioned Found 105 distributions that did not have a release with a valid version Add 'verbose' to list the distribution names ``` Show how many distributions there are in the ecosystem without valid version information (and which did **not** have a later release with a valid version value). Optionally also list the identities of these distributions. ## update ``` rea > update Ecosystem: Raku Ecosystem Archive ('rea' 12066 identities) Updated: 2024-12-03T19:02:03 Period: 2011-05-10 - 2024-12-03 ``` Update the in-memory information about the current ecosystem from its original source. ## use-targets ``` rea > use-targets Crane::A Use targets that match Crane::A Add 'verbose' to also see their distribution ---------------------------------------------------------------------- Crane::Add Crane::At ``` Show the names of the `use` targets with the given search term (aka search all keys that are specified in `provides` sections of distributions in the ecosystem). The search term may be expressed as a regular expression. ## verbose ``` rea > verbose Verbosity is: OFF rea > verbose on Verbosity set to ON ``` Show or set the default verbosity level to be used in showing the result of ecosystem searches. The default is **OFF**. ## SEE ALSO This module is basically a replacement of the [`CLI::Ecosystem`](https://raku.land/zef:lizmat/CLI::Ecosystem) module, which suffers from noticeable startup delay because of ecosystem information loading on **each** invocation. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/App-Ecosystems> . Comments and Pull Requests are welcome. If you like this module, or what I'm doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2024, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-nkh-Data-Dump-Tree.md # Data::Dump::Tree [![Build Status](https://travis-ci.org/nkh/P6-Data-Dump-Tree.svg?branch=release)](https://travis-ci.org/nkh/P6-Data-Dump-Tree) ## For perl6 Data::Dump::Tree - Renders data structures in a tree fashion with colors Some blog entries you may want to look at: <http://blogs.perl.org/users/nadim_khemir/2017/08/perl-6-datadumptree-version-15.html> <http://blogs.perl.org/users/nadim_khemir/2017/08/take-a-walk-on-the-c-side.html> <https://perl6advent.wordpress.com/2016/12/21/show-me-the-data/> ![Imgur](http://i.imgur.com/P7eRSwl.png?1) *Warning*: This module is developed and tested with the latest rakudo. It may not work or install properly with your version of rakudo, there is a test suite run to check its fitness. # NAME Data::Dump::Tree - Renders data structures as a tree # SYNOPSIS ``` use Data::Dump::Tree ; ddt @your_data ; my $d = Data::Dump::Tree.new(...) ; $d.ddt: @your_data ; $d does role { ... } ; $d.ddt: @your_data ; ``` # DESCRIPTION Data::Dump::Tree renders your data structures as a tree for legibility. It also can: * colors the output if you install Term::ANSIColor (highly recommended) * filter the data before rendering it * display two data structures side by side (DDTR::MultiColumns) * display the difference between two data structures (DDTR::Diff) * generate DHTML output (DDTR::DHTML) * display an interactive folding data structure (DDTR::Folding) * display parts of the data structure Horizontally (see :flat) * show NativeCall data types and representations (see int32 in examples/) * be used to "visit" a data structure and call callbacks you define # INTERFACE ## sub ddt $data\_to\_dump, [$data\_to\_dump2, ...] :adverb, :named\_argument, ... Renders $data\_to\_dump This interface accepts the following adverbs: * **:print** prints the rendered data, the default befhavior without adverb * **:note** 'note's the rendered data * **:get** returns the rendered data as a single string * **:get\_lines** returns the rendering in its native format * **:get\_lines\_integrated** returns a list of rendered lines * **:fold** opens a Terminal::Print interface, module must be installed * **:remote** sends a rendering the to a listener See examples/ddt.pl and ddt\_receive.pl * **:remote\_fold** sends a foldable rendering to a listener See *examples/remote/ddt\_fold\_send.pl* and *ddt\_fold\_receive.pl*. ## method ddt: $data\_to\_dump, [$data\_to\_dump2, ...], :adverb, :named\_argument, ... Renders $data\_to\_dump, see above for a list of adverbs. # USAGE ``` use Data::Dump::Tree ; class MyClass { has Int $.size ; has Str $.name } my $s = [ 'text', Rat.new(31, 10), { a => 1, b => 'string', }, MyClass.new(:size(6), :name<P6 class>), 'aaa' ~~ m:g/(a)/, ] ; ddt $s, :title<A complex structure> ; ddt $s, :!color ; ``` ## Output ``` A complex structure [5] @0 ├ 0 = text.Str ├ 1 = 3.1 (31/10).Rat ├ 2 = {2} @1 │ ├ a => 1 │ └ b => string.Str ├ 3 = .MyClass @2 │ ├ $.size = 6 │ └ $.name = P6 class.Str └ 4 = (3) @3 ├ 0 = a[0] ├ 1 = a[1] └ 2 = a[2] ``` ## **:caller** and **method ddt\_backtrace: $backtrace = True** if **:caller** is given as an argument, the call site is added to the title if you call **ddt\_backtrace**, all the calls to method **ddt**, or sub **ddt**, will display a call stack. # Rendering Each line of output consists 6 elements. Data::Dump::Tree (DDT) has a default render mode for all data types but you can greatly influence what and how things are rendered. ## Rendering elements ``` tree binder type address | | | | v v v v |- key = value .MyClass @2 ``` ### tree (glyphs) The tree shows the relationship between the data elements. Data is indented under its container. DDT default tree rendering makes it easy to see relationship between the elements of your data structure but you can influence its rendering. ### key The key is the name of the element being displayed; in the examples above the container is an array; Data:Dump::Tree uses the index of the element as the key its key. IE: '0', '1', '2', ... ### binder The string displayed between the key and the value. ### value The element's value; Data::Dump::Tree renders "terminal" variables, eg: Str, Int, Rat. Container have no value, but a content. ### Type The element's type with a '.' prepended. IE: '.Str', '.MyClass' Data::Dump::Tree will render some types specifically: * Ints, and Bools, the type is not displayes to reduce noise * Hashes as **{n}** where n is the number of element of the hash * Arrays as **[n]** * Lists as **(n)** * Sets as **.Set(n)** * Sequences as **.Seq(n)** or **.Seq(\*)** when lazy. You control if sequences are rendered vertically or horizontally, how much of the sequence is rendered and if lazy sequences are rendered (and how many elements for lazy sequences). Check *examples/sequences.pl* as well as the implementation in *lib/Data/Dump/Tree/DescribeBaseObjects.pm*. * Matches as **[x..y]** where x..y is the match range See *Match objects* in the roles section below for configuration of the Match objects rendering. ### address The Data::Dump::Tree address is added to every container in the form of a '@' and an index that is incremented for each container. If a container is found multiple times in the output, it will be rendered as *@address* once then as a reference as *§address* Containers can be named using *set\_element\_name* prior to rendering. ``` my $d = Data::Dump::Tree.new ; $d.set_element_name: $s[5], 'some list' ; $d.set_element_name: @a, 'some array' ; $d.ddt: $s ; ``` A container's name will be displayed next to his address. ## Configuration and Overrides There are multiple ways to configure the Dumper. You can pass a configuration to the ddt() or create a dumper object with your configuration. ``` # subroutine interface ddt $s, :titlei<text>, :width(115), :!color ; # basic object my $dumper = Data::Dump::Tree.new ; # pass you configuration at every call $dumper.ddt: $s, :width(115), :!color ; # configure object at creation time my $dumper = Data::Dump::Tree.new: :width(79) ; # use as configured $dumper.ddt: $s ; # or with a call time configuration override $dumper.ddt: $s, :width(115), :max_depth(3) ; # see roles for roles configuration ``` The example directory contain a lot of examples. Read and run the examples to learn how to use DDT. ### colors #### $color = True Coloring is on if Term::ANSIColor is installed. Setting this option to False forces the output to be monochrome. ``` ddt $s, :!color ; ``` #### %colors You can pass your own colors. The default are: ``` %.colors = < ddt_address blue perl_address yellow link green header magenta key cyan binder cyan value reset gl_0 yellow gl_1 reset gl_2 green gl_3 red > ; ``` Where colors are ANSI colors. *reset* means the default color. By default the tree will not be colored and the key and binder use colors 'key' and 'binder'. For renderings with many and very long continuation lines, having colored glyphs and key-binder colored per level helps greatly. #### $color\_glyphs Will set a default glyph color cycle. ``` # colored glyphs, will cycle ddt @data, :color_glyphs ; # uses < gl_0 gl_1 gl_2 gl_3 > ``` #### @glyph\_colors You can also define your own color cycle with **@glyph\_colors**: ``` # colored glyphs ddt @data, :color_glyphs, glyph_colors => < gl_0 gl_1 > ; ``` #### $color\_kbs Will set a default key and binding color cycle. ``` # used color 'kb_0', 'kb_1' ... and cycles ddt @data, :color_kbs ; #uses < kb_0 kb_1 ... kb_10 > ``` #### @kb\_colors You can also define your own cycle with **@kb\_colors**: ``` # colored glyphs, will cycle ddt @data, :color_kbs, kb_colors => < kb_0 kb_1 > ; ``` ### $width = terminal width Note that the glyps' width is subtracted from the width you pass, ``` ddt $s, :width(40) ; ``` DDT uses the whole terminal width if no width is given. ### $width\_minus = Int Reduces the width, you can use it to reduce the computed width. ### $indent = Str The string is prepended to each line of the rendering ### $nl = Bool Add an empty line after the last line of the rendering ### $max\_depth = Int Limit the depth of a dump. Default is: no limit. ### $max\_depth\_message = True Display a message telling that you have reached the $max\_depth limit, setting this flag to false disable the message. ### $max\_lines = Int Limit the number of lines in the rendering, an approximation as *ddt* does not end rendering in the middle of a multi line. There is no limit by default. ### $display\_info = True When set to false, neither the type nor the address are displayed. ### $display\_type = True By default this option is set. ### $display\_address = DDT\_DISPLAY\_ALL By default this option is set, to change it use: ``` use Data::Dump::Tree; use Data::Dump::Tree::Enums; my $ddt = Data::Dump::Tree.new( :display_address(DDT_DISPLAY_NONE) ); ``` ### $display\_perl\_address = False Display the internal address of the objects. Default is False. ### Str rendering By default Str is rendered as the string with '.Str' You can Control quoting and type display directly in the dumper without having to write a role for it. * $string\_type The type displayed for a Str. * $string\_quote The quote surrounding the string, it will be used on both sides of the string unless $string\_quote\_end is set. * $string\_quote\_end Setting it allows you to have 'asymmetrical quotes' like **[ the string ]**. ### Tree rendering The tree is drawn by default with Unicode characters (glyphs) + one space. You can influence the rendering of the tree in multiple ways: * using glyphs or simple indenting See role *DDTR::FixedGlyphs*. * rendering caracter set and spacing See role *AsciiGlyphs* and *CompactUnicodeGlyphs*. You can also create a role that defines the glyphs to use. * the color of the tree See *$color\_glyphs* above. * "color blob mode" See for a way to gain control over the tree rendering. ### Horizontal layout You can use *:flat( conditions ...)* to render parts of your data horizontally. Horizontal layout is documented in the *LayoutHorizontal.pm* module and you can find examples in *examples/flat.pm*. You can chose which elements, which type of element, even dynamically, to flatten, EG: Arrays with more than 15 elements. ``` dd's example output: $($[[1, [2, [3, 4]]], ([6, [3]],), [1, [2, [3, 4]]]], [[1, [2, [3, 4]]], [1, [2, [3, 4]]]], $[[1, 2], ([1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]]).Seq], [[1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, 2], [1, 2, 3], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]]], $[[1, 2], ([1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]], [1, [2, [3, 4]]]).Seq], "12345678") Same data rendered with ddt and I<:flat>: (6) @0 0 = [3] @1 1 = [2] @9 2 = [2] @12 3 = [10] @25 ├ 0 = [2] @2 ├ 0 = [2] §2 ├ 0 = [2] @13 ├ 0 = [2] §2 │ ├ 0 = 1 └ 1 = [2] §2 │ ├ 0 = 1 ├ 1 = [2] §2 │ └ 1 = [2] @3 │ └ 1 = 2 ├ 2 = [2] §13 │ ├ 0 = 2 └ 1 = .Seq(11) @14 ├ 3 = [3] @29 │ └ 1 = [2] @4 ├ 0 = [2] §2 │ ├ 0 = 1 │ ├ 0 = 3 ├ 1 = [2] §2 │ ├ 1 = 2 │ └ 1 = 4 ├ 2 = [2] §2 │ └ 2 = 3 ├ 1 = (1) @5 ├ 3 = [2] §2 ├ 4 = [2] §2 │ └ 0 = [2] @6 ├ 4 = [2] §2 ├ 5 = [2] §2 │ ├ 0 = 6 ├ 5 = [2] §2 ├ 6 = [2] §2 │ └ 1 = [1] @7 ├ 6 = [2] §2 ├ 7 = [2] §2 │ └ 0 = 3 ├ 7 = [2] §2 ├ 8 = [2] §2 └ 2 = [2] §2 ├ 8 = [2] §2 └ 9 = [2] §2 ├ 9 = [2] §2 └ ... 4 = [2] §12 5 = 12345678.Str ``` ## Handling specific types This section explains how to write specific handlers in classes that create a custom rendering ### in your own classes When Data::Dump::Tree renders an object, it first checks if it has an internal handler for that type; if no handler is found, the object is queried and its handler is used if it is found; finally, DDT uses a generic handler. The module tests, examples directory, and Data::Dump::Tree::DescribeBaseobjects are a good places to look at for more examples of classes defining a custom rendering. #### method **ddt\_get\_header** in your class ``` method ddt_get_header { # return # some text # class type # usually blank for containers | # the value for terminals | | | v v '', '.' ~ self.^name } ``` #### method **ddt\_get\_elements** in your class ``` method ddt_get_elements { # return a list of elements data for each element of the container # key # binder # value (1, ' = ', 'has no name'), (3, ' => ', 'abc'), ('attribute', ': ', '' ~ 1), ('sub object', '--> ', [1 .. 3]), ('from sub', '', something()), } ``` The content of the original container is ignored, what you return is used. This lets you remove/add/modify elements. ### someone else's class and base types You can not add methods to classes that you do not control. Data::Dump::Tree has type handlers, via roles, that it uses to handle specific types contained the structure you want to render. You can override the default handlers and add new ones. Create a role following this template (here a hash example): ``` role your_hash_handler { # Type you want to handle is Hash # |||| # vvvv multi method get_header (Hash $h) { # return # optional description # type (string to display) '', '{' ~ $h.elems ~ '}' } multi method get_elements (Hash $h) { # return the elements of your object $h.sort(*.key)>>.kv.map: -> ($k, $v) {$k, ' => ', $v} } } ``` To make that handler active, make your dumper **do** the role ``` # using 'does' my $d = Data::Dump::Tree.new: :width(80) ; $d does your_hash_handler ; $d.ddt: @your_data ; # or by passing roles to the constructor my $d = Data::Dump::Tree.new: :does(DDTR::MatchDetails, your_hash_handler) ; # or by passing roles to dump() method my $d = Data::Dump::Tree.new ; $d.ddt: $m, :does(DDTR::MatchDetails, your_hash_handler) ; # or by passing roles to ddt sub ddt: $m, :does(DDTR::MatchDetails, your_hash_handler) ; ``` ### FINAL elements So far we have seen how to render containers but sometimes we want to handle a type as if it was a Str or an Int, EG: not display its elements but instead display it on a single line. You can, in a handler, specify that a type rendered is not a container, by returning DDT\_FINAL in the type's *get\_header* handler. For example, the Rat class type handler does not show a floating number, it displays the Rat on a single line. Here is the handler: ``` multi method get_header (Rat $r) { # the rendering of the Rat $r ~ ' (' ~ $r.numerator ~ '/' ~ $r.denominator ~ ')', # its type '.' ~ $r.^name, # hint DDT that this is final DDT_FINAL, # hint DDT that this is has an address DDT_HAS_ADDRESS, } ``` ## Filtering ![Imgur](https://i.imgur.com/GCTcmdP.png) Data::Dump::Tree lets you filter the data to dump. NOTE: filter must be **multi** subs. NOTE: **$path**, a list passed to filters, is set if you use **:keep\_paths** option, otherwise an empty list is passed to the filters. To pass a filter to the dumper: ``` ddt( $s, # all below are optional :removal_filter(&removal_filter, ...), :header_filters(&header_filter, ...), :elements_filters(&elements_filter,), :footer_filters(&footer_filters,), :keep_paths ) ; ``` Data::Dump::Tree filters are called in this order: check if the element is to be removed from the rendering ``` * removal filters are called ``` let you change the header rendering returned by the type's handler ``` * header filters are called ``` let you change the elements of a container returned by the type's handler ``` * element filters are called ``` after the element is rendered ``` * footer filters are called ``` ### removal filter This is called before the type's handler **get\_header** is called. This allows you to efficiently remove elements from the rendering. ``` multi sub remove_filter( $dumper, $s, # "read only" object $path # path in the data structure ) { True # return True if you want the element removed } ``` ### header filter This is called just after the type's *get\_header* is called, this allows you, EG, to insert something in the tree rendering ``` multi sub header_filter( $dumper, # the dumper $replacement # replacement $s, # "read only" object ($depth, $path, $glyph, @renderings), # info about tree ($key, $binder, $value, $type, $final, $want_address) # element info ) { # Add something to the tree @renderings.push: (|$glyph , ('', "HEADER", '')) ; } ``` or change the default **rendering** of the object ``` multi sub header_filter( $dumper, # the dumper \replacement # replacement Int $s, # will only filter Ints ($depth, $path, $glyph, @renderings), # info about the tree # what the type's handler has returned (\key, \binder, \value, \type, \final, \want_address) # can be changed ) { @renderings.push: (|$glyph, ('', 'Int HEADER ' ~ $depth, '')) ; # in this example we need to set limit or we would create lists forever if $depth < 2 { replacement = <1 2> } ; # key, binder, value, and type are Str key = key ~ 'Hash replacement' ; #binder = '' ; #value = '' ; #type = '' ; final = DDT_NOT_FINAL ; want_address = True ; } ``` Note: You can not filter elements of type *Mu* with header filters but you can in element filters. ### elements filter Called after the type's *get\_elements*. You can change the elements. ``` multi sub elements_filter( $dumper, Hash $s, # type to filter (ie Hash) # rendering data you can optionaly use ($depth, $glyph, @renderings, ($key, $binder, $value, $path)), # elements you can modify @sub_elements ) { # optionaly add something in the rendering @renderings.push: (|$glyph, ('', 'SUB ELEMENTS', '')) ; # set/filter the elements @sub_elements = (('key', ' => ', 'value'), ('other_key', ': ', 1)) ; } ``` ### footer filter Called after the element is rendered. ``` multi sub footer_filter($dumper, $s, ($depth, $filter_glyph, @renderings)) { # add message to the rendering after the element is rendered @renderings.push: (|$filter_glyph, ('', "done with {$s.^name}", '')) ; } ``` ## Removing elements ### In removal filters See removal filters above. ### In header filters * remove the element If you return a Data::Dump::Tree::Type::Nothing replacement in your filter, the element will not be displayed at all. ``` multi sub header_filter($dumper, \replacement, Tomatoe $s, $, $) { replacement = Data::Dump::Tree::Type::Nothing ; } ``` As DDT streams the rendering, it can not go back to fix the glyphs of the previous element, this will probably show as slightly wrong tree lines. * or reduce the type's rendering in a type handler This does not remove the element but can be useful, create a type handler which renders the type with minimal text. This is sometime preferable to removing. ### In elements filters * use an elements filter for the **container** of the type you want to remove If the element you don't want to see only appears in some containers, you can create a type handler, or filter, for that container type and weed out any reference to the element you don't want to see. * or reduce the element rendering Returning a Data::Dump::Tree::Type::Nothing.new as value, that type renders an empty string. ``` multi sub elements_filter( ... ) { # other elements data ... # the element to reduce rendering of # key # binder #value ('your key', '', Data::Dump::Tree::Type::Nothing.new), } ``` ## Color Blob Mode (for lack of a better name) When rendering very large data structures the default coloring helps, a better way to render large data set is to turn off coloring for most of the data and highlight only the data that is of greater interest. This makes it easier to visually skip large amount of data quickly. The best way of highlighting is by using background color not text color. You can define "glyph filter" that controls the shape and color of the glyphs. An example can be found in *examples/background\_color.pl6*. A few renderings are generated, some look noisy but they are there to show you the different possibilities, the most interesting examples are the ones that highlight as little as possible. Remember to pass :!color to DDT so element coloring is off. A simpler example is in *examples/html.pl6*, it uses a role defined in Data::Dump::Tree::ColorBlobLevel to set blob colors and filters to transform **DOM::Tiny** parsed data into a rendering more *"HTML"* like. ``` use Data::Dump::Tree::ColorBlobLevel ; my $d = Data::Dump::Tree.new: :string_type(''), :string_quote('"'), :does[DDTR::ColorBlobLevel], :color_kbs, :header_filters[&header], :elements_filters[&elements], :nl ; # you can also override foreground and background color per level # after you have used the ColorBlobLevel role # $d.blob_colors = < on_125 on_61 on_33 on_37 on_64 > ; # $d.blob_colors_fg = < 0 37 64 61> ; ``` This mode also work surprisingly well for very short renderings, in that case try to use role *DDTR::FixedGlyphs*. ## Roles provided with Data::Dump::Tree Data::Dump::Tree comes with a few extra roles that are not **does**'ed by the object returned by new() Please feel free to send me roles you think would be useful to other. You are welcome to make your own distribution for the roles too, I recommend using namespace DDTR::YourRole. ### DDTR::AsciiGlyphs Uses ASCII codes rather than Unicode to render the tree. ### DDTR::CompactUnicodeGlyphs This is the tightest rendering as only one character per level is used to display the tree glyphs. ### DDTR::PerlString Renders string containing control codes (eg: \n, ANSI, ...) with backslashed codes and hex values. ### DDTR::FixedGlyphs Replace all the glyphs by a single glyph; default is a two spaces glyph. ``` my $d = Data::Dump::Tree.new does DDTR::FixedGlyphs(' . ') ; ``` ### DDTR::NumberedLevel Will add the level of the elements to the tree glyphs, useful with huge trees. If a Superscribe role is on, the level umber will also be superscribed ### DDTR::SuperscribeType Use this role to display the type in Unicode superscript letters. ### DDTR::SuperscribeAddress Use this role to display the address in Unicode superscript letters. You can also use the method it provides in your type handlers and filters. ### DDTR::Superscribe Use this role to display the type and address in Unicode superscript letters. ### Data::Dump::Tree::ColorBlobLevel Colors the rendering per level. ### Match objects *Match* objects are displayed as the string that it matched as well as the match start and end position (inclusive, unlike .perl). ``` # multiline match aaaaa aaaaa aaaaa aaaaa [0..23] # same match with PerlString role "'aaaaa\naaaaa\naaaaa\naaaaa\n'[0..23]" ``` Some Roles are provided to allows you to change how Match object are displayed. #### DDTR::MatchLimitString Limits the length of the match string. ``` # default max length of 10 characters aaaaa\naaaa(+14)[0..23] ``` You can set the maximum string length either by specifying a length when the role is added to the dumper. ``` $dumper does DDTR::MatchLimit(15) ; aaaaa\naaaaa\n(+12)'[0..23] ``` or by setting the *$.match\_string\_limit* member variable ``` $dumper does DDTR::MatchLimit ; $dumper.match_string_limit = 15 ; aaaaa\naaaaa\n(+12)[0..23] ``` The specified length is displayed, the length of the remaining part is displayed within parenthesis. #### DDTR::MatchDetails Give complete details about a Match. The match string is displayed as well as the match start and end position. You can set the maximum string length either by specifying a length when the role is added to the dumper or by setting the *$.match\_string\_limit* member variable. ``` # from examples/match.pl Match [passwords]\n jack=password1\n (+74) ⁰··¹¹³ ├ <section> ⁰··⁶⁸ │ ├ <header> [passwords]⁴··¹⁴ │ ├ <kvpair> │ │ ├ <key> jack ²⁴··²⁷ │ │ └ <value> password1 ²⁹··³⁷ │ └ <kvpair> │ ├ <key> joy ⁴⁷··⁴⁹ │ └ <value> muchmoresecure123 ⁵¹··⁶⁷ └ <section> ⁶⁹··¹¹³ ├ <header> [quotas]⁷³··⁸⁰ ├ <kvpair> │ ├ <key> jack ⁹⁰··⁹³ │ └ <value> 123 ⁹⁵··⁹⁷ └ <kvpair> ├ <key> joy ¹⁰⁷··¹⁰⁹ └ <value> 42 ¹¹¹··¹¹² ``` ## Custom Setup Roles If you configure DDT in different ways to render different types, and you should, you will en up writing boilerplate setup code everywhere, you can define functions to return a setup object (or call ddt) or you can use a *custom setup role*. Custom Setup roles define a **custom\_setup** method which is called by DDT before rendering your data. A complete example can be found in *examples/CustomSetup/CustomSetup.pm* and *examples/custom\_setup.pl*. # BUGS Submit bugs (preferably as executable tests) and feel free to make suggestions. ## Dumper Exception As this module uses the MOP interface, it happens that it may use interfaces not implemented by some internal classes. An example is Grammar that I tried to dump and got an exception about a class that I didn't even know existed. Those exception are caught and displayed by the dumper as "DDT Exception: the\_caught\_exception" Please let me know about them so I can add the necessary handlers to the distribution. # AUTHOR Nadim ibn hamouda el Khemir <https://github.com/nkh> Do not hesitate to ask for help. # LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl6 itself. # SEE-ALSO README.md in the example directory Perl 5: * Data::TreeDumper Perl 6: * Data::Dump * Pretty::Printer
## dist_github-JuneKelly-Config-Clever.md # Config::Clever A clever, heirarchical config loader for perl6. [![Build Status](https://travis-ci.org/ShaneKilkelly/perl6-config-clever.svg?branch=master)](https://travis-ci.org/ShaneKilkelly/perl6-config-clever) ## Config files `Config::Clever.load` takes a String `environment` parameter and loads json files from the `config/` directory. The json objects are loaded and merged together in the following order: * `default.json` * `<environment>.json` * `local-<environment>.json` Calling `Config::Clever.load` without any parameters will use `default` as the environment. You can also supply a path to another config directory: ``` my %config = Config::Clever.load(:environment("staging"), :config-dir("./my/weird/path")); ``` ## Example Imagine we have a directory `config`, with two files: `default.json` and `development.json`. ``` // default.json { "db": { "host": "localhost", "port": 27017, "user": null, "password": null, "auth": false }, "logLevel": "DEBUG" } // development.json { "db": { "user": "apprunner", "password": "a_terrible_password", "auth": true } } ``` If we call `Config::Clever.load`, with `"development"` as the environment, we'll get a hash which consists of the data from `development.json` merged on top of the data in `default.json`. ``` use v6; use Config::Clever; my %config = Config::Clever.load(:environment('development')); say %config # %config is a hash equivalent to: # { # "db": { # "host": "localhost", # "port": 27017, # "user": "apprunner", # "password": "a_terrible_password", # "auth": true # }, # "logLevel": "DEBUG" # } ``` ## Todo * more tests * support more file formats such as `ini`, `yaml` and `toml`