txt
stringlengths
93
37.3k
## dist_zef-japhb-MUGS-UI-TUI.md [![Actions Status](https://github.com/Raku-MUGS/MUGS-UI-TUI/workflows/test/badge.svg)](https://github.com/Raku-MUGS/MUGS-UI-TUI/actions) # NAME MUGS::UI::TUI - Fullscreen Terminal UI for MUGS, including App and game UIs # SYNOPSIS ``` # Set up a full-stack MUGS-UI-TUI development environment mkdir MUGS cd MUGS git clone [email protected]:Raku-MUGS/MUGS-Core.git git clone [email protected]:Raku-MUGS/MUGS-Games.git git clone [email protected]:Raku-MUGS/MUGS-UI-TUI.git cd MUGS-Core zef install --exclude="pq:ver<5>:from<native>" . mugs-admin create-universe cd ../MUGS-Games zef install . cd ../MUGS-UI-TUI zef install --deps-only . # Or skip --deps-only if you prefer ### LOCAL PLAY # Play games using a local TUI UI, using an internal stub server and ephemeral data mugs-tui # Play games using an internal stub server accessing the long-lived data set mugs-tui --universe=<universe-name> # 'default' if set up as above # Log in and play games on a WebSocket server using a local TUI UI mugs-tui --server=<host>:<port> ### GAME SERVERS # Start a TLS WebSocket game server on localhost:10000 using fake certs mugs-ws-server # Specify a different MUGS identity universe (defaults to "default") mugs-ws-server --universe=other-universe # Start a TLS WebSocket game server on different host:port mugs-ws-server --host=<hostname> --port=<portnumber> # Start a TLS WebSocket game server using custom certs mugs-ws-server --private-key-file=<path> --certificate-file=<path> # Write a Log::Timeline JSON log for the WebSocket server LOG_TIMELINE_JSON_LINES=log/mugs-ws-server mugs-ws-server ``` # DESCRIPTION **NOTE: See the [top-level MUGS repo](https://github.com/Raku-MUGS/MUGS) for more info.** MUGS::UI::TUI is a TUI (Terminal UI) app (`mugs-tui`) and a growing set of UI plugins to play games in [MUGS-Core](https://github.com/Raku-MUGS/MUGS-Core) and [MUGS-Games](https://github.com/Raku-MUGS/MUGS-Games) via the TUI. **This early version only contains very limited modules and plugins, is missing significant functionality, and should not be considered "fully released" in the same way that the CLI and WebSimple UIs are.** # ROADMAP MUGS is still in its infancy, at the beginning of a long and hopefully very enjoyable journey. There is a [draft roadmap for the first few major releases](https://github.com/Raku-MUGS/MUGS/tree/main/docs/todo/release-roadmap.md) but I don't plan to do it all myself -- I'm looking for contributions of all sorts to help make it a reality. # CONTRIBUTING Please do! :-) In all seriousness, check out [the CONTRIBUTING doc](docs/CONTRIBUTING.md) (identical in each repo) for details on how to contribute, as well as [the Coding Standards doc](https://github.com/Raku-MUGS/MUGS/tree/main/docs/design/coding-standards.md) for guidelines/standards/rules that apply to code contributions in particular. The MUGS project has a matching GitHub org, [Raku-MUGS](https://github.com/Raku-MUGS), where you will find all related repositories and issue trackers, as well as formal meta-discussion. More informal discussion can be found on IRC in Libera.Chat #mugs. # AUTHOR Geoffrey Broadwell [[email protected]](mailto:[email protected]) (japhb on GitHub and Libera.Chat) # COPYRIGHT AND LICENSE Copyright 2021-2024 Geoffrey Broadwell MUGS is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-bbkr-TinyID.md # Shorten and obfuscate IDs in [Raku](https://www.raku.org) language [![test](https://github.com/bbkr/TinyID/actions/workflows/test.yml/badge.svg)](https://github.com/bbkr/TinyID/actions/workflows/test.yml) ## SYNOPSIS ``` use TinyID; my $key = ( 'a'..'z', 'A'..'Z', 0..9 ).flat.pick( * ).join; # example key is '2BjLhRduC6Tb8Q5cEk9oxnFaWUDpOlGAgwYzNre7tI4yqPvXm0KSV1fJs3ZiHM' my $tinyid = TinyID.new( key => $key ); say $tinyid.encode( 48888851145 ); # will print '1FN7Ab' say $tinyid.decode( '1FN7Ab' ); # will print 48888851145 ``` ## DESCRIPTION With the help of this module you can shorten and obfuscate your IDs at the same time. Useful for: * Hiding real database IDs in URLs or REST APIs. * Saving space where it is limited, like in SMS or Push messages. ## METHODS ### new( key => 'qwerty' ) Keyt must consist of at least two unique unicode characters. The **longer the key** - the **shorter encoded ID** will be. Encoded ID will be **made exclusively out of characters from the key**. Choose your key characters wisely, for example: * For SMS messages generate key from `a-z,A-Z,0-9` range. You will get excellent shortening like `1234567890` -> `380FQs`. * For NTFS file names generate key from `a-z` range. You will get good shortening and avoid case insensitivity collisions, like `1234567890` -> `iszbmfx`. * When trolling generate key from Emojis. So `1234567890` will be represented as `😣😄😹😧😋😳`. ### encode( 123 ) Encode unsigned integer into a string. Note that this should not be considered a strong encryption. It does not contain consistency checks. And key is easy to reverse engineer with small amount of encoded/decoded samples given. Treat it as really, really fast obfuscation only. ### decode( 'rer' ) Decode string back into unsigned integer. ## TRICKS If you provide sequential characters in key you can convert your numbers to some weird numeric systems, for example base18: ``` TinyID.new( key => '0123456789ABCDEFGH' ).encode( 48888851145 ).say; # '47F709HFF' ``` ## OTHER IMPLEMENTATIONS * [Rust](https://crates.io/crates/squishyid) * [Perl](http://search.cpan.org/~bbkr/Integer-Tiny-0.3/lib/Integer/Tiny.pm) * [PHP](https://github.com/krowinski/tinyID)
## dist_zef-jjmerelo-MetamodelX-Dataclass.md # Dataclasses in Raku Dataclasses have all the mechanisms that classes have (can be inherited, have accessors), but they don't have any method. Inspired by [Python dataclasses](https://docs.python.org/3/library/dataclasses.html). With private instance variables, they will be effectively frozen. There's probably an use case for this somewhere, but this was created mainly to illustrate the metamodel. ## Installing ``` zef install dataclass ``` ## Running Pretty much as any other class... Except no methods (only [submethods](https://docs.raku.org/type/Submethod)): ``` use lib "."; use MetamodelX::Dataclass; dataclass Foo { has $.bar; has $.baz = 33; } my $foo = Foo.new(:3bar); say $foo.bar; # Can be created by simply using the class name my $bar = Foo(:33bar); ``` Check out also the [`resources/examples`](resources/examples) directory for (possibly) more examples and a negative example. A `dataclass` will not compile if it's got any method, and will throw if a method is added to it dynamically. ## See also There's not a lot of information about the Metamodel in the documentation, but you can check out [the docs for `ClassHOW`](<https://docs.raku>. org/type/Metamodel::ClassHOW). ## License Licensed under the Artistic 2.0 License (the same as Raku itself). ## Author (c) JJ Merelo, `[email protected]`, 2022
## dist_zef-antononcube-DSL-Entity-Metadata.md # Raku DSL::Entity::Metadata Raku grammar and role for metadata entities (types, names, or dataset names.) Used in packages, like, ["DSL::English::DataAcquisitionWorkflows"](https://github.com/antononcube/Raku-DSL-English-DataAcquisitionWorkflows), [AAr1]. --- ## Installation From Zef ecosystem: ``` zef install DSL::Entity::Metadata ``` From GitHub: ``` zef install https://github.com/antononcube/Raku-DSL-Entity-Metadata.git ``` --- ## Examples Here are examples of recognizing different types of data acquisition related specifications: ``` use DSL::Entity::Metadata; use DSL::Entity::Metadata::Grammar; my $pCOMMAND = DSL::Entity::Metadata::Grammar; $pCOMMAND.set-resources(DSL::Entity::Metadata::resource-access-object()); say $pCOMMAND.parse('DateTime'); ``` ``` # 「DateTime」 # metadata-entity-command => 「DateTime」 # entity-metadata-name => 「DateTime」 # 0 => 「DateTime」 # word-value => 「DateTime」 ``` ``` say $pCOMMAND.parse('time series'); ``` ``` # 「time series」 # data-type-entity-command => 「time series」 # entity-data-type-name => 「time series」 # 0 => 「time series」 # word-value => 「time」 # word-value => 「series」 ``` ``` say $pCOMMAND.parse('Titanic'); ``` ``` # 「Titanic」 # dataset-entity-command => 「Titanic」 # entity-dataset-name => 「Titanic」 # 0 => 「Titanic」 # entity-name-part => 「Titanic」 ``` --- ## References ### Metadata [SO1] <https://www.schema.org>. ### Datasets [VAB1] Vincent Arel-Bundock, [Rdatasets](https://github.com/vincentarelbundock/Rdatasets/), (2020), [GitHub/vincentarelbundock](https://github.com/vincentarelbundock/). [WRI1] Wolfram Research (2007), [ExampleData](https://reference.wolfram.com/language/ref/ExampleData.html), (introduced 2007), (updated 2016), Wolfram Language function. [WRI2] Wolfram Research, Inc., [ExampleData Source Information](https://reference.wolfram.com/language/note/ExampleDataSourceInformation.html). ### Repositories [SOr1] Schema.org, [Schema.org project repository](https://github.com/schemaorg/schemaorg), (2105-2021), [GitHub/schemaorg](https://github.com/schemaorg). ### Packages [AAp1] Anton Antonov, [DSL::English::DataAcquisitionWorkflows Raku package](https://github.com/antononcube/Raku-DSL-English-DataAcquisitionWorkflows), (2021), [GitHub/antononcube](https://github.com/antononcube). [AAp2] Anton Antonov, [DSL::Shared Raku package](https://github.com/antononcube/Raku-DSL-Shared), (2020), [GitHub/antononcube](https://github.com/antononcube). [AAp3] Anton Antonov, [DSL::Entity::Geographics Raku package](https://github.com/antononcube/Raku-DSL-Entity-Geographics), (2021), [GitHub/antononcube](https://github.com/antononcube). [AAp4] Anton Antonov, [DSL::Entity::Jobs Raku package](https://github.com/antononcube/Raku-DSL-Entity-Jobs), (2021), [GitHub/antononcube](https://github.com/antononcube). [AAp5] Anton Antonov, [DSL::Entity::Foods Raku package](https://github.com/antononcube/Raku-DSL-Entity-Foods), (2021), [GitHub/antononcube](https://github.com/antononcube). [AAp6] Anton Antonov, [Data::ExampleDatasets Raku package](https://github.com/antononcube/Raku-Data-ExampleDatasets), (2021), [GitHub/antononcube](https://github.com/antononcube). ### Videos [AAv1] Anton Antonov, ["FOSDEM2022 Multi language Data Wrangling and Acquisition Conversational Agents (in Raku)"](https://www.youtube.com/watch?v=3OUkSa-5vEk&t=2665s), (2022), [Anton Antonov's YouTube channel](https://www.youtube.com/@AAA4Predoction). ([Dedicated FOSDEM 2022 page](https://archive.fosdem.org/2022/schedule/event/dataaquisition/).)
## dist_zef-jonathanstowe-UNIX-Privileges.md # UNIX::Privileges A module for handling UNIX privileges ## Example Synopsis: ``` use UNIX::Privileges; UNIX::Privileges::userinfo($user); UNIX::Privileges::chown($user, $file); UNIX::Privileges::drop($user); UNIX::Privileges::chroot($directory); ``` You can also do ``` use UNIX::Privileges :ALL; userinfo($user); chown($user, $file); drop($user); chroot($directory); ``` The `:CH` tag will import `chown` and `chroot` and the `USER` tag will import only `USER`. Example usage: ``` use UNIX::Privileges; UNIX::Privileges::chown("nobody", "test.txt"); UNIX::Privileges::drop("nobody"); ``` Example with a chroot: ``` use UNIX::Privileges; my $user = UNIX::Privileges::userinfo("nobody"); UNIX::Privileges::chown($user, "/tmp/test.txt"); UNIX::Privileges::chroot("/tmp"); # once in the chroot access to the system password file is lost # therefore UNIX::Privileges::drop("nobody") will no longer work # as the system cannot find the uid or gid of "nobody" anymore # fortunately we already have this information in the $user var # that we defined above by calling UNIX::Privileges::userinfo # just remember you have to do this *before* creating the chroot UNIX::Privileges::drop($user); ``` ## Installation Assuming ypu have a working Rakudo installation you can install this with *zef* : ``` zef install UNIX::Privileges ``` Some of the tests won't be run unless they are run as 'root', and you may not be comfortable running a remote installer with escalated privileges, so you may want to checkout or otherwise download this package, run the 'root' tests with something like: ``` sudo zef test . ``` (assuming that the Rakudo toolchain is in the global PATH.) ## Support Please send any suggestions or patches via <https://github.com/jonathanstowe/raku-unix-privileges/issues> ## License & Copyright This is free software, please see the <LICENCE> file in the distribution. © carlin 2015 © Jonathan Stowe 2017 - 2020
## dist_zef-lizmat-Acme-Don-t.md [![Actions Status](https://github.com/lizmat/Acme-Don-t/workflows/test/badge.svg)](https://github.com/lizmat/Acme-Don-t/actions) # NAME Acme::Don't - The opposite of do # SYNOPSIS ``` use Acme::Don't; don't { print "This won't be printed\n" }; # NO-OP ``` # DESCRIPTION The Acme::Don't module provides a `don't` command, which is the opposite of Perl's built-in `do`. It is used exactly like the `do BLOCK` function except that, instead of executing the block it controls, it...well...doesn't. Regardless of the contents of the block, `don't` returns `Nil`. You can even write: ``` don't { # code here } while condition(); ``` And, yes, in strict analogy to the semantics of Perl's magical `do...while`, the `don't...while` block is *unconditionally* not done once before the test. ;-) Note that the code in the `don't` block must be syntactically valid Perl. This is an important feature: you get the accelerated performance of not actually executing the code, without sacrificing the security of compile-time syntax checking. # LIMITATIONS ## No opposite Doesn't (yet) implement the opposite of `do STRING`. The current workaround is to use: ``` don't {"filename"}; ``` ## Double don'ts The construct: ``` don't { don't { ... } } ``` isn't (yet) equivalent to: ``` do { ... } ``` because the outer `don't` prevents the inner `don't` from being executed, before the inner `don't` gets the chance to discover that it actually *should* execute. This is an issue of semantics. `don't...` doesn't mean `do the opposite of...`; it means `do nothing with...`. In other words, doin nothing about doing nothing does...nothing. ## Unless not You can't (yet) use a: ``` don't { ... } unless condition(); ``` as a substitute for: ``` do { ... } if condition(); ``` Again, it's an issue of semantics. `don't...unless...` doesn't mean `do the opposite of...if...`; it means `do nothing with...if not...`. ## PORTING CAVEATS Since Perl 6 doesn't have `undef`, the closest thing to it (`Nil`) is being returned by `don't` instead. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Acme-don-t> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2021 Elizabeth Mattijsen Original author: Damian Conway. Re-imagined from Perl 5 as part of the CPAN Butterfly Plan. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-antononcube-WWW-PaLM.md # WWW::PaLM Raku package Raku package for connecting with [PaLM (Pathways Language Model)](https://blog.google/technology/ai/google-palm-2-ai-large-language-model/). The design and implementation of the package closes follows that of ["WWW::OpenAI"](https://raku.land/zef:antononcube/WWW::OpenAI), [AAp1]; ## Installation From [Zef ecosystem](https://raku.land): ``` zef install WWW::PaLM ``` From GitHub: ``` zef install https://github.com/antononcube/Raku-WWW-PaLM ``` --- ## Usage examples Show models: ``` use WWW::PaLM; palm-models() ``` ``` # (models/chat-bison-001 models/text-bison-001 models/embedding-gecko-001) ``` Show text generation: ``` .say for palm-generate-text('what is the population in Brazil?', format => 'values', n => 3); ``` ``` # 211,768,929 # 213,317,639 # 212,609,039 ``` Show message generation: ``` .say for palm-generate-message('Who wrote the book "Dune"?'); ``` ``` # {candidates => [{author => 1, content => Frank Herbert wrote the book "Dune". It was first published in 1965 and is considered one of the greatest science fiction novels of all time. The book tells the story of Paul Atreides, a young man who is thrust into a war for control of the desert planet Arrakis. Dune has been adapted into a film, a television series, and a number of video games.}], messages => [{author => 0, content => Who wrote the book "Dune"?}]} ``` Show text embeddings: ``` my @vecs = palm-embed-text(["say something nice!", "shout something bad!", "wher is the best coffee made?"], format => 'values'); .say for @vecs; ``` ``` # [0.0011238843 -0.040586308 -0.013174802 0.015497498 0.04383781 0.012527679 0.017876161 0.031339817 -0.0042566974 -0.024129443 -0.023050068 -0.015625203 0.03501345 -0.006033779 -0.011984176 -0.033368077 -0.040653296 0.022117265 -0.02034076 -0.040752005 -0.12748374 0.029760985 0.00084632 -0.017502416 -0.03893842 -0.07151896 0.0609997 -0.0046266303 -0.044301335 -0.022592714 0.023920823 0.0020489343 -0.0048049283 -0.038431767 0.007275116 0.018562535 0.017131427 -0.00043720857 0.02810143 0.053296003 0.031831037 -0.067091785 0.015640317 -0.0036152988 -0.04691379 -0.044070054 -0.022364588 -0.0083763655 -0.0490714 -0.007302964 0.006516001 -0.004685413 0.03979989 -0.014196505 0.01065721 -0.0073698894 -0.036348466 -0.008763353 -0.01892632 -0.054501593 0.032021806 -0.007242739 0.0220439 -0.07687204 -0.0740849 0.01748987 -0.027381063 -0.015533608 -0.013165218 -0.04867313 0.041797243 0.017989235 -0.00982055 0.03691631 0.010164966 -0.03985747 0.024958102 0.015761184 0.02152081 -0.06986678 -0.012039569 0.00056548475 -0.030969337 -0.07435745 -0.028182292 0.012739926 0.042157806 0.023305222 -0.03230193 -0.0033747193 -0.061240233 0.021881713 0.009969781 -0.010255637 -0.0049942187 -0.034989387 0.020215971 -0.020086009 0.0010875552 0.017283859 ...] # [0.008541122 -0.024862545 5.7058678e-05 0.0038867046 0.067829944 0.021747978 -0.029083902 -0.004656434 -0.012782786 -0.018360043 -0.019952606 0.007747536 -0.0056520714 -0.038842484 0.0144888265 -0.028959233 -0.034373183 0.0086536445 0.0030540912 0.005582053 -0.123638585 0.04185863 0.009929637 0.017287828 -0.018644271 -0.08450658 -0.014902289 -0.05526195 -0.020689102 -0.0024103096 0.019860586 0.024158986 -0.05455204 -0.01493725 0.0006892038 0.00323405 -0.0006728824 -0.010576684 -0.014293131 0.038979508 0.01347389 -0.050580844 0.004814549 -0.031785876 -0.017129553 -0.013408159 -0.019374503 0.008474182 0.0013470884 -0.01079351 -0.011820318 0.002939847 0.019571697 0.030853825 0.013096097 -0.015389974 -0.017276747 -0.0005738943 -0.029613884 -0.035326067 0.002852012 0.016189976 0.025315559 -0.07327017 -0.039907347 0.03896169 -0.050800353 -0.039951827 0.0016103057 -0.06276334 0.03115886 0.011537878 -0.034277618 0.015627442 0.020582594 -0.040219635 0.011975396 0.037462063 0.06526648 -0.068473086 -0.014561573 0.005528434 -0.0057561444 -0.0419415 -0.007748433 0.012975432 0.01270717 0.046910107 -0.038431607 -0.0022757803 -0.08964604 0.020557715 0.017819826 0.0076504718 -0.053408835 0.012460911 -0.021491397 -0.02011912 -0.011796679 0.007281153 ...] # [-0.04053886 -0.028188298 0.0223612 0.04598037 0.018368412 -0.04011965 0.042926013 0.021050882 -0.0094422195 -0.01832212 0.019964134 -0.0013347232 0.04966835 0.048276108 -0.005766044 -0.02433299 -0.040598087 -0.065635845 0.02209697 0.06312037 -0.085269 -0.012106354 0.0056219148 0.0030168872 -0.07658486 -0.048572473 -0.04269039 0.026315054 -0.006883465 -0.010089017 0.009539455 -0.030142343 -0.058066234 -0.03262922 -0.0018920723 0.062120162 -0.008042096 0.04948106 -0.00028861413 0.026026316 0.04703804 -0.012234463 0.058435097 -0.05434934 -0.049611546 -0.020385403 -0.05354296 0.07173936 0.014864944 -0.016838027 -0.024500856 0.008486 -0.0027952811 0.016175343 0.019633992 -0.0010128785 -0.03879283 -0.0091371685 0.041809056 -0.024545915 -0.009020674 0.018044515 0.025408195 -0.07722929 -0.04280286 -0.0077904514 -0.0014599559 -0.045557976 -0.009131333 -0.038542382 0.0069833044 0.043738525 -0.011051313 -0.010426432 -0.05466805 0.013140538 0.0069446876 -0.035760716 0.04011649 -0.066007614 -0.035028048 -0.03821088 -0.031489357 -0.06864613 0.0075672227 -0.0032299925 0.007995906 0.0020973664 -0.02571021 0.070727535 -0.09410694 -0.011029921 -0.010794598 -0.022694781 -0.041388575 0.038010556 -0.006979773 -0.034256544 -0.015818557 -0.0064860974 ...] ``` --- ## Command Line Interface ### Maker suite access The package provides a Command Line Interface (CLI) script: ``` palm-prompt --help ``` ``` # Usage: # palm-prompt [<words> ...] [--path=<Str>] [-n[=UInt]] [--mt|--max-output-tokens[=UInt]] [-m|--model=<Str>] [-t|--temperature[=Real]] [-a|--auth-key=<Str>] [--timeout[=UInt]] [-f|--format=<Str>] [--method=<Str>] -- Command given as a sequence of words. # # --path=<Str> Path, one of 'generateText', 'generateMessage', 'embedText', or 'models'. [default: 'generateText'] # -n[=UInt] Number of completions or generations. [default: 1] # --mt|--max-output-tokens[=UInt] The maximum number of tokens to generate in the completion. [default: 100] # -m|--model=<Str> Model. [default: 'Whatever'] # -t|--temperature[=Real] Temperature. [default: 0.7] # -a|--auth-key=<Str> Authorization key (to use PaLM API.) [default: 'Whatever'] # --timeout[=UInt] Timeout. [default: 10] # -f|--format=<Str> Format of the result; one of "json", "hash", "values", or "Whatever". [default: 'values'] # --method=<Str> Method for the HTTP POST query; one of "tiny" or "curl". [default: 'tiny'] ``` **Remark:** When the authorization key argument "auth-key" is specified set to "Whatever" then `palm-prompt` attempts to use the env variable `PALM_API_KEY`. --- ## Mermaid diagram The following flowchart corresponds to the steps in the package function `palm-prompt`: ``` graph TD UI[/Some natural language text/] TO[/"PaLM<br/>Processed output"/] WR[[Web request]] PaLM{{PaLM}} PJ[Parse JSON] Q{Return<br>hash?} MSTC[Compose query] MURL[[Make URL]] TTC[Process] QAK{Auth key<br>supplied?} EAK[["Try to find<br>PALM_API_KEY<br>in %*ENV"]] QEAF{Auth key<br>found?} NAK[/Cannot find auth key/] UI --> QAK QAK --> |yes|MSTC QAK --> |no|EAK EAK --> QEAF MSTC --> TTC QEAF --> |no|NAK QEAF --> |yes|TTC TTC -.-> MURL -.-> WR -.-> TTC WR -.-> |URL|PaLM PaLM -.-> |JSON|WR TTC --> Q Q --> |yes|PJ Q --> |no|TO PJ --> TO ``` --- ## TODO * TODO Implement moderations. * DONE Comparison with "WWW::OpenAI", [AAp1]. * The comparison is done via workflows with "LLM::Functions", [AAp3] * DONE Hook-up finding textual answers implemented in "WWW::OpenAI", [AAp1]. * There is a dedicated package for this now -- see "ML::FindTextualAnswer", [AAp4]. --- ## References ### Articles [AA1] Anton Antonov, ["Workflows with LLM functions"](https://rakuforprediction.wordpress.com/2023/08/01/workflows-with-llm-functions/), (2023), [RakuForPredictions at WordPress](https://rakuforprediction.wordpress.com). [AA2] Anton Antonov, ["Number guessing games: PaLM vs ChatGPT"](https://rakuforprediction.wordpress.com/2023/08/06/number-guessing-games-palm-vs-chatgpt/) (2023), [RakuForPredictions at WordPress](https://rakuforprediction.wordpress.com). [ZG1] Zoubin Ghahramani, ["Introducing PaLM 2"](https://blog.google/technology/ai/google-palm-2-ai-large-language-model/), (2023), [Google Official Blog on AI](https://blog.google/technology/ai/). ### Packages, platforms [AAp1] Anton Antonov, [WWW::OpenAI Raku package](https://github.com/antononcube/Raku-WWW-OpenAI), (2023), [GitHub/antononcube](https://github.com/antononcube). [AAp2] Anton Antonov, [Lingua::Translation::DeepL Raku package](https://github.com/antononcube/Raku-Lingua-Translation-DeepL), (2022), [GitHub/antononcube](https://github.com/antononcube). [AAp3] Anton Antonov, [LLM::Functions Raku package](https://github.com/antononcube/Raku-LLM-Functions), (2023), [GitHub/antononcube](https://github.com/antononcube). [AAp4] Anton Antonov, [ML::FindTextualAnswer Raku package](https://github.com/antononcube/Raku-ML-FindTextualAnswer), (2023), [GitHub/antononcube](https://github.com/antononcube). [OAI1] OpenAI Platform, [OpenAI platform](https://platform.openai.com/).
## dist_zef-jforget-Arithmetic-PaperAndPencil.md # NAME Arithmetic::PaperAndPencil - simulating paper and pencil techniques for basic arithmetic operations # SYNOPSIS ``` use Arithmetic::PaperAndPencil; my Arithmetic::PaperAndPencil $paper-sheet .= new; my Arithmetic::PaperAndPencil::Number $x .= new(value => '355000000'); my Arithmetic::PaperAndPencil::Number $y .= new(value => '113'); $paper-sheet.division(dividend => $x, divisor => $y); my Str $html = $paper-sheet.html(lang => 'fr', silent => False, level => 3); 'division.html'.IO.spurt($html); $paper-sheet .= new; # emptying previous content my Arithmetic::PaperAndPencil::Number $dead .= new(value => 'DEAD', radix => 16); my Arithmetic::PaperAndPencil::Number $beef .= new(value => 'BEEF', radix => 16); $paper-sheet.addition($dead, $beef); $html = $paper-sheet.html(lang => 'fr', silent => False, level => 3); 'addition.html'.IO.spurt($html); ``` The first HTML file ends with ``` 355000000|113 0160 |--- 0470 |3141592 0180 | 0670 | 1050 | 0330| 104| ``` and the second one with ``` DEAD BEEF ----- 19D9C ``` # DESCRIPTION Arithmetic::PaperAndPencil is a module which allows simulating the paper and pencil techniques for basic arithmetic operations on integers: addition, subtraction, multiplication and division, but also square root extraction and conversion from a radix to another. # PATCHES WELCOME When rendering an operation as HTML, the module displays spoken French sentences. If you know the equivalent sentences in another language, you can contact me to add the other language to the distribution, or you can even send me a patch. Thank you in advance. # AUTHOR Jean Forget [[email protected]](mailto:[email protected]) # DEDICATION This module is dedicated to my primary school teachers, who taught me the basics of arithmetics, and even some advanced features, and to my secondary school math teachers, who taught me other advanced math concepts and features. # COPYRIGHT AND LICENSE Copyright 2023, 2024 Jean Forget This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-p6steve-CLI-AWS-EC2-Simple.md [![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) ### *PLEASE EXERCISE CAUTION USING AWSCLI SINCE IT WILL CREATE BILLABLE AWS SERVICES IN YOUR ACCOUNT AND MAY NOT TERMINATE THEM AUTOMATICALLY* # Raku CLI::AWS::EC2-Simple This module provide a simple abstraction of the AWS command line interface, aka [awscli](https://aws.amazon.com/cli/), for Amazon's EC2 compute web service. If you encounter a feature of EC2 you want that's not implemented by this module (and there are many), please consider sending a pull request. ## Getting Started * apt-get update && apt-get install awscli [macOS brew update && brew install awscli] * aws configure *[enter your config here]* (output format 'json') * zef install CLI::AWS::EC2-Simple * raws-ec2 *[enter your commands here]* ## Usage ``` ./raws-ec2 [--id=<Str>] [--nsu] [--eip] [-y] <cmd> <cmd> One of <list launch setup connect state stop start terminate nuke> --id=<Str> Running InstanceId of form 'i-0785d8bd98b5f458b' --nsu No setup (suppress launch from running setup) --eip Allocates (if needed) and Associates Elastic IP -y Silence confirmation <nuke> cmd only ``` Will make an (e.g.) `MyKeyPair1672164025.pem` from your credentials in your $\*HOME dir ## Config `launch` reads `aws-ec2-launch.yaml` which is preloaded with the standard AWS Canonical, Ubuntu, 22.04 LTS, amd64 jammy image build on 2022-12-01. Edit this yaml file to meet your needs... * cat .raws-config/aws-ec2-launch.yaml ``` instance: image: ami-0f540e9f488cfa27d # <== the standard, clean AWS Ubuntu #image: ami-0ebdbe39cf24185c1 # <== AWS Ubuntu plus raws-ec2 setup already applied (use --nsu flag) type: t2.micro # <== the basic, free tier eligible test machine #type: c6a.4xlarge # <== my choice of reasonably priced server class machine type: t2.micro storage: 30 # <== EBS size for launch security-group: name: MySG rules: - inbound: port: 22 cidr: 0.0.0.0/0 - inbound: port: 80 cidr: 0.0.0.0/0 - inbound: port: 443 cidr: 0.0.0.0/0 - inbound: port: 8080 cidr: 0.0.0.0/0 - inbound: port: 8888 cidr: 0.0.0.0/0 ``` ### *PLEASE REVIEW SECURITY GROUP RULES AND ADAPT TO YOUR NEEDS - SPECIFICALLY REMOVE THE PORT:22 RULE UNLESS YOU WANT ALL IPS TO HAVE ACCESS* ## Setup `setup` deploys docker, docker-compose, raku and zef to the launchee... * cat .raws-config/launch.pl ``` #!/usr/bin/perl `sudo apt-get update -y`; `sudo apt-get install rakudo -y`; `sudo git clone https://github.com/ugexe/zef.git`; `sudo raku -I./zef zef/bin/zef install ./zef --/test`; `sudo apt-get install docker -y`; `sudo apt-get install docker-compose -y`; ``` ## Wordpress Deploy & Control [This section will probably go into raku-CLI-WP-Simple] viz. [digital ocean howto](https://www.digitalocean.com/community/tutorials/how-to-install-wordpress-with-docker-compose#step-3-defining-services-with-docker-compose) * client script 'raku-wp --launch' ## NOTES * unassigned Elastic IPs are chargeable ($5 per month ish), may be better to run one free tier instance * rules about rules * will always open port 22 (SSH) inbound from this client IP * will re-use the existing named Security Group (or create if not present) * only inbound are supported for now * if you want to keep the name and change the rules, then delete via the aws console ### Copyright copyright(c) 2022 Henley Cloud Consulting Ltd.
## dist_github-Raku-Blin.md ## Project Blin – Toasting Reinvented Blin is a quality assurance tool for [Rakudo](https://github.com/rakudo/rakudo/) releases. Blin is based on [Whateverable](https://github.com/perl6/whateverable/). Blin was inspired by [Toaster](https://github.com/perl6-community-modules/perl6-Toaster). Here are some advantages: * Fetches archives from [whateverable](https://github.com/perl6/whateverable/wiki/Shareable#bot-usage-examples) instead of spending time to build rakudo * Installs modules in proper order to avoid testing the same module more than once * Deflaps modules that fail intermittently * Automatically bisects regressed modules * Avoids segfaults by producing no useful output instead of using DBIish ### Installation Install required packages: ``` sudo apt install zstd lrzip graphviz ``` Install dependencies: ``` zef install --deps-only . ``` Many modules require native dependencies. See [this page](https://github.com/perl6-community-modules/perl6-Toaster/wiki) for the list of packages to install. ### Running Currently it is supposed to run only on 64-bit linux systems. If you want to test one or more modules: ``` RAKULIB=lib bin/blin.p6 SomeModuleHere AnotherModuleHere ``` Here is a more practical example: ``` time RAKULIB=lib bin/blin.p6 --old=2018.06 --new=2018.09 Foo::Regressed Foo::Regressed::Very Foo::Dependencies::B-on-A ``` You can also test arbitrary scripts. The code can depend on modules, in which case they have to be listed on the command line (e.g. for a script depending on WWW you should list WWW module, dependencies of WWW will be resolved automatically). Using this ticket as an example: <https://github.com/rakudo/rakudo/issues/2779> Create file `foo.p6` with this content: ``` use WWW; my @stations; @stations = | jpost "https://www.perl6.org", :limit(42); ``` Then run Blin: ``` ./bin/blin.p6 --old=2018.12 --new=HEAD --custom-script=foo.p6 WWW ``` Then check out the output folder to see the results. Essentially, it is a local Bisectable. If you want to test the whole ecosystem: ``` time RAKULIB=lib bin/blin.p6 ``` Estimated time to test the whole ecosystem with 24 cores is ≈60 minutes. **⚠☠ SECURITY NOTE: [issues mentioned in Toaster still apply.](https://github.com/perl6-community-modules/perl6-Toaster#warning-dangerus-stuf-ahed) Do not run this for the whole ecosystem on non-throwaway installs. ☠⚠** ### Viewing See `output/overview` file for a basic overview of results. More details for specific modules can be found in `installed/` directory. Betters ways to view the data should come soon (hopefully). ### Docker For info about the Docker image, have a look at the [Readme file](docker/README.md) in the docker directory.
## dist_zef-raku-community-modules-GD-Raw.md [![Actions Status](https://github.com/raku-community-modules/GD-Raw/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/GD-Raw/actions) [![Actions Status](https://github.com/raku-community-modules/GD-Raw/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/GD-Raw/actions) # NAME GD::Raw - Low level language bindings to GD Graphics Library # SYNOPSIS ``` use GD::Raw; my $fh = fopen("my-image.png", "rb"); my $img = gdImageCreateFromPng($fh); LEAVE gdImageDestroy($_) with $img; say "Image resolution is ", gdImageSX($img), "x", gdImageSX($img); ``` # DESCRIPTION `GD::Raw` is a low level language bindings to LibGD. It does not attempt to provide you with an rakuish interface, but tries to stay as close to its `C` origin as possible. LibGD is large and this module far from covers it all. Feel free to add anything your missing and submit a pull request! # AUTHORS * Dagur Valberg Johannsson * Raku Community # COPYRIGHT AND LICENSE Copyright 2013 - 2018 Dagur Valberg Johannsson Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-CTILMES-GPGME.md # Raku GPGME - GNU Privacy Guard (GPG) Made Easy ## Introduction From the [GPGME Manual](https://gnupg.org/documentation/manuals/gpgme/index.html): ``` ‘GnuPG Made Easy’ (GPGME) is a C language library that allows to add support for cryptography to a program. It is designed to make access to public key crypto engines like GnuPG or GpgSM easier for applications. GPGME provides a high-level crypto API for encryption, decryption, signing, signature verification and key management. GPGME uses GnuPG and GpgSM as its backends to support OpenPGP and the Cryptographic Message Syntax (CMS). ``` So essentially, this is a Raku Module interfacing with a C library interfacing with GnuPG and GpgSM command line programs. Understanding how this module works will benefit from an understanding of the [Gnu Privacy Guard](https://gnupg.org/documentation/manuals/gnupg/) and [GnuPG Made Easy (GPGME)](https://gnupg.org/documentation/manuals/gpgme/). **Note, this is still a work in progress, more features may or may not be forthcoming!! Patches welcome!!** # Basic Usage ``` use GPGME; my $gpg = GPGME.new(:armor); # ASCII armor for key export $gpg.create-key('[email protected]'); # Add key to key ring my $joes-key = $gpg.get-key('[email protected]'); # Retrieve a key put $joes-key; # Stringify key summary put my $key = $gpg.export('[email protected]'); # Export from key ring $gpg.import($key); # Import key my $cipher = $gpg.encrypt('message', '[email protected]'); my $plain = $gpg.decrypt($cipher); $gpg.signers('[email protected]'); my $signed = $gpg.sign('My message'); ``` # Functionality ## Basic ``` use GPGME; put GPGME.version; put GPGME.dirinfo('gpg-name'); GPGME.set-locale('C'); ``` ## GPGME Object and Context The main [GPGME](doc/GPGME.md) object holds a `context` with various settings, and can be used to perform various functions. ``` use GPGME; my $gpg = GPGME.new; my $gpg = GPGME.new(:armor, :homedir</tmp/dir>); ``` See [GPGME](doc/GPGME.md) for more information. ## Results After performing an operation, the result of the operation can be retrieved from the context with the C method. As a convenience, most methods from the result objects are passed through to the result object. For example, after a key generation operation, the CGPGME::GenKeyResult object can be retrieved with the C method. One of the attributes of that object is the fingerprint of the generated key, which can be retrieved with its C method. ``` $gpg.create-key('[email protected]'); my $result = $gpg.result; my $fpr = $result.fpr; ``` This does the same thing, passing the I from the context to the result: ``` my $fpr = $gpg.fpr; ``` Of course, for key generation, the result object is returned from the I operation, so you can also just do: ``` my $fpr = $gpg.create-key('[email protected]').fpr; ``` You can additionally retrieve the result object immediately following the appropriate operation with these methods: ``` $gpg.genkey-result $gpg.import-result $gpg.sign-result $gpg.encrypt-result $gpg.decrypt-result $gpg.verify-result ``` These are sometimes needed when an operation performs two actions (e.g. decrypt and verify). These are only valid immediately following the appropriate operation, and all results must be used or copied prior to the next operation, when the results are no longer available. ## Engine Information ``` .put for GPGME.engine-info; GPGME.engine-info('openpgp', :homedir</tmp/dir>); ``` See [GPGME::EngineInfo](doc/GPGME/EngineInfo.md) for more information. ## Data Objects A lot of data has to be exchanged between the user and the crypto engine, like plaintext messages, ciphertext, signatures and information about the keys. The technical details about exchanging the data information are completely abstracted by GPGME. The user provides and receives the data via `GPGME::Data` objects, regardless of the communication protocol between GPGME and the crypto engine in use. In general the API will construct the appropriate `GPGME::Data` object for you. For input objects, you can provide one of these types: * `Blob` -- Actual data to use * `Str` -- Actual data to use * `IO::Path` -- Filename of file to use * `IO::Handle` -- File with a `native-descriptor` to read from For output objects, you can provide one of these types: * `Str` -- Filename of file to write to * `IO::Path` -- Filename to write to * `IO::Handle` -- File with a C to write to When an output object is omitted, a memory buffer will be used and returned. When a `GPGME::Data` object is returned, you can stringify it if and only if the data are `utf8` encoded or ascii (usually produced when the *:armor* option was specified during context creation). The object can also be treated as an `IO::Handle` and read from as usual. ## Key Management An important fact to remember is that in addition to providing mechanisms to manipulate keys, GPG also serves as a Key Store or 'Key Ring'. Keys can generally be referred to by patterns and fingerprints that map to actual keys stored in the key store. ## Key Generation GPGME Supports two different interfaces to Key Generation -- `create-key` and `genkey`. ``` $gpg.create-key('[email protected]'); my $key = $gpg.get-key('[email protected]'); $gpg.create-subkey($key); $gpg.adduid($key, '[email protected]'); $gpg.set-uid-flag($key, '[email protected]'); # Make new one primary $gpg.revuid($key, '[email protected]'); # Revoke a user ID ``` `genkey` takes a set of parameters, expressed either as a single string, or a set of named parameters: ``` $gpg.genkey(q:to/END/) Key-Type: default Name-Email: [email protected] END ``` or ``` $gpg.genkey(:Name-Email<[email protected]>); # Key-Type defaults to 'default' ``` See [GPG Key Generation](https://gnupg.org/documentation/manuals/gnupg/Unattended-GPG-key-generation.html) and [CSR and Certificate Creation](https://www.gnupg.org/documentation/manuals/gnupg/CSR-and-certificate-creation.html) for information on all the parameters. ## Listing Keys List keys in the key ring by specifying a list of patterns and optionally specifying the *:secret* option to retrieve secret keys. ``` $key = $gpg.get-key('[email protected]'); $key = $gpg.get-key($fpr, :secret); .put for $gpg.keylist('[email protected]', :secret); .put for $gpg.keylist(<alice harry bob>); ``` Individual attributes from the keys can be queried. See [GPGME::Key](doc/GPGME/Key.md) for more information. ## Deleting Keys ``` $gpg.delete-key($key, :secret, :force); ``` * *:secret* deletes secret keys * *:force* overrides a user confirmation, but is only available after version 1.8. ## Signing Keys Key signatures are a unique concept of the OpenPGP protocol. They can be used to certify the validity of a key and are used to create the Web-of-Trust (WoT). ``` $gpg.signers('[email protected]'); # select signers $gpg.keysign($key); # Default sign all user IDs $gpg.keysign($key, '[email protected]'); # Specify a user ID $gpg.keysign($key, :local); # Non exportable $gpg.keysign($key, '[email protected]', expires => $DateTime); ``` ## Exporting Keys ``` my $gpg = GPGME.new(:armor); # Use :armor to get ASCII export put $gpg.export('[email protected]'); # Stringify and print out $gpg.export('[email protected]', :out<outputfile>); # Export to filename $gpg.export('[email protected]', out => $*OUT); # Send to a file handle ``` ## Importing Keys ``` $gpg.import($someexportedkeydata); ``` Stores the [ImportResult](doc/GPGME/ImportResult.md). ## Encrypting a Plaintext ``` $cipher = $gpg.encrypt("my message", $key); # Encrypt for a key $cipher = $gpg.encrypt("my message", '[email protected]'); # Encrypt for a pattern $cipher = $gpg.encrypt("my message", '[email protected]', :sign); # Encrypt and sign ``` Stores the [EncryptResult](doc/GPGME/EncryptResult.md). If signed as well with the *:sign* option, [SignResult](doc/GPGME/SignResult.md) can be examined as well. ## Decrypting ``` $plain = $gpg.decrypt($cipher); $gpg.decrypt($cipher, out => 'filename'); $gpg.decrypt($cipher, out => $*OUT); $gpg.decrypt($cipher, :verify); ``` Stores the [DecryptResult](doc/GPGME/DecryptResult.md). If the signature was verified with the *:verify* option, the [VerifyResult](doc/GPGME/VerifyResult.md) is also available. ## Signing A signature can contain signatures by one or more keys. The set of keys used to create a signatures is contained in a context, and is applied to all following signing operations in this context (until the set is changed). They can be set either at `GPGME` creation with the *:signers* object, or with the `.signers` method later. ``` $gpg.signers('[email protected]'); my $signed = $gpg.sign('My message'); $gpg.sign($*IN, out => $*OUT); my $signature = $gpg.sign('My message', :detach); # Detached signature ``` The [SignResult](doc/GPGME/SignResult.md) will be available after signing. ## Verifying Signature ``` $message = $gpg.verify($signed); $gpg.verify('infile'.IO, :out<somefile>); put $gpg.verify($signature, $message).status; # Detached signature ``` The [VerifyResult](doc/GPGME/VerifyResult.md) will be available after verification. # Entropy Some `GPGME` actions (particularly key generation with very long keys) rely on the OS ability to generate a great deal of entropy. Things may appear to hang on entropy starved hosts. Tools like [haveged](https://www.issihosts.com/haveged/) can help the OS capture entropy. Even doing something simple like running `sudo dd if=/dev/sda of=/dev/zero` in the background can help speed things up. # INSTALL You must install `libgpgme` which usually has the right dependencies on GPG as well. * For debian or ubuntu: `apt install libgpgme11` * For alpine: `apk add gpgme` * For CentOS: `yum install gpgme` If you get locale errors on CentOS, you may need to run this: ``` yum install glibc-locale-source glibc-langpack-en localedef -i en_US -f UTF-8 en_US.UTF-8 ``` # License This work is subject to the Artistic License 2.0. See <LICENSE> for more information.
## dist_zef-lizmat-FINALIZER.md [![Actions Status](https://github.com/lizmat/FINALIZER/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/FINALIZER/actions) [![Actions Status](https://github.com/lizmat/FINALIZER/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/FINALIZER/actions) [![Actions Status](https://github.com/lizmat/FINALIZER/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/FINALIZER/actions) # NAME FINALIZER - dynamic finalizing for objects that need finalizing # SYNOPSIS ``` { use FINALIZER; # enable finalizing for this scope my $foo = Foo.new(...); # do stuff with $foo } # $foo has been finalized by exiting the above scope # different file / module use FINALIZER <role-only>; # only get the Finalizable role class Foo is Finalizable { method FINALIZE() { # do whatever we need to finalize, e.g. close db connection } } ``` # DESCRIPTION FINALIZER allows one to register finalization of objects in the scope that you want, rather than in the scope where objects were created (like one would otherwise do with `LEAVE` blocks or the `is leave` trait). # AS A MODULE DEVELOPER If you are a module developer, you need to use the Finalizable role in your code. Objects created with the `Finalizable` role applied may implement `FINALIZE` method to perform cleanup tasks after scope is completed. ``` use FINALIZER <role-only>; # only get the Finalizable role class Foo is Finalizable { method FINALIZE { # do whatever we need to finalize, e.g. close db connection } } ``` It is also possible to use the `FINALIZER` class from `FINALIZE` module in your code. In any logic that returns an object (typically the `new` method) that you want finalized at the moment the client decides, you register a code block to be executed when the object should be finalized. Typically that looks something like: ``` use FINALIZER <class-only>; # only get the FINALIZER class class Foo { has &!unregister; submethod TWEAK() { &!unregister = FINALIZER.register: { .finalize with self } } method finalize() { &!unregister(); # make sure there's no registration anymore # do whatever we need to finalize, e.g. close db connection } } ``` # AS A PROGRAM DEVELOPER Just use the module in the scope you want to have objects finalized for when that scope is left. If you don't use the module at all, all objects that have been registered for finalization, will be finalized when the program exits. If you want to have finalization happen for some scope, just add `use FINALIZER` in that scope. This could e.g. be used inside `start` blocks, to make sure all registered resources of a job run in another thread, are finalized: ``` await start { use FINALIZER; # open database handles, shared memory, whatever my $foo = Foo.new(...); } # all finalized after the job is finished ``` # RELATION TO DESTROY METHOD This module has **no** direct connection with the `.DESTROY` method functionality in Raku. However, if you, as a module developer, use this module, you do not need to supply a `DESTROY` method as well, as the finalization will have been done by the `FINALIZER` module. And as the finalizer code that you have registered, will keep the object otherwise alive until the program exits. It therefore makes sense to reset the variable in the code doing the finalization. For instance, in the above class Foo: ``` method finalize(\SELF: --> Nil) { # do stuff with SELF SELF = Nil } ``` The `\SELF:` is a way to get the invocant without it being decontainerized. This allows resetting the variable containing the object (by assigning `Nil` to it). # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/FINALIZER> . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2021, 2024, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-MARTIMM-Gnome-Gtk3.md ![gtk logo](https://martimm.github.io/gnome-gtk3/content-docs/images/gtk-perl6.png) # Gnome Gtk3 - Widget toolkit for graphical interfaces ![artistic-2.0](http://martimm.github.io/label/License-label.svg) Documentation at [this site](http://martimm.github.io/gnome-gtk3) has the ![GNU Free Documentation License](http://martimm.github.io/label/License-label-docs.svg). # Description The purpose of this project is to create an interface to the **GTK+** version 3 library. # History There is already a bit of history for this package. It started off building the `GTK::Glade` package which soon became too big. So a part was separated into `GTK::V3`. After some working with the library I felt that the class names were a bit too long and that the words `gtk` and `gdk` were repeated too many times in the class path. E.g. there was `GTK::V3::Gtk::GtkButton` and `GTK::V3::Gdk::GdkScreen` to name a few. So, finally it was split into several other packages named, `Gnome::N` for the native linkup on behalf of any other Gnome modules, `Gnome::Glib`, `Gnome::GObject`, `Gnome::Gdk3` and `Gnome::Gtk3` according to what is shown [on the developers page here](https://developer-old.gnome.org/references). The classes in these packages are now renamed into e.g. `Gnome::Gtk3::Button`, `Gnome::Gdk3::Screen`, `Gnome::GObject::Object` and `Gnome::Glib::List`. Note that all modules are now in `:api<1>` (as of 2024/4/5). This is done to prevent clashes with future distributions having the same class names only differing in this api string. So, add this string to your import statements and dependency modules of these classes in META6.json. Furthermore add this api string also when installing with zef. # Example This example does the same as the example from `GTK::Simple` to show you the differences between the implementations. What immediately is clear is that this example is somewhat longer. To sum up; ### Pros * The defaults of GTK+ are kept. * No fancy stuff like tapping into channels to run signal handlers. * Separation of callbacks from other code. Callbacks are always given to the routines as an object and a name. The name is the callback method which is defined in that object. Extra user data can be provided using named arguments to the callback setup. * The most common use of callback routines is for responding to events resulting from signals like button clicks, keyboard input and mouse events. To set a callback to handle events is by calling the `register-signal()` method. ### Cons * The code is larger because it is more low level, that is, closer to the GTK+ api. * Code is somewhat slower. The setup of the example shown next is about 0.05 sec slower. That isn't much seen in the light that a user interface is mostly set up and drawn once. * More worrying is the compile time of a sufficient large application. | | | | --- | --- | | **A screenshot of the example** | **A screenshot of Gtk Simple** | The code can be found down on the [Getting Started](https://martimm.github.io/gnome-gtk3/content-docs/tutorial/getting-started.html) page. ``` use v6.d; use Gnome::Gtk3::Main:api<1>; use Gnome::Gtk3::Window:api<1>; use Gnome::Gtk3::Grid:api<1>; use Gnome::Gtk3::Button:api<1>; # Instantiate main module for UI control my Gnome::Gtk3::Main $m .= new; # Class to handle signals class AppSignalHandlers { # Handle 'Hello World' button click method first-button-click ( :_widget($b1), :other-button($b2) ) { $b1.set-sensitive(False); $b2.set-sensitive(True); } # Handle 'Goodbye' button click method second-button-click ( ) { $m.gtk-main-quit; } # Handle window managers 'close app' button method exit-program ( ) { $m.gtk-main-quit; } } # Instantiate the event handler class and register signals my AppSignalHandlers $ash .= new; # Create buttons and disable the second one with my Gnome::Gtk3::Button $second .= new(:label('Goodbye')) { .set-sensitive(False); .register-signal( $ash, 'second-button-click', 'clicked'); } with my Gnome::Gtk3::Button $button .= new(:label('Hello World')) { .register-signal( $ash, 'first-button-click', 'clicked', :other-button($second) ); } # Create grid and add buttons to the grid with my Gnome::Gtk3::Grid $grid .= new { .attach( $button, 0, 0, 1, 1); .attach( $second, 0, 1, 1, 1); } # Create a top level window and set a title among other things with my Gnome::Gtk3::Window $top-window .= new { .set-title('Hello GTK!'); .set-border-width(20); # Create a grid and add it to the window .add($grid); .register-signal( $ash, 'exit-program', 'destroy'); # Show everything and activate all .show-all; } # Start the event loop $m.gtk-main; ``` ## Documentation * [🔗 Website](http://martimm.github.io/gnome-gtk3) * [ 🔗 Travis-ci run on master branch][travis-run] * [ 🔗 Appveyor run on master branch][appveyor-run] * [🔗 License document](http://www.perlfoundation.org/artistic_license_2_0) * [🔗 Release notes](https://martimm.github.io/gnome-gtk3//content-docs/about/release-notes-gtk3.html) * [🔗 Issues](https://github.com/MARTIMM/gnome-gtk3/issues) # TODO # Versions of involved software * Program is tested against the latest version of **Raku** on **rakudo** en **moarvm**. It is also necessary to have the (almost) newest compiler, because there are some code changes which made e.g. variable argument lists to the native subs possible. Older compilers cannot handle that (before summer 2019 I believe). Bugs come and go again. There was one the software had a problem with, which was ironed away just before Raku version 2020.10. Some steps to follow if you want to be at the top of things (but try the easy way first!). You need `git` to get software from the github site. 1. Make a directory to work in e.g. Raku 2. Go in that directory and run `git clone https://github.com/rakudo/rakudo.git` 3. Then go into the created rakudo directory and read README.md and INSTALL.md 4. Run `perl Configure.pl --gen-moar --gen-nqp --backends=moar` 5. Run `make test` 6. And run `make install` Subsequent updates of the Raku compiler and moarvm can be installed with 1. Go into the rakudo directory 2. Run `git pull` then repeat steps 4 to 6 from above Your path must then be set to the program directories where `$Rakudo` is your `rakudo` directory; `${PATH}:$Rakudo/install/bin:$Rakudo/install/share/perl6/site/bin` After this, you will notice that the `raku` command is available next to `perl6` so it is also a move forward in the renaming of perl6. The rakudo star installation must be removed, because otherwise there will be two raku compilers wanting to be the captain on your ship. Also all modules must be reinstalled of course and are installed at `$Rakudo/install/share/perl6/site`. * Gtk library used **Gtk 3.24**. The versioning of GTK+ is a bit different in that there is also a 3.90 and up. This is only meant as a prelude to version 4. So do not use those versions for the Raku packages. # Installation The version of Raku must be at least 2020.10, otherwise a few tests will not run! There are several dependencies from one package to the other because it was one package in the past. To get all packages, just install the *Gnome::Gtk3* package and the rest will be installed with it. ``` zef install 'Gnome::Gtk3:api<1>' ``` # Issues There are always some problems! If you find one, please help by filing an issue at [my github project](https://github.com/MARTIMM/gnome-gtk3/issues). # Attribution * The inventors of Raku, formerly known as Perl 6, of course and the writers of the documentation which helped me out every time again and again. * The builders of the GTK+ library and the documentation. * I would like to thank the developers of the `GTK::Simple` project because of the information I got while reading the code. Also because one of the files is copied unaltered for which I did not had to think about to get that right. The examples in that project are also useful to compare code with each other and to see what is or is not possible. * Other helpful modules for their insight and use. E.g. the Cairo package of Timo. * Documentation from [Wikibooks](https://en.wikibooks.org/wiki/GTK%2B_By_Example) and [Zetcode](http://zetcode.com/tutorials/gtktutorial/) * Helpful hands are there when issues are raised, after requesting for help or developers returning ideas tips, etcetera for documentation; Pixlmixr, Hkdtam, JackKuhan, Alain Barbason, Clifton Wood, Rob Ransbottom, Håkon Hægland (some names are Github names). * Icons used from [www.iconfinder.com](http://www.iconfinder.com), humility icons, Andy Fitzsimon, licensed GPL. * Prof Stewart Weiss, [web address](http://www.compsci.hunter.cuny.edu/~sweiss/index.php). On his site are numerous documents under which many about GTK+. I have used parts from these to explain many aspects of the user interface system. # Licenses * Raku code and pod documentation: Artistic License 2.0 * Use of Gnome reference documentation: GNU Free Documentation License Version 1.3 * Documentation from other external sources used in tutorials: Creative Commons Attribution-ShareAlike 4.0 International Public License # Author Name: **Marcel Timmerman** Github account name: **MARTIMM** # Copyright © 2019 - ∞ 😉. **Marcel Timmerman**
## dist_zef-raku-community-modules-Concurrent-Iterator.md [![Actions Status](https://github.com/raku-community-modules/Concurrent-Iterator/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Concurrent-Iterator/actions) [![Actions Status](https://github.com/raku-community-modules/Concurrent-Iterator/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Concurrent-Iterator/actions) [![Actions Status](https://github.com/raku-community-modules/Concurrent-Iterator/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Concurrent-Iterator/actions) # NAME Concurrent::Iterator - Enables safe concurrent consumption of Iterable values # SYNOPSIS ``` use Concurrent::Iterator; ``` # DESCRIPTION A standard Raku `Iterator` should only be consumed from one thread at a time. `Concurrent::Iterator` allows any `Iterable` to be iterated concurrently. -head1 SYNOPSIS ``` use Concurrent::Iterator; # Make a concurrent iterator over an infinite Range # of ascending integers. my $ids = concurrent-iterator(0..Inf); # Many concurrent workers can use it to obtain the IDs, # being confident of no duplication. do await for ^10 { start { say "I got $ids.pull-one()"; } } ``` # Overview The purpose of `Concurrent::Iterator` is to allow multiple threads to safely race to obtain values from a single iterable source of data. It: * Uses locking to ensure that only one thread can be pulling a value from the underlying iterator at a time * Will return `IterationEnd` to all future requests for values after it is returned by the underlying iterator (it is erroneous to call pull-one on a normal Iterator that has already produced `IterationEnd`) * Will rethrow any exception thrown by the underlying iterator on all future requests Together, these mean that it is possible to use a `Concurrent::Iterator` to have many workers compete for data items to process, and have them all terminate on end of sequence or exception. That might look something like this ``` my \to-process = concurrent-seq(@data); my @results = flat await do for ^4 { start (compute-stuff($_) for to-process) } ``` However, there's no reason to use `Concurrent:Iterator` for such a simple use case. It is far more simply expressed without this module as just: ``` my @results = @data.hyper.map(&compute-stuff); ``` Or, if you really wanted to enforce one-at-a-time and exactly 4 workers: ``` my @results = @data.hyper(:degree(4), :batch(1)).map(&compute-stuff); ``` # Concurrent::Iterator The `Concurrent::Iterator` class is constructed with a single positional argument, which must be of type `Iterable:D`: ``` my $ci = Concurrent::Iterator.new(1..Inf); ``` It implements the Raku standard `Iterator` interface. # Convenience subs There is a convenience sub to form a `Concurrent::Iterator`: ``` my $ci = concurrent-iterator(1..Inf); ``` There is also one to have it wrapped in a `Seq`: ``` my $cs = concurrent-seq(1..Inf); ``` Which literally just passes the result of calling `concurrent-iteratorr` to `Seq.new`. # AUTHOR Jonathan Worthington # COPYRIGHT AND LICENSE Copyright 2016 - 2024 Jonathan Worthington Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## period.md class Telemetry::Period Performance data over a period ```raku class Telemetry::Period is Telemetry { } ``` **Note:** This class is a Rakudo-specific feature and not standard Raku. ```raku # basic usage use Telemetry; my $t0 = Telemetry.new; # execute some code my $t1 = Telemetry.new; my $period = $t1 - $t0; # creates Telemetry::Period object say "Code took $period<wallclock> microseconds to execute"; ``` A `Telemetry::Period` object contains the difference between two [`Telemetry`](/type/Telemetry) objects. It is generally not created by calling .new, but it can be if needed. For all practical purposes, it is the same as the [`Telemetry`](/type/Telemetry) object, but the **meaning** of the values is different (and the values are generally much smaller, as they usually are the difference of two big values of the [`Telemetry`](/type/Telemetry) objects from which it was created).
## filename-extensions.md Filename extensions The extensions recommended for files with Raku content. | File contents | Extension | Historic extensions | | --- | --- | --- | | Raku script | .raku | .pl, .p6 | | Raku module | .rakumod | .pm, .pm6 | | Raku documentation | .rakudoc | .pm, pm6, pod, pod6 | | Test files in raku | .rakutest | .t | | Not Quite Perl (NQP) | .nqp | | Note that in most cases, the historic extensions will still work. # [Introduction](#Filename_extensions "go to top of document")[§](#Introduction "direct link") An extension is the part of the filename after the final '.'; if no '.' is present, there is no extension. Filename extensions can be used to associate behavior with the file content, such as opening a specialized reader or editor, running a program with the file content as input, etc. Even when it is not required by the operating system, filename extensions can provide a useful reminder about the contents of the file. # [History](#Filename_extensions "go to top of document")[§](#History "direct link") The Raku language was originally known as Perl 6, and this is reflected in the historic column above. Please use the current extensions whenever possible when generating new code.
## dist_zef-tbrowder-RakupodObject.md [![Actions Status](https://github.com/tbrowder/RakupodObject/actions/workflows/linux.yml/badge.svg)](https://github.com/tbrowder/RakupodObject/actions) [![Actions Status](https://github.com/tbrowder/RakupodObject/actions/workflows/macos.yml/badge.svg)](https://github.com/tbrowder/RakupodObject/actions) [![Actions Status](https://github.com/tbrowder/RakupodObject/actions/workflows/windows.yml/badge.svg)](https://github.com/tbrowder/RakupodObject/actions) # NAME **RakupodObject** - An obsolete attempt to provide a routine to extract the '$=pod' object from an external Rakupod source (a file or a string) **Please use Pod::Loader instead.** # 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.
## our.md our Combined from primary sources listed below. # [In Variables](#___top "go to top of document")[§](#(Variables)_declarator_our "direct link") See primary documentation [in context](/language/variables#The_our_declarator) for **The our declarator**. `our` variables are created in the scope of the surrounding package. They also create an alias in the lexical scope, therefore they can be used like `my` variables as well. ```raku module M { our $Var; # $Var available here } # Available as $M::Var here. ``` In order to create more than one variable with package scope, at the same time, surround the variables with parentheses: ```raku our ( $foo, $bar ); ``` see also [the section on declaring a list of variables with lexical or package scope](/language/variables#index-entry-declaring_a_list_of_variables).
## dist_zef-jonathanstowe-Manifesto.md # Manifesto Make a supply of the results of Promises [![CI](https://github.com/jonathanstowe/Manifesto/actions/workflows/main.yml/badge.svg)](https://github.com/jonathanstowe/Manifesto/actions/workflows/main.yml) ## Synopsis A different version of the old 'sleep sort' ``` use Manifesto; my $manifesto = Manifesto.new; for (^10).pick(*).map( -> $i { Promise.in($i + 0.5).then({ $i })}) -> $p { $manifesto.add-promise($p); } my $channel = Channel.new; react { whenever $manifesto -> $v { $channel.send: $v; } whenever $manifesto.empty { $channel.close; done; } } say $channel.list; ``` ## Description This manages a collection of Promise objects and provides a Supply of the result of the kept Promises. This is useful to aggregate a number of Promises to a single stream of results, which may then be used in, a *react* or *supply* block or otherwise tapped. ## Installation Assuming you have a working installation of Rakudo installed with *zef* you should be able to do either: ``` zef install Manifesto # or from a local checkout zef install . ``` Other equally capable installers may become available in the future. ## Support This is so simple I'm not sure there is much scope for many bugs, but if you have any questions, suggestions, patches or whatever please send them via [GitHub](https://github.com/jonathanstowe/Manifesto/issues) ## Copyright and Licence © Jonathan Stowe 2016 - 2021 This is free software, the terms are described in the <LICENCE> file in this repository.
## dist_github-Atrox-Haikunator.md # Haikunator for Perl 6 [![Build Status](https://img.shields.io/travis/Atrox/haikunatorperl.svg?style=flat-square)](https://travis-ci.org/Atrox/haikunatorperl) Generate Heroku-like random names to use in your **perl 6** applications. ## Installation ``` panda install Haikunator ``` or in your META.info: ``` "depends" : [ "Haikunator" ], ``` ## Usage Haikunator is pretty simple. ``` use Haikunator; # default usage haikunate() # => "wispy-dust-1337" # custom length (default=4) haikunate(:tokenLength(6)) # => "patient-king-887265" # use hex instead of numbers haikunate(:tokenHex(True)) # => "purple-breeze-98e1" # use custom chars instead of numbers/hex haikunate(:tokenChars("HAIKUNATE")) # => "summer-atom-IHEA" # don't include a token haikunate(:tokenLength(0))) # => "cold-wildflower" # use a different delimiter haikunate(:delimiter("."))) # => "restless.sea.7976" # no token, space delimiter haikunate(:tokenLength(0)), :delimiter(" ")) # => "delicate haze" # no token, empty delimiter haikunate(:tokenLength(0)), :delimiter("")) # => "billowingleaf" ``` ## Options The following options are available: ``` haikunate( :delimiter("-"), :tokenLength(4), :tokenHex(False), :tokenChars("0123456789") ) ``` *If `tokenHex` is true, it overrides any tokens specified in `tokenChars`* ## Contributing Everyone is encouraged to help improve this project. Here are a few ways you can help: * [Report bugs](https://github.com/atrox/haikunatorperl/issues) * Fix bugs and [submit pull requests](https://github.com/atrox/haikunatorperl/pulls) * Write, clarify, or fix documentation * Suggest or add new features ## Other Languages Haikunator is also available in other languages. Check them out: * Node: <https://github.com/Atrox/haikunatorjs> * .NET: <https://github.com/Atrox/haikunator.net> * Python: <https://github.com/Atrox/haikunatorpy> * PHP: <https://github.com/Atrox/haikunatorphp> * Java: <https://github.com/Atrox/haikunatorjava> * Go: <https://github.com/Atrox/haikunatorgo> * Dart: <https://github.com/Atrox/haikunatordart> * Ruby: <https://github.com/usmanbashir/haikunator> * Rust: <https://github.com/nishanths/rust-haikunator>
## dist_cpan-ANDINUS-antlia.md ``` ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ANTLIA Antlia is a text based Rock paper scissors game Andinus ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Table of Contents ───────────────── Demo Installation Documentation News ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Website Source GitHub (mirror) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Demo ════ This was recorded with `asciinema'. [https://asciinema.org/a/410736.png] ⁃ Antlia v0.1.0: [https://asciinema.org/a/410736.png] Installation ════════════ Antlia is released to CPAN, you can get it from there or install it from source. In any case, `zef' is required to install the distribution. You can run Antlia without `zef'. Just run `raku -Ilib bin/antlia' from within the source directory. Release ─────── 1. Run `zef install antlia'. Antlia should be installed, try running `antlia --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/antlia │ cd antlia │ │ # Install octans. │ zef install . └──── [PGP Key] Documentation ═════════════ Implementation ────────────── Just enter the player names & it'll print each throw along with scores. Press enter to play another round. Options ─────── players ╌╌╌╌╌╌╌ Number of players. Default is 2, should be an integer equal to or greater than 2. News ════ v0.1.1 - 2021-05-01 ─────────────────── ⁃ Added support for more than 2 players. ⁃ Prints a scorecard after the last round. v0.1.0 - 2021-04-29 ─────────────────── Initial Implementation ```
## compilation.md CompUnits and where to find them How and when Raku modules are compiled, where they are stored, and how to access them in compiled form. # [Overview](#CompUnits_and_where_to_find_them "go to top of document")[§](#Overview "direct link") Programs in Raku, as a member of the Perl language family, tend at the top level to be more at the interpreted end of the interpreted-compiled spectrum. In this tutorial, an 'interpreted' program means that the source code, namely the human-readable text such as `say 'hello world';`, is immediately processed by the `Raku` program into code that can be executed by the computer, with any intermediate stages being stored in memory. A compiled program, by contrast, is one where the human readable source is first processed into machine-executable code and some form of this code is stored 'on disk'. In order to execute the program, the machine-readable version is loaded into memory and then run by the computer. Both compiled and interpreted forms have advantages. Briefly, interpreted programs can be 'whipped up' quickly and the source changed quickly. Compiled programs can be complex and take a significant time to pre-process into machine-readable code, but then running them is much faster for a user, who only 'sees' the loading and running time, not the compilation time. `Raku` has both paradigms. At the **top level** a Raku program is interpreted, but code that is separated out into a Module will be compiled and the preprocessed version is then loaded when necessary. In practice, Modules that have been written by the community will only need to be precompiled once by a user when they are 'installed', for example by a Module manager such as `zef`. Then they can be `use`d by a developer in her own program. The effect is to make `Raku` top level programs run quickly. One of the great strengths of the `Perl` family of languages was the ability to integrate a whole ecosystem of modules written by competent programmers into a small program. This strength was widely copied and is now the norm for all languages. `Raku` takes integration even further, making it relatively easy for `Raku` programs to incorporate system libraries written in other languages into `Raku` programs, see [Native Call](/language/nativecall). The experience from `Perl` and other languages is that the distributive nature of Modules generate several practical difficulties: * a popular module may go through several iterations as the API gets improved, without a guarantee that there is backward compatibility. So, if a program relies on some specific function or return, then there has to be a way to specify the [`Version`](/type/Version). * a module may have been written by Bob, a very competent programmer, who moves on in life, leaving the module unmaintained, so Alice takes over. This means that the same module, with the same name, and the same general API may have two versions in the wild. Alternatively, two developers (e.g., Alice and Bob) who initially cooperated on a module, then part company about its development. Consequently, it sometimes is necessary for there to be a way to define the **Auth** of the module. * a module may be enhanced over time and the maintainer keeps two versions up to date, but with different APIs. So it is may be necessary to define the **API** required. * when developing a new program a developer may want to have the modules written by both Alice and Bob installed locally. So it is not possible simply to have only one version of a module with a single name installed. `Raku` enables all of these possibilities, allowing for multiple versions, multiple authorities, and multiple APIs to be present, installed, and available locally. The way classes and modules can be accessed with specific attributes is explained [elsewhere](/language/typesystem#Versioning,_authorship,_and_API_version.). This tutorial is about how `Raku` handles these possibilities. # [Introduction](#CompUnits_and_where_to_find_them "go to top of document")[§](#Introduction "direct link") Before considering the `Raku` framework, let's have a look at how languages like `Perl` or `Python` handle module installation and loading. 「text」 without highlighting ``` ``` ACME::Foo::Bar -> ACME/Foo/Bar.pm os.path -> os/path.py ``` ``` In those languages, module names have a 1:1 relation with filesystem paths. We simply replace the double colons or periods with slashes and add a `.pm` or `.py`. Note that these are relative paths. Both `Python` and `Perl` use a list of include paths, to complete these paths. In `Perl` they are available in the global `@INC` array. 「text」 without highlighting ``` ``` @INC /usr/lib/perl5/site_perl/5.22.1/x86_64-linux-thread-multi /usr/lib/perl5/site_perl/5.22.1/ /usr/lib/perl5/vendor_perl/5.22.1/x86_64-linux-thread-multi /usr/lib/perl5/vendor_perl/5.22.1/ /usr/lib/perl5/5.22.1/x86_64-linux-thread-multi /usr/lib/perl5/5.22.1/ ``` ``` Each of these include directories is checked for whether it contains a relative path determined from the module name. If the shoe fits, the file is loaded. Of course that's a bit of a simplified version. Both languages support caching compiled versions of modules. So instead of just the `.pm` file `Perl` first looks for a `.pmc` file. And `Python` first looks for `.pyc` files. Module installation in both cases means mostly copying files into locations determined by the same simple mapping. The system is easy to explain, easy to understand, simple and robust. ## [Why change?](#CompUnits_and_where_to_find_them "go to top of document")[§](#Why_change? "direct link") Why would `Raku` need another framework? The reason is there are features that those languages lack, namely: * Unicode module names * Modules published under the same names by different authors * Having multiple versions of a module installed The set of 26 Latin characters is too restrictive for virtually all real modern languages, including English, which have diacritics for many commonly-used words. With a 1:1 relation between module names and filesystem paths, you enter a world of pain once you try to support Unicode on multiple platforms and filesystems. Then there's sharing module names between multiple authors. This one may or may not work out well in practice. I can imagine using it for example for publishing a module with some fix until the original author includes the fix in the "official" version. Finally there's multiple versions. Usually people who need certain versions of modules reach for local::lib or containers or some home grown workarounds. They all have their own disadvantages. None of them would be necessary if applications could just say, hey I need good old, trusty version 2.9 or maybe a bug fix release of that branch. If you had any hopes of continuing using the simple name mapping solution, you probably gave up at the versioning requirement. Because, how would you find version 3.2 of a module when looking for a 2.9 or higher? Popular ideas included collecting information about installed modules in JSON files but when those turned out to be toe-nail growing slow, text files were replace by putting the metadata into SQLite databases. However, these ideas can be easily shot down by introducing another requirement: distribution packages. Packages for Linux distributions are mostly just archives containing some files plus some metadata. Ideally the process of installing such a package means just unpacking the files and updating the central package database. Uninstalling means deleting the files installed this way and again updating the package database. Changing existing files on install and uninstall makes packagers' lives much harder, so we really want to avoid that. Also the names of the installed files may not depend on what was previously installed. We must know at the time of packaging what the names are going to be. ## [Long names](#CompUnits_and_where_to_find_them "go to top of document")[§](#Long_names "direct link") 「text」 without highlighting ``` ``` Foo::Bar:auth<cpan:nine>:ver<0.3>:api<1> ``` ``` Step 0 in getting us back out of this mess is to define a long name. A full module name in `Raku` consists of the short-name, auth, version and API At the same time, the thing you install is usually not a single module but a distribution which probably contains one or more modules. Distribution names work just the same way as module names. Indeed, distributions often will just be called after their main module. An important property of distributions is that they are immutable. `Foo:auth<cpan:nine>:ver<0.3>:api<1>` will always be the name for exactly the same code. ## [$\*REPO](#CompUnits_and_where_to_find_them "go to top of document")[§](#$*REPO "direct link") In `Perl` and `Python` you deal with include paths pointing to filesystem directories. In `Raku` we call such directories "repositories" and each of these repositories is governed by an object that does the [`CompUnit::Repository`](/type/CompUnit/Repository) role. Instead of an **`@INC`** array, there's the `$*REPO` variable. It contains a single repository object. This object has a **next-repo** attribute that may contain another repository. In other words: repositories are managed as a *linked list*. The important difference to the traditional array is, that when going through the list, each object has a say in whether to pass along a request to the next-repo or not. `Raku` sets up a standard set of repositories, "core", "vendor", and "site". In addition, there is a "home" repository for the current user. Repositories must implement the `need` method. A `use` or `require` statement in `Raku` code is basically translated to a call to **`$*REPO`**'s `need` method. This method may in turn delegate the request to the next-repo. ```raku role CompUnit::Repository { has CompUnit::Repository $.next-repo is rw; method need(CompUnit::DependencySpecification $spec, CompUnit::PrecompilationRepository $precomp, CompUnit::Store :@precomp-stores --> CompUnit:D ) { ... } method loaded( --> Iterable ) { ... } method id( --> Str ) { ... } } ``` ## [Repositories](#CompUnits_and_where_to_find_them "go to top of document")[§](#Repositories "direct link") Rakudo comes with several classes that can be used for repositories. The most important ones are [`CompUnit::Repository::FileSystem`](/type/CompUnit/Repository/FileSystem) and [`CompUnit::Repository::Installation`](/type/CompUnit/Repository/Installation). The FileSystem repo is meant to be used during module development and actually works just like `Perl` when looking for a module. It doesn't support versions or `auth`s and simply maps the short-name to a filesystem path. The Installation repository is where the real smarts are. When requesting a module, you will usually either do it via its exact long name, or you say something along the lines of "give me a module that matches this filter." Such a filter is given by way of a `CompUnit::DependencySpecification` object which has fields for * short-name, * auth-matcher, * version-matcher and * api-matcher. When looking through candidates, the Installation repository will smartmatch a module's long name against this DependencySpecification or rather the individual fields against the individual matchers. Thus a matcher may be some concrete value, a version range, or even a regex (though an arbitrary regex, such as `.*`, would not produce a useful result, but something like `3.20.1+` will only find candidates higher than 3.20.1). Loading the metadata of all installed distributions would be prohibitively slow. The current implementation of the `Raku` framework uses the filesystem as a kind of database. However, another implementation may use another strategy. The following description shows how one implementation works and is included here to illustrate what is happening. We store not only a distribution's files but also create indices for speeding up lookups. One of these indices comes in the form of directories named after the short-name of installed modules. However most of the filesystems in common use today cannot handle Unicode names, so we cannot just use module names directly. This is where the now infamous SHA-1 hashes enter the game. The directory names are the ASCII encoded SHA-1 hashes of the UTF-8 encoded module short-names. In these directories we find one file per distribution that contains a module with a matching short name. These files again contain the ID of the dist and the other fields that make up the long name: auth, version, and api. So by reading these files we have a usually short list of auth-version-api triplets which we can match against our DependencySpecification. We end up with the winning distribution's ID, which we use to look up the metadata, stored in a JSON encoded file. This metadata contains the name of the file in the sources/ directory containing the requested module's code. This is what we can load. Finding names for source files is again a bit tricky, as there's still the Unicode issue and in addition the same relative file names may be used by different installed distributions (think versions). So for now at least, we use SHA-1 hashes of the long-names. ## [Resources](#CompUnits_and_where_to_find_them "go to top of document")[§](#Resources "direct link") 「text」 without highlighting ``` ``` %?RESOURCES %?RESOURCES<libraries/p5helper> %?RESOURCES<icons/foo.png> %?RESOURCES<schema.sql> Foo |___ lib | |____ Foo.rakumod | |___ resources |___ schema.sql | |___ libraries |____ p5helper | |___ |___ icons |___ foo.png ``` ``` It's not only source files that are stored and found this way. Distributions may also contain arbitrary resource files. These could be images, language files or shared libraries that are compiled on installation. They can be accessed from within the module through the `%?RESOURCES` hash. As long as you stick to the standard layout conventions for distributions, this even works during development without installing anything. A nice result of this architecture is that it's fairly easy to create special purpose repositories. ## [Dependencies](#CompUnits_and_where_to_find_them "go to top of document")[§](#Dependencies "direct link") Luckily precompilation at least works quite well in most cases. Yet it comes with its own set of challenges. Loading a single module is easy. The fun starts when a module has dependencies and those dependencies have again dependencies of their own. When loading a precompiled file in `Raku` we need to load the precompiled files of all its dependencies, too. And those dependencies **must** be precompiled, we cannot load them from source files. Even worse, the precomp files of the dependencies **must** be exactly the same files we used for precompiling our module in the first place. To top it off, precompiled files work only with the exact `Raku` binary, that was used for compilation. All of that would still be quite manageable if it weren't for an additional requirement: as a user you expect a new version of a module you just installed to be actually used, don't you? In other words: if you upgrade a dependency of a precompiled module, we have to detect this and precompile the module again with the new dependency. ## [Precomp stores](#CompUnits_and_where_to_find_them "go to top of document")[§](#Precomp_stores "direct link") Now remember that while we have a standard repository chain, the user may prepend additional repositories by way of `-I` on the command line or "use lib" in the code. These repositories may contain the dependencies of precompiled modules. Our first solution to this riddle was that each repository gets its own precomp store where precompiled files are stored. We only ever load precomp files from the precomp store of the very first repository in the chain because this is the only repository that has direct or at least indirect access to all the candidates. If this repository is a FileSystem repository, we create a precomp store in a `.precomp` directory. While being the safe option, this has the consequence that whenever you use a new repository, we will start out without access to precompiled files. Instead, we will precompile the modules used when they are first loaded. ## [Credit](#CompUnits_and_where_to_find_them "go to top of document")[§](#Credit "direct link") This tutorial is based on a `niner` [talk](http://niner.name/talks/A%20look%20behind%20the%20curtains%20-%20module%20loading%20in%20Perl%206/).
## dist_cpan-ROBERTLE-CucumisSextus.md # Cucumis Sextus ... a Cucumber-like Behavior-Driven Development (BDD) Test Framework for the Raku language ## State This is still in development, but already works for most basic cases. There are bound to be many bugs, please let me know how you get along. ### Missing Features * Harness improvements to allow parallel execution * TAP integration * Different types of reporting * Neater printing of features/scenarios/steps as they are being executed There is also a [ToDo List](TODO.md), and there are a lot of `XXX` fixmes in the code. ## Usage This is trying to be faithful and compatible to the "consensus" Cucumber implementation, which also means that most of this documentation applies and will also explain background and theory better than I possibly could: <https://github.com/cucumber/cucumber/wiki/A-Table-Of-Content> Please let me know if there are any surprising discrepancies. ### Basic Feature Files By default, cucumis will search for feature files under `features/*.feature`, the syntax of these is the same as in other cumumber implementations. Currently only basic scenarios are supported, no tables or templates. An example: ``` Feature: Basic Calculator Functions In order to check I've written the Calculator class correctly As a developer I want to check some basic operations So that I can have confidence in my Calculator class. Scenario: First Key Press on the Display Given a new Calculator object And having pressed 1 Then the display should show 1 ``` ### Step Definitions Cucumis will load all .pm6/.rakumod files under 'step\_definitions' in the same directory that holds the feature file in question, e.g. "features/step\_definitions/StepDefs.rakumod": ``` unit module StepDefs; use CucumisSextus::Glue; Given /'a new Calculator object'/, sub () { # implement! }; Step /'having pressed' \s* (\d+)/, sub ($num) { # implement! }; ``` Step definition modules are using semi-keywords from the CucumisSextus::Glue module and a regular expression to define step definitions. The "Step" keywords matches any type/verb in the scenario steps, and serves as a sort of wildcard. When cucumis executes a feature file, it will find the appropriate step definition for each step, and execute it. If there is no step definition or there is a problem with it, it will report an error. Note that the step definitions can have arguments that are taken from captures within the regular expression, as in the "having pressed example above. You can even use non-capturing groups in the regex and slurpy arguments (quite cool!): ``` Step /'having pressed' \s+ (\S+) [\s+ 'and' \s+ (\S+)]*/, sub (+@btns) { for @btns -> $b { # implement! } } ``` Within your glue code, you can use any exception (except X::CucumisSextus::FeatureExecFailure, which is to signal problems when trying to run the step, not *within* the step) to signal a failure. The next steps of the scenario will be skipped, but the remaining scenarios of the feature will be executed, as will be other features. ``` Then /'the display should be off'/, sub () { die "display should be off, but isn't"; } ``` ### Execution In order to execute the tests described in a feature file, the "cucumis6" tool can be used: ``` cucumis6 features ``` Cucumis will execute your features, producing some more output, and then report the results: ``` 14 scenarios executed, 4 skipped, 12 succeeded, 2 failed ``` The return code form the command will only be 0 if there are no problems executing cucumis, and if there are no failed scenarios. ### Tags You can tag your features and scenarios like this: ``` @calc @basic Feature: Basic Calculator Functions In order to check I've written the Calculator class correctly As a developer I want to check some basic operations So that I can have confidence in my Calculator class. @positive Scenario: First Key Press on the Display Given a new Calculator object And having pressed 1 Then the display should show 1 ``` And then select only certain features and scenarios (the latter inherit all the tags from the corresponding feature as well as have their own tags) when executing cucumis: ``` cucumis6 --tags=@calc ``` You can negate the matches with a '~', and OR them together with commas: ``` cucumis6 --tags=@calc,@print cucumis6 --tags=~@positive ``` And you can AND them together by repeatedly specifying --tags: ``` cucumis6 --tags=@calc --tags@basic ``` ### Background Scenarios You can define "background" scenarios: ``` Feature: Basic Calculator Functions In order to check I've written the Calculator class correctly As a developer I want to check some basic operations So that I can have confidence in my Calculator class. Background: Unboxing a new Calculator Given a freshly unboxed Calculator And having it switched on Scenario: First Key Press on the Display Given a new Calculator object And having pressed 1 Then the display should show 1 Scenario: Second Key Press on the Display Given a new Calculator object And having pressed 1 And having pressed 2 Then the display should show 12 ``` These background scenarios will get executed before each of the other scenarios of the feature. There can only be one background scenario and it needs to be the first one in the feature. ### Tables Your steps can contain tabular data: ``` Scenario: Separation of calculations Given a new Calculator object And having successfully performed the following calculations | first | operator | second | result | | 0.5 | + | 0.1 | 0.6 | | 0.01 | / | 0.01 | 1 | | 10 | * | 1 | 10 | And having pressed 3 Then the display should show 3 ``` Your step definition code will get the table passed in as a array of hashes, in the final parameter after the captures. The keys come from the first line of the table in your feature file, and you get one entry per following row: ``` Step /'having successfully performed the following calculations'/, sub (@table) { say @table.perl; } ``` would yield: ``` [{:first("0.5"), :operator("+"), :result("0.6"), :second("0.1")}, {:first("0.01"), :operator("/"), :result("1"), :second("0.01")}, {:first("10"), :operator("*"), :result("10"), :second("1")}] ``` ### Multiline Data In a way similar to tables, you can add multiline verbatim data to your step definitions by starting and ending such a section with three quotes: ``` Feature: Basic Calculator Functions In order to check I've written the Calculator class correctly As a developer I want to check some basic operations So that I can have confidence in my Calculator class. Scenario: Ticker Tape Given a new Calculator object And having entered the following sequence """ 1 + 2 + 3 + 4 + 5 + 6 - 100 * 13 \=\=\= + 2 = """ Then the display should show -1025 ``` Note that while the indentation of the three quotes themselves, like any other line in a feature file, is not relevant, that indentation is removed from each line in the multiline data. This also means that your indentation needs to be somewhat conistent or cucumis will fail to do so. The multiline data is passed to your step definition as a single argument after any captures, just like with tables. Note that you can only use multiline data or tables in a step, not both. ### Hooks You can create "before" and "after" hooks in your glue code, these will be executed before and after each scenario respectively. Before hooks will be executed in the order they are registered, and after hooks in reverse order. Note however that registration order is unpredicatble across multiple glue code modules. These hooks get executed for *any* scenario, so you typically want to inspect the feature and scenario passed in before doing anything: ``` Before sub ($feature, $scenario) { if $feature.tags.first(* ~~ 'hooked') { # implement! } } After sub ($feature, $scenario) { # implement! } ``` ### Outlines and Examples You can write a single scenario and execute it multiple times for different sets of input and output values using outlines and examples: ``` Scenario Outline: Basic arithmetic Given a new Calculator object And having keyed <first> And having keyed <operator> And having keyed <second> And having pressed = Then the display should show <result> Examples: | first | operator | second | result | | 5.0 | + | 5.0 | 10 | | 6 | / | 3 | 2 | | 10 | * | 7.550 | 75.5 | | 3 | - | 10 | -7 | ``` Note that the glue code regular expression has to match the substituted value, not the original one from the step text. ### Other Languages If you want to write your feature files in your native language rather than in english, you can certianly do that by putting a language directive into the first line of your feature file: ``` #language: hi रूप लेख: मूलभूत गणक कार्य जाँच करने के लिए मैंने गणक वर्ग को सही ढंग से लिखा है एक विकासक के रूप में मैं कुछ बुनियादी कार्यों की जांच करना चाहता हूं ताकि मेरे गणक वर्ग में मुझे भरोसा हो। परिदृश्य: प्रदर्शन पर प्रथम कुंजी दबाएं पूर्वानुमान एक नई गणक वस्तु और 1 दबाया हुआ अतः प्रदर्शन 1 दिखाना चाहिए ``` And then write the appropriate step definition code: ``` Then /'प्रदर्शन' \s+ (\d+) \s+ 'दिखाना चाहिए'/, sub ($num) { # XXX implement } ``` Note that you could even use Hindi number literals like १ instead of the arabic ones in the example above, the \d does detect them correctly and $num.Int will convert to a number as well! This should even work for right-to-left languages, but of course you get the usual problems with shells, editors and the like: ``` #language: fa ویژگی: عملیات ساده ماشین حساب جهت ارزیابی اینکه کلاس ماشین حساب را به درستی نوشته ام به عنوان یک برنامه نویس چند عملیات ساده ریاضی را ارزیابی می کنم تا از کلاس ماشین حسابم اطمینان حاصل کنم سناریو: اولین دکمه فشرده شده در صفحه نمایش با فرض یک شی جدید ماشین حساب و فشرده شدن ۱۲۳ آنگاه صفحه نمایش باید ۱۲۳ را نشان بدهد ``` ## License CucumisSextus is licensed under the [Artistic License 2.0](https://opensource.org/licenses/Artistic-2.0). ## Feedback and Contact Please let me know what you think: Robert Lemmen [[email protected]](mailto:[email protected])
## dist_zef-jforget-Date-Calendar-Bahai.md # NAME Date::Calendar::Bahai - Conversions from / to the Baháʼí calendar # SYNOPSIS ``` use Date::Calendar::Bahai; my Date $dt-greg; my Date::Calendar::Bahai $dt-bahai; $dt-greg .= new(2021, 5, 17); $dt-bahai .= new-from-date($dt-greg); say $dt-bahai; # --> 0178-04-01 say $dt-bahai.strftime("%A %d %B %Y"); # --> Kamál 1 ‘Aẓamat 178 ``` Converting a Bahai date (e.g. 19 Jamál 178) into Gregorian ``` use Date::Calendar::Bahai; my Date::Calendar::Bahai $dt-bahai; my Date $dt-greg; $dt-bahai .= new(year => 178, month => 3, day => 19); $dt-greg = $dt-bahai.to-date; say $dt-greg; # --> 2021-05-16 ``` # DESCRIPTION Date::Calendar::Bahai is a class representing dates in the Baháʼí calendar. It allows you to convert a Baháʼí date into Gregorian or into other implemented calendars, and it allows you to convert dates from Gregorian or from other calendars into Baháʼí. The Date::Calendar::Bahai class gives the early version of the Baháʼí calendar, which is synchronised with the Gregorian calendar. The new version, after the 2015 reform, is partially implemented in Date::Calendar::Bahai::Astronomical, included in this distribution. # INSTALLATION ``` zef install Date::Calendar::Bahai ``` or ``` git clone https://github.com/jforget/raku-Date-Calendar-Bahai.git cd raku-Date-Calendar-Bahai zef install . ``` # AUTHOR Jean Forget # COPYRIGHT AND LICENSE Copyright 2021, 2024 Jean Forget This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-grondilu-Base58.md ![Sparky](https://sparky.sparrowhub.io/badge/grondilu-base58-raku?foo=bar) # Base58 Satoshi Nakamoto's binary-to-text encoding in Raku. No checksum. ## Synopis ``` use Base58; say Base58::encode "Hello World!"; # 2NEpo7TZRRrLZSi2U say Base58::decode "2NEpo7TZRRrLZSi2U"; # Blob[uint8]:0x<48 65 6C 6C 6F 20 57 6F 72 6C 64 21> say Base58::encode blob8.new: ^10; # 1kA3B2yGe2z4 ```
## dist_zef-FRITH-Math-Libgsl-Series.md [![Actions Status](https://github.com/frithnanth/raku-Math-Libgsl-Series/actions/workflows/test.yml/badge.svg)](https://github.com/frithnanth/raku-Math-Libgsl-Series/actions) # NAME Math::Libgsl::Series - An interface to libgsl, the Gnu Scientific Library - Series Acceleration # SYNOPSIS ``` use Math::Libgsl::Series; ``` # SYNOPSIS ``` use Math::Libgsl::Series; my Math::Libgsl::Series $s .= new: N; constant \N = 20; my @array := Array[Num].new; (^N).map: -> $n { my $np1 = $n + 1e0; @array[$n] = 1e0 / ($np1 * $np1) } my ($sum, $err) = $s.levin-accel: @array; say "The series' sum is $sum, with an estimated error $err"; ``` # DESCRIPTION Math::Libgsl::Series is an interface to the Series Acceleration functions of libgsl, the Gnu Scientific Library. ### new(UInt:D() $size!, Bool $truncation? = False) ### new(UInt:D() :$size!, Bool :$truncation? = False) The constructor accepts one or optionally two simple or named arguments: the mandatory series size and the optional error estimation type. This last argoment may have two values: propagation of rounding error or truncation error in the estrapolation. If the **Bool :$truncation** parameter is **True** then the error is estimated by means of the truncation error in the estrapolation. If the **Bool :$truncation** parameter is **False** then the error is estimated by means of the propagation of rounding errors. ### levin-accel(\*@array where \*.all > 0 --> List) This method computes the extrapolated limit of the series using a Levin u-transform. It returns a **List**: the extrapolated **$sum**, the estimated **$error**, and the number of **$terms-used** during the computation. # C Library Documentation For more details on libgsl see <https://www.gnu.org/software/gsl/>. The excellent C Library manual is available here <https://www.gnu.org/software/gsl/doc/html/index.html>, or here <https://www.gnu.org/software/gsl/doc/latex/gsl-ref.pdf> in PDF format. # Prerequisites This module requires the libgsl library to be installed. Please follow the instructions below based on your platform: ## Debian Linux and Ubuntu 20.04+ ``` sudo apt install libgsl23 libgsl-dev libgslcblas0 ``` That command will install libgslcblas0 as well, since it's used by the GSL. ## Ubuntu 18.04 libgsl23 and libgslcblas0 have a missing symbol on Ubuntu 18.04. I solved the issue installing the Debian Buster version of those three libraries: * <http://http.us.debian.org/debian/pool/main/g/gsl/libgslcblas0_2.5+dfsg-6_amd64.deb> * <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl23_2.5+dfsg-6_amd64.deb> * <http://http.us.debian.org/debian/pool/main/g/gsl/libgsl-dev_2.5+dfsg-6_amd64.deb> # Installation To install it using zef (a module management tool): ``` $ zef install Math::Libgsl::Series ``` # AUTHOR Fernando Santagata [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2022 Fernando Santagata This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-martimm-Gnome-Pango.md ![](https://martimm.github.io/gnome-gtk3/content-docs/images/gtk-perl6.png) # Gnome Pango ![Artistic License 2.0](https://martimm.github.io/label/License-label.svg) # Description Pango is a library for layout and rendering of text, with an emphasis on internationalization. Pango can be used anywhere that text layout is needed; however, most of the work on Pango so far has been done using the GTK widget toolkit as a test platform. Pango forms the core of text and font handling for GTK. ## Documentation * [🔗 Website, entry point for all documents and blogs](https://martimm.github.io/) * [🔗 License document](https://www.perlfoundation.org/artistic_license_2_0) * [🔗 Release notes of all the packages in `:api<2>`](https://github.com/MARTIMM/gnome-source-skim-tool/blob/main/CHANGES.md) * [🔗 Issues of all the packages in `:api<2>`](https://github.com/MARTIMM/gnome-source-skim-tool/issues) # Installation Do not install this package on its own. Instead install `Gnome::Gtk4` newest api. `zef install Gnome::Gtk4:api<2>` # 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 github project](https://github.com/MARTIMM/gnome-source-skim-tool/issues). # Attribution * The inventors of Raku, formerly known as Perl 6, of course and the writers of the documentation which helped me out every time again and again. * The builders of all the Gnome libraries and the documentation. * Other helpful modules for their insight and use.
## dist_zef-raku-community-modules-Terminal-WCWidth.md [![Actions Status](https://github.com/raku-community-modules/Terminal-WCWidth/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Terminal-WCWidth/actions) [![Actions Status](https://github.com/raku-community-modules/Terminal-WCWidth/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Terminal-WCWidth/actions) [![Actions Status](https://github.com/raku-community-modules/Terminal-WCWidth/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Terminal-WCWidth/actions) # NAME Terminal::WCWidth - returns character width on a terminal # SYNOPSIS ``` use Terminal::WCWidth; sub print-right-aligned($s) { print " " x (80 - wcswidth($s)); say $s; } print-right-aligned("this is right-aligned"); print-right-aligned("another right-aligned string") ``` # DESCRIPTION A Raku port of a [Python module](https://github.com/jquast/wcwidth). # SUBROUTINES ## `wcwidth` Takes a single *codepoint* and outputs its width: ``` wcwidth(0x3042) # "あ" - returns 2 ``` Returns: * `-1` for a control character * `0` for a character that does not advance the cursor (NULL or combining) * `1` for most characters * `2` for full width characters ## `wcswidth` Takes a *string* and outputs its total width: ``` wcswidth("*ウルヰ*") # returns 8 = 2 + 6 ``` Returns -1 if any control characters are found. Unlike the Python version, this module does not support getting the width of only the first `n` characters of a string, as you can use the `.substr` method. # ACKNOWLEDGEMENTS Thanks to Jeff Quast (jquast), the author of the Python module, which in turn is based on the C library by Markus Kuhn. # AUTHORS * +merlan #flirora * José Joaquín Atria * Raku Community # COPYRIGHT AND LICENSE Copyright 2015 - 2017 +merlan #flirora Copyright 2020, 2024 Raku Commuity This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## relative.md relative Combined from primary sources listed below. # [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_relative "direct link") See primary documentation [in context](/type/IO/Path#method_relative) for **method relative**. ```raku method relative(IO::Path:D: $base = $*CWD --> Str) ``` Returns a new [`Str`](/type/Str) object with the path relative to the `$base`. If `$base` is not provided, `$*CWD` is used in its place. If the invocant is not an absolute path, it's first made to be absolute using the `.CWD` attribute the object was created with, and then is made relative to `$base`.
## dist_github-yowcow-String-CamelCase.md [![Build Status](https://travis-ci.org/yowcow/p6-String-CamelCase.svg?branch=master)](https://travis-ci.org/yowcow/p6-String-CamelCase) # NAME String::CamelCase - Camelizes and decamelizes given string # SYNOPSIS ``` use String::CamelCase; ``` # DESCRIPTION String::CamelCase is a module to camelize and decamelize a string. # FUNCTIONS Following functions are exported: ## camelize (Str) returns Str ``` camelize("hoge_fuga"); # => "HogeFuga" camelize("hoge-fuga"); # => "HogeFuga" ``` ## decamelize (Str, [Str $expr = '-']) returns Str ``` decamelize("HogeFuga"); # => hoge-fuga decamelize("HogeFuga", "_"); # => hoge_fuga ``` ## wordsplit (Str) returns List ``` wordsplit("HogeFuga"); # => ["Hoge", "Fuga"] wordsplit("hoge-fuga"); # => ["hoge", "fuga"] ``` # SEE ALSO [String::CamelCase](http://search.cpan.org/dist/String-CamelCase/lib/String/CamelCase.pm) # AUTHOR Yoko Ohyama [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2015 yowcow This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-raku-community-modules-Form.md [![Actions Status](https://github.com/raku-community-modules/Form/workflows/test/badge.svg)](https://github.com/raku-community-modules/Form/actions) # NAME Form - A Raku implementation of Perl-style string formatting # SYNOPSIS ``` use Form; ``` # DESCRIPTION An implementation of Perl's Form module, as described by Exegesis 7 and Damian Conway's Perl6::Form module. This is a WORK IN PROGRESS and most likely doesn't work at any given time. # AUTHOR Matthew Walton Source can be located at: <https://github.com/raku-community-modules/Form> . Comments and Pull Requests are welcome. # TODO * DOCUMENTATION * Data specified as lists * Numeric fields with decimal separator and justification * Numeric fields with thousands separators and justification * Currencies * Rendering of Complex numbers (currently restricted to Real) * Everything else # COPYRIGHT AND LICENSE Copyright 2009 - 2012 Matthew Walton Copyright 2013 - 2022 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-dwarring-PDF-Grammar.md [[Raku PDF Project]](https://pdf-raku.github.io) / [PDF::Grammar](https://pdf-raku.github.io/PDF-Grammar-raku) # PDF-Grammar Although PDF documents do not lend themselves to an overall BNF style grammar description; there are areas where these can be put to use, including: * PDF file header and trailer/xref parsing * Parsing of objects fetched via the xref index. Top level objects commomly include: dictionarys , streams, arrays or numbers. * The overall file structure for FDF files (which are not indexed), or for full-scan recovery of PDF files (headers, objects, cross-reference tables and footers). * Parsing the operands that make up content streams. These are used to markup text, forms, images and graphical elements. PDF::Grammar is a set of Raku grammars for parsing and validation of real-world PDF examples. There are four grammars: `PDF::Grammar::Content` - describes the text and graphics operators that are used to produce page layout. `PDF::Grammar::Content::Fast` - is an optimized version of PDF::Grammar::Content. `PDF::Grammar::FDF` - this describes the file structure of FDF (Form Data) exchange files. `PDF::Grammar::PDF` - this describes the file structure of PDF documents, including headers, trailers, top-level objects and the cross-reference table. `PDF::Grammar::Function` - a tokeniser for Postscript Calculator (type 4) functions. PDF-Grammar has so far been tested against a number of sample of PDF documents and may still be subject to change. I have been working off the [PDF 32000-1:2008 1.7](https://opensource.adobe.com/dc-acrobat-sdk-docs/standards/pdfstandards/pdf/PDF32000_2008.pdf) specification. I've relaxed rules, when needed, to handle real-world examples. ## Usage Notes * PDF input files typically contain a mixture of ASCII directives and binary data, plus byte-orientated addressing. For this reason: * files should be read as binary (avoid encoding layers) * strings should be decoded as `latin1` `% rakudo -MPDF::Grammar::PDF -e"say PDF::Grammar::PDF.parse: slurp($f, :bin).decode('latin-1')"` * This module is put to work by the down-stream [PDF](https://pdf-raku.github.io/PDF-raku) module. E.g. to uncompress a PDF, using the installed `pdf-rewriter` script: ``` % pdf-rewriter.raku --uncompress flyer.pdf ``` ## Examples * parse some markup content: `% raku -M PDF::Grammar::Content -e"say PDF::Grammar::Content.parse('(Hello, world\041) Tj')"` * parse a PDF file: `% rakudo -MPDF::Grammar::PDF -e"say PDF::Grammar::PDF.parsefile( $f )"` * dump the contents of a PDF ``` use v6; use PDF::Grammar::PDF; use PDF::Grammar::PDF::Actions; sub MAIN(Str $pdf-file) { my $actions = PDF::Grammar::PDF::Actions.new; if PDF::Grammar::PDF.parsefile( $pdf-file, :$actions ) { say $/.ast.raku; } else { say "failed to parse PDF: $pdf-file"; } } ``` ## AST Reference The action methods in this module return AST trees. Each node in the tree consists of a key, value pair, where the key is the AST Tag, indicating the type of the AST node. For example, here's the AST tree for the following parse: ``` use PDF::Grammar::PDF; use PDF::Grammar::PDF::Actions; my $actions = PDF::Grammar::PDF::Actions.new; PDF::Grammar::PDF.parse( q:to"--END-DOC--", :rule<ind-obj>, :$actions); 3 0 obj << /Type /Pages /Count 1 /Kids [4 0 R] >> endobj --END-DOC-- say '# ' ~ $/.ast.raku; # :ind-obj($[3, 0, :dict({:Count(:int(1)), :Kids(:array([:ind-ref($[4, 0])])), :Type(:name("Pages"))})]) ``` Note that there's also a `lite` mode which skips types `bool`, `int`, `real` and `null`: ``` $actions .= new: :lite; PDF::Grammar::PDF.parse( q:to"--END-", :rule<ind-obj>, :$actions); 3 0 obj << /Count 1 >> endobj --END-- say '# ' ~ $/.ast.raku; # :ind-obj($[3, 0, :dict({:Count(1)})]) ``` This is an indirect object (`ind-obj`), it contains a dictionary object (`dict`). Entries in the dictionary are: * `Count` with integer value (`int`) of 1. * `Kids`, and array (`array`) containing one indirect reference (`ind-ref`). * `Type` with name (`name`) 'Pages'. In most cases, the node type corresponds to the name of the rule or token that was used to construct the node. This AST representation is used extensively throughout the PDF tool-chain. For example, as an intermediate format by `PDF::Writer` for reserialization. For reference, here is a list of all AST node types: | *AST Tag* | Raku Type | Description | | --- | --- | --- | | array | Array[Any] | Array object type, e.g. `[ 0 0 612 792 ]` | | body | Array[Hash] | The FDF/PDF body consisting of `ind-obj` and `comment` entries. A PDF with revisions has multiple body segments | | bool | Bool | Boolean object type, e.g. `true` [1] | | comment | Str | (Write only) a comment string | | cos | Hash | A PDF or FDF document, consisting of a `header` and `body` array | | dict | Hash | Dictionary object type, e.g. `<< /Type /Catalog /Pages 3 0 R >>` | | encoded | Str | Raw encoded stream data. This is returned as a latin-1 byte-string. | | entries | Array[Hash] | A list of entries in a cross reference segment | | decoded | Str | Uncompressed/unencrypted stream data | | gen-num | UInt | Object generation number | | header | Hash | PDF or FDF header, e.g. `%PDF1.4` | | hex-string | Str | A hex-string, e.g. `<736e6f6f7079>` | | ind-ref | Array[UInt] | An indirect reference, .e.g. `23 2 R` | | ind-obj | Any | An indirect object. This is a three element array that contains an object number, generation number and the object | | int | Int | Integer object type, e.g. `42` [1] | | obj-count | UInt | object count/number of entries in a cross reference segment | | obj-first-num | UInt | object first number in a cross reference segment | | obj-num | UInt | Object number | | offset | UInt | byte offset of an indirect object in the file. | | literal | Str | A literal string, e.g. `(Hello, World!)` | | name | Str | Name string, e.g. `/Fred` | | null | Mu | Null object type, e.g. `null` [1] | | real | Real | Real object type, e.g. `42.0` [1] | | start | UInt | Start position of stream data (returned by `ind-obj-nibble` rule) | | startxref | UInt | byte offset from the start of the file to the start of the trailer | | stream | Hash | Stream object type. A dictionary indirect object followed by stream data | | trailer | Hash | Trailer. This typically contains the trailer `dict` entry. | | type | Str | Document type; 'pdf', or 'fdf' | | version | Rat | The PDF / FDF version number, parsed from the header | Note [1] Types `bool`, `int`, `real`, and `null` don't appear in `lite` mode. ## See also * [PDF](https://pdf-raku.github.io/PDF-raku) - Raku module for PDF manipulation, including compression, encryption and reading and writing of PDF data.
## dist_github-azawawi-Odoo-Client.md # Odoo::Client [![Actions Status](https://github.com/azawawi/raku-odoo-client/workflows/test/badge.svg)](https://github.com/azawawi/raku-odoo-client/actions) A simple Odoo ERP client that uses JSON RPC. ## Example ``` use v6; use Odoo::Client; my $odoo = Odoo::Client.new( hostname => "localhost", port => 8069 ); my $uid = $odoo.login( database => "<database>", username => '<email>', password => "<password>" ); printf("Logged on with user id '%d'\n", $uid); ``` For more examples, please see the <examples> folder. ## Installation To install it using zef (a module management tool bundled with Rakudo Star): ``` $ zef install Odoo::Client ``` ## Testing * To run tests: ``` $ prove --ext .rakutest -ve "raku -I." ``` * To run all tests including author tests (Please make sure [Test::Meta](https://github.com/jonathanstowe/Test-META) is installed): ``` $ zef install Test::META $ AUTHOR_TESTING=1 prove --ext .rakutest -ve "raku -I." ``` ## See Also * [JSON::RPC](https://github.com/bbkr/jsonrpc) * [Odoo ERP](http://odoo.com) * [JSON-RPC Library](https://www.odoo.com/documentation/10.0/howtos/backend.html#json-rpc-library) ## Author Ahmad M. Zawawi, [azawawi](https://github.com/azawawi/) on #raku ## License MIT License
## dist_zef-ohmycloudy-SnowFlake.md ## NAME SnowFlake - A tool for generating unique ID numbers. ## SYNOPSIS ``` use SnowFlake; my $worker = SnowFlake.new(worker_id => 1, sequence => 2); say $worker.get_id(); ``` ## DESCRIPTION SnowFlake is a tool for generating unique ID numbers. ## LICENSE [![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) ## AUTHORS * [[email protected]](mailto:[email protected])
## dist_github-jaffa4-Log-D.md # Log::D The module provides support for logging. There are different type of logging: error, warning, debug, verbose, info and plain. You create a log object, then you call methods e,w,d,v,i or p. Methods accept one argument, the logging message or two , section and message. Sections can be allowed or banned. Logging types can be enebled or disabled. The prefix of the log message can be given by a prefix function. Default output is $\*ERR. ## Usage ``` use Log::D; my $f = Log::D.new(:w,:i); # create a new object , enable warning and infos $f.prefix = sub { callframe(2).file~" "~callframe(2).line~" "~$*THREAD.id~" "~DateTime.now~" "; }; #show line number of logging $f.i("reached destructor"); $f.enable(:v); # let us enable verbose error messages too $f.allow("engine func"); # if no allow is given, everything is allowed $f.i("engine func", "engine starting"); $f.remove_allow("engine func"); # it is not longer allowed, if no allow left, all is turned on $f.ban("low level func"); # or use ban, then it is not displayed for sure $f.i("low level func", "print invoice"); $f.remove_ban("low level func"); # need to be able to remove it $f.o = $*OUT; # change output of the log use Log::Empty; my $f = Log::Empty.new(:w,:i); # all logging is off.. useful to replace Log::D with Log::Empty $f.notify = True; # show bans, allows..etc in the log as well to track their usages ```
## fail.md fail Combined from primary sources listed below. # [In Failure](#___top "go to top of document")[§](#(Failure)_sub_fail "direct link") See primary documentation [in context](/type/Failure#sub_fail) for **sub fail**. ```raku multi fail(--> Nil) multi fail(*@text) multi fail(Exception:U $e --> Nil ) multi fail($payload --> Nil) multi fail(|cap (*@msg) --> Nil) multi fail(Failure:U $f --> Nil) multi fail(Failure:D $fail --> Nil) ``` Exits the calling [`Routine`](/type/Routine) and returns a `Failure` object wrapping the exception `$e` - or, for the `cap` or `$payload` form, an [`X::AdHoc`](/type/X/AdHoc) exception constructed from the concatenation of `@text`. If the caller activated fatal exceptions via the pragma `use fatal;`, the exception is thrown instead of being returned as a `Failure`. ```raku # A custom exception defined class ForbiddenDirectory is Exception { has Str $.name; method message { "This directory is forbidden: '$!name'" } } sub copy-directory-tree ($dir) { # We don't allow for non-directories to be copied fail "$dir is not a directory" if !$dir.IO.d; # We don't allow 'foo' directory to be copied too fail ForbiddenDirectory.new(:name($dir)) if $dir eq 'foo'; # or above can be written in method form as: # ForbiddenDirectory.new(:name($dir)).fail if $dir eq 'foo'; # Do some actual copying here ... } # A Failure with X::AdHoc exception object is returned and # assigned, so no throwing Would be thrown without an assignment my $result = copy-directory-tree("cat.jpg"); say $result.exception; # OUTPUT: «cat.jpg is not a directory␤» # A Failure with a custom Exception object is returned $result = copy-directory-tree('foo'); say $result.exception; # OUTPUT: «This directory is forbidden: 'foo'␤» ``` If it's called with a generic `Failure`, an ad-hoc undefined failure is thrown; if it's a defined `Failure`, it will be marked as unhandled. ```raku sub re-fail { my $x = +"a"; unless $x.defined { $x.handled = True; say "Something has failed in \$x ", $x.^name; # OUTPUT: «Something has failed in $x Failure␤» fail($x); return $x; } } my $x = re-fail; say $x.handled; # OUTPUT: «False␤» ``` # [In Exception](#___top "go to top of document")[§](#(Exception)_routine_fail "direct link") See primary documentation [in context](/type/Exception#routine_fail) for **routine fail**. ```raku multi fail(Exception $e) method fail(Exception:D:) ``` Exits the calling [`Routine`](/type/Routine) and returns a [`Failure`](/type/Failure) object wrapping the exception. ```raku # A custom exception defined class ForbiddenWord is Exception { has Str $.word; method message { "This word is forbidden: «$!word»" } } sub say-word ( $word ) { ForbiddenWord.new(:word($word)).fail if $word eq 'foo'; $word.say; } my $result = say-word("foo"); say $result.exception; ``` The routine form works in the same way, with an alternative syntax: `fail ForbiddenWord.new(:word($word))`. # [In Channel](#___top "go to top of document")[§](#(Channel)_method_fail "direct link") See primary documentation [in context](/type/Channel#method_fail) for **method fail**. ```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!␤» ```
## im.md im Combined from primary sources listed below. # [In Complex](#___top "go to top of document")[§](#(Complex)_method_im "direct link") See primary documentation [in context](/type/Complex#method_im) for **method im**. ```raku method im(Complex:D: --> Real:D) ``` Returns the imaginary part of the complex number. ```raku say (3+5i).im; # OUTPUT: «5␤» ```
## dist_zef-antononcube-JavaScript-Google-Charts.md # JavaScript::Google::Charts This repository has the Raku package for generation of the [JavaScript Google Charts](https://developers.google.com/chart) code for making plots and charts. This package is intended to be used in Jupyter notebooks with the [Raku kernel implemented by Brian Duggan](https://github.com/bduggan/raku-jupyter-kernel), [BD1], or ["Jupyter::Chatbook"](https://github.com/antononcube/Raku-Jupyter-Chatbook), [AAp4]. The commands of the package generate JavaScript code that produces (nice) [Google Charts plots or charts](https://developers.google.com/chart/interactive/docs/gallery). The package JavaScript graphs can be also included in HTML and Markdown documents. One nice feature of Google Charts is that it allows the download of the plots and charts made with it. --- ## Mission statement Make first class -- beautiful, tunable, and useful -- plots and charts with Raku using concise specifications. --- ## Design and philosophy Here is a list of guiding design principles: * Google Charts gives a simple user interface, hence, we preserve and follow it as much as we can * Make Google Charts' documentation completely applicable for the implemented functions * That documentation is very detailed and high quality. * *(Raku is just "conduit" to Google Charts.)* * Facilitate the use of data simpler than that required by Google Charts * For example, just giving a list of numbers to a scatter plot should work. * Facilitate the generation of both HTML code and (just) JavaScript code * Keep the implementation simple * Do not to try to make an extensive interface to Google Charts or have complicated code snippets system. * *(Like the efforts in ["JavaScript::D3"](https://raku.land/zef:antononcube/JavaScript::D3).)* --- ## The chart types currently implemented | Chart Type | Chart Type | Chart Type | | --- | --- | --- | | Annotated Timeline ▢ | Area Chart ✓ | Bar Chart ✓ | | Bubble Chart ✓ | Calendar Chart ▢ | Candlestick Chart ▢ | | Column Chart ✓ | Combo Chart ✓ | Gauge ✓ | | Geo Chart ✓ | Histogram ✓ | Line Chart ✓ | | Org Chart ▢ | Pie Chart ✓ | Sankey Diagram ✓ | | Scatter Chart ✓ | Stepped Area Chart ✓ | Timeline ✓ | | TreeMap ✓ | Waterfall Chart ▢ | Word Tree ✓ | --- ## How does it work? Here is a diagram that summarizes the evaluation path from a Raku plot spec to a browser diagram: ``` graph TD Raku{{Raku}} IRaku{{"Raku<br>Jupyter kernel"}} Jupyter{{Jupyter}} JS{{JavaScript}} RakuInput[/Raku code input/] JSOutput[/JavaScript code output/] CellEval[Cell evaluation] JSResDisplay[JavaScript code result display] Jupyter -.-> |1|IRaku -.-> |2|Raku -.-> |3|JSOutput -.-> |4|Jupyter Jupyter -.-> |5|JS -.-> |6|JSResDisplay RakuInput ---> CellEval ---> Jupyter ---> JSResDisplay ``` Here is the corresponding narration: 1. Enter Raku plot command in cell that starts with [the magic spec `%% js`](https://github.com/bduggan/raku-jupyter-kernel/issues/100#issuecomment-1349494169). * Like `js-google-charts-plot('Scatter', (^12)>>.rand)`. 2. Jupyter via the Raku kernel evaluates the Raku plot command. 3. The Raku plot command produces JavaScript code. 4. The Jupyter "lets" the web browser to evaluate the obtained JavaScript code. * Instead of web browser, say, Visual Studio Code can be used. The evaluation loop spelled out above is possible because of the magics implementation in the Raku package [Jupyter::Kernel](https://github.com/bduggan/raku-jupyter-kernel#features), [BD1]. --- ## Alternatives ### Raku packages The Raku package ["JavaScript::D3"](https://raku.land/zef:antononcube/JavaScript::D3), [AAp1, AAv1], provides a similar set of JavaScript computed plots and charts using the library [D3.js](https://d3js.org). D3.js is (much more) of lower level library than Google Charts. **Remark:** Google Charts is customizable, but its set of plots and charts is a streamlined and relatively rigid compared to D3.js. The Raku packages "Text::Plot", [AAp2] and "SVG::Plot", [MLp1], provide similar functionalities and both can be used in Jupyter notebooks. (Well, "Text::Plot" can be used anywhere.) --- ## Examples ### [Scatter plot](https://developers-dot-devsite-v2-prod.appspot.com/chart/interactive/docs/gallery/scatterchart) ``` use JavaScript::Google::Charts; my @res = 120.rand xx 12; js-google-charts('Scatter', @res, format => 'html', :png-button); ``` ![](https://raw.githubusercontent.com/antononcube/Raku-JavaScript-Google-Charts/main/docs/Raku-JavaScript-Google-Charts-scatter-plot-demo.png) ### [Bubble chart](https://developers-dot-devsite-v2-prod.appspot.com/chart/interactive/docs/gallery/bubblechart) ``` my @res2 = [('A'..'Z').pick, 120.rand, 130.rand, <a b>.pick, 10.rand] xx 12; @res2 = @res2.map({ <label x y group z>.Array Z=> $_.Array })».Hash; js-google-charts('Bubble', @res2, column-names => <label x y group z>, format => 'html', :png-button, div-id => 'bubble'); ``` ![](https://raw.githubusercontent.com/antononcube/Raku-JavaScript-Google-Charts/main/docs/Raku-JavaScript-Google-Charts-bubble-chart-demo.png) --- ## References ### Articles [OV1] Olivia Vane, ["D3 JavaScript visualisation in a Python Jupyter notebook"](https://livingwithmachines.ac.uk/d3-javascript-visualisation-in-a-python-jupyter-notebook), (2020), [livingwithmachines.ac.uk](https://livingwithmachines.ac.uk). [SF1] Stefaan Lippens, [Custom D3.js Visualization in a Jupyter Notebook](https://www.stefaanlippens.net/jupyter-custom-d3-visualization.html), (2018), [stefaanlippens.net](https://www.stefaanlippens.net). ### Packages [AAp1] Anton Antonov, [JavaScript::D3 Raku package](https://raku.land/zef:antononcube/Text::Plot), (2022-2024), [GitHub/antononcube](https://github.com/antononcube/Raku-JavaScript-D3). [AAp1] Anton Antonov, [Text::Plot Raku package](https://raku.land/zef:antononcube/Text::Plot), (2022), [GitHub/antononcube](https://github.com/antononcube/Raku-Text-Plot). [AAp3] Anton Antonov, [JavaScriptD3 Python package](https://github.com/antononcube/Python-packages/tree/main/JavaScriptD3), (2022), [Python-packages at GitHub/antononcube](https://github.com/antononcube/Python-packages). [AAp4] Anton Antonov, [Jupyter::Chatbook Raku package](https://github.com/antononcube/Raku-Jupyter-Chatbook), (2023-2024), [GitHub/antononcube](https://github.com/antononcube). [BD1] Brian Duggan, [Jupyter::Kernel Raku package](https://raku.land/cpan:BDUGGAN/Jupyter::Kernel), (2017-2022), [GitHub/bduggan](https://github.com/bduggan/raku-jupyter-kernel). [MLp1] Moritz Lenz, [SVG::Plot Raku package](https://github.com/moritz/svg-plot) (2009-2018), [GitHub/moritz](https://github.com/moritz/svg-plot). ### Videos [AAv1] Anton Antonov, ["The Raku-ju hijack hack for D3.js"](https://www.youtube.com/watch?v=YIhx3FBWayo), (2022), [YouTube/@AAA4Prediction](https://www.youtube.com/@AAA4prediction).
## dist_zef-knarkhov-Node-Ethereum-Keccak256-Native.md # Raku binding to original Keccak256-2011 Fast original Keccak256-2011 computation using NativeCall to C. ## License Module `Node::Ethereum::Keccak256::Native` is free and opensource software, so you can redistribute it and/or modify it under the terms of the [The Artistic License 2.0](https://opensource.org/licenses/Artistic-2.0). ## Credits 1. <https://medium.com/@ConsenSys/are-you-really-using-sha-3-or-old-code-c5df31ad2b0> 2. <https://github.com/epicblockchain/whitepapers/blob/master/ETC/SHA3/SHA-3_Transition_Whitepaper_Impact_on_Ethereum_Classic_Mining_Hardware_and_Network_Security.md> 3. [keccak256.c](https://github.com/firefly/wallet/blob/master/source/libs/ethers/src/keccak256.c), [keccak256.h](https://github.com/firefly/wallet/blob/master/source/libs/ethers/src/keccak256.h) ## Author Please contact me via [LinkedIn](https://www.linkedin.com/in/knarkhov/) or [Twitter](https://twitter.com/CondemnedCell). Your feedback is welcome at [narkhov.pro](https://narkhov.pro/contact-information.html).
## dist_zef-librasteve-PDF-Extract.md [![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) # raku PDF::Extract Simple binding of the pdftotext command line utility ### Installation 1. `brew install poppler` (MacOS) or `sudo apt-get install poppler-utils` (ubuntu) 2. `zef install PDF::Extract` To install poppler on other popular (geddit?) systems such as Nix or Windows, please see the installation instructions [here](https://poppler.freedesktop.org) and use your Nix package manager (e.g. `sudo aptitude` on Debian) or go [here](https://github.com/oschwartz10612/poppler-windows) for Windoze binaries (this module not yet tested on Windows). ### Synopsis ``` use PDF::Extract; my $extract = Extract.new: file => '../resources/sample.pdf'; say $extract.text; say $extract.html; say $extract.xml; say $extract.so; #test for PDF headers say $extract.info; say $extract.info<CreationDate>; ... ### Copyright copyright(c) 2023 Henley Cloud Consulting Ltd. ```
## dist_zef-raku-community-modules-SOAP-Client.md [![Actions Status](https://github.com/raku-community-modules/SOAP-Client/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/SOAP-Client/actions) [![Actions Status](https://github.com/raku-community-modules/SOAP-Client/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/SOAP-Client/actions) # NAME SOAP::Client - Quick and dirty SOAP client # SYNOPSIS ``` use SOAP::Client; my $temp = SOAP::Client.new('https://www.w3schools.com/xml/tempconvert.asmx?WSDL'); say $temp.call('CelsiusToFahrenheit', Celsius => 100); ``` # DESCRIPTION Warning: This library currently only supports the simplest of SOAP calls. # AUTHOR Andrew Egeler # COPYRIGHT AND LICENSE Copyright 2015- 2017 Andrew Egeler Copyright 2018 - 2024 Raku Community Licensed under the MIT license.
## dist_zef-raku-community-modules-MIME-Types.md [![Actions Status](https://github.com/raku-community-modules/MIME-Types/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/MIME-Types/actions) # NAME MIME::Types - determine mime type by file extension # SYNOPSIS ``` use MIME::Types; # Specify the mime file you wisg to use # Or don't pass anything and get the default from the 'resources' directory my $mime = MIME::Types.new("/etc/mime.types"); my $type = $mime.type('txt'); ## Returns: 'text/plain'; my @known_extensions = $mime.extensions('application/vnd.ms-excel'); # Returns: [ 'xls', 'xlb', 'xlt' ] ``` # DESCRIPTION A Raku library that reads the `mime.types` file as used by many Linux distributions, and web servers, and returns an object that can be queried by either type or extension. # EXAMPLE An example mime.types is included in the resources/ directory, and is used by the tests in t/. # AUTHOR Timothy Totten # COPYRIGHT AND LICENSE Copyright 2011 - 2015 Timothy Totten Copyright 2016 - 2022 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-yguillemot-Qt-QtWidgets.md # Qt::QtWidgets A Raku module and native wrapper providing an interface to the Qt5 GUI. ## CONTENT * 1. DESCRIPTION * 2. LIMITATIONS * 3. IMPLEMENTED FUNCTIONALITIES * 4. DOCUMENTATION * 4.1 Classes and methods * 4.2 Instantiation * 4.3 Calling a method * 4.4 Enums * 4.5 Signals and slots * 4.6 Connect * 4.7 Disconnect * 4.8 Emit a QtSignal\_\_ * 4.9 Subclassing a Qt object\_\_ * 5. EXAMPLES * 5.1 clock\_fixedSize.raku * 5.2 clock\_resizable.raku * 5.3 2deg\_eqn\_solver.raku\_\_ * 5.4 sketch\_board.raku * 5.5 editor.raku * 5.6 sliders.raku * 5.7 sudoku\_grid.raku * 5.8 QMainWindow examples\_\_ * 5.9 show\_mouse\_events.raku\_\_ * 5.10 moving\_objects.raku\_\_ * 6. TOOL * 7. PREREQUISITES * 8. INSTALLATION * 9. SOURCE CODE * 10. AUTHOR * 11. COPYRIGHT AND LICENSE ## 1. DESCRIPTION This module defines Raku classes trying to mimic the Qt GUI C++ classes. Qt objects are created and used through the Raku classes with native calls. This is a work in progress and, currently, only a few classes and methods are defined. Nevertheless, this module is already usable (see paragraph 5 *EXAMPLES* below). ## 2. LIMITATIONS Currently, this module is only working with Linux. Although already usable, this interface is still limited to a few of the most basic objects of the Qt GUI. ## 3. IMPLEMENTED FUNCTIONALITIES The list of Qt classes and methods already ported is given in the file doc/Qt/QtWidgets/Classes.html included in the distribution. ## 4. DOCUMENTATION ### 4.1 Classes and methods The Raku API aims to be as close as possible to the C++ one. Classes defined by the Raku API implement the Qt C++ classes and the Raku methods have the same arguments as their related C++ methods. Therefore the Qt C++ documentation should apply to its Raku interface. This documentation is available here: <https://doc.qt.io/qt-5>. The Raku API hides the C++ passing mode of the parameters. Each class resides in its own compunit. So, before using a class, an **use** instruction have to be provided for the related module. For example, the following line: ``` use Qt::QtWidgets::QPushButton; ``` has to be issued before using any instruction related to a QPushButton. The script **guessuse** is provided to help writing the needed **use** instructions. See the paragraph 6 *TOOL* below. ### 4.2 Instantiation To instantiate a Qt class object from Raku, just use new with the same arguments than the C++ constructor. For example the C++ call of a QPushButton constructor is : `QPushButton * button = new QPushButton("some text");` the raku equivalent is: `my $button = QPushButton.new("some text");` ### 4.3 Calling a method Raku methods are called exactly as the original C++ method. The C++ code : `button->setDisable(true);` is translated to Raku as : `$button.setDisable(True);` ### 4.4 Enums Similarly the C++ enums have their Raku equivalent : the C++ code : `QPen * pen = new QPen(Qt::DashLine);` is translated to Raku as : `my $pen = QPen.new(Qt::DashLine);` ### 4.5 Signals and slots The signals and slots mechanism used by Qt allows unrelated objects to communicate. A C++ Qt object can have **slots** and/or **signals** if it inherits from the C++ class **QObject**. Similarly, a Raku object can have **QtSlots** and/or **QtSignals** if it inherits from the Raku class **QtObject**. The class **QtObject** and the related subroutines **connect** and **disconnect** are exported from the compunit **Qt::QtWidgets** and have to be imported with: `use Qt::QtWidgets;` A Raku Qt::QtWidgets **Qtslot** is an ordinary method defined with the trait **is QtSlot**. ``` class MyClass is Qt::QtWidgetsObject { ... # Some code method mySlot(...) is QtSlot { ... # Some code } ... # Some code } ``` As well, a Raku Qt::QtWidgets **Qtsignal** is a method defined with the trait **is QtSignal**. Its associated code will never be executed. So a stub should be used when defining the method. ``` class MyClass2 is Qt::QtWidgetsObject { ... # Some code method mySignal(...) is QtSignal { ... } ... # Some code } ``` ### 4.6 Connect The subroutine **connect** connects a QtSignal to a QtSlot (or to another QtSignal). `sub connect(QtObject $src, Str $signal, QtObject $dst, Str $slot)` The names of signal and slot are passed to connect in strings. The signal and slot must have compatible signatures. > TODO: explanations needed Example: ``` my $src = MyClass2.new; my $dst = MyClass.new; connect $src, "mySignal", $dst, "mySlot"; ``` ### 4.7 Disconnect The subroutine **disconnect** does the opposite of **connect**. `sub disconnect(QtObject $src, Str $signal, QtObject $dst, Str $slot)` Example: `disconnect $src, "mySignal", $dst, "mySlot";` ### 4.8 Emit a QtSignal In C++ Qt, the keyword **emit** is used to emit a signal. `emit mySignal(some_arg);` In Raku Qt::QtWidgets, you only have to execute the method to emit the associated **QtSignal**. `self.mySignal(some_arg);` ### 4.9 Subclassing a Qt object When programming with Qt and C++, some features can only be accessed by overriding a Qt C++ virtual method. A parallel mechanism is implemented in the Qt::QtWidgets module. Subclassing a Qt object needs three steps: * Define a Raku class inheriting the Qt class * Call the **subClass** method of the parent class from the BUILD or TWEAK submethod of the new class. * Override the virtual methods. The overriding method must have the same name and signature that the overrided method and doesn't need any specific syntax. The first and third steps are obvious. The second one is used to instantiate the C++ counterpart of the Raku class and to pass it the parameters its constructor needs. In this second step, the parent class whose the subClass method is called must be explicitely specified: `self.ParentClass::subClass($param, ...);` The following example shows how to subclass a QLabel and override its QMousePressEvent method. **Pure C++ version:** ``` #include <QtWidgets> class MyLabel : public QLabel { public : MyLabel(const QString txt) : QLabel(txt) { } void mousePressEvent(QMouseEvent* event) { // Do something when the mouse is pressed on the label } }; ... // Instantiation of the label in the main function : MyLabel * label = new MyLabel("text on the label"); ``` **Raku version:** ``` use Qt::QtWidgets; use Qt::QtWidgets::QLabel; use Qt::QtWidgets::QMouseEvent; class MyLabel is QLabel { has Str $.txt; submethod TWEAK { self.QLabel::subClass($!txt); } method mousePressEvent(QMouseEvent $event) { # Do something when the mouse is pressed on the label } } ... # Instantiation of the label in the main program : my $label = MyLabel.new(txt => "text on the label"); ``` ## 5. EXAMPLES They are available in the **examples** directory of the distribution. ### 5.1 clock\_fixedSize.raku A very simple clock displaying the current time. `raku examples/clock_fixedSize.raku` ### 5.2 clock\_resizable.raku The same clock with a resizable window. `raku examples/clock_resizable.raku` ### 5.3 2deg\_eqn\_solver.raku A graphical interface to solve quadratic equations. `raku examples/2deg_eqn_solver.raku` ### 5.4 sketch\_board.raku A small example showing how to draw with the mouse and how to get file names using QFileDialog methods. `raku examples/sketch_board.raku` ### 5.5 editor.raku A tiny text editor build with QTextEdit `raku examples/editor.raku` ### 5.6 sliders.raku A demonstration of QSlider, QDial, QCheckBox and QRadioButton widgets. `raku examples/sliders.raku` ### 5.7 sudoku\_grids.raku A QGrid layout usage example. `raku examples/sudoku_grid.raku` ### 5.8 QMainWindow examples editor\_mv.raku and sketch\_board\_mw.raku are modifications of the previous editor and sketch\_board examples which show how to use main window menus and status bar. `raku examples/editor_mw.raku` `raku examples/sketch_board_mw.raku` ### 5.9 show\_mouse\_events.raku A small example which shows how to read mouse events. `raku examples/show_mouse_events.raku` ### 5.10 moving\_objects.raku An example showing how to create QGraphics objects and move them on a QGraphicsScene. `raku examples/moving_objects.raku` ### 5.11 show\_dialog.raku An example of a popup dialog to enter some data `raku examples/show_dialog.raku` ## 6. TOOL Ideally, inserting "use Qt::QtWidgets;" at the beginning of a script should be sufficient to import all the elements of the Qt::QtWidgets module. Unfortunately it's not the case and seems not to be possible with the current version of Raku (except by gathering all the classes of this API inside a single huge source file). Currently a specific **use** instruction is needed for each Qt class used in a script. That's why a tool named **guessuse** is provided to help the user to find what **use** instructions a given script needs. When called with the name of a raku file as argument, it writes out the list of **use** instructions related to **Qt::QtWidgets** needed by this script. For example, the command: ``` guessUse examples/sketch_board.raku ``` prints out the following lines: ``` use Qt::QtWidgets; use Qt::QtWidgets::QAction; use Qt::QtWidgets::QApplication; use Qt::QtWidgets::QBrush; use Qt::QtWidgets::QColor; use Qt::QtWidgets::QFileDialog; use Qt::QtWidgets::QHBoxLayout; use Qt::QtWidgets::QMenu; use Qt::QtWidgets::QMouseEvent; use Qt::QtWidgets::QPaintEvent; use Qt::QtWidgets::QPainter; use Qt::QtWidgets::QPen; use Qt::QtWidgets::QPushButton; use Qt::QtWidgets::QVBoxLayout; use Qt::QtWidgets::QWidget; use Qt::QtWidgets::Qt; ``` Beware that this tool, when scanning a source file, doesn't make any difference between code, comments and character strings and may very well print out "use" instruction for some unneeded compunit. **guessuse** resides in the the bin directory of the distribution and is installed by **zef** along with the **Qt::QtWidgets** module. ## 7. PREREQUISITES * Linux OS * Qt5 development package * C++ compiler This module has been tested with **Qt 5.15.7** and **gcc 12.3.0**. Many other versions should be usable as well. ## 8. INSTALLATION `zef install Qt::QtWidgets` Warning: Given the many classes and methods provided, the installation may need several minutes. Please, be patient. ## 9. SOURCE CODE The source code is available here: <https://github.com/yguillemot/Raku-Qt-QtWidgets.git> Given the large number of Qt Classes and methods, manually writing such a code is very tedious and error prone. That's why this source and its associated documentation have been automatically generated from the Qt C++ headers files coming with the Qt development package. The building tools are available here: <https://github.com/yguillemot/RaQt_maker.git> ## 10. AUTHOR Yves Guillemot <[[email protected]](mailto:[email protected])> ## 11. COPYRIGHT AND LICENSE Copyright (C) 2021-2025 Yves Guillemot This software is free: you can redistribute and/or modify it under the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This software 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
## dist_github-moznion-Text-LTSV.md [![Build Status](https://travis-ci.org/moznion/p6-Text-LTSV.svg?branch=master)](https://travis-ci.org/moznion/p6-Text-LTSV) # NAME Text::LTSV - LTSV (Labeled Tab Separated Value) toolkit # SYNOPSIS ``` use Text::LTSV; my $ltsv = Text::LTSV.new; ## one line $ltsv.stringify(Array[Pair].new( 'foo' => 'bar', 'buz' => 'qux', 'john' => 'paul', )); # => "foo:bar\tbuz:qux\tjohn:paul" ## multiple lines $ltsv.stringify(Array[Array[Pair]].new( Array[Pair].new('foo' => 'bar'), Array[Pair].new('buz' => 'qux'), )); # => "foo:bar\nbuz:qux" ## With parser use Text::LTSV::Parser; my $parser = Text::LTSV::Parser.new; $ltsv.stringify($parser.parse-line("foo:bar\tbuz:qux\tjohn:paul\n")); # => "foo:bar\tbuz:qux\tjohn:paul" $ltsv.stringify($parser.parse-text("foo:bar\tbuz:qux\njohn:paul\tgeorge:ringo\n")); # => "foo:bar\tbuz:qux\njohn:paul\tgeorge:ringo" ``` # DESCRIPTION Text::LTSV is a builder for [LTSV (Labeled Tab Separated Values)](http://ltsv.org/). # METHODS ## `multi method stringify(Pair @key-values) returns Str` Stringify LTSV as one line. ## `multi method stringify(Array[Pair] @multi-key-values) returns Str` Stringify LTSV as multiple lines. You can specify new line character by `$.nl`. Default `$.nl` is `"\n"`; # SEE ALSO * Text::LTSV::Parser # 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.
## uniname.md uniname Combined from primary sources listed below. # [In Cool](#___top "go to top of document")[§](#(Cool)_routine_uniname "direct link") See primary documentation [in context](/type/Cool#routine_uniname) for **routine uniname**. ```raku sub uniname(Str(Cool) --> Str) method uniname(--> Str) ``` Interprets the invocant or first argument as a [`Str`](/type/Str), and returns the Unicode codepoint name of the first codepoint of the first character. See [uninames](/routine/uninames) for a routine that works with multiple codepoints, and [uniparse](/routine/uniparse) for the opposite direction. ```raku # Camelia in Unicode say ‘»ö«’.uniname; # OUTPUT: «RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK␤» say "Ḍ̇".uniname; # Note, doesn't show "COMBINING DOT ABOVE" # OUTPUT: «LATIN CAPITAL LETTER D WITH DOT BELOW␤» # Find the char with the longest Unicode name. say (0..0x1FFFF).sort(*.uniname.chars)[*-1].chr.uniname; # OUTPUT: «BOX DRAWINGS LIGHT DIAGONAL UPPER CENTRE TO MIDDLE RIGHT AND MIDDLE LEFT TO LOWER CENTRE␤» ``` Available as of the 2021.04 Rakudo compiler release.
## dist_zef-jjmerelo-Array-Shaped-Console.md # NAME [Test-install distro](https://github.com/JJ/raku-array-shaped-console/actions/workflows/test.yaml) Array::Shaped::Console - Renders 2d arrays to a console using block symbols # SYNOPSIS ``` use Array::Shaped::Console; my @array[2;2] = (-1,1;1,-1); # Prints "□▧\n▧□\n" using default "grayscale" console symbols array printed(@array).say; # Prints "□■\n■□\n" with infinity having a special default symbol. @array = (-1,Inf;Inf,-1); say printed( @array ); ``` # DESCRIPTION Array::Shaped::Console includes functions and ranges to easily render numeric 2d arrays to the console, using the same shape of the array, and adapting the array range to the number of symbols that are also handled in the function. These arrays, as well as the "infinity" symbol, are predefined; ``` @grayscale = chr(0x25A1)..chr(0x25A9); @dashes = '–'..'―'; @lines = '⎽'...'⎺'; @shades = '░'..'▓'; @lower = '▁'..'█'; @left = '▏'...'█'; @squares = <▪◾◼>; @chars = ".:-=+*#%@".comb; $inf-char = chr(0x25A0); ``` @grayscale is used by default. ## method printed( @array, @shapes = @grayscale, $non-symbol = $inf-char) Returns a string that collates, using the array shape, in a single string that separates rows by a carriage return. # AUTHOR JJ Merelo [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2020-2022 JJ Merelo This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-zero-overhead-App-Workflows-Github.md | last push | [Linux Status](https://github.com/zero-overhead/App-Workflows-Github/actions) | [MacOS Status](https://github.com/zero-overhead/App-Workflows-Github/actions) | [Windows Status](https://github.com/zero-overhead/App-Workflows-Github/actions) | | --- | --- | --- | --- | | scheduled check | [Linux Status](https://github.com/zero-overhead/App-Workflows-Github/actions) | [MacOS Status](https://github.com/zero-overhead/App-Workflows-Github/actions) | [Windows Status](https://github.com/zero-overhead/App-Workflows-Github/actions) | # NAME App::Workflows::Github - a CI/CD workflow collection for Raku Module developers. # SYNOPSIS ``` zef install App::Workflows::Github cd your-module-directory create-workflows-4-github ``` # DESCRIPTION [![last version](https://raku.land/zef:zero-overhead/App::Workflows::Github/badges/version)](https://raku.land/zef:zero-overhead/App::Workflows::Github/badges) [![downloads](https://raku.land/zef:zero-overhead/App::Workflows::Github/badges/downloads)](https://raku.land/zef:zero-overhead/App::Workflows::Github/badges) App::Workflows::Github is collecting Github workflows for testing your [Module](https://raku.land) on Linux, MacOS and Windows. Scheduled workflows only run automatically on github if the .yml files are pushed to the default branch - usually 'main'. ## Microsoft Windows If you are on [Windows](https://learn.microsoft.com/en-us/linux/install) and can not use [WSL](https://learn.microsoft.com/en-us/windows/wsl/): consider switching off the [maximum-path-length-limitation](https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=powershell) in case of failed tests during installation. ``` New-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem" -Name "LongPathsEnabled" -Value 1 -PropertyType DWORD -Force ``` You might get away with temporarily setting TEMP to a short path. ``` set TEMP=D:\T mkdir -Force %TEMP% set TMP=%TEMP% set ZEF_CONFIG_TEMPDIR=%TEMP% ``` ## Installation Linux/MacOS/Windows install module command: ``` zef install App::Workflows::Github ``` Finally execute the following commands: ``` cd your-module-directory create-workflows-4-github ``` This will create or overwrite the following files: ``` your-module-directory/.github/workflows/runner.yml your-module-directory/.github/workflows/dispatch.yml your-module-directory/.github/workflows/Linux.yml your-module-directory/.github/workflows/MacOS.yml your-module-directory/.github/workflows/Windows.yml your-module-directory/run-tests.raku ``` Then do the usual three git steps to push the changes to github. ``` git add .github/workflows/ git add run-tests.raku git commit -m"adding github workflows" git push ``` ## Workflow Dispatch To [dispatch a workflow run](https://cli.github.com/manual/gh_workflow_run) using [gh](https://cli.github.com/manual/) CLI use e.g. ``` cd your-module-directory echo '{"verbosity":"debug", "os":"windows", "ad_hoc_pre_command":"pwd", "ad_hoc_post_command":"ls -alsh", "os_version":"2019", "raku_version":"2023.02", "run_prove6":"true", "install_module":"true", "run_tests_script":"true", "skip_deps_tests":"false"}' > run_parameters.json cat run_parameters.json | gh workflow run 'dispatch' --ref branch-to-run-on --json ``` For 'os' you can choose any of 'ubuntu|macos|windows'. For 'os\_version' check [supported-runners-and-hardware-resources](https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#supported-runners-and-hardware-resources). For available 'raku\_version' check [here](https://www.rakudo.org/downloads/rakudo). ![screenshot of dispatch menu](https://github.com/zero-overhead/App-Workflows-Github/blob/main/resources/dispatch-screenshot.png?raw=true) Open <https://github.com/your-name/your-module/actions> to check the workflow results or dispatch a run via browser. # AUTHOR rcmlz [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2023 rcmlz This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-ANTONOV-Data-Summarizers.md # Raku Data::Summarizers [![Build Status](https://app.travis-ci.com/antononcube/Raku-Data-Summarizers.svg?branch=main)](https://app.travis-ci.com/github/antononcube/Raku-Data-Summarizers) [![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) This Raku package has data summarizing functions for different data structures that are coercible to full arrays. The supported data structures (so far) are: * 1D Arrays * 1D Lists * Positional-of-hashes * Positional-of-arrays --- ## Usage examples ### Setup Here we load the Raku modules [`Data::Generators`](https://modules.raku.org/dist/Data::Generators:cpan:ANTONOV), [`Data::Reshapers`](https://modules.raku.org/dist/Data::Reshapers:cpan:ANTONOV) and this module, [`Data::Summarizers`](https://github.com/antononcube/Raku-Data-Summarizers): ``` use Data::Generators; use Data::Reshapers; use Data::Summarizers; ``` ``` # (Any) ``` ### Summarize vectors Here we generate a numerical vector, place some NaN's or Whatever's in it: ``` my @vec = [^1001].roll(12); @vec = @vec.append( [NaN, Whatever, Nil]); @vec .= pick(@vec.elems); @vec ``` ``` # [740 311 434 300 (Whatever) 192 705 202 576 561 544 NaN (Any) 744 133] ``` Here we summarize the vector generated above: ``` records-summary(@vec) ``` ``` # O────────────────────────────────────O # │ numerical │ # O────────────────────────────────────O # │ 1st-Qu => 251 │ # │ Max => 744 │ # │ Median => 489 │ # │ (Any-Nan-Nil-or-Whatever) => 3 │ # │ Mean => 453.5 │ # │ Min => 133 │ # │ 3rd-Qu => 640.5 │ # O────────────────────────────────────O ``` ### Summarize tabular datasets Here we generate a random tabular dataset with 16 rows and 3 columns and display it: ``` srand(32); my $tbl = random-tabular-dataset(16, <Pet Ref Code>, generators=>[random-pet-name(4), -> $n { ((^20).rand xx $n).List }, random-string(6)]); to-pretty-table($tbl) ``` ``` # O────────────────O───────────O──────────O # │ Code │ Ref │ Pet │ # O────────────────O───────────O──────────O # │ A2Ue69EWAMtJCi │ 0.050176 │ Guinness │ # │ KNwmt0QmoqABwR │ 0.731900 │ Truffle │ # │ A2Ue69EWAMtJCi │ 0.739763 │ Jumba │ # │ aY │ 7.342107 │ Guinness │ # │ xgZjtSP6VrKbH │ 19.868591 │ Jumba │ # │ 20CO9FGD │ 12.956172 │ Jumba │ # │ 20CO9FGD │ 15.854088 │ Guinness │ # │ A2Ue69EWAMtJCi │ 4.774780 │ Guinness │ # │ A2Ue69EWAMtJCi │ 18.729798 │ Guinness │ # │ xgZjtSP6VrKbH │ 13.383997 │ Guinness │ # │ aY │ 9.837488 │ Jumba │ # │ 20CO9FGD │ 2.912506 │ Truffle │ # │ xgZjtSP6VrKbH │ 11.782221 │ Truffle │ # │ KNwmt0QmoqABwR │ 9.825102 │ Truffle │ # │ xgZjtSP6VrKbH │ 16.277717 │ Jumba │ # │ CQmrQcQ4YkXvaD │ 1.740695 │ Guinness │ # O────────────────O───────────O──────────O ``` **Remark:** The values of the column "Pet" is sampled from a set of four pet names, and the values of the column and "Code" is sampled from a set of 6 strings. Here we summarize the tabular dataset generated above: ``` records-summary($tbl) ``` ``` # O───────────────O──────────────────────────────O─────────────────────O # │ Pet │ Ref │ Code │ # O───────────────O──────────────────────────────O─────────────────────O # │ Guinness => 7 │ Min => 0.0501758995572299 │ xgZjtSP6VrKbH => 4 │ # │ Jumba => 5 │ 1st-Qu => 2.3266005718178704 │ A2Ue69EWAMtJCi => 4 │ # │ Truffle => 4 │ Mean => 9.175443804770861 │ 20CO9FGD => 3 │ # │ │ Median => 9.831294839627123 │ KNwmt0QmoqABwR => 2 │ # │ │ 3rd-Qu => 14.619042446877677 │ aY => 2 │ # │ │ Max => 19.868590809216744 │ CQmrQcQ4YkXvaD => 1 │ # O───────────────O──────────────────────────────O─────────────────────O ``` ### Summarize collections of tabular datasets Here is a hash of tabular datasets: ``` my %group = group-by($tbl, 'Pet'); %group.pairs.map({ say("{$_.key} =>"); say to-pretty-table($_.value) }); ``` ``` # Guinness => # O────────────────O───────────O──────────O # │ Code │ Ref │ Pet │ # O────────────────O───────────O──────────O # │ A2Ue69EWAMtJCi │ 0.050176 │ Guinness │ # │ aY │ 7.342107 │ Guinness │ # │ 20CO9FGD │ 15.854088 │ Guinness │ # │ A2Ue69EWAMtJCi │ 4.774780 │ Guinness │ # │ A2Ue69EWAMtJCi │ 18.729798 │ Guinness │ # │ xgZjtSP6VrKbH │ 13.383997 │ Guinness │ # │ CQmrQcQ4YkXvaD │ 1.740695 │ Guinness │ # O────────────────O───────────O──────────O # Truffle => # O─────────O───────────O────────────────O # │ Pet │ Ref │ Code │ # O─────────O───────────O────────────────O # │ Truffle │ 0.731900 │ KNwmt0QmoqABwR │ # │ Truffle │ 2.912506 │ 20CO9FGD │ # │ Truffle │ 11.782221 │ xgZjtSP6VrKbH │ # │ Truffle │ 9.825102 │ KNwmt0QmoqABwR │ # O─────────O───────────O────────────────O # Jumba => # O───────────O────────────────O───────O # │ Ref │ Code │ Pet │ # O───────────O────────────────O───────O # │ 0.739763 │ A2Ue69EWAMtJCi │ Jumba │ # │ 19.868591 │ xgZjtSP6VrKbH │ Jumba │ # │ 12.956172 │ 20CO9FGD │ Jumba │ # │ 9.837488 │ aY │ Jumba │ # │ 16.277717 │ xgZjtSP6VrKbH │ Jumba │ # O───────────O────────────────O───────O ``` Here is the summary of that collection of datasets: ``` records-summary(%group) ``` ``` # summary of Guinness => # O──────────────────────────────O─────────────────────O───────────────O # │ Ref │ Code │ Pet │ # O──────────────────────────────O─────────────────────O───────────────O # │ Min => 0.0501758995572299 │ A2Ue69EWAMtJCi => 3 │ Guinness => 7 │ # │ 1st-Qu => 1.7406953436440742 │ CQmrQcQ4YkXvaD => 1 │ │ # │ Mean => 8.839377375678543 │ 20CO9FGD => 1 │ │ # │ Median => 7.34210706081909 │ xgZjtSP6VrKbH => 1 │ │ # │ 3rd-Qu => 15.854088005472917 │ aY => 1 │ │ # │ Max => 18.72979803423013 │ │ │ # O──────────────────────────────O─────────────────────O───────────────O # summary of Truffle => # O──────────────O──────────────────────────────O─────────────────────O # │ Pet │ Ref │ Code │ # O──────────────O──────────────────────────────O─────────────────────O # │ Truffle => 4 │ Min => 0.7318998724597869 │ KNwmt0QmoqABwR => 2 │ # │ │ 1st-Qu => 1.822202836225727 │ 20CO9FGD => 1 │ # │ │ Mean => 6.312932174017679 │ xgZjtSP6VrKbH => 1 │ # │ │ Median => 6.368803873269801 │ │ # │ │ 3rd-Qu => 10.803661511809633 │ │ # │ │ Max => 11.782221077071329 │ │ # O──────────────O──────────────────────────────O─────────────────────O # summary of Jumba => # O──────────────────────────────O────────────O─────────────────────O # │ Ref │ Pet │ Code │ # O──────────────────────────────O────────────O─────────────────────O # │ Min => 0.7397628145038704 │ Jumba => 5 │ xgZjtSP6VrKbH => 2 │ # │ 1st-Qu => 5.28862527360509 │ │ 20CO9FGD => 1 │ # │ Mean => 11.935946110102654 │ │ A2Ue69EWAMtJCi => 1 │ # │ Median => 12.956171789492936 │ │ aY => 1 │ # │ 3rd-Qu => 18.073154106905072 │ │ │ # │ Max => 19.868590809216744 │ │ │ # O──────────────────────────────O────────────O─────────────────────O ``` ### Skim *TBD...* --- ## TODO * User specified `NA` marker * Tabular dataset summarization tests * Skimmer * Peek-er --- ## References ### Functions, repositories [AAf1] Anton Antonov, [RecordsSummary](https://resources.wolframcloud.com/FunctionRepository/resources/RecordsSummary), (2019), [Wolfram Function Repository](https://resources.wolframcloud.com/FunctionRepository).
## dist_cpan-MANWAR-Games-Maze.md [![Actions Status](https://github.com/manwar/Games-Maze/workflows/test/badge.svg)](https://github.com/manwar/Games-Maze/actions) # NAME Games::Maze - Maze generator. # SYNOPSIS ``` use Games::Maze; my $maze = Games::Maze.new( :height(10), :width(10) ); $maze.make.render.say; ``` # DESCRIPTION Games::Maze is the implementation of the work that I contributed to the [Raku Advent Calendar 2019](https://raku-advent.blog/2019/12/17/maze-maker-for-fun/). It was my first ever participation to the Advent Calendar for Raku. I used the opportunity to explore the language. I was meant to package it as library and release it long time ago but for some reason it didn't work out. I have finally managed to find the time to bundle the package. # AUTHOR Mohammad S Anwar [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2020 Mohammad S Anwar This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-TYIL-Hash-Merge.md ### sub merge-hashes ``` sub merge-hashes( *@hashes ) returns Hash ``` Merge any number of Hashes together. ## class \*@hashes Any number of Hashes to merge together. ### sub merge-hash ``` sub merge-hash( %first, %second, Bool:D :$deep = Bool::True, Bool:D :$positional-append = Bool::True ) returns Hash ``` Merge two hashes together. ## class %first The original Hash to merge the second Hash into. ## class %second The second hash, which will be merged into the first Hash. ## class Bool:D :$deep = Bool::True Boolean to set whether Associative objects should be merged on their own. When set to False, Associative objects in %second will overwrite those from %first. ## class Bool:D :$positional-append = Bool::True Boolean to set whether Positional objects should be appended. When set to False, Positional objects in %second will overwrite those from %first.
## dist_zef-raku-community-modules-Text-Caesar.md [![Actions Status](https://github.com/raku-community-modules/Text-Caesar/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Text-Caesar/actions) [![Actions Status](https://github.com/raku-community-modules/Text-Caesar/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Text-Caesar/actions) [![Actions Status](https://github.com/raku-community-modules/Text-Caesar/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Text-Caesar/actions) # NAME Text::Caesar - Encrypt / Decrypt using a Caesar cipher # SYNOPSIS ``` use Text::Caesar; my $message = Message.new( key => 3, text => "I am a secret message" ); my $secret = Secret.new( key => 3, text => $message.encrypt(); ); say $message.encrypt; say $secret.decrypt; ``` # DESCRIPTION This module allows you to use 4 functions. You can encrypt a message: ``` use Text::Caesar; my Str $secret = "I'm a secret message."; my Str $message = encrypt(3, $secret); say $message; ``` You can decrypt a message : ``` my Str $secret = 'LPDVHFUHWPHVVDJH' my Str $message = decrypt(3, $secret); say $message; ``` You can encrypt (or decrypt) a file: ``` encrypt-from-file($key, $origin, $destination) ``` This code will encrypt `$origin`'s text into the `$destination` file. You can also use objects: ``` my $message = Message.new( key => 3, text => "I am a secret message" ); say $message.encrypt; ``` ``` my $secret = Secret.new( key => 3, text => $message.encrypt; ); say $secret.decrypt; ``` # AUTHOR Emeric Fischer # COPYRIGHT AND LICENSE Copyright 2016 - 2017 Emeric Fischer Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## initialization.md class X::Role::Initialization Error due to passing an initialization value to an ineligible role ```raku class X::Role::Initialization is Exception { } ``` Thrown when the `SomeRole($init)` syntax is used, but SomeRole does not have exactly one public attribute. For example: ```raku role R { }; "D2" but R(2) CATCH { default { put .^name, ': ', .Str } } # OUTPUT: «X::Role::Initialization: Can only supply an initialization value for a role if it has a single public attribute, but this is not the case for 'R'␤» ``` # [Methods](#class_X::Role::Initialization "go to top of document")[§](#Methods "direct link") ## [method role](#class_X::Role::Initialization "go to top of document")[§](#method_role "direct link") ```raku method role() ``` Returns the role that caused the error.
## dist_zef-jonathanstowe-Monitor-Monit.md # Monitor::Monit Provide an interface to the monit monitoring daemon ![Build Status](https://github.com/jonathanstowe/Monitor-Monit/workflows/CI/badge.svg) ## Synopsis ``` use Monitor::Monit; # use default settings my $mon = Monitor::Monit.new; for $mon.service -> $service { say $service.name, " is ", $service.status-name; } ``` ## Description Monit is a lightweight, relatively simple and widely used system and application monitoring service. This provides a mechanism to interact with its http api. ## Installation In order for this to be useful you will need to have 'monit' installed, most Linux distributions provide it as a package. If you set the enviromment variable `MONIT_TEST_LIVE` the tests will attempt to connect to a monit daemon on the local host with the default port and credentials, if there is no connection then the online tests will be skipped. By default the monit daemon will be configured to only listen for local connections on the loopback interface, if you wish to work with a remote monit daemon you may need to alter the monit configuration accordingly. You can provide the details for the running monit daemon you want to test with by setting some environment variables before running the tests: * `MONIT_TEST_HOST` - the hostname on which the daemon is running * `MONIT_TEST_PORT` - the port the daemon is using (default 2812) * `MONIT_TEST_USER` - the username to authenticate (default `admin`) * `MONIT_TEST_PASS` - the password to authenticate (default `monit`) Additionally, if the environment variable `MONIT_TEST_CONTROL` is set to a true value, the tests will attempt to control the services, you probably don't want to do this on a production system. Assuming you have a working Rakudo installation then you should be able to install with `zef` : zef install Monitor::Monit ## Support I've only tested this against my particular configuration of monit so it is entirely possible that I have missed something that is important to you, please feel to make suggestions at <https://github.com/jonathanstowe/Monitor-Monit/issues> It is possible that it may not work properly with certain older versions of monit though I can't pinpoint which versions and it's difficult to test so any help with that would be appreciated. ## Copyright and Licence This is free software. Please see the <LICENCE> file in this directory. © Jonathan Stowe 2016 - 2021
## dist_zef-antononcube-FunctionalParsers.md # FunctionalParsers Raku package ## Introduction This Raku package provides a (monadic) system of Functional Parsers (FPs). The package design and implementation follow closely the article "Functional parsers" by Jeroen Fokker, [JF1]. That article can be used as *both* a theoretical- and a practical guide to FPs. ### Two in one The package provides both FPs and [Extended Backus-Naur Form (EBNF)](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) parsers and interpreters. The reasons for including the EBNF functionalities are: * EBNF parsing is discussed in [JF1] * EBNF parsers and interpreters are very good examples of FPs application ### Previous work #### Anton Antonov * FPs packages implementations in Lua, Mathematica, and R. See [these blog posts](https://mathematicaforprediction.wordpress.com/?s=functional+parsers) and [AAp1, AAp2]. **Remark:** In this document Mathematica and Wolfram Language (WL) are used as synonyms. #### Jeroen Fokker * "Functional parsers" article using Haskell, [JF1]. #### Wim Vanderbauwhede * Interesting and insightful blog post ["List-based parser combinators in Haskell and Raku"](https://limited.systems/articles/list-based-parser-combinators/). * The corresponding Raku code repository [WVp1] is not (fully) productized. * Perl package ["Parser::Combinators"](https://github.com/wimvanderbauwhede/Perl-Parser-Combinators), [WVp2]. --- ## Installation From [Zef ecosystem](https://raku.land): ``` zef install FunctionalParsers; ``` From GitHub: ``` zef install https://github.com/antononcube/Raku-FunctionalParsers.git ``` --- ## Motivation Here is a list of motivations for implementing this package: 1. Word-based backtracking 2. Elevate the "tyranny" of Raku grammars 3. Easier transfer of Raku grammars into other languages 4. Monadic parser construction 5. Quick, elegant implementation ### Word-based backtracking I had certain assumptions about certain slow parsing with Raku using regexes. For example, is not that easy to specify backtracking over sequences of words (instead of characters) in grammars. To check my assumptions I wrote the basic eight FPs (which is quick to do.) After my experiments, I could not help myself making a complete package. ### Elevate the "tyranny" of Raku grammars and transferring to other languages The "first class citizen" treatment of grammars is one of the most important and unique features of Raku. It is one of the reasons why I treat Raku as a "secret weapon." But that uniqueness does not necessarily facilitate easy utilization or transfer in large software systems. FPs, on the other hand, are implemented in almost every programming language. Hence, making or translating grammars with- or to FPs would provide greater knowledge transfer and integration of Raku-derived solutions. ### Monadic parser construction Having a monadic way of building parsers or grammars is very appealing. (To some people.) Raku's operator making abilities can be nicely utilized. **Remark:** The monad of FPs produces Abstract Syntax Trees (ASTs) that are simple lists. I prefer that instead of using specially defined types (as, say, in [WV1, WVp1].) That probably, comes from too much usage of LISP-family programming languages. (Like Mathematica and R.) ### Quick, elegant implementation The Raku code implementing FPs was quick to write and looks concise and elegant. (To me at least. I would not be surprised if that code can be simplified further.) --- ## Naming considerations ### Package name I considered names like "Parser::Combinator", "Parser::Functional", etc. Of course, I looked up names of similar packages. Ultimately, I decided to use "FunctionalParsers" because: * Descriptive name that corresponds to the title of the article by Jeroen Fokker, [JF1]. * The package has not only parser combinators, but also parser transformers and modifiers. * The connections with corresponding packages in other languages are going to be more obvious. * For example, I have used the name "FunctionalParsers" for similar packages in other programming languages (Lua, R, WL.) ### Actions vs Contexts I considered to name the directory with EBNF interpreters "Context" or "Contexts", but since "Actions" is used a lot I chose that name. **Remark:** In [JF1] the term "contexts" is used. --- ## Examples Make a parser for a family of (two) simple sentences: ``` use FunctionalParsers :ALL; my &p1 = (symbol('numerical') «|» symbol('symbolic')) «&» symbol('integration'); ``` ``` # -> @x { #`(Block|6352212853176) ... } ``` Here we parse sentences adhering to the grammar of the defined parser: ``` .say for ("numerical integration", "symbolic integration")>>.words.map({ $_ => &p1($_)}); ``` ``` # (numerical integration) => ((() (numerical integration))) # (symbolic integration) => ((() (symbolic integration))) ``` These sentences are not parsed: ``` ("numeric integration", "symbolic summation")>>.words.map({ $_ => &p1($_)}); ``` ``` # ((numeric integration) => () (symbolic summation) => ()) ``` --- ## Infix operators Several notation alternatives are considered for the infix operations corresponding to the different combinators and transformers. Here is a table with different notation styles: | Description | set | double | n-ary | | --- | --- | --- | --- | | sequential combination | (&) | «&» | ⨂ | | left sequential pick | (<&) | «& | ◁ | | right sequential pick | (&>) | &» | ▷ | | alternatives combination | (⎸) | «⎸» | ⨁ | | function application | (^) | «o | ⨀ | Consider the parsers: ``` my &p1 = apply( {1}, symbol('one')); my &p2 = apply( {2}, symbol('two')); my &p3 = apply( {3}, symbol('three')); my &p4 = apply( {4}, symbol('four')); my &pM = symbol('million'); my &pTh = symbol('things'); ``` ``` # -> @x { #`(Block|6352245759584) ... } ``` Here are spec examples for each style of infix operators: ``` # set my &p = (&p1 (|) &p2 (|) &p3 (|) &p4) (&) (&pM (^) {10**6}) (&) &pTh; &p('three million things'.words.List).head.tail; ``` ``` # (3 (1000000 things)) ``` ``` # double (&p1 «|» &p2 «|» &p3 «|» &p4) «&» &pM «o {10**6} «&» &pTh; ``` ``` # n-ary (&p1 ⨁ &p2 ⨁ &p3 ⨁ &p4) ⨂ {10**6} ⨀ &pM ⨂ &pTh ``` **Remark:** The arguments of the apply operator `⨀` are "reversed" when compared to the arguments of the operators `(^)` and `«o`. For `⨀` the function to be applied is the first argument. --- ## Parser generation Here is an EBNF grammar: ``` my $ebnfCode = q:to/END/; <digit> = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ; <integer> = <digit> , { <digit> } ; <top> = <integer> ; END ``` ``` # <digit> = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ; # <integer> = <digit> , { <digit> } ; # <top> = <integer> ; ``` Here generation is the corresponding functional parsers code: ``` use FunctionalParsers::EBNF; .say for fp-ebnf-parse($ebnfCode, actions => 'Raku::Code').head.tail; ``` ``` # my &pDIGIT = alternatives(symbol('0'), symbol('1'), symbol('2'), symbol('3'), symbol('4'), symbol('5'), symbol('6'), symbol('7'), symbol('8'), symbol('9')); # my &pINTEGER = sequence(&pDIGIT, many(&pDIGIT)); # my &pTOP = &pINTEGER; ``` For more detailed examples see ["Parser-code-generation.md"](./doc/Parser-code-generation.md). --- ## Random sentence generation Here is an EBNF grammar: ``` my $ebnfCode2 = q:to/END/; <top> = <who> , <verb> , <lang> ; <who> = 'I' | 'We' ; <verb> = 'love' | 'hate' | { '♥️' } | '🤮'; <lang> = 'Julia' | 'Perl' | 'Python' | 'R' | 'WL' ; END ``` ``` # <top> = <who> , <verb> , <lang> ; # <who> = 'I' | 'We' ; # <verb> = 'love' | 'hate' | { '♥️' } | '🤮'; # <lang> = 'Julia' | 'Perl' | 'Python' | 'R' | 'WL' ; ``` Here is generation of random sentences with the grammar above: ``` .say for fp-random-sentence($ebnfCode2, 12); ``` ``` # We love R # We hate WL # I love Perl # I hate Julia # We 🤮 R # We R # We Julia # I hate R # We ♥️ WL # I ♥️ ♥️ WL # We 🤮 WL # We love Julia ``` --- ## Generating Mermaid diagrams for EBNFs The function `fp-ebnf-parse` can produce [Mermaid-JS diagrams](https://mermaid.js.org) corresponding to grammars with the target "MermaidJS::Graph". Here is an example: ``` my $ebnfCode3 = q:to/END/; <top> = <a> | <b> ; <a> = 'a' , { 'A' } , [ '1' ]; <b> = 'b' , ( 'B' | '2' ); END fp-ebnf-parse($ebnfCode3, target=>"MermaidJS::Graph", dir-spec => 'LR').head.tail ``` ``` graph LR alt1((or)) NT:top["top"] seq12((and)) T:A("A") NT:b["b"] T:B("B") T:2("2") T:a("a") NT:a["a"] T:b("b") rep7((*)) alt14((or)) opt9((?)) T:1("1") seq5((and)) alt1 --> NT:a alt1 --> NT:b NT:top --> alt1 rep7 --> T:A opt9 --> T:1 seq5 --> |1|T:a seq5 --> |2|rep7 seq5 --> |3|opt9 NT:a --> seq5 alt14 --> T:B alt14 --> T:2 seq12 --> |1|T:b seq12 --> |2|alt14 NT:b --> seq12 ``` Here is a legend: * The non-terminals are shown with rectangles * The terminals are shown with round rectangles * The "conjunctions" are shown in disks **Remark:** The Markdown cell above has the parameters `result=asis, output-lang=mermaid, output-prompt=NONE` which allow for direct diagram rendering of the obtained Mermaid code in various Markdown viewers (GitHub, IntelliJ, etc.) Compare the following EBNF grammar and corresponding diagram with the ones above: ``` my $ebnfCode4 = q:to/END/; <top> = <a> | <b> ; <a> = 'a' , { 'A' } , [ '1' ] ; <b> = 'b' , 'B' | '2' ; END fp-grammar-graph($ebnfCode4, dir-spec => 'LR') ``` ``` graph LR T:A("A") rep7((*)) NT:a["a"] T:B("B") T:2("2") seq5((and)) alt12((or)) NT:top["top"] NT:b["b"] T:a("a") seq13((and)) alt1((or)) opt9((?)) T:b("b") T:1("1") alt1 --> NT:a alt1 --> NT:b NT:top --> alt1 rep7 --> T:A opt9 --> T:1 seq5 --> |1|T:a seq5 --> |2|rep7 seq5 --> |3|opt9 NT:a --> seq5 seq13 --> |1|T:b seq13 --> |2|T:B alt12 --> seq13 alt12 --> T:2 NT:b --> alt12 ``` --- ## CLI The package provides a Command Line Interface (CLI) script for parsing EBNF. Here is its usage message: ``` fp-ebnf-parse --help ``` ``` # Usage: # fp-ebnf-parse <ebnf> [-t|--actions=<Str>] [-n|--parser-name=<Str>] [-p|--rule-name-prefix=<Str>] [-m|--rule-name-modifier=<Str>] [-s|--style=<Str>] -- Generates parser code for a given EBNF grammar. # fp-ebnf-parse <file> [-t|--actions=<Str>] [-n|--parser-name=<Str>] [-p|--rule-name-prefix=<Str>] [-m|--rule-name-modifier=<Str>] [-s|--style=<Str>] -- Generates parser code for a given EBNF grammar file. # # <ebnf> EBNF text. # -t|--actions=<Str> Actions ('t' for 'target'.) [default: 'Raku::Class'] # -n|--parser-name=<Str> Parser name. [default: 'MyParser'] # -p|--rule-name-prefix=<Str> Rule names prefix. [default: 'p'] # -m|--rule-name-modifier=<Str> Rule names modifier. [default: 'WhateverCode'] # -s|--style=<Str> EBNF style, one of 'G4', 'Inverted', 'Standard', 'Relaxed', or 'Whatever'. [default: 'Whatever'] # <file> EBNF file name. ``` If [mermaid-cli](https://github.com/mermaid-js/mermaid-cli) is installed here is an example UNIX shell pipeline with it: ``` fp-ebnf-parse ./resources/Arithmetic.ebnf -s=relaxed -t=mermaid > diag.md && mmdc -i diag.md -o diag.png -w 1200 && open diag.png ``` --- ## Implementation considerations ### Infix operators The infix operators have to be reviewed and probably better sets of symbols would be chosen. The challenge is to select operators that are "respected" by the typical Raku IDEs. (I only experimented with Emacs and Comma IDE.) ### EBNF parser All EBNF parser functions in `FunctionalParsers::EBNF` have apply-transformers that use the attributes of a dedicated object: ``` unit module FunctionalParsers::EBNF; ... our $ebnfActions = FunctionalParsers::EBNF::Actions::Raku::AST.new; .... ``` By assigning instances of different classes to `$ebnfActions` we get different parsing interpretations. ### Not having abstract class Looking at the Raku EBNF interpreter classes it can be easily seen that each can inherit from a common abstract class. But since the EBNF parsing methods (or attributes that callables) are approximately a dozen one-liners, it seems more convenient to have all class method- and attribute definitions on “one screen.” ### Flowchart ``` graph TD FPs[[EBNF<br/>Functional Parsers]] RakuAST[Raku::AST] RakuClass[Raku::Class] RakuCode[Raku::Code] RakuGrammar[Raku::Grammar] WLCode[WL::Code] WLGrammar[WL::Grammar] JavaFuncJ[Java::FuncJ] JavaANTLR[Java::ANTLR] Input[/- EBNF code<br/>- Properties/] PickTarget[Assign context] Parse[Parse] QEVAL{Evaluate?} EVAL[[EVAL]] Code>Code] Context[Context object] Result{{Result}} Input --> PickTarget PickTarget -.- WL PickTarget -.- Java PickTarget -..- Raku PickTarget -.-> Context PickTarget --> Parse Parse -.- FPs Context -.-> FPs Parse --> QEVAL Parse -.-> Code QEVAL --> |yes|EVAL Code -.-> EVAL EVAL ---> Result QEVAL ---> |no|Result subgraph Raku RakuAST RakuClass RakuCode RakuGrammar end subgraph WL WLCode WLGrammar end subgraph Java JavaFuncJ JavaANTLR end ``` --- ## TODO * TODO Parsing EBNF refactoring & additional features * DONE Parse any combination of sequence operators * Initially, only these were parsed: * `'a' <& 'b' <& 'c' | 'a' &> 'd';` * `'a' , 'b' , 'c' | 'a' &> 'd';` * These are also parsed: * `'a' , 'b' &> 'c'` * `'a' <& 'b' &> 'c'` * DONE Class-based parsers * DONE From characters * DONE From tokens * DONE Themed parsers * DONE Inheritance based implementation * DONE "Simpler" * DONE ANTLR / G4 * DONE Whatever * TODO "Named" tokens * `'_?StringQ'` or `'_String'` * `'_WordString'`, `'_LetterString'`, and `'_IdentifierString'` * `'_?NumberQ'` and `'_?NumericQ'` * `'_Integer'` * `'Range[*from*, *to*]'` * TODO Interpreters of EBNF * DONE Java * DONE ["funcj.parser"](https://github.com/typemeta/funcj/tree/master/parser) * TODO [GraphViz](https://graphviz.org) * TODO [DOT](https://graphviz.org/doc/info/lang.html) * DONE MermaidJS * TODO Scala * TODO built-in * TODO [parsley](https://github.com/j-mie6/parsley) * MAYBE Python * TODO Raku * DONE AST * DONE Class * DONE Code * DONE Grammar * TODO Tokenizer (of character sequences) * Other EBNF styles * TODO WL * DONE FunctionalParsers, [AAp1, AAp2] * [P] TODO GrammarRules * Implemented to a point, not tested in WL. * Graph * Via MermaidJS classes. * TODO Translators * TODO FPs code into EBNF * Very cool to have, but seems to be a lot of work. * DONE Raku grammars to FPs * See the class "Grammar::TokenProcessing::Actions::EBNF" of the package "Grammar::TokenProcessing". * DONE Stand-alone grammar-graph translation function. * `fp-grammar-graph` * TODO Extensions * DONE First-matched alternation * The standard `alterations` parser is ["longest alternation"](https://docs.raku.org/language/regexes#Longest_alternation:_%7C) (in Raku's terms.) * TODO Extra parsers * DONE `pInteger` * DONE `pNumber` * DONE `pWord` * DONE `pLetterWord` * DONE `pIdentifier` * TODO `pNumberRange` * Other? * TODO Zero-width assertions implementation * TODO Lookahead * TODO Lookbehind * DONE Random sentence generation * DONE Basic class code * DONE Preventing infinite recursion * DONE "Named" tokens interpretation * `'_?StringQ'` or `'_String'` * `'_WordString'`, `'_LetterString'`, and `'_IdentifierString'` * `'_?NumberQ'` and `'_?NumericQ'` * `'_Integer'` * `'Range[*from*, *to*]'` * TODO Documentation * DONE README * DONE Parser code generation * TODO Raku * DONE Class * TODO Code * DONE Grammar * DONE WL * DONE FunctionalParsers * DONE GrammarRules * TODO Java * TODO Random sentences generation * TODO Mermaid flowchart * TODO Mermaid class diagram? * TODO Videos * TODO Introduction * TODO TRC-2023 presentation --- ## References ### Articles [JF1] Jeroen Fokker, ["Function Parsers"](https://www.researchgate.net/publication/2426266_Functional_Parsers), (1997), Conference: Advanced Functional Programming, First International Spring School on Advanced Functional Programming Techniques-Tutorial Text. 10.1007/3-540-59451-5\_1. [WV1] Wim Vanderbauwhede, ["List-based parser combinators in Haskell and Raku"](https://limited.systems/articles/list-based-parser-combinators/), (2020), [Musings of an Accidental Computing Scientist at codeberg.page](https://wimvanderbauwhede.codeberg.page). ### Packages, paclets, repositories [AAp1] Anton Antonov, ["FunctionalParsers.m"](https://github.com/antononcube/MathematicaForPrediction/blob/master/FunctionalParsers.m), (2014), [MathematicaForPrediction at GitHub](https://github.com/antononcube/MathematicaForPrediction). [AAp2] Anton Antonov, ["FunctionalParsers" WL paclet](https://resources.wolframcloud.com/PacletRepository/resources/AntonAntonov/FunctionalParsers/), (2023), [Wolfram Language Paclet Repository](https://resources.wolframcloud.com/PacletRepository/). [WVp1] Wim Vanderbauwhede, [List-based parser combinator library in Raku](https://github.com/wimvanderbauwhede/list-based-combinators-raku), (2020), [GitHub/wimvanderbauwhede](https://github.com/wimvanderbauwhede). [WVp2] Wim Vanderbauwhede, [Parser::Combinators Perl package](https://github.com/wimvanderbauwhede/Perl-Parser-Combinators), (2013-2015), [GitHub/wimvanderbauwhede](https://github.com/wimvanderbauwhede).
## dist_zef-lizmat-List-UtilsBy.md [![Actions Status](https://github.com/lizmat/List-UtilsBy/workflows/test/badge.svg)](https://github.com/lizmat/List-UtilsBy/actions) # NAME Raku port of Perl's List::UtilsBy module 0.11 # SYNOPSIS ``` use List::UtilsBy <nsort_by min_by>; my @files_by_age = nsort_by { .IO.modified }, @files; my $shortest_name = min_by { .chars }, @names; ``` # DESCRIPTION This module tries to mimic the behaviour of Perl's `List::UtilsBy` module as closely as possible in the Raku Programming Language. List::UtilsBy provides some trivial but commonly needed functionality on lists which is not going to go into `List::Util`. # Porting Caveats Raku does not have the concept of `scalar` and `list` context. Usually, the effect of a scalar context can be achieved by prefixing `+` to the result, which would effectively return the number of elements in the result, which usually is the same as the scalar context of Perl of these functions. Many functions take a `&code` parameter of a `Block` to be called by the function. Many of these assume **$\_** will be set. In Raku, this happens automagically if you create a block without a definite or implicit signature: ``` say { $_ == 4 }.signature; # (;; $_? is raw) ``` which indicates the Block takes an optional parameter that will be aliased as `$_` inside the Block. If you want to be able to change `$_` inside the block **without** changing the source array, you can use the `is copy` trait thus: ``` -> $_ is copy { ... code changing $_ ... } ``` Raku also doesn't have a single `undef` value, but instead has `Type Objects`, which could be considered undef values, but with a type annotation. In this module, `Nil` (a special value denoting the absence of a value where there should have been one) is used instead of `undef`. Also note there are no special parsing rules with regards to blocks in Raku. So a comma is **always** required after having specified a block. Some functions return something different in scalar context than in list context. Raku doesn't have those concepts. Functions that are supposed to return something different in scalar context also the `Scalar` type as the first positional parameter to indicate the result like the result of a scalar context, is required. It will be noted with the function in question if that feature is available. # FUNCTIONS ## sort\_by BLOCK, LIST Returns the list of values sorted according to the string values returned by the BLOCK. A typical use of this may be to sort objects according to the string value of some accessor, such as: ``` my @sorted = sort_by { .name }, @people; ``` The key function is being passed each value in turn, The values are then sorted according to string comparisons on the values returned. This is equivalent to: ``` my @sorted = sort -> $a, $b { $a.name cmp $b.name }, @people; ``` except that it guarantees the `name` accessor will be executed only once per value. One interesting use-case is to sort strings which may have numbers embedded in them "naturally", rather than lexically: ``` my @sorted = sort_by { S:g/ (\d+) / { sprintf "%09d", $0 } / }, @strings; ``` This sorts strings by generating sort keys which zero-pad the embedded numbers to some level (9 digits in this case), helping to ensure the lexical sort puts them in the correct order. ### Idiomatic Raku ways ``` my @sorted = @people.sort: *.name; ``` ## nsort\_by BLOCK, LIST Similar to `/sort_by` but compares its key values numerically. ### Idiomatic Raku ways ``` my @sorted = <10 1 20 42>.sort: +*; ``` ## rev\_sort\_by BLOCK, LIST ## rev\_nsort\_by BLOCK, LIST ``` my @sorted = rev_sort_by { KEYFUNC }, @values; my @sorted = rev_nsort_by { KEYFUNC }, @values; Similar to L<sort_by> and L<nsort_by> but returns the list in the reversei order. ``` ## max\_by BLOCK, LIST ``` my @optimal = max_by { KEYFUNC }, @values; my $optimal = max_by Scalar, { KEYFUNC }, @values; ``` Returns the (first) value(s) from `@vals` that give the numerically largest result from the key function. ``` my $tallest = max_by Scalar, { $_->height }, @people; my $newest = max_by Scalar, { .IO.modified }, @files; ``` If the `Scalar` positional parameter is specified, then only the first maximal value is returned. Otherwise a list of all the maximal values is returned. This may be used to obtain positions other than the first, if order is significant. If called on an empty list, an empty list is returned. For symmetry with the </nsort_by> function, this is also provided under the name `nmax_by` since it behaves numerically. ### Idiomatic Raku ways ``` my @tallest = @people.max( *.height ); # all tallest people my $tallest = @people.max( *.height ).head; # only the first ``` ## min\_by BLOCK, LIST ``` my @optimal = min_by { KEYFUNC }, @values; my $optimal = min_by Scalar, { KEYFUNC }, @values; ``` Similar to </max_by> but returns values which give the numerically smallest result from the key function. Also provided as `nmin_by` ### Idiomatic Raku ways ``` my @smallest = @people.min: *.height; # all smallest people my $smallest = @people.min( *.height ).head; # only the first ``` ## minmax\_by ``` my ($minimal, $maximal) = minmax_by { KEYFUNC }, @values; ``` Similar to calling both </min_by> and </max_by> with the same key function on the same list. This version is more efficient than calling the two other functions individually, as it has less work to perform overall. Also provided as `nminmax_by`. ### Idiomatic Raku ways ``` my ($smallest,$tallest) = @people.minmax: *.height; ``` ## uniq\_by BLOCK, LIST ``` my @unique = uniq_by { KEYFUNC }, @values; ``` Returns a list of the subset of values for which the key function block returns unique values. The first value yielding a particular key is chosen, subsequent values are rejected. ``` my @some_fruit = uniq_by { $_->colour }, @fruit; ``` To select instead the last value per key, reverse the input list. If the order of the results is significant, don't forget to reverse the result as well: ``` my @some_fruit = reverse uniq_by { $_->colour }, reverse @fruit; ``` Because the values returned by the key function are used as hash keys, they ought to either be strings, or at least stringify in an identifying manner. ### Idiomatic Raku ways ``` my @some_fruit = @fruit.uniq: *.colour; ``` ## partition\_by BLOCK, LIST ``` my %parts = partition_by { KEYFUNC }, @values; ``` Returns a Hash of Arrays containing all the original values distributed according to the result of the key function block. Each value will be an Array containing all the values which returned the string from the key function, in their original order. ``` my %balls_by_colour = partition_by { $_->colour }, @balls; ``` Because the values returned by the key function are used as hash keys, they ought to either be strings, or at least stringify in an identifying manner. ### Idiomatic Raku ways ``` my %balls_by_colour = @balls.classify: *.colour; ``` ## count\_by BLOCK, LIST ``` my %counts = count_by { KEYFUNC }, @values; ``` Returns a Hash giving the number of times the key function block returned the key, for each value in the list. ``` my %count_of_balls = count_by { $_->colour }, @balls; ``` Because the values returned by the key function are used as hash keys, they ought to either be strings, or at least stringify in an identifying manner. ### Idiomatic Raku ways ``` my %count_of_balls = @balls.map( *.colour ).Bag; ``` ## zip\_by BLOCK, ARRAYS ``` my @vals = zip_by { ITEMFUNC }, @arr0, @arr1, @arr2, ... ; ``` Returns a list of each of the values returned by the function block, when invoked with values from across each each of the given Arrays. Each value in the returned list will be the result of the function having been invoked with arguments at that position, from across each of the arrays given. ``` my @transposition = zip_by { [ @_ ] }, @matrix; my @names = zip_by { "$_[1], $_[0]" }, @firstnames, @surnames; print zip_by { "$_[0] => $_[1]\n" }, %hash.keys, %hash.values; ``` If some of the arrays are shorter than others, the function will behave as if they had `Any` in the trailing positions. The following two lines are equivalent: ``` zip_by { f(@_) }, [ 1, 2, 3 ], [ "a", "b" ]; f( 1, "a" ), f( 2, "b" ), f( 3, Any ); ``` If the item function returns a list, and you want to have the separate entries of that list to be included in the result, you need to return that slip that list. This can be useful for example, for generating a hash from two separate lists of keys and values: ``` my %nums = zip_by { |@_ }, <one two three>, (1, 2, 3); # %nums = ( one => 1, two => 2, three => 3 ) ``` (A function having this behaviour is sometimes called `zipWith`, e.g. in Haskell, but that name would not fit the naming scheme used by this module). ### Idiomatic Raku ways ``` my @names = zip @firstnames, @surnames, :with({ "$^b, $^a" }); zip [1,2,3], [<a b>], :with(&f); my %nums = zip <one two three>, (1, 2, 3); ``` ## unzip\_by BLOCK, LIST ``` my (@arr0, @arr1, @arr2, ...) = unzip_by { ITEMFUNC }, @vals ``` Returns a list of Arrays containing the values returned by the function block, when invoked for each of the values given in the input list. Each of the returned Arrays will contain the values returned at that corresponding position by the function block. That is, the first returned Array will contain all the values returned in the first position by the function block, the second will contain all the values from the second position, and so on. ``` my (@firstnames, @lastnames) = unzip_by { .split(" ",2) }, @names; ``` If the function returns lists of differing lengths, the result will be padded with `Any` in the missing elements. This function is an inverse of </zip_by>, if given a corresponding inverse function. ## extract\_by BLOCK, ARRAY ``` my @vals = extract_by { SELECTFUNC }, @array; ``` Removes elements from the referenced array on which the selection function returns true, and returns a list containing those elements. This function is similar to `grep`, except that it modifies the referenced array to remove the selected values from it, leaving only the unselected ones. ``` my @red_balls = extract_by { .color eq "red" }, @balls; # Now there are no red balls in the @balls array ``` This function modifies a real array, unlike most of the other functions in this module. Because of this, it requires a real array, not just a list. This function is implemented by invoking `splice` on the array, not by constructing a new list and assigning it. ## extract\_first\_by BLOCK, ARRAY ``` my $value = extract_first_by { SELECTFUNC }, @array; ``` A hybrid between </extract_by> and `List::Util::first`. Removes the first element from the referenced array on which the selection function returns true, returning it. As with </extract_by>, this function requires a real array and not just a list, and is also implemented using `splice`. If this function fails to find a matching element, it will return an empty list unless called with the `Scalar` positional parameter: in that case it will return `Nil`. ## weighted\_shuffle\_by BLOCK, LIST ``` my @shuffled = weighted_shuffle_by { WEIGHTFUNC }, @values; ``` Returns the list of values shuffled into a random order. The randomisation is not uniform, but weighted by the value returned by the `WEIGHTFUNC`. The probability of each item being returned first will be distributed with the distribution of the weights, and so on recursively for the remaining items. ## bundle\_by BLOCK, NUMBER, LIST ``` my @bundled = bundle_by { BLOCKFUNC }, $number, @values; ``` Similar to a regular `map` functional, returns a list of the values returned by `BLOCKFUNC`. Values from the input list are given to the block function in bundles of `$number`. If given a list of values whose length does not evenly divide by `$number`, the final call will be passed fewer elements than the others. ### Idiomatic Raku ways ``` my @bundled = @values.batch(3).map: -> @_ { ... }; ``` # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! Source can be located at: <https://github.com/lizmat/List-UtilsBy> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2018, 2019, 2020, 2021, 2023 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. Re-imagined from the Perl version as part of the CPAN Butterfly Plan. Perl version developed by Paul Evans.
## dist_zef-raku-community-modules-LN.md [![Actions Status](https://github.com/raku-community-modules/LN/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/LN/actions) # NAME LN - Get $\*ARGFILES with line numbers via $\*LN # SYNOPSIS ``` perl -wlnE 'say "$.:$_"; close ARGV if eof' foo bar # Perl raku -MLN -ne 'say "$*LN:$_"' foo bar # Raku ``` ``` $ echo -e "a\nb\nc" > foo $ echo -e "d\ne" > bar $ raku -MLN -ne 'say "$*LN:$_"' foo bar 1:a 2:b 3:c 1:d 2:e $ raku -ne 'use LN "no-reset"; say "$*LN:$_"' foo bar 1:a 2:b 3:c 4:d 5:e ``` # DESCRIPTION Mixes in [`IO::CatHandle::AutoLines`](https://raku.land/zef:raku-community-modules/IO::CatHandle::AutoLines)) into [`$*ARGFILES`](https://docs.perl6.org/language/variables#index-entry-%24%2AARGFILES) which provides an `.ln` method containing current line number of the current handle (or total line number if `'no-reset'` option was passed to `use`). For ease of access to that method `$*LN` dynamic variable containing its value is available. # EXPORTED TERMS ## $\*LN Contains same value as `$*ARGFILES.ln`https://raku.land/zef:raku-community-modules/IO::CatHandle::AutoLines#synopsis| which is a method exported by [`IO::CatHandle::AutoLines`](https://raku.land/zef:raku-community-modules/IO::CatHandle::AutoLines) that gives the current line number of the handle. By default, the line number will get reset on each new file in `$*ARGFILES`. If you wish it to *not* reset, pass `"no-reset"` positional argument to the `use` line: ``` use LN 'no-reset'; =head1 EXPORTED TYPES =head2 role IO::CatHandle::AutoLines Exports L<C<IO::CatHandle::AutoLines>|https://raku.land/zef:raku-community-modules/IO::CatHandle::AutoLines> role, for you to use, if needed. ``` # AUTHOR Zoffix Znet # COPYRIGHT AND LICENSE Copyright 2017 Zoffix Znet Copyright 2018 - 2022 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-CTILMES-DB-MySQL.md # DB::MySQL - MySQL access for Perl 6 [![Build Status](https://travis-ci.org/CurtTilmes/perl6-dbmysql.svg)](https://travis-ci.org/CurtTilmes/perl6-dbmysql) This is a reimplementation of Perl 6 bindings for MySQL. ## Basic usage ``` use DB::MySQL; my $mysql = DB::MySQL.new(); # You can pass in various options ``` Execute a query, and get a single value: ``` say $mysql.execute('select 42').value; # 42 ``` Create a table: ``` $mysql.execute('create table foo (x int, y varchar(80))'); ``` Insert some values using placeholders: ``` $mysql.query('insert into foo (x,y) values (?,?)', 1, 'this'); ``` Execute a query returning a row as an array or hash; ``` say $mysql.query('select * from foo where x = ?', 1).array; say $mysql.query('select * from foo where x = ?', 1).hash; ``` Execute a query returning a bunch of rows as arrays or hashes: ``` .say for $mysql.query('select * from foo').arrays; .say for $mysql.query('select * from foo').hashes; ``` `.query()` caches a prepared statement, and can have placeholders and arguments - `.execute()` does not prepare/cache and can't have placeholders. Both can return results. ## Installation This module relies on `libmysqlclient.so`. For Ubuntu, I install this with: ``` sudo apt install libmysqlclient-dev ``` I worked with version 5.7 of the API. It may or may not work with other versions. You can see the client version with: ``` perl6 -MDB::MySQL::Native -e 'say mysql_get_client_info' ``` There are likely 64-bit Linux dependencies in the code. Patches welcome if someone wants to make it on other OSes. ## Connection Information There are many options that can be specified to `DB::MySQL.new()`: * `:host` - defaults to `localhost` * `:port` - defaults to `3306` * `:user` * `:password` * `:socket` * `:database` - optional, sets current database * `:connect-timeout` - timeout in seconds for a connect attempt. * `:read-timeout` - timeout in seconds for each attempt to read from the servers. * `:write-timeout` - timeout in seconds for each attempt to write to the server. * `:default-file` - Read options from the named file instead of `my.cnf`. * `:group` - defaults to 'client'. Reads options from the specified group in the `.my.cnf` file. Undefine this to ignore defaults file. The easiest way to connect is to put your options in `.my.cnf`. ## DB::MySQL::Connection The main **DB::MySQL** object acts as a factory for connections, maintaining a cache of connections already created. A new connection can be requested with the `.db` method, but often this isn't needed. When you are finished with a connection, you can explicitly return it to the cache with `.finish`. You can call `.query()` or `.execute()` on the main **DB::SQLite** object, but all they really do is allocate a **DB::SQLite::Connection** (either from the cache, or create a new one) and call those methods on it, then return the connection to the cache. These are equivalent: ``` .say for $mysql.query('select * from foo').arrays; ``` ``` my $db = $mysql.db; .say for $mysql.query('select * from foo').arrays; $db.finish; ``` The connection object also has some extra methods for separately preparing and executing the query: ``` my $db = $mysql.db; my $sth = $db.prepare('insert into foo (x,y) values (?,?)'); $sth.execute(1, 'this'); $sth.execute(2, 'that'); $db.finish; ``` You can also call `.finish()` on the statement: ``` my $sth = $mysql.db.prepare('insert into foo (x,y) values (?,?)'); $sth.execute(1, 'this'); $sth.execute(2, 'that'); $sth.finish; ``` The statement will finish the associated connection, returning it to the cache. Yet another way to do it is to pass `:finish` in to the execute. ``` my $sth = $mysql.db.prepare('insert into foo (x,y) values (?,?)'); $sth.execute(1, 'this'); $sth.execute(2, 'that', :finish); ``` And finally, a cool Perl 6ish way is the `will` trait to install a Phaser directly on the variable: ``` { my $sth will leave { .finish } = $mysql.db.prepare('insert into foo (x,y) values (?,?)'); $sth.execute(1, 'this'); $sth.execute(2, 'that'); } ``` Calling `.prepare()` on the **DB::MySQL::Connection** prepares and returns a **DB::MySQL::Statement** that can then be `.execute()`ed. The prepared statement is also retained in a cache with the connection. If the same statement is prepared again on the same connection, the cached object will be returned instead of re-preparing. If you don't want it to be cached, you can pass in the `:nocache` option. ``` my $sth = $mysql.db.prepare('insert into foo (x,y) values (?,?)', :nocache); $sth.execute(1, 'this'); $sth.execute(2, 'that', :finish); ``` You must still take care to call `.finish()` to return the connection to the connection cache so it will get reused. (Or take care NOT to call `.finish()` if you don't want the connection to be reused, possibly in another thread.) For the main object, or the connection object, `.execute()` is used instead of `.query()` if you don't need placeholders/arguments. ## Transactions The database connection object can also manage transactions with the `.begin`, `.commit`, and `.rollback` methods: ``` my $db = $mysql.db; my $sth = $db.prepare('insert into foo (x,y) values (?,?)'); $db.begin; $sth.execute(1, 'this'); $sth.execute(2, 'that'); $db.commit; $db.finish; ``` The `begin`/`commit` ensure that the statements between them happen atomically, either all or none. Transactions can also dramatically improve performance for some actions, such as performing thousands of inserts/deletes/updates since the indexes for the affected table can be updated in bulk once for the entire transaction. If you `.finish` the database prior to a `.commit`, an uncommitted transaction will automatically be rolled back. As a convenience, `.commit` also returns the database object, so you can just `$db.commit.finish`. ## Results Calling `.query()` on a **DB::MySQL** or **DB::MySQL::Connection**, or calling `.execute()` on a **DB::SQLite::Statement** with an SQL SELECT or something that returns data, a `DB::SQLite::Result` object will be returned. The query results can be consumed from that object with the following methods: * `.value` - a single scalar result * `.array` - a single array of results from one row * `.hash` - a single hash of results from one row * `.arrays` - a sequence of arrays of results from all rows * `.hashes` - a sequence of hashes of results from all rows If the query isn't a select or otherwise doesn't return data, such as an INSERT, UPDATE, or DELETE, it will return the number of rows affected. By default, the entire result of the query is retrieved immediately from the server to the client. You can pass in the `:nostore` option to `.query` or `.execute` to avoid this behavior. It will then retrieve the results from the server as you consume them on the client. This will hold up server resources while you retrieve the results, so exercise care with this. ## Exceptions All database errors, including broken SQL queries, are thrown as exceptions. ## Acknowledgements Inspiration taken from the existing Perl6 [DBIish](https://github.com/perl6/DBIish) module as well as the Perl 5 [Mojo::Pg](http://mojolicious.org/perldoc/Mojo/Pg) from the Mojolicious project. ## License Portions thanks to DBIish: Copyright © 2009-2016, the DBIish contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## dist_cpan-ATROXAPER-Propius.md [![Build Status](https://travis-ci.org/atroxaper/p6-Propius.svg?branch=master)](https://travis-ci.org/atroxaper/p6-Propius) # Propius Memory cache with loader and eviction by time. Inspired by [Guava's CacheLoader](https://github.com/google/guava/wiki/CachesExplained). ## Examples ``` use Propius; my $cache = eviction-based-cache( loader => { $:key ** 2 }, # calculation of the new value for key removal-listener => { say 'removed ', $:key, ':', $:value, ' cause ', $:cause }, # optional listener for removed values expire-after-write => 60); # freshness time of cached values; $cache.get(5); # returns prodused the new value - 25; $cache.get(5): # returns cached value - 25; $cache.get-if-exists(6); # returns Any $cache.put(:9key, loader => { $:key ** 3 }); # cache value for specified loader $cache.get(9); # returns cached value - 729 # ... 60 seconds later in output (in case you use the cache) removed 5:25 cause Expired removed 9:729 cause Expired ``` ## Create You can use sub `eviction-based-cache` for creation the new cache. Arguments are: `:&loader! where .signature ~~ :(:$key)` - sub with signature like `(:$key)`. The sub will be used for producing the new values. Obligatory argument. `:&removal-listener where .signature ~~ :(:$key, :$value, :$cause)` - sub with signature like `(:$key, :$value, :$cause)`. The sub will be called in case when value removed from the cache. Cause is element of enum `RemoveCause`. `:$expire-after-write` - how long the cache have to store value after its last re/write `:$expire-after-access` - how long the cache have to store value after its last access (read or write) `:$time-unit` - object of `TimeUnit`, indicate time unit of expire-after-write/access value. Seconds by default. `:$ticker` - object of `Ticker`, witch is used for retrieve 'current' time. Can be specified for overriding standard behaviour (current system time), for example for testing. `:$size` - max capacity of the cache. ## Notes The cache can use object keys. If you want that you have to control .WHICH method of keys. Of course the cache is thread-save. It simply uses OO::Monitors for synchronisation. ## Available methods ### get(Any:D $key) Retrieve value by key. ``` my $is-primitive = $cache.get(655360001); ``` If there is no value for specified key then loader with be used to produce the new value. ### get-if-exists(Any:D $key) Retrieve value by key only if it exists. ``` my $is-primitive = $cache.get-if-exists(900900900900990990990991); ``` If there is no value for specified key then Any will be returned. ### put(Any:D :$key, Any:D :$value) ### put(Any:D :$key, :&loader! where .signature ~~ :(:$key)) Store a value in cache with/without specified loader. ``` $cache.put(:900900900900990990990991key, :value); $cache.put(:2key, loader => { True }); ``` It will rewrite any cached value for specified key. In that case removal-listener will be called with old value cause Replaced. In case of cache already reached max capacity value which has not been used for a longest time will be removed. In that case removal-listener will be called with old value cause Size. ### invalidate ### invalidateAll(List:D @keys) ### invalidateAll Mark value/values for specified/all key/keys as invalidate. ``` $cache.invalidate(655360001); $cache.invalidateAll(<1 2 3>); $cahce.invalidateAll(); ``` The value will be removed and removal-listener will be called for each old values cause Explicit. ### elems Return keys and values stored in cache as Hash. ``` $cache.elems(); ``` ### hash Return keys and values stored in cache as Hash. ``` $cache.hash(); ``` This is a copy of values. Any modification of returned cache will no have an effect on values in the store. ### clean-up Clean evicted values from cache. ``` $cache.clean-up(); ``` This method may be invoked directly by user. The method invoked on each write operation and ones for several read operation if there was no write operation recently. It means that evicted values will not be removed on just in time of its eviction. This is done for the purpose of optimisation - is it not requires special thread for checking an eviction. If it is issue for you then you can call it method yourself by some scheduled Promise for example. ## Sources [GitHub](https://github.com/atroxaper/p6-Propius) ## Author Mikhail Khorkov [[email protected]](mailto:[email protected]) ## License See <LICENSE> file for the details of the license of the code in this repository.
## dist_cpan-RIBNOTTER-Text-Names.md Text::Names generates American English names. I wrote this project as a way of learning perl6 so the code may not be fully idiomatic perl6. # Usage ``` get-full() # generates a random name with a first name and last name get-full("male") # generates a random male full name get-full("female") # generates a random female full name get-male() # generates just a male first name get-female() # generates just a female first name get-last() # generates just a last name ``` You can significantly increase performance for large numbers of generated names by setting `$*buffer-size` to the number of names you plan on generating. By default, the file is reread every time a name is generated. `$*buffer-size` tells the library to fetch that many names at once from each file used. `$*buffer-size` will likely not significantly improve performance for small numbers of generated names. If you prefer enums to magic strings, you can use `male`, `female`, and `both` from the enum `Gender`. # Known Issues Performance is a bit rubbish. The current algorithm is slower than it needs to be. Some speed increases can be implemented likely by indexing the source file instead of reading though almost the entire name database every time a rare name is generated. Alternatively a heuristic could likely be used to allow greater leaps down the text file to find the target name quicker. In theory, the automatic tests could rarely fail just from drawing the same random name several times in a row. I have never seen this happen and is extremely unlikely. # Credit This module was written using the python ["names"](https://github.com/treyhunner/names) module heavily as reference. Ribbon-otter (me) copied the public domain source files as well as the basic algorithm from it. The names python project, at time of writing, lists their authors as * Trey Hunner <http://treyhunner.com> * Simeon Visser <http://simeonvisser.com>
## charsorbytes.md class X::Proc::Async::CharsOrBytes Error due to tapping the same Proc::Async stream for both text and binary reading ```raku class X::Proc::Async::CharsOrBytes is Exception {} ``` A [`Proc::Async`](/type/Proc/Async) object allows subscription to the output or error stream either for bytes ([`Blob`](/type/Blob)) or for text data ([`Str`](/type/Str)), but not for both. If you do try both, it throws an exception of type `X::Proc::Async::CharsOrBytes`. ```raku my $proc = Proc::Async.new('echo'); $proc.stdout.tap(&print); $proc.stdout(:bin).tap(&print); CATCH { default { put .^name, ': ', .Str } }; # OUTPUT: «X::Proc::Async::CharsOrBytes: Can only tap one of chars or bytes supply for stdout␤» ``` # [Methods](#class_X::Proc::Async::CharsOrBytes "go to top of document")[§](#Methods "direct link") ## [method handle](#class_X::Proc::Async::CharsOrBytes "go to top of document")[§](#method_handle "direct link") ```raku method handle(X::Proc::Async::CharsOrBytes:D: --> Str:D) ``` Returns the name of the handle that was accessed both for text and for binary data, `stdout` or `stderr`.
## dist_cpan-ARNE-Time-Repeat.md # NAME Time::Repeat - Modules for working with time intervals. # SYNOPSIS use Time::Repeat::String; # Work with text strings use Time::Repeat::HHMM; # Work with HHMM objects (hour and minutes), defined in the module use Time::Repeat::HHMM::Interval; # Work with intervals, based on HHMM objects use Time::Repeat::MM; # Work with MM objects (minutes), defined in the module use Time::Repeat::DateTime; # Work with DateTime objects # DESCRIPTION See the indvividual module documentation for a list of procedures and methods they provide. # AUTHOR Arne Sommer; arne at perl6.eu # COPYRIGHT AND LICENSE Copyright 2018-2019 Arne Sommer. This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## variable.md class Variable Object representation of a variable for use in traits ```raku class Variable {} ``` Variables have a wealth of compile-time information, but at runtime, accesses to a variable usually act on the value stored inside it, not the variable itself. The runtime class of a variable is [`Scalar`](/type/Scalar). Class `Variable` holds the compile-time information that traits can use to introspect and manipulate variables. # [Traits](#class_Variable "go to top of document")[§](#Traits "direct link") ## [trait is default](#class_Variable "go to top of document")[§](#trait_is_default "direct link") Sets the default value with which a variable is initialized, and to which it is reset when [`Nil`](/type/Nil) is assigned to it. Trait arguments are evaluated at compile time. Closures won't do what you expect: they are stored as is and need to be called by hand. ```raku my Int $x is default(42); say $x; # OUTPUT: «42␤» $x = 5; say $x; # OUTPUT: «5␤» # explicit reset: $x = Nil; say $x; # OUTPUT: «42␤» ``` The trait `is default` can be used also with subscripting things like arrays and hashes: ```raku my @array is default( 'N/A' ); @array[22].say; # OUTPUT: N/A @array = Nil; @array.say; # OUTPUT: [N/A] @array[4].say; # OUTPUT: N/A my %hash is default( 'no-value-here' ); %hash<non-existent-key>.say; # OUTPUT: no-value-here %hash<foo> = 'bar'; %hash<>.say; # OUTPUT: {foo => bar} %hash<wrong-key>.say; # OUTPUT: no-value-here ``` ## [trait is dynamic](#class_Variable "go to top of document")[§](#trait_is_dynamic "direct link") ```raku multi trait_mod:<is>(Variable:D, :$dynamic) ``` Marks a variable as dynamic, that is, accessible from inner dynamic scopes without being in an inner lexical scope. ```raku sub introspect() { say $CALLER::x; } my $x is dynamic = 23; introspect; # OUTPUT: «23␤» { # not dynamic my $x; introspect() # dies with an exception of X::Caller::NotDynamic } ``` The `is dynamic` trait is a rather cumbersome way of creating and accessing dynamic variables. A much easier way is to use the `* twigil`: ```raku sub introspect() { say $*x; } my $*x = 23; introspect; # OUTPUT: «23␤» { # not dynamic my $x; introspect() # dies with an exception of X::Dynamic::NotFound } ``` ## [trait of](#class_Variable "go to top of document")[§](#trait_of "direct link") ```raku multi trait_mod:<of>(Mu:U $target, Mu:U $type) ``` Sets the type constraint of a container bound to a variable. ```raku my $i of Int = 42; $i = "forty plus two"; CATCH { default { say .^name, ' ', .Str } } # OUTPUT: «X::TypeCheck::Assignment Type check failed in assignment to $i; expected Int but got Str ("forty plus two")␤» ``` You can use any value defined in compile time as a type constraint, including constants: ```raku constant \T = Int; my $i of T = 42; ``` which would be equivalent to the previous definition. # [Methods](#class_Variable "go to top of document")[§](#Methods "direct link") ## [method name](#class_Variable "go to top of document")[§](#method_name "direct link") ```raku method name(Variable:D: str) ``` Returns the name of the variable, including the sigil. # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link") Type relations for `Variable` raku-type-graph Variable Variable Any Any Variable->Any Mu Mu Any->Mu [Expand chart above](/assets/typegraphs/Variable.svg)
## dist_zef-FCO-Test-Describe.md [![Actions Status](https://github.com/FCO/Test-Describe/workflows/test/badge.svg)](https://github.com/FCO/Test-Describe/actions) # NAME Test::Describe - blah blah blah # SYNOPSIS ``` use Test::Describe; describe Int, { context "should have some methods", { define "is-prime-example", 42; define "a-code", 97; it "should have a working is-prime", -> :$described-class, :$is-prime-example { expect($described-class).to: have-method "is-prime"; expect($is-prime-example).to: be-false; } it "should have a working is-prime", -> :$described-class, :$a-code { expect($described-class).to: have-method "is-prime"; expect($a-code.chr).to: be-false; } } context "should work with math operators", { define "one-plus-one", { 1 + 1 }; it "sum", -> :&one-plus-one { expect(one-plus-one).to: be-eq 2 } } } ``` # DESCRIPTION Test::Describe is a RSpec like testing for Raku # AUTHOR ``` Fernando Correa de Oliveira <[email protected]> ``` # COPYRIGHT AND LICENSE Copyright 2021 This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-samgwise-Algorithm-Genetic.md # [Build Status](https://travis-ci.org/samgwise/p6-algorithm-genetic) NAME Algorithm::Genetic - A basic genetic algorithm implementation for Perl6! Use the Algorithm::Genetic distribution to implement your own evolutionary searches. This library was written primarily for learning so there likely are some rough edges. Feel to report any issues and contributions are welcome! # SYNOPSIS ``` use Algorithm::Genetic; use Algorithm::Genetic::Genotype; use Algorithm::Genetic::Selection::Roulette; my $target = 42; # First implement the is-finished method for our specific application. # Note that we compose in our selection behaviour of the Roulette role. class FindMeaning does Algorithm::Genetic does Algorithm::Genetic::Selection::Roulette { has int $.target; method is-finished() returns Bool { #say "Gen{ self.generation } - pop. size: { @!population.elems }"; self.population.tail[0].result == $!target; } } # Create our Genotype class Equation does Algorithm::Genetic::Genotype { our $eq-target = $target; our @options = 1, 9; # Note that we use the custom is mutable trait to provide a routine to mutate our attribute. has Int $.a is mutable( -> $v { (-1, 1).pick + $v } ) = @options.pick; has Int $.b is mutable( -> $v { (-1, 1).pick + $v } ) = @options.pick; method result() { $!a * $!b } # A scoring method is required for our genotype :) method !calc-score() returns Numeric { (self.result() - $eq-target) ** 2 } } # Instantiate our search my FindMeaning $ga .= new( :genotype(Equation.new) :mutation-probability(4/5) :$target ); # Go! $ga.evolve(:generations(1000), :size(16)); say "stopped at generation { $ga.generation } with result: { .a } x { .b } = { .result } and a score of { .score }" given $ga.population.tail[0]; ``` # DESCRIPTION Algorithm::Genetic distribution currently provides the following classes: * Algorithm::Genetic * Algorithm::Genetic::Crossoverable * Algorithm::Genetic::Genotype * Algorithm::Genetic::Selection * Algorithm::Genetic::Selection::Roulette # AUTHOR Sam Gillespie [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2016 Sam Gillespie This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. # Reference # NAME Algorithm::Genetic - A role for genetic algorithms. ``` unit role Algorithm::Genetic does Algorithm::Genetic::Selection ``` # METHODS ``` method new( Int:D :$population-size = 100, Rat:D :$crossover-probability = 7/10, Rat:D :$mutation-probability = 1/100, Algorithm::Genetic::Genotype :$genotype is required ) ``` Probability values are expected to be between 0 and 1. ### method generation ``` method generation() returns Int ``` Returns the current generation. Returns 0 if there have been no evolutions ### method population ``` method population() returns Seq ``` Returns a sequence of the current population. This may be an empty list if no calls to Evolve have been made. ### method evolve ``` method evolve( Int :$generations = 1, Int :$size = 1 ) returns Mu ``` Evolve our population. generations sets an upper limit of generations if the conditions in is-finished our not satisfied. Size is how many couples to pair each generation. ### method sort-population ``` method sort-population() returns Mu ``` Sort our population by score. The higher the score the better! (This is a private method but may not appear that way in the doc...) ### method is-finished ``` method is-finished() returns Bool ``` The termination condition for this algorithm. This must be implemented by an algorithm for assessing if we have achieved our goal. # NAME Algorithm::Genetic::Selection - A role for selection algorithms. ``` unit role Algorithm::Genetic::Selection; ``` # METHODS ### method selection-strategy ``` method selection-strategy( Int $selection = 2 ) returns Seq ``` The selection strategy for an algorithm. This method holds the logic for a selection strategy and must be implemented by consuming roles. The selection parameter specifies how many entities from our population to select. ### method population ``` method population() returns Seq ``` A method for accessing a population. We expect that all elements of the returned list will implement the score method as per Genotype. # NAME Algorithm::Genetic::Selection::Roulette - A role for roulette selection. ``` unit role Algorithm::Genetic::Selection::Roulette does Algorithm::Genetic::Selection; ``` # METHODS ### method selection-strategy ``` method selection-strategy( Int $selection = 2 ) returns Mu ``` implements roulette selection for a population provided by the population method. Roulette selection selects randomly from the population with a preference towards higher scoring individuals. # NAME Algorithm::Genetic::Genotype - A role for defining genotypes. ``` unit role Algorithm::Genetic::Genotype does Algorithm::Genetic::Crossoverable; ``` # METHODS ### method score ``` method score() returns Numeric ``` Score this genotype instance. The score will be calculated and cached on the first call. ### multi sub trait\_mod: ``` multi sub trait_mod:<is>( Attribute $attr, :$mutable! ) returns Mu ``` The is mutable trait attaches a mutation function to an attribute. the :mutable argument must be Callable. On mutation the mutator will be executed with the current value of the attribute. The return value of the mutator will be assigned to the attribute. ### method calc-score ``` method calc-score() returns Numeric ``` This method must be implemented by a consuming class. The calc-score method is called by score the score method. (This method is private but may not appear that way in the docs!) ### method new-random ``` method new-random() returns Algorithm::Genetic::Genotype ``` This method may be optionally overridden if the genotype has required values. new-random is called when construction the initial population for a Algorithm::Genetic implementing class. # NAME Algorithm::Genetic::Crossoverable - A role providing crossover behaviour of attribute values. ``` unit role Algorithm::Genetic::Crossoverable; ``` # METHODS ### method crossover ``` method crossover( Algorithm::Genetic::Crossoverable $other, Rat $ratio ) returns List ``` Crossover between this and another Crossoverable object. Use the ratio to manage where the crossover point will be. standard attribute types will be swapped by value and Arrays will be swapped recursively. Note that this process effectively duck types attributes so best to only crossover between instances of the same class!
## dist_zef-markldevine-MessageStream.md # MessageStream For modules that require multiple output destinations. Often times in elaborate scripts, you find that you need to report things to multiple destinations: TTY, logfile, etc. It would be handy to simply post the information once and have some controls at your disposal as to where it is distributed. MessageStream is a role that implements the necessary Supplier/Supply/tap incantations to provide a single message sending .post() in your class that can be acted on by multiple subscribers. Implement a receiver method, instantiate a MessageStream to a destination, then subscribe as many different receivers as necessary. You send a message (and any options you desire) with .post(). The resulting stream will convert your string and optional named arguments into a MessageStream::Message object. post() will marshal that into JSON on the emit-side, the tap block will unmarshal it, and your receiver(s) can unpack it in your class. In other words, you .post() and it all arrives intact and easy to unpack for all of your receivers. Once a message stream is instantiated, subscribe to it (run-time). If you want a particular destination to take a rest, unsubscribe from it. Repeat as desired. # SYNOPSIS See the example file. # AUTHOR Mark Devine [[email protected]](mailto:[email protected])
## dist_zef-jnthn-Dev-ContainerizedService.md # Dev::ContainerizedService This module aims to ease the process of setting up services (such as Postgres) for the purpose of having a local development environment for Raku projects. For example, one might have a Raku web application that uses a database. In order to try out the application locally, a database instance needs to be set up. Ideally this should be effortless and also isolated. As the name suggests, this module achieves its aims using containers. It depends on nothing more than Raku and having a functioning `docker` installation. ## Usage ### Getting Started Let's assume we have a web application that uses a Postgres database and expects that the `DB_CONN_INFO` environment variable will be populated with a connection string. To make a development environment configuration using this module, we create a script `devenv.raku`: ``` #!/usr/bin/env raku use Dev::ContainerizedService; service 'postgres', :tag<13.0>, -> (:$conninfo, *%) { env 'DB_CONN_INFO', $conninfo; } ``` The `service` function specifies the service ID, a Docker image tag, and a block that should be called when the service is up and running. The `env` function, located in a service, specifies an environment variable to be set. We can then (assuming `chmod +x devenv.raku`) use the script as follows: ``` ./devenv.raku run raku -Ilib service.raku ``` This will: 1. Pull the Postgres docker container if required 2. Run the container, setting up a database user/password and binding it to a free port 3. Run `raku -Ilib service.raku` with the `DB_CONN_INFO` environment variable set If using the `cro` development tool, one could do: ``` ./devenv.raku run cro run ``` ### Additional Actions The service block is run after the container is started (service implementations include readiness checks). As well as - or instead of - specifying environment variables to pass to the process, one can write any Raku code there. For example, one could run database migrations (in the case where it's desired to have them explicitly applied to production, rather than having them applied at application startup time). ### Retaining data By default, any created databases are not persisted once the `run` command is completed. To change this, alter the configuration file to specify a project name (the name of your application) and call `store`: ``` #!/usr/bin/env raku use Dev::ContainerizedService; project 'my-app'; store; service 'postgres', :tag<13.0>, -> (:$conninfo, *%) { env 'DB_CONN_INFO', $conninfo; } ``` Now when using `./devenv.raku run ...`, for services that support it, Docker volume(s) will be created and the generated password(s) for services will be saved (in your home directory). These will be reused on subsequent runs. To clean up this storage, use: ``` ./devenv.raku delete ``` Which will remove any created volumes along with saved settings. ### Showing produced configuration When using storage, it is also possible to see the most recently passed service settings for each service by using: ``` ./devenv.raku show ``` The output looks like this: ``` postgres conninfo: host=localhost port=29249 user=test password=xxlkC2MrOv4yJ3vP1V-pVI7 dbname=test dbname: test host: localhost password: xxlkC2MrOv4yJ3vP1V-pVI7 port: 29249 user: test ``` When used while `run` is active, this is handy for obtaining connection string information in order to connect to the database using tools of your choice. ### Tools Some service specifications also come with a way to run related tools. For example, the `postgres` specification can run the `psql` command line client (using the version in the container, to be sure of server compatibility), injecting the correct credentials. Thus: ``` ./devenv.raku tool postgres client ``` Is sufficient to launch the client to look at the database. Note that this only works when the service is running (so one would run it in one terminal window, and then use the tool subcommand in another). ### Multiple stores Calling: ``` store; ``` Is equivalent to calling: ``` store 'default'; ``` That is, it specifies the name of a default store. It is possible to have multiple independent stores, which are crated using the `--store` argument before the `run` subcommand: ``` ./devenv.raku --store=bug42 run cro run ``` To see the created stores, use: ``` ./devenv.raku stores ``` To show the produced service configuration for a particular store, use: ``` ./devenv.raku --store=bug42 show ``` To use a tool against a particular store, use: ``` ./devenv.raku --store=bug42 tool postgres client ``` To delete a particular store, rather than the default one, use: ``` ./devenv.raku --store=bug42 delete ``` ### Multiple instances of a given service One can have multiple instances of a given service. When doing this, it is wise to assign them names (otherwise names like `postgres-2` will be generated, and this will not be too informative in `show` output): ``` service 'postgres', :tag<13.0>, :name<pg-products> -> (:$conninfo, *%) { env 'PRODUCT_DB_CONN_INFO', $conninfo; } service 'postgres', :tag<13.0>, :name<pg-billing> -> (:$conninfo, *%) { env 'BILLING_DB_CONN_INFO', $conninfo; } ``` These names are used in the `tool` subcommand: ``` ./devenv.raku -tool pg-billing client ``` ### Custom images Sometimes you might not want to use the default docker images for a service; for exmaple, if doing Postgres with pgvector you might need an image with that extension installed instead. In that case, pass in `image-name`: ``` service 'postgres', :image-name<pgvector/pgvector>, :tag<0.8.0-pg17>, -> (:$conninfo, :$host, :$port, :$user, :$password, :$dbname) { ... } ``` ### Is this magic? Not really; the `Dev::ContainerizedService` module exports a `MAIN` sub, which is how it gets to provide the program entrypoint. ## Available Services ### Postgres Either obtain a connection string: ``` service 'postgres', :tag<13.0>, -> (:$conninfo, *%) { env 'DB_CONN_INFO', $conninfo; } ``` Or the individual parts of the database connection details: ``` service 'postgres', :tag<13.0>, -> (:$host, :$port, :$user, :$password, :$dbname, *%) { env 'DB_HOST', $host; env 'DB_PORT', $port; env 'DB_USER', $user; env 'DB_PASS', $password; env 'DB_NAME', $dbname; } ``` Postgres supports storage of the database between runs when `store` is used. The `client` tool is available, and runs the `psql` client: ``` ./devenv.raku tool postgres client ``` ### Redis Obtain the host and port of the started instance: ``` service 'redis', :tag<7.0>, -> (:$host, :$port) { env 'REDIS_HOST', $host; env 'REDIS_PORT', $port; } ``` Redis is currently always in-memory and will never be stored. ## The service I want isn't here! 1. Fork this repository. 2. Add a module `Dev::ContainerizedService::Spec::Foo`, and in it write a class of the same name that does `Dev::ContainerizedService::Spec`. See the role's documentation as well as other specs as an example. 3. Add a mapping to the `constant %specs` in `Dev::ContainerizedService`. 4. Write a test to make sure it works. 5. Add an example to the `README.md`. 6. Submit a pull request.
## dist_zef-knarkhov-Bitcoin-Core-Secp256k1.md # Raku binding to optimized C library for ECDSA Raku binding to optimized C library for ECDSA signatures and secret/public key operations on curve secp256k1. ## Synopsys ``` my $data = { key => '6fcc37ea5e9e09fec6c83e5fbd7a745e3eee81d16ebd861c9e66f55518c19798', msg => '1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8' }; my $secp256k1 = Bitcoin::Core::Secp256k1.new; my $signature = $secp256k1.ecdsa_sign(:privkey($data<key>), :msg($data<msg>)); $signature.gist.say; ``` ## Further work For now `Bitcoin::Core::Secp256k1` module does not cover full `secp256k1` API in C, so I'm working on this and will deliver complete binding ASAP. ## License Module `Bitcoin::Core::Secp256k1` is free and open source software, so you can redistribute it and/or modify it under the terms of the [The Artistic License 2.0](https://opensource.org/licenses/Artistic-2.0). ## Credits 1. <https://github.com/bitcoin-core/secp256k1> 2. `secp256k1` C API: <https://github.com/bitcoin-core/secp256k1/blob/master/include/secp256k1.h> ## Author Please contact me via [Matrix](https://matrix.to/#/@k.narkhov:matrix.org) or [LinkedIn](https://www.linkedin.com/in/knarkhov/). Your feedback is welcome at [narkhov.pro](https://narkhov.pro/contact-information.html).
## dist_github-pierre-vigier-HTTP-Signature.md # Perl6-HTTP-Signature [![Build Status](https://travis-ci.org/pierre-vigier/Perl6-HTTP-Signature.svg?branch=master)](https://travis-ci.org/pierre-vigier/Perl6-HTTP-Signature) ## SYNOPSIS ALPHA Implementation of http signature as defined in [IETFF draft version 3](http://tools.ietf.org/html/draft-cavage-http-signatures-03) Heavily inspired from [Authen::HTTP::Signature](https://github.com/mrallen1/Authen-HTTP-Signature) on perl5 *To sign a request:* ``` use HTTP::Signature; use HTTP::UserAgent; use HTTP::Request; my $req = HTTP::Request.new( :GET('http://www.example.com/path') ); my $signer = HTTP::Signature.new( keyid => 'Test', secret => 'MySuperSecretKey', algorithm => 'hmac-sha256', ); my $signed-request = $signer->sign-request( $req ); my $ua = HTTP::UserAgent.new; my $response = $ua.request( $signed-request ); ``` *To verify a request:* ``` use HTTP::Signature; my $signer = HTTP::Signature.new( secret => 'MySuperSecretKey', ); if $signer.verify-request( $req ) { ... } ``` ## DESCRIPTION
## dist_zef-jonathanstowe-Acme-Insult-Lala.md # Acme::Insult::Lala Construct an insulting epithet in the manner of an old IRC bot ![Build Status](https://github.com/jonathanstowe/Acme-Insult-Lala/workflows/CI/badge.svg) ## Synopsis ``` use Acme::Insult::Lala; my $lala = Acme::Insult::Lala.new; say $lala.generate-insult; ``` ## Description This makes an insulting epithet in the manner of 'lala' an IRC bot that used to be on the #london.pm channel back in the mists of time. I think I originally got the source data from an analysis of epithets in Shakespeare plays or something, but I can't actually remember it was that long ago. Anyhow at some point the lovely Simon Wistow retrieved the basic code and data and incorporated it in the Perl 5 module [Acme::Scurvy::Whoreson::BilgeRat::Backend::insultserver](http://search.cpan.org/~simonw/Acme-Scurvy-Whoreson-BilgeRat-Backend-insultserver-1.0/). From whence I retrieved the data and made it into a Raku module. There's also a handy script that does this for you without having to make any code: generate-insult [--number|-n=] I suppose you could use it for generating test data or something but there's nothing more to it than you see in the Synopsis. ## Installation Assuming you have a working Rakudo installation you should be able to do : ``` zef install Acme::Insult::Lala ``` ## Support If you don't like the language, don't use it. If you don't think it's insulting enough, write your own. In the unlikely event you should find a bug please report it at <https://github.com/jonathanstowe/Acme-Insult-Lala/issues> ## Licence and Copyright I guess the data in resources/lala.txt should properly be considered to be in the public domain as it's likely that it came from some such source in the first place. All the rest of the code is free software and licensed under the terms described in the <LICENCE> file. © Jonathan Stowe 2016 - 2023
## dist_zef-p6steve-Physics-Constants.md [![Build Status](https://app.travis-ci.com/p6steve/raku-Physics-Constants.svg?branch=master)](https://app.travis-ci.com/p6steve/raku-Physics-Constants) Bridging physical constants into [Physics::Measure](https://github.com/p6steve/raku-Physics-Measure) objects # SYNOPSIS ``` #!/usr/bin/env raku use Physics::Constants; #<== must use before Physics::Measure use Physics::Measure :ALL; say ~kg-amu; #6.02214076e+26 mol^-1 (avogadro number = Na) say ~plancks-h; #6.626070015e-34 J.s say ~faraday-constant; #96485.33212 C/mol say ~fine-structure-constant; #0.0072973525693 (dimensionless) say ~μ0; #1.25663706212e-06 H/m say ~ℏ; #1.054571817e-34 J.s my \λ = 2.5nm; say "Wavelength of photon (λ) is " ~λ; my \ν = c / λ; say "Frequency of photon (ν) is " ~ν.in('petahertz'); my \Ep = ℎ * ν; say "Energy of photon (Ep) is " ~Ep.in('attojoules'); #Wavelength of photon (λ) is 2.5 nm #Frequency of photon (ν) is 119.9169832 petahertz #Energy of photon (Ep) is 79.45783266707788 attojoules This module is a wrapper on JJ Merelo Math::Constants https://github.com/JJ/p6-math-constants #say '----------------'; #say @physics-constants; #say '----------------'; #say @physics-constants-names.sort; #say '----------------'; #say @physics-constants-abbreviations.sort; ```
## mkdir.md mkdir Combined from primary sources listed below. # [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_sub_mkdir "direct link") See primary documentation [in context](/type/independent-routines#sub_mkdir) for **sub mkdir**. ```raku sub mkdir(IO() $path, Int() $mode = 0o777 --> IO::Path:D) ``` Creates a new directory; see [`mode`](/routine/mode) for explanation and valid values for `$mode`. Returns the [`IO::Path`](/type/IO/Path) object pointing to the newly created directory on success; [fails](/routine/fail) with [`X::IO::Mkdir`](/type/X/IO/Mkdir) if directory cannot be created. Also creates parent directories, as needed (similar to \*nix utility `mkdir` with `-p` option); that is, `mkdir "foo/bar/ber/meow"` will create `foo`, `foo/bar`, and `foo/bar/ber` directories if they do not exist, as well as `foo/bar/ber/meow`. # [In IO::Path](#___top "go to top of document")[§](#(IO::Path)_method_mkdir "direct link") See primary documentation [in context](/type/IO/Path#method_mkdir) for **method mkdir**. ```raku method mkdir(IO::Path:D: Int() $mode = 0o777 --> IO::Path:D) ``` Creates a new directory, including its parent directories, as needed (similar to \*nix utility `mkdir` with `-p` option). That is, `mkdir "foo/bar/ber/meow"` will create `foo`, `foo/bar`, and `foo/bar/ber` directories as well if they do not exist. Returns the `IO::Path` object pointing to the newly created directory on success; [fails](/routine/fail) with [`X::IO::Mkdir`](/type/X/IO/Mkdir) if directory cannot be created. See also [`mode`](/routine/mode) for explanation and valid values for `$mode`.
## dist_zef-raku-community-modules-Digest-xxHash.md [![Actions Status](https://github.com/raku-community-modules/Digest-xxHash/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Digest-xxHash/actions) [![Actions Status](https://github.com/raku-community-modules/Digest-xxHash/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Digest-xxHash/actions) # NAME Digest::xxHash - xxHash bindings for Raku # SYNOPSIS ``` # 32 or 64 bit xxHash from a string say xxHash("dupa"); # 32 or 64 bit xxHash from a file say xxHash(:file<filename.txt>); # 32 or 64 bit xxHash from a file IO handle say xxHash(filehandle); # 32 or 64 bit xxHash from Buf say xxHash(Buf[uint8].new(0x64, 0x75, 0x70, 0x61)) # You may call the 32 or 64 bit specific versions directly if desired, # bypassing the architecture check. # 32 bit say xxHash32("dupa"); # 64 bit say xxHash64("dupa"); ``` # DESCRIPTION The Digest::xxHash distribution exports three subroutines: `xxHash`, `xxHash32` and `xxHash64`. The `xxHash` subroutine returns a 64 bit xxHash from a string (32 bit if no native 64 bit logic is available). The `xxHash32` and `xxHash64` subroutines return a 32 bit / 64 bit xxHash respectively (64 bit only if supported by architecture). Depends on the [libxxhash](https://github.com/Cyan4973/xxHash) native library. # AUTHORS * Bartłomiej Palmowski * Andy Weidenbaum * Steve Schulze # COPYRIGHT AND LICENSE Copyright 2013 - 2014 Bartłomiej Palmowski Copyright 2013 - 2023 Andy Weidenbaum Copyright 2024 Raku Community This is free and unencumbered public domain software. For more information, see <http://unlicense.org/> or the accompanying UNLICENSE file.
## indir.md indir Combined from primary sources listed below. # [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_sub_indir "direct link") See primary documentation [in context](/type/independent-routines#sub_indir) for **sub indir**. ```raku sub indir(IO() $path, &code, :$d = True, :$r, :$w, :$x) ``` Takes [`Callable`](/type/Callable) `&code` and executes it after locally (to `&code`) changing `$*CWD` variable to an [`IO::Path`](/type/IO/Path) object based on `$path`, optionally ensuring the new path passes several file tests. If `$path` is relative, it will be turned into an absolute path, even if an [`IO::Path`](/type/IO/Path) object was given. **NOTE:** that this routine does *NOT* alter the process's current directory (see [`&*chdir`](/routine/&*chdir)). The `$*CWD` outside of the `&code` is not affected, even if `&code` explicitly assigns a new value to `$*CWD`. Returns the value returned by the `&code` call on success. On failure to successfully change `$*CWD`, returns [`Failure`](/type/Failure). **WARNING:** keep in mind that lazily evaluated things might end up NOT having the `$*CWD` set by `indir` in their dynamic scope by the time they're actually evaluated. Either ensure the generators have their `$*CWD` set or [eagerly evaluate](/routine/eager) them before returning the results from `indir`: ```raku say indir("/tmp", { gather { take ".".IO } })».CWD; # OUTPUT: «(/home/camelia)␤» say indir("/tmp", { eager gather { take ".".IO } })».CWD; # OUTPUT: «(/tmp)␤» say indir("/tmp", { my $cwd = $*CWD; gather { temp $*CWD = $cwd; take ".".IO } })».CWD; # OUTPUT: «(/tmp)␤» ``` The routine's `$path` argument can be any object with an IO method that returns an [`IO::Path`](/type/IO/Path) object. The available file tests are: * `:d` — check [`.d`](/routine/d) returns `True` * `:r` — check [`.r`](/routine/d) returns `True` * `:w` — check [`.w`](/routine/d) returns `True` * `:x` — check [`.x`](/routine/d) returns `True` By default, only `:d` test is performed. ```raku say $*CWD; # OUTPUT: «"/home/camelia".IO␤» indir '/tmp', { say $*CWD }; # OUTPUT: «"/tmp".IO␤» say $*CWD; # OUTPUT: «"/home/camelia".IO␤» indir '/not-there', {;}; # returns Failure; path does not exist ```
## dist_zef-japhb-App-SerializerPerf.md [![Actions Status](https://github.com/japhb/App-SerializerPerf/workflows/test/badge.svg)](https://github.com/japhb/App-SerializerPerf/actions) # NAME serializer-perf - Performance tests for Raku data serializer codecs # SYNOPSIS ``` # SETUP METHOD 1: Installing into Raku module repository zef update zef install App::SerializerPerf serializer-perf --source=$HOME/.zef/store/360.zef.pm # SETUP METHOD 2: Running from a git clone, rather than installing git clone [email protected]:japhb/App-SerializerPerf.git cd App-SerializerPerf zef update zef install --deps-only . raku -I. bin/serializer-perf --source=$HOME/.zef/store/360.zef.pm # OPTIONS: --runs=<UInt> Runs per test (for stable results) [default: 1] --count=<UInt> Encodes/decodes per run (for sufficient duration) [default: 1] --source=<Path> Test file containing JSON data [default: fez-test.json] ``` # DESCRIPTION `serializer-perf` is a test suite of performance and correctness (fidelity) tests for Raku data serializer codecs. It is currently able to test the following codecs: | Codec | Format | Size | Speed | Fidelity | Human-Friendly | | --- | --- | --- | --- | --- | --- | | BSON::Document | BSON | Mixed | Poor | Poor | Poor | | BSON::Simple | BSON | Mixed | Fair | Fair | Poor | | CBOR::Simple | CBOR | BEST | BEST | Good | Poor | | JSON::Fast | JSON | Fair | Good | Fair | Good | | JSON::Hjson | JSON | \* | Poor | Fair | Good\* | | Data::MessagePack | MessagePack | Good | Mixed | Fair | Poor | | MessagePack | MessagePack | \* | Mixed | Poor | Poor\* | | TOML::Thumb | TOML | Poor | Mixed | Poor | Good | | TOML(tony-o) | TOML | Poor | Poor | Poor | Good | | Config::TOML | TOML | Poor | Poor | Poor | Good | | YAMLish | YAML | Poor | Poor | Fair | BEST | | .raku/EVAL | Raku | Poor | Poor | BEST | Fair | (Note: `JSON::Hjson` is a decoder *only*, and has no native encode ability. Thus performance and fidelity was tested against inputs in the JSON subset of Hjson, though of course the point of Hjson is to allow more human-friendly variation in data formatting -- similar to YAML in that respect. Similarly, `MessagePack` is a decoder only as well, with no native encode ability; it was tested with data packed by `Data::MessagePack`.) Because some of the tests are *very* slow, the default values for `--runs` and `--count` are both set to 1. If only testing the faster codecs (those with Speed of Fair or better in the table above), these will be too low; 5 runs and 100 count are more appropriate values in that case. # AUTHOR Geoffrey Broadwell [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2021-2023 Geoffrey Broadwell This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-raku-community-modules-overload-constant.md [![Actions Status](https://github.com/raku-community-modules/overload-constant/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/overload-constant/actions) [![Actions Status](https://github.com/raku-community-modules/overload-constant/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/overload-constant/actions) [![Actions Status](https://github.com/raku-community-modules/overload-constant/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/overload-constant/actions) # NAME overload::constant - Change stringification behaviour of literals # SYNOPSIS ``` use overload::constant; sub integer { "i$^a" } sub decimal { "d$^a" } sub radix { "r$^a" } sub numish { "n$^a" } use overload::constant &integer, &decimal, &radix, &numish; ok 42 ~~ Str && 42 eq 'i42', 'can overload integer'; ok 0.12 ~~ Str && 0.12 eq 'd0.12', 'can overload decimal'; ok .1e-003 ~~ Str && .1e-003 eq 'd.1e-003', 'can overload decimal in scientific notation'; ok :16<FF> ~~ Str && :16<FF> eq 'r:16<FF>', 'can overload radix'; ok NaN ~~ Str && NaN eq 'nNaN', 'can overload other numish things'; ``` # DESCRIPTION It is meant to work a bit like Perl's [overload::constant](https://perldoc.perl.org/overload#Overloading-Constants), though it is kind of pre-alpha here. # AUTHOR Tobias Leich # COPYRIGHT AND LICENSE Copyright 2014 - 2017 Tobias Leich Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-raku-community-modules-Date-WorkdayCalendar.md [![Actions Status](https://github.com/raku-community-modules/Date-WorkdayCalendar/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Date-WorkdayCalendar/actions) [![Actions Status](https://github.com/raku-community-modules/Date-WorkdayCalendar/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Date-WorkdayCalendar/actions) [![Actions Status](https://github.com/raku-community-modules/Date-WorkdayCalendar/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Date-WorkdayCalendar/actions) # NAME Date::WorkdayCalendar - Calendar and Date objects to handle business days, holidays and weekends # SYNOPSIS ``` use Date::WorkdayCalendar; # construct a default workday calendar my $calendar = WorkdayCalendar.new; # work out the next workday away from the given date # 2016-11-18 is a Friday $calendar.workdays-away(Date.new('2016-11-18'), 1); # 2016-11-21 # construct a workday calendar from a file my $calendar-from-file = WorkdayCalendar.new('days.cal'); # create a workdate from a date string my $workdate = Workdate.new('2016-05-02'); # create a workdate from a Date object my $date = Date.new('2016-11-18'); my $workdate-from-date = Workdate.new($date); # is the day a workday? $workdate = Workdate.new('2016-11-18'); $workdate.is-workday; # True $workdate.is-weekend; # False $workdate.is-holiday; # False ``` # DESCRIPTION The `WorkdayCalendar` and `Workdate` objects allow date calculations to be made on a calendar that considers workdays (also called "business days"). Built on top of the `Date` datatype, it uses a calendar file to specify how many days a workweek has and which days are to be considered holidays. By default, the workweek is composed of Monday, Tuesday, Wednesday, Thursday, and Friday. Saturday and Sunday form the weekend. Although most countries have a Monday to Friday workweek, some have very different ones. More information about workweeks can be found at <http://en.wikipedia.org/wiki/Workweek>. # INTRODUCTION The module provides two classes: `WorkdayCalendar` and `Workday`. Objects of these classes allow date calculations to be made on a calendar that takes workdays (also called "business days") into account. Built on top of the `Date` datatype, it uses a calendar file to specify how many days a workweek has and which days are to be considered holidays. By default, the *workweek* is composed by **Mon**, **Tue**, **Wed**, **Thu**, and **Fri**. **Sat** and **Sun** form the *weekend*. Alhough most countries have a workweek of **Mon** to **Fri**, some have very different ones. More information about workweeks can be found at <http://en.wikipedia.org/wiki/Workweek>. # CALENDAR FILE FORMAT ``` # An example calendar file W:Mon,Tue,Wed,Thu,Fri H:2011/01/01 H:2011-04-05 ``` This calendar specifies that **Mon** to **Fri** are to be considered workdays, and that 2011/01/01 and 2011/04/05 are national holidays. You can use `/` or `-` as separators in a date. The format of the date **must be** in the order Year, Month, Day. If the `W:` specification is incorrect, the default workweek (**Mon**, **Tue**, **Wed**, **Thu**, **Fri**) is used. If a holiday (a row starting with `H:`) is not well defined, it is ignored. Lines starting with `#` are comments and will be ignored when parsing the file. # WorkdayCalendar class ## method new ``` my $wdc1 = WorkdayCalendar.new; my $wdc2 = WorkdayCalendar.new('calendar.cal'); ``` Creates a new calendar. Optionally, accepts the name of a file using the calendar format specified above. If a filename is not specified, the calendar will have no holidays and a default workweek of **Mon**, **Tue**, **Wed**, **Thu**, **Fri**. ## method clear Empties the information for holidays and workdays, and resets the workweek to the default: **Mon**, **Tue**, **Wed**, **Thu**, **Fri**. ## method read(Str $calendar\_filename) Reads the data of holidays and workdays from a calendar file. ## method is-workday(Date $day) Returns `True` if the day is part of the workweek and not a holiday. ## method is-weekend(Date $day) Returns `True` if the day is not part of the workweek. ## method is-holiday(Date $day) Returns `True` if the day has been defined as holiday in the calendar file. ## method workdays-away(Date $start, Int $days) Returns a `Date` that corresponds to the workday at which `$days` working days have passed. With this method you can ask questions like: "what is the next working day for some date?" or "what is the previous working day of some date?" or "what date is 2 working days from a date?". Examples: Considering the workdays = **Mon Tue Wed Thu Fri**... ``` $start : July 29, 2011 (it is a Friday) $days : +1 Return Value : Aug 1, 2011 (it is a Monday) $start : July 30, 2011 (it is a Saturday) $days : +1 Return Value : Aug 1, 2011 (it is a Monday) ``` This also works for a negative number of days. ## method workdays-to(Date $start, Date $target) Returns the 'distance', in workdays, of `$start` and `$target` dates. ## method networkdays(Date $start, Date $target) Works like the `workdays-to` method, but emulates the NETWORKDAYS function in Microsoft Excel. Examples: ``` Start Target workdays-to networkdays 2011-07-07 2011-07-14 5 6 2011-07-07 2011-07-07 0 1 2011-07-07 2011-07-08 1 2 2011-07-07 2011-07-01 -4 -5 2011-01-01 2011-01-01 0 0 2011-01-01 2011-01-02 0 0 2011-01-01 2011-01-03 1 1 ``` ## method range(Date $start, Date $end) Returns a part of a calendar as a new `WorkdayCalendar` object, between the `$start` and `$end` dates, inclusive. For example, if you have a calendar that contains holiday information for 3 years, you can use `range` to obtain a new calendar that covers a period of 6 months of these 3 years. Useful with the `eq` operator for `WorkdayCalendar` objects. ## method raku Returns a string representing the contents of the `WorkdayCalendar` attributes. # `Workdate` class Implemented as a subclass of `Date`. It replaces `Date`'s `.succ` and `.pred` methods to take workdays into account and provides the functionality to perform basic workdate calculations. You can specify a previously created `WorkdayCalendar` object as a parameter, or none at all. If a `WorkdayCalendar` is not specified, it uses a default workweek of **Mon** , **Tue**, **Wed**, **Thu**, **Fri** and no holidays. Example: ``` # July 1st of 2011 is a Friday my $wdate = Workdate.new(year=>2011, month=>07, day=>01); #--- Uses a default calendar with #--- default workweek and no holidays my $next_day = $wdate.succ; # $next_day is Monday, July 4, 2011 ``` Another example: ``` my $CAL = WorkdayCalendar.new('example.cal'); # Some calendar file with 2011-Feb-2 as holiday my $date = Workdate.new(year=>2011, month=>02, day=>01, calendar=>$CAL); # February 1 of 2011 is a Tuesday my $next_day = $date.succ; # $next_day is Thursday, February 3, 2011 ``` ## method new ``` my $wd1 = Workdate.new(year=>2000, month=>12, day=>01, calendar=>$aWorkdayCalendar); my $wd2 = Workdate.new(2000, 12, 01, $aWorkdayCalendar); my $wd3 = Workdate.new($aDateString, $aWorkdayCalendar); my $wd4 = Workdate.new($aDateTimeObject, $aWorkdayCalendar); my $wd4 = Workdate.new($aDateObject, $aWorkdayCalendar); ``` We try to provide the same constructors as the base `Date` class, plus another to create `Workdate`s from regular `Date`s. Thus, we can create a `Workdate` in 4 different ways, from named and positional parameters, and by using a `Date` or a `DateTime` object for specifying the date. In all cases, the calendar is optional, and if it is not specified a default calendar will be applied to the new `Workdate`. ## method succ Returns the next workdate. ## method pred Returns the previous workdate. ## method is-workday Returns True if the workdate is not a holiday and is not part of the weekend. ## method is-weekend Returns True if the workdate is not part of the workweek. ## method is-holiday Returns True if the workdate is reported as a holiday. ## method workdays-away(Int $days) Returns the workdate that is `$days` workdays from the given workdate. ## method workdays-to(Date $target) Return the number of workdays until `$target`. ## method raku Returns a string representing the contents of the `Workdate` attributes. # OPERATORS ## Comparison: eq Compares two calendars and returns True if they are equivalent. For that, they must have the same holidays and the same workweek. For instance, this would be as if they used the same calendar file. You can use the `range` method for `WorkdayCalendar` objects to compare smaller periods of time instead of a whole `WorkdayCalendar`. ## Comparison: ne Returns the opposite of `eq`. ## Arithmetic: infix - Returns the difference, in workdays, between `$wd1` and `$wd2`. # AUTHOR Shinobi # COPYRIGHT AND LICENSE Copyright 2012 - 2013 Shinobi Copyright 2014 - 2022 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-FCO-CRDT.md [![Actions Status](https://github.com/FCO/CRDT/workflows/test/badge.svg)](https://github.com/FCO/CRDT/actions) # NAME CRDT - Conflict-free Replicated Data Type # SYNOPSIS ``` use G-Counter; use PN-Counter; use G-Set; use P2-Set; use LWW-Element-Set; use OR-Set; use LWW-Register; ``` # DESCRIPTION CRDT is <https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type> # AUTHOR Fernando Correa [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2020 Fernando Correa This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-ulisesb-RKDS.md # RKDS RKDS (RaKu Deployment System) is a tool that takes a directory filled with [ERK](https://raku.land/zef:ulisesb/ERK) templates and *deploys* them to another directory. Supports including raku modules defined in a `.rkds/lib` directory and customizing the deployment of templates individually. ## Example Say you have these directories and files: * input-dir/ * .rkds/ * lib/ * MyMod.rakumod * template1 * template2 * output-dir/ Inside `input-dir/.rkds/lib/MyMod.rakumod`: ``` unit module MyMod; sub squared(\n) is export { n ** 2 } constant $fav-number is export = 42; ``` Inside `input-dir/template1`: ``` Welcome to the first template. <%- use RKDS -%> This was deployed to <%= get-output-dir %> <%- use MyMod -%> The square of my favorite number is <%= squared($fav-number) %> :) ``` Inside `input-dir/template2`: ``` Second template! I’m not so sure about this one... <% use RKDS; don't-deploy %> This will be executed though: <% note "hello!" %> ``` Running `rkds input-dir output-dir` will output this: ``` rkds: template1: executing rkds: template1: deploying rkds: template2: executing template2: hello! rkds: template2: not deploying ``` and create the file output-dir/template1 like so: ``` Welcome to the first template. This was deployed to /path/to/output-dir The square of my favorite number is 1764 :) ``` For more information, see `lib/RKDS.rakumod` and `bin/rkds`.
## dist_zef-jjatria-PublicSuffix.md ## NAME PublicSuffix - Query Mozilla's Public Suffix List ## SYNOPSIS ``` use PublicSuffix; # The effective TLD of a host name say public-suffix 'www.example.com'; # OUTPUT: com # New TLDs are valid public suffix by default say public-suffix 'www.example.unknownnewtld'; # OUTPUT: unknownnewtld # Accept host names in Unicode say public-suffix 'www.example.香港'; # OUTPUT: 香港 # Accept host names in punycode say public-suffix 'www.example.xn--j6w193g'; # OUTPUT: xn--j6w193g # Shortest domain that can be registered say registrable-domain 'www.example.com'; # OUTPUT: example.com # Returns a type object if registrable domain is not found say registrable-domain 'com'; # OUTPUT: (Str) ``` ## DESCRIPTION This module provides functions to query Mozilla's [Public Suffix List](http://publicsuffix.org): a community-maintained list of domain name suffixes. The data in this list can be used to determine the effective top-level domain of a host name, or to test whether two hosts share an origin, as well as other similar validation functions. This most commonly used when validating the scope of HTTP cookies to prevent [supercookies](https://en.wikipedia.org/wiki/Supercookie), but it has [a variety of other uses](https://publicsuffix.org/learn). ## FUNCTIONS ### Host name validation The functions described below take host names as their parameter, and run some validation on their input before processing. When given a malformed or otherwise invalid host name, the functions below will throw a X::PublicSuffix::BadDomain exception with the reason for the failure as its `message`. For a domain to be valid, it must be a non-empty string, with a maximum length of 253 octets, and no more than 63 octets per label. Domains can be provided as either UTF-8 strings or their ASCII punycoded variants. The returned strings will use the format of the strings provided. In other words, if you provide a UTF-8 string, you will receive a UTF-8 string back, while giving an ASCII string will generate an ASCII string in return. Providing partially punycoded strings is not supported, and the behaviour of these functions with that input is undefined. ### public-suffix ``` sub public-suffix ( Str $host ) returns Str ``` Takes a host name as a Str and returns the [public suffix](https://url.spec.whatwg.org/#host-public-suffix) for that host, or the type object if no public-suffix is found or if the host is the string representation of a IPv4 or IPv6 address. This function will throw a X::PublicSuffix::BadDomain exception if the host name is not valid. According to [§ 3.2 of the URL living standard](https://url.spec.whatwg.org/#host-miscellaneous), the public suffix is "the portion of a host which is included on the Public Suffix List". ### registrable-domain ``` sub registrable-domain ( Str $host ) returns Str ``` Takes a host name as a Str and returns the [registrable domain](https://url.spec.whatwg.org/#host-registrable-domain) for that host, or the type object if no registrable domain is found or if the host is the string representation of a IPv4 or IPv6 address. This function will throw a X::PublicSuffix::BadDomain exception if the host name is not valid. According to [§ 3.2 of the URL living standard](https://url.spec.whatwg.org/#host-miscellaneous), the registrable domain of a host is "the most specific public suffix, along with the domain label immediately preceding it, if any". ## AUTHOR José Joaquín Atria [[email protected]](mailto:[email protected]) ## ACKNOWLEDGEMENTS The code in this distribution takes inspiration from a number of similar Perl libraries. In particular: * [Mozilla::PublicSuffix](https://metacpan.org/pod/Mozilla::PublicSuffix) * [IO::Socket::SSL::PublicSuffix](https://metacpan.org/pod/IO::Socket::SSL::PublicSuffix) In addition to the distributions mentioned above, the API was mostly inspired by the [publicsuffixlist](https://pypi.org/project/publicsuffixlist) Python module by ko-zu. This module owes a debt of gratitude to their authors and those who have contributed to them, and to their choice to make their code and work publicly available. ## COPYRIGHT AND LICENSE Copyright 2022 José Joaquín Atria This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## hash.md Hash Combined from primary sources listed below. # [In Any](#___top "go to top of document")[§](#(Any)_method_Hash "direct link") See primary documentation [in context](/type/Any#method_Hash) for **method Hash**. ```raku multi method Hash( --> Hash:D) ``` Coerces the invocant to [`Hash`](/type/Hash). # [In role QuantHash](#___top "go to top of document")[§](#(role_QuantHash)_method_Hash "direct link") See primary documentation [in context](/type/QuantHash#method_Hash) for **method Hash**. ```raku method Hash() ``` Coerces the `QuantHash` object to a [`Hash`](/type/Hash) (by stringifying the objects for the keys) without any limitations on the values, and returns that.
## dist_zef-titsuki-Terminal-Getpass.md [![Actions Status](https://github.com/titsuki/raku-Terminal-Getpass/workflows/test/badge.svg)](https://github.com/titsuki/raku-Terminal-Getpass/actions) # NAME Terminal::Getpass - A getpass implementation for Raku # SYNOPSIS ``` use Terminal::Getpass; my $password = getpass; say $password; ``` # DESCRIPTION Terminal::Getpass is a getpass implementation for Raku. ## METHODS ### getpass Defined as: ``` sub getpass(Str $prompt = "Password: ", IO::Handle $stream = $*ERR --> Str) is export ``` Reads password from a command line secretly and returns the text. # AUTHOR Itsuki Toyota [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2018 Itsuki Toyota This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-tbrowder-PDF-NameTags.md [![Actions Status](https://github.com/tbrowder/PDF-NameTags/actions/workflows/linux.yml/badge.svg)](https://github.com/tbrowder/PDF-NameTags/actions) [![Actions Status](https://github.com/tbrowder/PDF-NameTags/actions/workflows/macos.yml/badge.svg)](https://github.com/tbrowder/PDF-NameTags/actions) [![Actions Status](https://github.com/tbrowder/PDF-NameTags/actions/workflows/windows.yml/badge.svg)](https://github.com/tbrowder/PDF-NameTags/actions) # NAME **PDF::NameTags** - Provides a Raku program to create name tags on a PDF document: eight per two-sided page # SYNOPSIS ``` $ ./make-name-tags # OUTPUT Usage: make-name-tags go | <csv file> [...options...] Given a list of names, writes them on reversible paper for a two-sided name tag on Letter paper. The front side of the first two-sided page will contain job details (and the back side will be blank). Options: 1|2 - Select option 1 (original method) or 2 (XForm object method), default: 1. show - Gives details of the job based on the input name list and card dimension parameters, then exits. The information is the same as on the printed job cover sheet. p=N - For printer N. See list by number, default: 1 (Tom's HP) ptest - Create a printer test page for the selected printer. media=X - Where X is Letter or A4, default: Letter ``` # DESCRIPTION **PDF::NameTags** is a **work in progress (WIP)**, but it **can** be used to create name tags. See the '/examples/GBUMC' directory for all the pieces needed for creating a set of two-sided name tags for a local church. They can be modified as needed to suit your situation. # TODO A more generic example will be created following the GBUMC example, but without the elaborate overlay or the awkward name listing format used for GBUMC (first middle last). The generic method should require only: 1. A text file with each line consisting of a list of the name of one person: LAST FIRST. If a person goes by two familiar names such as 'Mary Ann', then you will put both names following the LAST name, for example: 'Brown Mary Ann'. Names may be space or comma delimited (or both). 2. A job entry text file with entries describing various features required such as media format (Letter or A4); width and length of the total badge area; and upper border color, content, and dimensions. Any prospective user is encouraged to file appropriate issues concerning the future of this module. # AUTHOR Tom Browder [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE © 2024 Tom Browder This library is free software; you may redistribute it or modify it under the Artistic License 2.0.
## dist_zef-jjmerelo-Pod-Utils.md # NAME [Test-install distro](https://github.com/JJ/raku-pod-utils/actions/workflows/test.yaml) Pod::Utils - Set of helper functions to ease working with Pods! # SYNOPSIS ``` use Pod::Utils; # time to work with Pod::* elements! say first-subtitle($=pod[0].contents); =begin pod =SUBTITLE Some cool text =end pod ``` # DESCRIPTION Pod::Utils is a set of routines that help you to deal with Pod elements. It lets you manipulate several kinds of Pod objects, obtain gists and modify headings. ### sub first-code-block ``` sub first-code-block ( Array @pod ) returns Str; ``` Returns the first `Pod::Block::Code` found in an array, concatenating all lines in it. If none is found, it will return an empty string. Example: ``` =begin pod =begin code say "some code"; say "more code"; =end code =end pod first-code-block($=pod[0].contents) # OUTPUT «say "some code";␤say "more code";␤» ``` ### sub first-title ``` sub first-title ( Array @pod ) returns Pod::Block::Named; ``` Returns the first `=TITLE` element found in `@pods`. Example: ``` =begin pod =TITLE title =end pod first-title($=pod[0].contents) # OUTPUT equivalent to: =TITLE title ``` ### sub first-subtitle ``` sub first-subtitle ( Array @pod ) returns Pod::Block::Named; ``` Returns the first `=SUBTITLE` element found in `@pods`. Example: ``` =begin pod =subTITLE subtitle =end pod first-subtitle($=pod[0].contents) # OUTPUT equivalent to: =SUBTITLE subtitle ``` ### multi sub textify-guts ``` multi textify-guts (Any:U, ) return Str; multi textify-guts (Str:D \v) return Str; multi textify-guts (List:D \v) return Str; multi textify-guts (Pod::Block \v) return Str; ``` Converts lists of `Pod::Block::*` objects and `Pod::Block` objects to strings. Example: ``` my $block = Pod::Block::Para.new(contents => ["block"]); say textify-guts($block); # OUTPUT «block␤» say textify-guts([$block, $block]); # OUTPUT «block block␤» ``` ### multi sub recurse-until-str ``` multi sub recurse-until-str(Str:D $s) return Str; multi sub recurse-until-str(Pod::Block $n) return Str; ``` Accepts a `Pod::Block::*` object and returns a concatenation of all subpods content. Example: ``` my $block = Pod::Block::Para.new(contents => ["block"]); my $complex-block = pod-block("one", pod-block("two"), pod-bold("three")); say recurse-until-str($block); # OUTPUT «block␤» say recurse-until-str($complex-block); # OUTPUT «onetwothree␤» ``` # Pod::Utils::Build # SYNOPSIS ``` use Pod::Utils::Build; # time to build Pod::* elements! say pod-bold("bold text"); ``` # DESCRIPTION Pod::Utils::Build is a set of routines that help you to create new Pod elements. ### sub pod-title ``` sub pod-title ( Str $title, ) returns Pod::Block::Named; ``` Creates a new `Pod::Block::Named` object (with `:name` set to `"TITLE"`) and populates it with a `Pod::Block::Para` containing `$title`. Example: ``` pod-title("title"); # OUTPUT Equivalent to: =begind pod =TITLE title =end pod ``` ### sub pod-with-title ``` sub pod-with-title ( Str $title, Array @blocks ) returns Pod::Block::Named; ``` Creates a new `Pod::Block::Named` object (with `:name` set to "pod") and populate it with a title (using `pod-title`) and `@blocks`. Example: ``` =begind pod Normal paragraph =end pod pod-with-title("title", $=pod.first.contents[0]); # OUTPUT Equivalent to: =beging pod =TITLE title Normal paragraph =end pod ``` ### sub pod-block ``` sub pod-block ( Array *@contents ) returns Pod::Block::Para; ``` Creates a `Pod::Block::Para` with contents set to `@contents`. Example: ``` say pod-block("title", Pod::Block::Para.new(contents => ["paragraph"])); # OUTPUT Pod::Block::Para title Pod::Block::Para paragraph ``` ### sub pod-link ``` sub pod-link ( Str $text, Str $url ) returns Pod::FormattingCode; ``` Creates a `Pod::FormattingCode` (type Link) with contents set to `$text`. and meta set to `$url`. Example: ``` pod-link("text","url"); # OUTPUT Equivalent to: L<text|url> ``` ### sub pod-bold ``` sub pod-bold ( Str $text, ) returns Pod::FormattingCode; ``` Creates a `Pod::FormattingCode` (type B) with contents set to `$text`. Example: ``` pod-bold("text"); # OUTPUT Equivalent to: B<text> ``` ### sub pod-code ``` sub pod-code ( Str $text, ) returns Pod::FormattingCode; ``` Creates a `Pod::FormattingCode` (type C) with contents set to `$text`. Example: ``` pod-code("text"); # OUTPUT Equivalent to: C<text> ``` ### sub pod-item ``` sub pod-item ( Array *@contents , Int :$level = 1, ) returns Pod::Item; ``` Creates a `Pod::Item` object with contents set to `@contents` and level to `$level`. Example: ``` pod-item(pod-block("item"), level => 1); # OUTPUT Equivalent to: =item item ``` ### sub pod-heading ``` sub pod-heading ( Str $name, Int :$level = 1, ) returns Pod::Heading; ``` Creates a `Pod::Heading` object with level set `$level` and contents initialized with a `Pod::Block::Para` object containing `$name`. Example: ``` pod-heading("heading", level => 1); # OUTPUT Equivalent to: =head1 heading ``` ### sub pod-table ``` sub pod-table ( Array @contents, Array :@headers, ) returns Pod::Block::Table; ``` Creates a `Pod::Block::Table` object with the headers `@headers` and rows `@contents`. `$caption` is set to `""`. Example: ``` pod-table([["col1", "col2"],], headers => ["h1", "h2"]); # OUTPUT Equivalent to: =begin table h1 | h2 ============ col1 | col2 =end table ``` ### sub pod-lower-headings ``` sub pod-lower-headings ( Array @content, Int :$to, ) returns Array; ``` Given an array of Pod objects, lower the level of every heading following the next formula => `current-level - $by + $to`, where `$by` is the level of the first heading found in the array. Example: ``` my @contents = [ pod-heading("head", level => 2), pod-heading("head", level => 3) ]; pod-lower-headings(@contents) # OUTPUT Equivalent to: =head1 head =head2 head ``` # AUTHORS Alexander Mouquin <@Mouq> Will Coleda <@coke> Rob Hoelz <@hoelzro> <@timo> Moritz Lenz <@moritz> Juan Julián <@JJ> <@MasterDuke17> Zoffix Znet <@zoffixznet> Antonio <@antoniogamiz> # COPYRIGHT AND LICENSE Copyright 2019 Perl 6 team This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_github-salortiz-NativeLibs.md # NativeLibs The simple use in your module is: ``` use NativeLibs; # This also re-exports NativeCall :DEFAULTS for convenience my $Lib; # To keep the reference sub some_native_func() is native { * } # Note no library needed … The rest of your module INIT { # Load the needed library without $Lib = NativeLibs::Loader.load('libsomelib.so.4') { .fail; } } … ``` If in your native library binding you need to support a range of versions: ``` use NativeLibs; constant LIB = NativeLibs::Searcher.at-runtime( 'mysqlclient', # The library short name 'mysql_init', # A 'well known symbol' 16..20 # A List of supported versions, a range in this example ); sub mysql_get_client_info(--> Str) is export is native(LIB) { * } ... ``` This is a grow-up version of the original NativeLibs (v0.0.3) included in DBIish now released to allow the interested people the testing and discussion of the module. So, if you use this in your own module, please use with a version, for example: ``` use NativeLibs:ver<0.0.5>; ``` and include `"NativeLibs:ver<0.0.5+>"` in your META6's depends Other examples in the drivers of <https://github.com/perl6/DBIish>
## dist_zef-lizmat-Sub-Memoized.md [![Actions Status](https://github.com/lizmat/Sub-Memoized/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/Sub-Memoized/actions) [![Actions Status](https://github.com/lizmat/Sub-Memoized/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/Sub-Memoized/actions) [![Actions Status](https://github.com/lizmat/Sub-Memoized/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/Sub-Memoized/actions) # NAME Sub::Memoized - trait for memoizing calls to subroutines # SYNOPSIS ``` use Sub::Memoized; sub a($a,$b) is memoized { # do some expensive calculation } sub b($a, $b) is memoized( my %cache ) { # do some expensive calculation with direct access to cache } use Hash::LRU; sub c($a, $b) is memoized( my %cache is LRU( elements => 2048 ) ) { # do some expensive calculation, keep last 2048 results returned } sub d(Int:D $a, Int:D $b) is memoized({ "$_[0],$_[1]" }) { # do some expensive calculation with cheaper key maker } sub e(Str:D $a, Str:D $b) is memoized(my %cache, *.list.sort.join("'")) { # do some expensive calculation with direct access to cache # without making the order of the arguments matter } ``` # DESCRIPTION The `Sub::Memoized` distribution provides a `is memoized` trait on `Sub`routines as an easy way to cache calculations made by that subroutine (assuming a given set of input parameters will always produce the same result). Optionally, one can specify an `Associative` that will serve as the cache. This allows later access to the generated results. Or you can specify a specially crafted hash, such as one made with [`Hash::LRU`](https://raku.land/zef:lizmat/Hash::LRU). # IDENTIFICATION KEY By default, the identification key used to lookup values in the cache, is built from the `.WHICH` values of **all** the arguments passed to the subroutine. This may not always be the fastest or best way to do this. Therefore one can specify a `Callable` that will be called to generate the identification key, bypassing the default key maker. This can e.g. be used to create a more efficient key generator, or can be used to create a key generator with special properties, e.g. making the arguments commutative. This `Callable` will be given a `Capture` and is expected to return something that can be used as a key in the `Associative` that has been (implicitely) specified (usually a string). # CAVEAT Please note that if you do **not** use a store that is thread-safe, the memoization will **not** be thread-safe either. This is the default. # SEE ALSO The experimental [`is cached`](https://docs.raku.org/routine/is%20cached) trait provides similar but more limited functionality. # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/Sub-Memoized> . 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, 2024, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_cpan-BDUGGAN-Repl-Tools.md ## Name Repl::Tools -- Some simple tools to accompany Raku's built-in repl statement. ## Description These are some simple tools to improve the experience of using the built-in `repl` to debug a raku program. Currently, there are two tools: * `w` : show information about the current file and stack. * `qq` : quit the repl and also exit the current process ## Example Write a program that calls `repl` at some point: ``` use Repl::Tools; sub hello { world; } sub world { my $x = 10; say "x is $x"; repl; } hello; ``` Then, run the program, and type `w` to see where you are. ``` $ raku eg/hello.raku x is 10 Type 'exit' to leave > w --- current stack --- in sub world at eg/hello.raku line 12 in sub hello at eg/hello.raku line 6 -- current file (eg/hello.raku) -- 3 | use Repl::Tools; 4 | 5 | sub hello { 6 | world; 7 | } 8 | 9 | sub world { 10 | my $x = 10; 11 | say "x is $x"; 12 > repl; 13 | } 14 | 15 | hello; 16 | ``` That's it! ## Author Brian Duggan (bduggan at matatu.org)
## unival.md unival Combined from primary sources listed below. # [In Str](#___top "go to top of document")[§](#(Str)_method_unival "direct link") See primary documentation [in context](/type/Str#method_unival) for **method unival**. ```raku multi method unival(Str:D: --> Numeric) ``` Returns the numeric value that the first codepoint in the invocant represents, or `NaN` if it's not numeric. ```raku say '4'.unival; # OUTPUT: «4␤» say '¾'.unival; # OUTPUT: «0.75␤» say 'a'.unival; # OUTPUT: «NaN␤» ``` # [In Int](#___top "go to top of document")[§](#(Int)_routine_unival "direct link") See primary documentation [in context](/type/Int#routine_unival) for **routine unival**. ```raku multi unival(Int:D --> Numeric) multi method unival(Int:D: --> Numeric) ``` Returns the number represented by the Unicode codepoint with the given integer number, or [NaN](/type/Num#NaN) if it does not represent a number. ```raku say ord("¾").unival; # OUTPUT: «0.75␤» say 190.unival; # OUTPUT: «0.75␤» say unival(65); # OUTPUT: «NaN␤» ```
## dist_cpan-GARLANDG-NativeHelpers-iovec.md # NAME NativeHelpers::iovec - An implementation of the iovec struct # SYNOPSIS ``` use NativeHelpers::iovec; my iovec $iov .= new("Hello World"); say $iov.elems; # 11 ``` # DESCRIPTION NativeHelpers::iovec is an implementation of the iovec struct. It supports creating iovecs from Blob and Str objects, or from a Pointer and a number of bytes. # METHODS ## elems Returns the size of the buffer in bytes ## base Returns a void Pointer to the start of the memory buffer ## free Frees the allocated memory ## Blob Returns a new Blob with a copy of the memory buffer ## Str(:$enc = 'utf-8') Returns a new Str containing the decoded memory buffer ## new(Str, :$enc = 'utf-8') Create a new iovec containing the encoded string ## new(Blob) Create a new iovec containing the contents of the Blob ## new(Pointer:D, Int:D) Create a new iovec with the given Pointer and size # AUTHOR Travis Gibson [[email protected]](mailto:[email protected]) # COPYRIGHT AND LICENSE Copyright 2020 Travis Gibson This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-lizmat-App-IRC-Log.md [![Actions Status](https://github.com/lizmat/App-IRC-Log/workflows/test/badge.svg)](https://github.com/lizmat/App-IRC-Log/actions) # NAME App::IRC::Log - Cro application for presenting IRC logs # SYNOPSIS ``` use App::IRC::Log; my $ail := App::IRC::Log.new: :$channel-class, # IRC::Channel::Log compatible class :$log-class, # IRC::Log compatible class :$log-dir, :$rendered-dir, :$state-dir, :$static-dir, :$template-dir, :$zip-dir, colorize-nick => &colorize-nick, htmlize => &htmlize, special-entry => &special-entry, channels => @channels, live-plugins => live-plugins(), day-plugins => day-plugins(), search-plugins => search-plugins(), gist-plugins => gist-plugins(), scrollup-plugins => scrollup-plugins(), scrolldown-plugins => scrolldown-plugins(), descriptions => %descriptions, one-liners => %one-liners, highlight-before => "<strong>", highlight-after => "</strong>", ; my $service := Cro::HTTP::Server.new: :application($ail.application), :$host, :$port, ; $service.start; react whenever signal(SIGINT) { $service.stop; $ail.shutdown; exit; } ``` # DESCRIPTION App::IRC::Log is a class for implementing an application to show IRC logs. It is still heavily under development and may change its interface at any time. It is currently being used to set up a website for showing the historical IRC logs of the development of the Raku Programming Language (see `App::Raku::Log`). # AUTHOR Elizabeth Mattijsen [[email protected]](mailto:[email protected]) Source can be located at: <https://github.com/lizmat/App-IRC-Log> . Comments and Pull Requests are welcome. # COPYRIGHT AND LICENSE Copyright 2021 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-raku-community-modules-Grammar-Common.md [![Actions Status](https://github.com/raku-community-modules/Grammar-Common/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/Grammar-Common/actions) # NAME Grammar::Common - Common bits for grammars, such as math expressions # SYNOPSIS ``` use Grammar::Common; # load all modules: # Grammar::Common::Text # Grammar::Common::Expression::Prefix # Grammar::Common::Expression::Prefix::Actions # Grammar::Common::Expression::Infix # Grammar::Common::Expression::Infix::Actions grammar PostScript does Grammar::Common::Expression::Prefix { token value { <[ - + ]>? <[ 0 .. 9 ]>+ } rule TOP { 'dup' <expression> } } say PostScript.parse( 'dup + 1 3' ); # 「dup + 1 3」 # expression => 「+ 1 3」 # operation => 「+ 1 3」 # plus-symbol => 「+」 # lhs => 「1 」 # value => 「1」 # expression => 「1 」 # value => 「1」 # expression => 「3」 # value => 「3」 # rhs => 「3」 # value => 「3」 ``` # DESCRIPTION `Grammar::Common` gives you a library of common grammar roles to use in your own code, from simple numbers and strings to validation tools. All files here will be roles, rather than standalone grammars and actions. Yes, simple actions are included that return simple hashes containing the parse tree. You can override these as well, or simply include your own actions. The test suite shows you how to return more complex objects - I elected not to do this even though it does make quite a bit more sense because I didn't want to arbitrary clutter the grammar namespace. Read the individual Grammar::Common files: these are generally meant to be dropped in with `does Grammar::Common::Expression::Infix` and using the resulting rule as you like. In most cases default values will be provided, although I'm probably going to go with C-style variables and values, just because adding a full Perl-style expression encourages people to think it's reparsing Raku, but that's another module. # EXAMPLES Using prefix expressions: ``` use Grammar::Common::Expression::Prefix; grammar PostScript does Grammar::Common::Expression::Prefix { token c-variable { <[ a .. z ]> <[ a .. z A .. Z 0 .. 9 _ ]>* } token number { '-'? [ || <[ 1 .. 7 ]> [ <[ 0 .. 7 _ ]> | '_' <[ 0 .. 7 ]> ]* || 0 ] } token value { || <c-variable> || <number> } rule TOP { <expression> } } say PostScript.parse( '+ 0 b' ); say PostScript.parse( '+ + 1 2 3' ); ``` Or common text patterns: ``` use Grammar::Common::Text; grammar Sentences does Grammar::Common::Text { token TOP { <sentence>+ % \s+ } } say Sentences.parse( "One, two, three."); say Sentences.parse( "One, two, three. Four, five!"); ``` # AUTHOR Jeffrey Goff # COPYRIGHT AND LICENSE Copyright 2017 - 2018 Jeffrey Goff Copyright 2019 - 2022 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
## dist_zef-antononcube-JavaScript-D3.md # JavaScript::D3 Raku package [![SparrowCI](https://ci.sparrowhub.io/project/gh-antononcube-Raku-JavaScript-D3/badge)](https://ci.sparrowhub.io) This repository has the Raku package for generation of [JavaScript's D3](https://d3js.org/what-is-d3) code for making plots and charts. This package is intended to be used in Jupyter notebooks with the [Raku kernel implemented by Brian Duggan](https://github.com/bduggan/raku-jupyter-kernel), [BD1], or ["Jupyter::Chatbook"](https://github.com/antononcube/Raku-Jupyter-Chatbook), [AAp4]. The commands of the package generate JavaScript code that produces (nice) [D3.js](https://d3js.org/) plots or charts. See the video [AAv1]. The package JavaScript graphs can be also included in HTML and Markdown documents. See the videos [AAv2, AAv3]. For illustrative examples see the Jupyter notebook ["Tests-for-JavaScript-D3"](https://nbviewer.org/github/antononcube/Raku-JavaScript-D3/blob/main/resources/Tests-for-JavaScript-D3.ipynb). The (original versions of the) JavaScript snippets used in this package are (mostly) taken from ["The D3.js Graph Gallery"](https://d3-graph-gallery.com/index.html). Here is a corresponding video demo (≈7 min): ["The Raku-ju hijack hack of D3.js"](https://www.youtube.com/watch?v=YIhx3FBWayo) (≈ 7 min.) And here is the demo notebook: ["The-Raku-ju-hijack-hack-for-D3.js-demo"](https://nbviewer.org/github/antononcube/Raku-JavaScript-D3/blob/main/resources/The-Raku-ju-hijack-hack-for-D3.js-demo.ipynb). --- ## Mission statement Make first class -- beautiful, tunable, and useful -- plots and charts with Raku using concise specifications. --- ## Design and philosophy Here is a list of guiding design principles: * Concise plot and charts specifications. * Using Mathematica's plot functions for commands signatures inspiration. (Instead of, say, R's ["ggplot2"](https://ggplot2.tidyverse.org).) * For example, see [`ListPlot`](https://reference.wolfram.com/language/ref/ListPlot.html), [`BubbleChart`](https://reference.wolfram.com/language/ref/BubbleChart.html). * The primary target data structure to visualize is an array of hashes, with all array elements having one of these sets of keys * `<x y>` * `<x y group>` * `<x y z>` * `<x y z group>` * Multiple-dataset plots are produced via dataset records that have the key "group". * Whenever possible deduce the keys from arrays of scalars. * The data reshaping functions in "Data::Reshapers", [AAp1], should fit nicely into workflows with this package. * The package functions are tested separately: * As Raku functions that produce output for given signatures * As JavaScript plots that correspond to the corresponding intents --- ## How does it work? Here is a diagram that summarizes the evaluation path from a Raku plot spec to a browser diagram: ``` graph TD Raku{{Raku}} IRaku{{"Raku<br>Jupyter kernel"}} Jupyter{{Jupyter}} JS{{JavaScript}} RakuInput[/Raku code input/] JSOutput[/JavaScript code output/] CellEval[Cell evaluation] JSResDisplay[JavaScript code result display] Jupyter -.-> |1|IRaku -.-> |2|Raku -.-> |3|JSOutput -.-> |4|Jupyter Jupyter -.-> |5|JS -.-> |6|JSResDisplay RakuInput ---> CellEval ---> Jupyter ---> JSResDisplay ``` Here is the corresponding narration: 1. Enter Raku plot command in cell that starts with [the magic spec `%% js`](https://github.com/bduggan/raku-jupyter-kernel/issues/100#issuecomment-1349494169). * Like `js-d3-list-plot((^12)>>.rand)`. 2. Jupyter via the Raku kernel evaluates the Raku plot command. 3. The Raku plot command produces JavaScript code. 4. The Jupyter "lets" the web browser to evaluate the obtained JavaScript code. * Instead of web browser, say, Visual Studio Code can be used. The evaluation loop spelled out above is possible because of the magics implementation in the Raku package [Jupyter::Kernel](https://github.com/bduggan/raku-jupyter-kernel#features), [BD1]. --- ## Alternatives ### Raku packages The Raku packages "Text::Plot", [AAp2], and "SVG::Plot", [MLp1], provide similar functionalities and both can be used in Jupyter notebooks. (Well, "Text::Plot" can be used anywhere.) ### Different backend Instead of using [D3.js](https://d3js.org) as a "backend" it is possible -- and instructive -- to implement Raku plotting functions that generate JavaScript code for the library [Chart.js](https://www.chartjs.org). D3.js is lower level than Chart.js, hence in principle Chart.js is closer to the mission of this Raku package. I.e. at first I considered having Raku plotting implementations with Chart.js (in a package called "JavaScript::Chart".) But I had hard time making Chart.js plots work consistently within Jupyter. --- ## Command Line Interface (CLI) The package provides a CLI script that can be used to generate HTML files with plots or charts. ``` js-d3-graphics --help ``` ``` # Usage: # js-d3-graphics <cmd> [<points> ...] [-w|--width[=UInt]] [-h|--height[=UInt]] [-t|--title=<Str>] [--x-label=<Str>] [--y-label=<Str>] [--background=<Str>] [--color=<Str>] [--grid-lines] [--margins[=UInt]] [--format=<Str>] -- Generates HTML document code with D3.js plots or charts. # js-d3-graphics <cmd> <words> [-w|--width[=UInt]] [-h|--height[=UInt]] [-t|--title=<Str>] [--x-label=<Str>] [--y-label=<Str>] [--background=<Str>] [--color=<Str>] [--grid-lines] [--format=<Str>] -- Generates HTML document code with D3.js plots or charts by splitting a string of data points. # js-d3-graphics <cmd> [-w|--width[=UInt]] [-h|--height[=UInt]] [-t|--title=<Str>] [--x-label=<Str>] [--y-label=<Str>] [--background=<Str>] [--color=<Str>] [--grid-lines] [--format=<Str>] -- Generates HTML document code with D3.js plots or charts from pipeline input. # # <cmd> Graphics command. # [<points> ...] Data points. # -w|--width[=UInt] Width of the plot. (0 for Whatever.) [default: 800] # -h|--height[=UInt] Height of the plot. (0 for Whatever.) [default: 600] # -t|--title=<Str> Title of the plot. [default: ''] # --x-label=<Str> Label of the X-axis. If Whatever, then no label is placed. [default: ''] # --y-label=<Str> Label of the Y-axis. If Whatever, then no label is placed. [default: ''] # --background=<Str> Image background color [default: 'white'] # --color=<Str> Color. [default: 'steelblue'] # --grid-lines Should grid lines be drawn or not? [default: False] # --margins[=UInt] Size of the top, bottom, left, and right margins. [default: 40] # --format=<Str> Output format, one of 'jupyter' or 'html'. [default: 'html'] # <words> String with data points. ``` Here is an usage example that produces a list line plot: ``` js-d3-graphics list-line-plot 1 2 2 12 33 41 15 5 -t="Nice plot" --x-label="My X" --y-label="My Y" > out.html && open out.html ``` ``` # ``` Here is an example that produces bubble chart: ``` js-d3-graphics bubble-chart "1,1,10 2,2,12 33,41,15 5,3,30" -t="Nice plot" --x-label="My X" --y-label="My Y" > out.html && open out.html ``` ``` # ``` Here is an example that produces a random mandala: ``` js-d3-graphics random-mandala 1 --margins=100 -h=1000 -w=1000 --color='rgb(120,120,120)' --background='white' -t="Random mandala" > out.html && open out.html ``` ``` # ``` Here is an example that produces three random scribbles: ``` js-d3-graphics random-scribble 3 --margins=10 -h=200 -w=200 --color='blue' --background='white' > out.html && open out.html ``` ``` # ``` --- ## TODO In the lists below the highest priority items are placed first. ### Plots #### Single dataset 1. DONE List plot 2. DONE List line plot 3. DONE Date list plot 4. DONE Box plot #### Multiple datasets 1. DONE List plot 2. DONE List line plot 3. DONE Date list plot 4. TODO Box plot ### Graph plots 1. TODO Graph plot using d3-force * DONE Core graph plot * DONE Directed graphs * DONE Vertex label styling * DONE Edge label styling * DONE Highlight vertices and edges * Multiple groups can be specified. * TODO Vertex shape styling * TODO Edge shape styling * TODO Curved edges 2. TODO Graph plot using vertex coordinates * DONE Core graph plot * DONE Directed graphs * DONE Vertex label styling * DONE Edge label styling * TODO Vertex shape styling * TODO Edge shape styling * TODO Curved edges ### Charts #### Single dataset 1. DONE Bar chart * DONE Vertical * DONE Horizontal * DONE Chart label per bar 2. DONE Histogram 3. DONE Bubble chart 4. TODO Density 2D chart -- rectangular bins 5. TODO Radar chart 6. TODO Density 2D chart -- hexagonal bins 7. TODO Pie chart 8. DONE Heatmap plot 9. DONE Chessboard position #### Multiple datasets 1. TODO Bar chart 2. TODO Histogram 3. DONE Bubble chart 4. DONE Bubble chart with tooltips 5. TODO Pie chart 6. TODO Radar chart ### Decorations User specified or automatic: 1. DONE Plot label / title 2. DONE Axes labels 3. DONE Plot margins 4. DONE Plot legends (automatic for multi-datasets plots and chart) 5. DONE Plot grid lines * DONE Automatic * DONE User specified number of ticks 6. DONE Title style (font size, color, face) 7. DONE Axes labels style (font size, color, face) 8. TODO Grid lines style ### Infrastructural 1. DONE Support for different JavaScript wrapper styles * DONE Jupyter cell execution ready * DONE Standard HTML * Result output with JSON format? 2. TODO Better, comprehensive type checking * Using the type system of "Data::TypeSystem". 3. DONE CLI script 4. DONE JavaScript code snippets management * Initially the JavaScript snippets were kept with the Raku code, but it seems it is better to have them in a separate file. (With the corresponding accessors.) ## Second wave 1. Random Mandala, single plot 2. Random mandalas row 3. Random mandalas table/array * (I am not sure I will do this.) 4. Random Scribble, single plot 5. Random Scribbles row --- ## Implementation details ### Splicing of JavaScript snippets The package works by splicing of parametrized JavaScript code snippets and replacing the parameters with concrete values. In a sense, JavaScript macros are used to construct the final code through text manipulation. (Probably, unsound software-engineering-wise, but it works.) ### History Initially the commands of this package were executed in [Jupyter notebook with Raku kernel](https://raku.land/cpan:BDUGGAN/Jupyter::Kernel) properly [hacked to redirect Raku code to JavaScript backend](https://github.com/bduggan/p6-jupyter-kernel/issues/100) Brian Duggan fairly quickly implemented the suggested Jupyter kernel magics, so, now no hacking is needed. After I finished version 0.1.3 of this package I decided to write a Python version of it, see [AAp3]. Writing the Python version was a good brainstorming technique to produce reasonable refactoring (that is version 0.1.4). --- ## References ### Articles [OV1] Olivia Vane, ["D3 JavaScript visualisation in a Python Jupyter notebook"](https://livingwithmachines.ac.uk/d3-javascript-visualisation-in-a-python-jupyter-notebook), (2020), [livingwithmachines.ac.uk](https://livingwithmachines.ac.uk). [SF1] Stefaan Lippens, [Custom D3.js Visualization in a Jupyter Notebook](https://www.stefaanlippens.net/jupyter-custom-d3-visualization.html), (2018), [stefaanlippens.net](https://www.stefaanlippens.net). ### Packages [AAp1] Anton Antonov, [Data::Reshapers Raku package](https://github.com/antononcube/Raku-Data-Reshapers), (2021-2024), [GitHub/antononcube](https://github.com/antononcube). [AAp2] Anton Antonov, [Text::Plot Raku package](https://github.com/antononcube/Raku-Text-Plot), (2022), [GitHub/antononcube](https://github.com/antononcube). [AAp3] Anton Antonov, [Data::TypeSystem Raku package](https://github.com/antononcube/Raku-Data-TypeSystem), (2023-2024), [GitHub/antononcube](https://github.com/antononcube). [AAp3] Anton Antonov, [JavaScriptD3 Python package](https://github.com/antononcube/Python-packages/tree/main/JavaScriptD3), (2022), [Python-packages at GitHub/antononcube](https://github.com/antononcube/Python-packages). [AAp4] Anton Antonov, [Jupyter::Chatbook Raku package](https://github.com/antononcube/Raku-Jupyter-Chatbook), (2023-2024), [GitHub/antononcube](https://github.com/antononcube). [BD1] Brian Duggan, [Jupyter::Kernel Raku package](https://raku.land/cpan:BDUGGAN/Jupyter::Kernel), (2017-2022), [GitHub/bduggan](https://github.com/bduggan/raku-jupyter-kernel). [MLp1] Moritz Lenz, [SVG::Plot Raku package](https://github.com/moritz/svg-plot) (2009-2018), [GitHub/moritz](https://github.com/moritz/svg-plot). ### Videos [AAv1] Anton Antonov, ["The Raku-ju hijack hack for D3.js"](https://www.youtube.com/watch?v=YIhx3FBWayo), (2022), [YouTube/@AAA4Prediction](https://www.youtube.com/@AAA4prediction). [AAv2] Anton Antonov, ["Random mandalas generation (with D3.js via Raku)"](https://www.youtube.com/watch?v=THNnofZEAn4), (2022), [YouTube/@AAA4Prediction](https://www.youtube.com/@AAA4prediction). [AAv3] Anton Antonov, ["Raku Literate Programming via command line pipelines"](https://www.youtube.com/watch?v=2UjAdQaKof8), (2023), [YouTube/@AAA4Prediction](https://www.youtube.com/@AAA4prediction).
## dist_zef-FCO-OrderedHash.md [![Build Status](https://travis-ci.org/FCO/OrderedHash.svg?branch=master)](https://travis-ci.org/FCO/OrderedHash)
## dist_zef-librasteve-App-Racl.md [![](https://img.shields.io/badge/License-Artistic%202.0-0298c3.svg)](https://opensource.org/licenses/Artistic-2.0) # raku App::Racl raku calculator for the command line ## Install ``` zef install --verbose App::Ralc ``` ## Usage ``` ralc [--help] <cmd> ``` ## Examples ``` [1] > ralc 'say (1.6km / (60 * 60 * 1s)).in: <mph>' #0.994194mph [2] > ralc 'my \m=95kg; my \a=♎️"9.81 m/s^2"; my \f=m*a; say f' #931.95N [3] > ralc 'say (♎️"12.5 ft ±3%").in: <mm>' #3810mm ±114.3 [4] > ralc 'my \λ=2.5nm; my \ν=c/λ; say ν.norm' #119.916..PHz [5] > ralc 'my \x=♎️"37 °C"; my \y=♎️"98.6 °F"; say x cmp y' #Same [6] > ralc 'say ♓️<80°T> + (♓️<43°30′30″M>).T' #124°ESE (T) ``` ## More Info * <https://github.com/librasteve/raku-Physics-Measure.git> * <https://github.com/librasteve/raku-Physics-Unit.git> * <https://github.com/librasteve/raku-Physics-Error.git> * <https://github.com/librasteve/raku-Physics-Constants.git> * <https://github.com/librasteve/raku-Physics-Navigation.git> ### Copyright copyright(c) 2023 Henley Cloud Consulting Ltd.
## is-20required.md is required Combined from primary sources listed below. # [In Type system](#___top "go to top of document")[§](#(Type_system)_trait_is_required "direct link") See primary documentation [in context](/language/typesystem#trait_is_required) for **trait is required**. ```raku multi trait_mod:<is>(Attribute $attr, :$required!) multi trait_mod:<is>(Parameter:D $param, :$required!) ``` Marks a class or roles attribute as required. If the attribute is not initialized at object construction time throws [`X::Attribute::Required`](/type/X/Attribute/Required). ```raku class Correct { has $.attr is required; } say Correct.new(attr => 42); # OUTPUT: «Correct.new(attr => 42)␤» class C { has $.attr is required; } C.new; CATCH { default { say .^name => .Str } } # OUTPUT: «X::Attribute::Required => The attribute '$!attr' is required, but you did not provide a value for it.␤» ``` Note a class with a private attribute will give the same error: ```raku class D { has $!attr is required; } D.new; CATCH { default { say .^name => .Str } } # OUTPUT: «X::Attribute::Required => The attribute '$!attr' is required, but you did not provide a value for it.␤» ``` You can provide a reason why it's required as an argument to `is required` ```raku class Correct { has $.attr is required("it's so cool") }; say Correct.new(); # OUTPUT: «The attribute '$!attr' is required because it's so cool,␤but you did not provide a value for it.␤» ```
## dist_github-jpve-Net-Packet.md # Net::Packet (Perl6) Perl6 module for decoding network packets. Encoding/Generating packets is on the TODO list. The modules are written in pure Perl6. Both the `Buf` and the `C_Buf` class can be used as frames to decode. (`C_Buf` from the perl6-net-pcap module). The following protocols are implemented: Ethernet, IPv4, UDP and ARP. Each protocol has its own module `Net::Packet::*`. ## Documentation All modules are documented using in-file Pod. The in-file Pods are rendered to Markdown formatted files in the [docs/](/docs) directory. ## Installation Using panda: ``` $ panda update $ panda install Net::Packet ``` Using ufo: ``` $ ufo # Generates Makefile $ make $ make test $ make install ``` ## Usage: ``` use Net::Packet::Ethernet :short; # use :short for short notation: use Net::Packet::IPv4 :short; # Ethernet.decode use Net::Packet::UDP :short; # instead of # Net::Packet::Ethernet.decode my $pkt = Buf.new([...]); my $eth = Ethernet.decode($pkt); printf "%s -> %s: ", $eth.src.Str, $eth.dst.Str; # use .Str or .Int to convert .src/.dst to something usable. my $ip = IPv4.decode($eth.data, $eth); printf "%s -> %s: ", $ip.src.Str, $ip.src.Str; my $udp = UDP.decode($ip.data, $ip); printf "%d -> %d\n", $udp.src_port, $udp.dst_port; ``` ``` use Net::Ethernet :short; my $pkt = Buf.new([...]); my $eth = Ethernet.decode($pkt); printf "%s -> %s: ", $eth.src.Str, $eth.dst.Str; if $eth.pl ~~ IPv4 { # .pl (for PayLoad) decodes the payload printf "%s -> %s: ", $eth.pl.src.Str, $eth.pl.dst.Str; if $eth.pl.pl ~~ UDP { printf "%d -> %d: ", $eth.pl.pl.src_port, $eth.pl.pl.dst_port; } } ```
## call-me.md CALL-ME Combined from primary sources listed below. # [In role Enumeration](#___top "go to top of document")[§](#(role_Enumeration)_method_CALL-ME "direct link") See primary documentation [in context](/type/Enumeration#method_CALL-ME) for **method CALL-ME**. ```raku multi method CALL-ME(|) ``` Returns an `Enumeration` instance given an enum value. ```raku enum Mass ( mg => 1/1000, g => 1/1, kg => 1000/1 ); say Mass(1/1000); # OUTPUT: mg ``` # [In role Callable](#___top "go to top of document")[§](#(role_Callable)_method_CALL-ME "direct link") See primary documentation [in context](/type/Callable#method_CALL-ME) for **method CALL-ME**. ```raku method CALL-ME(Callable:D $self: |arguments) ``` This method is required for the [`( )` postcircumfix operator](/language/operators#postcircumfix_(_)) and the [`.( )` postcircumfix operator](/language/operators#index-entry-.(_)). It's what makes an object actually call-able and needs to be overloaded to let a given object act like a routine. If the object needs to be stored in an `&`-sigiled container, it has to implement Callable. ```raku class A does Callable { submethod CALL-ME(|c){ 'called' } } my &a = A; say a(); # OUTPUT: «called␤» ``` Applying the `Callable` role is not a requirement to make an object callable; if a class simply wants to add subroutine-like semantics in a regular scalar container, the submethod `CALL-ME` can be used for that. ```raku class A { has @.values; submethod CALL-ME(Int $x where 0 <= * < @!values.elems) { @!values[$x] } } my $a = A.new: values => [4,5,6,7]; say $a(2); # OUTPUT: «6␤» ```
## dist_github-tokuhirom-HTTP-Parser.md [![Build Status](https://travis-ci.org/tokuhirom/p6-HTTP-Parser.svg?branch=master)](https://travis-ci.org/tokuhirom/p6-HTTP-Parser) # NAME HTTP::Parser - HTTP parser. # SYNOPSIS ``` use HTTP::Parser; my ($result, $env) = parse-http-request("GET / HTTP/1.0\x0d\x0acontent-type: text/html\x0d\x0a\x0d\x0a".encode("ascii")); # $result => 43 # $env => ${:CONTENT_TYPE("text/html"), :PATH_INFO("/"), :QUERY_STRING(""), :REQUEST_METHOD("GET")} ``` # DESCRIPTION HTTP::Parser is tiny http request parser library for perl6. # FUNCTIONS * `my ($result, $env) = sub parse-http-request(Blob[uint8] $req) is export` parse http request. `$req` must be `Blob[uint8]`. Not **utf8**. Tries to parse given request string, and if successful, inserts variables into `$env`. For the name of the variables inserted, please refer to the PSGI specification. The return values are: * > =0 length of the request (request line and the request headers), in bytes * -1 given request is corrupt * -2 given request is incomplete # COPYRIGHT AND LICENSE Copyright 2015 Tokuhiro Matsuno [[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_zef-jjmerelo-Wikidata-API.md # Wikidata API in Raku Raku module to query the wikidata API. Install it the usual way ``` zef install Wikidata::API ``` Use it: ``` use Wikidata::API; my $query = q:to/END/; SELECT ?person ?personLabel WHERE { ?person wdt:P69 wd:Q1232180 . ?person wdt:P21 wd:Q6581072 . SERVICE wikibase:label { bd:serviceParam wikibase:language "en" . } } ORDER BY ?personLabel END my $UGR-women = query( $query ); my $to-file= q:to/END/; SELECT ?person ?personLabel ?occupation ?occupationLabel WHERE { ?person wdt:P69 wd:Q1232180. ?person wdt:P21 wd:Q6581072. ?person wdt:P106 ?occupation SERVICE wikibase:label { bd:serviceParam wikibase:language "es" . } } END spurt "ugr-women-by-job.sparql", $to-file; say query-file( $to-file ); ``` There are a few SPARQL queries you can try [in this other repo](https://github.com/JJ/wikidata-queries) Download one query from that repo to test the command-line utility that will be installed too ``` wdq.p6 one-query-or-other.sparql ``` ## LICENSE Released under the [Artistic License](LICENSE).
## map.md map Combined from primary sources listed below. # [In List](#___top "go to top of document")[§](#(List)_routine_map "direct link") See primary documentation [in context](/type/List#routine_map) for **routine map**. ```raku multi method map(\SELF: &block) multi map(&code, +values) ``` Examples applied to lists are included here for the purpose of illustration. For a list, it invokes `&code` for each element and gathers the return values in a sequence and returns it. This happens lazily, i.e. `&code` is only invoked when the return values are accessed.Examples: ```raku say ('hello', 1, 22/7, 42, 'world').map: { .^name } # OUTPUT: «(Str Int Rat Int Str)␤» say map *.Str.chars, 'hello', 1, 22/7, 42, 'world'; # OUTPUT: «(5 1 8 2 5)␤» ``` `map` inspects the arity of the code object, and tries to pass as many arguments to it as expected: ```raku sub b($a, $b) { "$a before $b" }; say <a b x y>.map(&b).join(', '); # OUTPUT: «a before b, x before y␤» ``` iterates the list two items at a time. Note that `map` does not flatten embedded lists and arrays, so ```raku ((1, 2), <a b>).map({ .join(',')}) ``` passes `(1, 2)` and `<a b>` in turn to the block, leading to a total of two iterations and the result sequence `"1,2", "a,b"`. If `&code` is a [`Block`](/type/Block) loop phasers will be executed and loop control statements will be treated as in loop control flow. Please note that `return` is executed in the context of its definition. It is not the return statement of the block but the surrounding Routine. Using a [`Routine`](/type/Routine) will also handle loop control statements and loop phasers. Any [`Routine`](/type/Routine) specific control statement or phaser will be handled in the context of that [`Routine`](/type/Routine). ```raku sub s { my &loop-block = { return # return from sub s }; say 'hi'; (1..3).map: &loop-block; say 'oi‽' # dead code }; s # OUTPUT: «hi␤» ``` # [In Any](#___top "go to top of document")[§](#(Any)_routine_map "direct link") See primary documentation [in context](/type/Any#routine_map) for **routine map**. ```raku multi method map(\SELF: &block) multi map(&code, +values) ``` `map` will iterate over the invocant and apply the number of positional parameters of the code object from the invocant per call. The returned values of the code object will become elements of the returned [`Seq`](/type/Seq). The `:$label` and `:$item` are useful only internally, since `for` loops get converted to `map`s. The `:$label` takes an existing [`Label`](/type/Label) to label the `.map`'s loop with and `:$item` controls whether the iteration will occur over `(SELF,)` (if `:$item` is set) or `SELF`. In `sub` form, it will apply the `code` block to the `values`, which will be used as invocant. The forms with `|c`, `Iterable:D \iterable` and `Hash:D \hash` as signatures will fail with `X::Cannot::Map`, and are mainly meant to catch common traps. Inside a `for` statement that has been sunk, a [`Seq`](/type/Seq) created by a map will also sink: ```raku say gather for 1 { ^3 .map: *.take; } # OUTPUT: «(0 1 2)␤» ``` In this case, `gather` sinks the `for` statement, and the result of sinking the [`Seq`](/type/Seq) will be iterating over its elements, calling `.take` on them. # [In HyperSeq](#___top "go to top of document")[§](#(HyperSeq)_method_map "direct link") See primary documentation [in context](/type/HyperSeq#method_map) for **method map**. ```raku method map(HyperSeq:D: $matcher, *%options) ``` Uses maps on the `HyperSeq`, generally created by application of `hyper` to a preexisting [`Seq`](/type/Seq). # [In RaceSeq](#___top "go to top of document")[§](#(RaceSeq)_method_map "direct link") See primary documentation [in context](/type/RaceSeq#method_map) for **method map**. ```raku method map(RaceSeq:D: $matcher, *%options) ``` Uses maps on the `RaceSeq`, generally created by application of `.race` to a preexisting [`Seq`](/type/Seq). # [In Backtrace](#___top "go to top of document")[§](#(Backtrace)_method_map "direct link") See primary documentation [in context](/type/Backtrace#method_map) for **method map**. ```raku multi method map(Backtrace:D: &block --> Seq:D) ``` It invokes `&block` for each element and gathers the return values in a sequence and returns it. This program: ```raku sub inner { Backtrace.new.map({ say "{$_.file}: {$_.line}" }); } sub outer { inner; } outer; ``` results in: 「text」 without highlighting ``` ``` SETTING::src/core.c/Backtrace.rakumod: 85 SETTING::src/core.c/Backtrace.rakumod: 85 test.raku: 1 test.raku: 2 test.raku: 3 test.raku: 1 ``` ``` # [In Supply](#___top "go to top of document")[§](#(Supply)_method_map "direct link") See primary documentation [in context](/type/Supply#method_map) for **method map**. ```raku method map(Supply:D: &mapper --> Supply:D) ``` Returns a new supply that maps each value of the given supply through `&mapper` and emits it to the new supply. ```raku my $supplier = Supplier.new; my $all = $supplier.Supply; my $double = $all.map(-> $value { $value * 2 }); $double.tap(&say); $supplier.emit(4); # OUTPUT: «8» ```