{"title":"Programming for fun and profit","link":[{"@attributes":{"href":"https:\/\/slar.se\/","rel":"alternate"}},{"@attributes":{"href":"https:\/\/slar.se\/feeds\/all.atom.xml","rel":"self"}}],"id":"https:\/\/slar.se\/","updated":"2025-10-04T00:00:00+02:00","subtitle":"A blog about software engineering, programming languages and technical tinkering","entry":[{"title":"Cleaning up unused packages with Pacman","link":{"@attributes":{"href":"https:\/\/slar.se\/cleaning-up-with-pacman.html","rel":"alternate"}},"published":"2025-10-04T00:00:00+02:00","updated":"2025-10-04T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2025-10-04:\/cleaning-up-with-pacman.html","summary":"<p>Every once in a while, I make a vain attempt to clean up packages. Lately, I've\nbeen upping my game in searching for packages I don't use anymore or don't have\nany recollection I even installed. In this article, I'll run through one full\ncleanup cycle using <code>pacman<\/code> to declutter \u2026<\/p>","content":"<p>Every once in a while, I make a vain attempt to clean up packages. Lately, I've\nbeen upping my game in searching for packages I don't use anymore or don't have\nany recollection I even installed. In this article, I'll run through one full\ncleanup cycle using <code>pacman<\/code> to declutter my Arch Linux machine.<\/p>\n<h1 id=\"removing-installed-packages\">Removing installed packages<\/h1>\n<p>There are two kinds of packages to look at:<\/p>\n<ul>\n<li>Native - packages that appear in the sync database(s)<ul>\n<li>You installed these with <code>pacman -S<\/code><sup id=\"sf-cleaning-up-with-pacman-1-back\"><a href=\"#sf-cleaning-up-with-pacman-1\" class=\"simple-footnote\" title=\"Or if you're a good citizen,   you installed them with pacman -Syu to ensure you're all up to date\">1<\/a><\/sup><\/li>\n<\/ul>\n<\/li>\n<li>Foreign - packages you've installed from other sources<ul>\n<li>For example, you downloaded a PKGBUILD from the <a href=\"https:\/\/wiki.archlinux.org\/title\/Arch_User_Repository\">AUR<\/a> and installed it with <code>makepkg<\/code><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>I usually deal with these one at a time.<\/p>\n<h2 id=\"pruning-foreign-packages\">Pruning foreign packages<\/h2>\n<p>I typically start with foreign packages. I prune these aggressively as foreign\npackages have no particular security standard - it'll vary by where you got the\npackage from.<\/p>\n<p>You can list foreign packages like so:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pacman<span class=\"w\"> <\/span>-Qqme\nautojump\nkanata-bin\nwdisplays\n<span class=\"o\">[<\/span>...<span class=\"o\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>The options are as follows:<\/p>\n<ul>\n<li><code>Q<\/code> - query, we're querying the local database<\/li>\n<li><code>q<\/code> - quiet, show less output<\/li>\n<li><code>m<\/code> - foreign, as described above<\/li>\n<li><code>e<\/code> - explicitly installed, as opposed to having been installed as a\n  dependency of something else<\/li>\n<\/ul>\n<p>Let's say I want to uninstall <code>wdisplays<\/code>. I'd do that like so:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>sudo<span class=\"w\"> <\/span>pacman<span class=\"w\"> <\/span>-Rsn<span class=\"w\"> <\/span>wdisplays\nchecking<span class=\"w\"> <\/span>dependencies...\n\nPackages<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">2<\/span><span class=\"o\">)<\/span><span class=\"w\"> <\/span>wayland-protocols-1.45-1<span class=\"w\">  <\/span>wdisplays-1.1.3-1\n\nTotal<span class=\"w\"> <\/span>Removed<span class=\"w\"> <\/span>Size:<span class=\"w\">  <\/span><span class=\"m\">1<\/span>.02<span class=\"w\"> <\/span>MiB\n\n::<span class=\"w\"> <\/span>Do<span class=\"w\"> <\/span>you<span class=\"w\"> <\/span>want<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span>remove<span class=\"w\"> <\/span>these<span class=\"w\"> <\/span>packages?<span class=\"w\"> <\/span><span class=\"o\">[<\/span>Y\/n<span class=\"o\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that the we're prompted to approve the removal<sup id=\"sf-cleaning-up-with-pacman-2-back\"><a href=\"#sf-cleaning-up-with-pacman-2\" class=\"simple-footnote\" title=\"For scripts, you can bypass the need for a prompt with --noconfirm. I tend to not script my system maintenance, however, as I like to be hands on when it comes to what's installed on my system.\">2<\/a><\/sup>, and also that prompt lists <em>two<\/em> packages for removal:\n<code>wdisplays<\/code> and <code>wayland-protocols<\/code>. The latter is a dependency of <code>wdisplays<\/code>,\nwhich shows up due to the use of the <code>s<\/code> option, as specified below:<\/p>\n<ul>\n<li><code>R<\/code> - remove, we're removing a local package<\/li>\n<li><code>s<\/code> - recursive, remove all dependencies of the package provided that they\n  have no other dependents and were not explicitly installed by the user<\/li>\n<li><code>n<\/code> - nosave, prevents Pacman from backing up removed files (I really want\n  them gone)<\/li>\n<\/ul>\n<blockquote>\n<p><strong>Aside:<\/strong> Another useful option <code>-c|--cascade<\/code>. By specifying this, you\nwill remove not only the target package, but any package that depends on it,\nrecursively. I rarely use this myself, but it can be very convenient if\nthere's a \"middle of the dependency chain\" package that you for one reason or\nanother really need to remove.<\/p>\n<\/blockquote>\n<h2 id=\"pruning-native-packages\">Pruning native packages<\/h2>\n<p>Now, we follow precisely the same procedure for native packages. To list native\npackages, we simply substitute the <code>m<\/code> option with the <code>n<\/code> argument.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pacman<span class=\"w\"> <\/span>-Qqne\n<span class=\"o\">[<\/span>...<span class=\"w\"> <\/span>very<span class=\"w\"> <\/span>long<span class=\"w\"> <\/span>list<span class=\"w\"> <\/span>...<span class=\"o\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>This list is going to be <em>way<\/em> larger than your list of foreign packages, so you\nmight want to pipe the result to <code>less<\/code> and have a little look through it.\nGenerally, I do not prune this as aggressively as I prune my foreign packages as\nthe security standards in the official Arch repositories are adequate for my\nneeds. That being said, it's still worth a little look every now and then, as\nevery installed package makes system updates slower.<\/p>\n<p>When you find something to uninstall, you use precisely the same command as for\na foreign package above.<\/p>\n<h2 id=\"pruning-orphaned-packages\">Pruning orphaned packages<\/h2>\n<p>As a final step, I prune <em>orphaned<\/em> packages. These are packages that were\ninstalled as dependencies at one point, but no longer have any dependents. I\ntypically accrue quite a few of these by forgetting the <code>s<\/code> option when removing\npackages, but they can also come about from e.g. a system update (<code>pacman -Syu<\/code>)\nwhere some updated package(s) no longer require prior dependencies. A system\nupdate <em>does not<\/em> remove orphans, meaning that you'll accumulate orphans in the\nsystem through normal usage.<\/p>\n<p>You can list orphaned packages like so:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pacman<span class=\"w\"> <\/span>-Qqdt\n<span class=\"o\">[<\/span>...<span class=\"o\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>The <em>new<\/em> arguments are as follows:<\/p>\n<ul>\n<li><code>d<\/code> - dependencies, only shows packages that were <em>not<\/em> explicitly installed<\/li>\n<li><code>t<\/code> - unrequired, lists packages that have no dependents<\/li>\n<\/ul>\n<p>This will often be quite a large list, typically with dozens or hundreds of\nentries depending on how often you clean up your system, so it's typically\nnecessary to pipe it to the removal command.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pacman<span class=\"w\"> <\/span>-Qqdt<span class=\"w\"> <\/span><span class=\"p\">|<\/span><span class=\"w\"> <\/span>sudo<span class=\"w\"> <\/span>pacman<span class=\"w\"> <\/span>-Rsn<span class=\"w\"> <\/span>-\n<span class=\"o\">[<\/span>...<span class=\"o\">]<\/span>\n\n::<span class=\"w\"> <\/span>Do<span class=\"w\"> <\/span>you<span class=\"w\"> <\/span>want<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span>remove<span class=\"w\"> <\/span>these<span class=\"w\"> <\/span>packages?<span class=\"w\"> <\/span><span class=\"o\">[<\/span>Y\/n<span class=\"o\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>As usual, you need to confirm your action via the prompt, and the presence of\nthe <code>s<\/code> option will likely cause the prompt to show more packages than the list\nyou piped into it.<\/p>\n<blockquote>\n<p><strong>Important:<\/strong> The <code>q<\/code> option is actually important in the above command chain, as\nthe extra information that's printed if you don't specify it causes <code>pacman\n-R<\/code> to error out.<\/p>\n<p><strong>Tip:<\/strong> You can trim the list a bit by adding the <code>t<\/code> option to exclude\npackages that are dependencies of other packages. Most often, I find that\nthese packages <em>are<\/em> indeed packages that I want to keep, and I only\nexplicitly installed them to resolve some issue with an update.<\/p>\n<\/blockquote>\n<h2 id=\"further-reading\">Further reading<\/h2>\n<p>If you want to learn more about how to maintain your system, here are a few additional resources to have a look at.<\/p>\n<ul>\n<li>The <a href=\"https:\/\/wiki.archlinux.org\/title\/System_maintenance\">System maintenance<\/a> page in the Arch Linux Wiki is a must-read for maintaining your system properly<\/li>\n<li>The <a href=\"https:\/\/wiki.archlinux.org\/title\/Pacman\/Tips_and_tricks\">pacman\/Tips and tricks<\/a> page in the Arch Linux Wiki is a great place to get ideas for what you can do with <code>pacman<\/code>. It's essentially a much more comprehensive version of this very article.<\/li>\n<li>The manual page (<code>man pacman<\/code>) is very useful once you already know roughly what you want to do<\/li>\n<\/ul>\n<h1 id=\"and-thats-it\">And that's it!<\/h1>\n<p>With that, you've learned how to prune packages on your system! It's not\ndifficult to do, you just need a little bit of discipline to do it regularly.\nPruning packages may seem unnecessary, but it has several benefits, not least of\nwhich is a smaller attack surface, less wasted disk space and faster system\nupdates.<\/p><ol class=\"simple-footnotes\"><li id=\"sf-cleaning-up-with-pacman-1\">Or if you're a good citizen,\n  you installed them with <code>pacman -Syu<\/code> to ensure you're all up to date <a href=\"#sf-cleaning-up-with-pacman-1-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-cleaning-up-with-pacman-2\">For scripts, you can\nbypass the need for a prompt with <code>--noconfirm<\/code>. I tend to not script my system\nmaintenance, however, as I like to be hands on when it comes to what's installed\non my system. <a href=\"#sf-cleaning-up-with-pacman-2-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><\/ol>","category":[{"@attributes":{"term":"Linux"}},{"@attributes":{"term":"linux"}},{"@attributes":{"term":"arch linux"}},{"@attributes":{"term":"pacman"}}]},{"title":"Programmatically set the pixel density (DPI) of a PNG image","link":{"@attributes":{"href":"https:\/\/slar.se\/set-png-dpi.html","rel":"alternate"}},"published":"2024-11-03T00:00:00+01:00","updated":"2024-11-03T00:00:00+01:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2024-11-03:\/set-png-dpi.html","summary":"<p>Earlier this week, I came across a situation where someone wanted a QR code to\n\"have 300 DPI so it looks good when printed\". As I don't have much experience\nwith image formats, it took me a while to figure out what the actual request\nwas: to print the QR \u2026<\/p>","content":"<p>Earlier this week, I came across a situation where someone wanted a QR code to\n\"have 300 DPI so it looks good when printed\". As I don't have much experience\nwith image formats, it took me a while to figure out what the actual request\nwas: to print the QR code on paper at a size of 2-3 cm, with sufficient\nresolution for even the crappiest of phone cameras to be able to scan it.<\/p>\n<p>The resolution was easily solved as the QR code library supported it, but the\nsize of the image on paper was a different story. I didn't even <em>really<\/em> know\nwhat DPI meant in the context of image metadata. While I knew that I could get the\ntask done in a heartbeat or two if I brought in a third party PNG library,\nbringing in an entire PNG library just to do a single tiny alteration felt a bit\nheavy-handed, not to mention that I wouldn't really understand what the library\nwas doing. So I decided to roll my own. And then write an article about how I\ndid it.<\/p>\n<blockquote>\n<p><strong>Note:<\/strong> The code in this article is not the actual code written for my\nemployer. It's not written in the same language and does not have the same\nconstraints.<\/p>\n<\/blockquote>\n<div class=\"toc\"><span class=\"toctitle\">Table of Contents<\/span><ul>\n<li><a href=\"#what-is-this-dpi-thing\">What is this DPI thing?<\/a><\/li>\n<li><a href=\"#the-structure-of-a-png-image\">The structure of a PNG image<\/a><ul>\n<li><a href=\"#the-png-signature\">The PNG signature<\/a><\/li>\n<li><a href=\"#chunk-format-and-order\">Chunk format and order<\/a><\/li>\n<li><a href=\"#the-phys-chunk\">The pHYs chunk<\/a><\/li>\n<li><a href=\"#validating-the-results\">Validating the results<\/a><\/li>\n<li><a href=\"#caveat-what-if-there-already-is-a-phys-chunk-in-the-file\">Caveat - what if there already is a pHYs chunk in the file?<\/a><\/li>\n<\/ul>\n<\/li>\n<li><a href=\"#and-now-you-know-how-to-set-the-dpi-on-a-png\">And now you know how to set the DPI on a PNG!<\/a><\/li>\n<li><a href=\"#putting-it-all-together\">Putting it all together<\/a><\/li>\n<\/ul>\n<\/div>\n<h1 id=\"what-is-this-dpi-thing\">What is this DPI thing?<\/h1>\n<p>My first order of business was figuring out what <em>dots per inch<\/em> (DPI) even\nmeans in relation to a digital image. I knew DPI only as a printer setting to\nset the quality of the output, but had no particular insight into how that\nrelates to images that are themselves just a bunch of pixels.<\/p>\n<p>Turns out, it's pretty much exactly what it sounds like: the amount of dots to\nprint per inch. As metadata on a digital image, it's essentially a scaling\nfactor for displaying the image, particularly when printing on physical media.\nFor example, if you print an image that is 100x100 pixels with a DPI of 100,\nthe image will be 1 inch by 1 inch on the physical paper. If you set the DPI to\n50 instead, the image will be 2 inches by 2 inches, smearing one pixel over two\ndots in each direction.<\/p>\n<div style=\"display: flex; justify-content: center; gap: 20%;\">\n    <figure style=\"text-align: center;\">\n        <img alt=\"PNG image without pixel density set\" src=\"\/images\/set_png_dpi\/qrcode_without_dpi.png\" style=\"width: 116px;\">\n        <figcaption>Pixel density set to 100 DPI<\/figcaption>\n    <\/figure>\n    <figure style=\"text-align: center;\">\n        <img alt=\"PNG image with pixel density set\" src=\"\/images\/set_png_dpi\/qrcode_without_dpi.png\" style=\"width: 228px;\">\n        <figcaption>Pixel density set to 50 DPI<\/figcaption>\n    <\/figure>\n<\/div>\n<p><br><\/p>\n<p>Actually, the above captions aren't entirely truthful. The images are one and\nthe same, just scaled with CSS. In general, DPI does not affect how the image\nis represented on a monitor, we have other scaling tools in the digital world\n(such as CSS). That is not to say that there are <em>no<\/em> image viewers that care\nabout DPI metadata, I'm sure there are, but none of the ones I currently have\ninstalled seem to care. Including my web browser.<\/p>\n<div style=\"display: flex; justify-content: center; gap: 20%;\">\n    <figure style=\"text-align: center;\">\n        <img alt=\"PNG image without pixel density set\" src=\"\/images\/set_png_dpi\/qrcode_100_dpi.png\">\n        <figcaption>Pixel density set to 100 DPI (for real)<\/figcaption>\n    <\/figure>\n    <figure style=\"text-align: center;\">\n        <img alt=\"PNG image with pixel density set\" src=\"\/images\/set_png_dpi\/qrcode_50_dpi.png\">\n        <figcaption>Pixel density set to 50 DPI (for real)<\/figcaption>\n    <\/figure>\n<\/div>\n\n<h1 id=\"the-structure-of-a-png-image\">The structure of a PNG image<\/h1>\n<p>To be able to set the pixel density of a PNG image, we need to dive into the\nimage format. As luck would have it, PNG is a <a href=\"https:\/\/www.w3.org\/TR\/png-3\/#5DataRep\">relatively simple\nformat<\/a>. The spec defines the data format\nas follows.<\/p>\n<blockquote>\n<p>The PNG datastream consists of a PNG signature followed by a sequence of\nchunks.<\/p>\n<\/blockquote>\n<p>Scanning through the available chunks, it seems like the ancillary<sup id=\"sf-set-png-dpi-1-back\"><a href=\"#sf-set-png-dpi-1\" class=\"simple-footnote\" title=\"That's fancy speak for &quot;optional&quot;\">1<\/a><\/sup> <a href=\"https:\/\/www.w3.org\/TR\/png-3\/#11pHYs\"><code>pHYs<\/code>\nchunk<\/a> is the one where we can set pixel\ndensity for printing. I'm guessing \"pHYs\" is short for \"physical\".<\/p>\n<p>Quickly scanning through the PNG that I needed to amend<sup id=\"sf-set-png-dpi-2-back\"><a href=\"#sf-set-png-dpi-2\" class=\"simple-footnote\" title=\"The PNG chunk types are readable as plaintext. Open a PNG in any text editor that isn't afraid to read a file that isn't entirely plaintext, and you'll most often be able to tell if a chunk is present or not.\">2<\/a><\/sup>, I could quickly determine that it simply\nlacked this chunk, so the task is simply to add it to the chunk sequence. But\nhow do we know where to place it? And what it should look like? Let's dive into\nthe format and find out.<\/p>\n<h2 id=\"the-png-signature\">The PNG signature<\/h2>\n<p>The signature makes up the first eight bytes of the file, and looks like this in\nhex.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"mf\">89<\/span><span class=\"w\"> <\/span><span class=\"mf\">50<\/span><span class=\"w\"> <\/span><span class=\"mf\">4<\/span><span class=\"n\">E<\/span><span class=\"w\"> <\/span><span class=\"mf\">47<\/span><span class=\"w\"> <\/span><span class=\"mf\">0<\/span><span class=\"n\">D<\/span><span class=\"w\"> <\/span><span class=\"mf\">0<\/span><span class=\"n\">A<\/span><span class=\"w\"> <\/span><span class=\"mf\">1<\/span><span class=\"n\">A<\/span><span class=\"w\"> <\/span><span class=\"mf\">0<\/span><span class=\"n\">A<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p><code>50 4E 47<\/code> maps to the ASCII characters <code>P N G<\/code>. That's the name of the\nmovie!<\/p>\n<\/blockquote>\n<p>If a file does <em>not<\/em> start with this signature, it's not a PNG file. But if it\ndoes there, it's a PNG file and there should now be a bunch of chunks for us to\nsink our teeth into.<\/p>\n<h2 id=\"chunk-format-and-order\">Chunk format and order<\/h2>\n<p>Each chunk in the PNG format has <a href=\"https:\/\/www.w3.org\/TR\/png-3\/#5Chunk-layout\">four\nfields<\/a>:<\/p>\n<ul>\n<li>Length: 4 bytes defining the amount of bytes in the data chunk.<\/li>\n<li>Type: 4 bytes defining the chunk type.<\/li>\n<li>Data: As many bytes of data as defined in the length field. This field\n  can be empty (and then the length field is 0).<\/li>\n<li>CRC checksum: A CRC32 checksum computed over the type and data fields.<\/li>\n<\/ul>\n<p>Every PNG datastream starts with an <a href=\"https:\/\/www.w3.org\/TR\/png-3\/#11IHDR\">IHDR\nchunk<\/a> and ends with an <a href=\"https:\/\/www.w3.org\/TR\/png-3\/#11IEND\">IEND\nchunk<\/a>. Everything in between is mostly\nunordered<sup id=\"sf-set-png-dpi-3-back\"><a href=\"#sf-set-png-dpi-3\" class=\"simple-footnote\" title=\"There are some ordering rules. For example, if there are multiple IDAT chunks, they must appear consecutively, with no other kinds of chunks in between.\">3<\/a><\/sup><\/p>\n<p>Assuming we have a file without a <code>pHYs<\/code> chunk, which is the situation I found\nmyself in earlier this week, it's therefore very simple to find out <em>where<\/em> to\nplace the <code>pHYs<\/code> chunk: after the required <code>IHDR<\/code> chunk, which just happens to\n<a href=\"https:\/\/www.w3.org\/TR\/png-3\/#11IHDR\">always be 25 bytes large<\/a>.<\/p>\n<p>This means that we can safely squeeze in our <code>pHYs<\/code> chunk <code>8 + 25 = 33<\/code> bytes\ninto the file. With Python, that would look something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">PNG_SIGNATURE<\/span> <span class=\"o\">=<\/span> <span class=\"sa\">b<\/span><span class=\"s1\">'<\/span><span class=\"se\">\\x89\\x50\\x4e\\x47\\x0D\\x0A\\x1A\\x0A<\/span><span class=\"s1\">'<\/span>\n\n<span class=\"n\">IHDR_SIZE<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">25<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">with_dpi<\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span> <span class=\"nb\">bytes<\/span><span class=\"p\">,<\/span> <span class=\"n\">dots_per_inch<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span><span class=\"p\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nb\">bytes<\/span><span class=\"p\">:<\/span>\n    <span class=\"k\">if<\/span> <span class=\"ow\">not<\/span> <span class=\"n\">data<\/span><span class=\"o\">.<\/span><span class=\"n\">startswith<\/span><span class=\"p\">(<\/span><span class=\"n\">PNG_SIGNATURE<\/span><span class=\"p\">):<\/span>\n        <span class=\"k\">raise<\/span> <span class=\"ne\">ValueError<\/span><span class=\"p\">(<\/span><span class=\"s2\">\"Not a PNG image\"<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"n\">signature_and_ihdr<\/span> <span class=\"o\">=<\/span> <span class=\"n\">data<\/span><span class=\"p\">[:<\/span><span class=\"nb\">len<\/span><span class=\"p\">(<\/span><span class=\"n\">PNG_SIGNATURE<\/span><span class=\"p\">)<\/span> <span class=\"o\">+<\/span> <span class=\"n\">IHDR_SIZE<\/span><span class=\"p\">]<\/span>\n    <span class=\"n\">rest<\/span> <span class=\"o\">=<\/span> <span class=\"n\">data<\/span><span class=\"p\">[<\/span><span class=\"nb\">len<\/span><span class=\"p\">(<\/span><span class=\"n\">signature_and_ihdr<\/span><span class=\"p\">):]<\/span>\n\n    <span class=\"n\">phys_chunk<\/span> <span class=\"o\">=<\/span> <span class=\"n\">create_phys_chunk<\/span><span class=\"p\">(<\/span><span class=\"n\">dots_per_inch<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"k\">return<\/span> <span class=\"n\">signature_and_ihdr<\/span> <span class=\"o\">+<\/span> <span class=\"n\">phys_chunk<\/span> <span class=\"o\">+<\/span> <span class=\"n\">rest<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now all we need to figure out is what the <code>pHYs<\/code> chunk should look like. In\nother words, we need to implement the <code>create_phys_chunk()<\/code> function!<\/p>\n<h2 id=\"the-phys-chunk\">The <code>pHYs<\/code> chunk<\/h2>\n<p>The <a href=\"https:\/\/www.w3.org\/TR\/png-3\/#11pHYs\"><code>pHYs<\/code> chunk<\/a> is simple. It follows\nthe format <a href=\"#chunk-format-and-order\">outlined above<\/a>, with a type field o <code>70 48\n59 73<\/code> (which decodes to <code>pHYs<\/code> in ASCII) and a 9-byte data chunk on the\nfollowing format:<\/p>\n<ul>\n<li>4 bytes of pixels per unit (X-axis)<\/li>\n<li>4 bytes of pixels per unit (Y-axis)<\/li>\n<li>1 byte of unit specifier which is either 0 or 1<ul>\n<li>0: The unit is <em>unknown<\/em> and the \"pixels per unit\" only defines aspect\n  ratio. This does not help us define DPI.<\/li>\n<li>1: The unit is \"meter\". This is what we want.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>So, apparently, the PNG format supports pixel density if we set the final byte\nto <code>1<\/code>, but it's natively in <em>pixels per meter<\/em>. With <code>1 inch = 2.54cm<\/code>, we get\nthe nice and round conversion factor <code>100 [cm\/m] \/ 2.54 [cm\/inch] \u2248 39.37008\n[inch\/m]<\/code>. Finally, we also need to compute the CRC32 checksum, which\nconveniently is implemented in the Python standard library <a href=\"https:\/\/docs.python.org\/3\/library\/binascii.html#binascii.crc32\"><code>binascii<\/code>\nmodule<\/a>.<\/p>\n<p>There's one more important piece of information, namely how to represent\nmulti-byte integers.<\/p>\n<blockquote>\n<p>All integers that require more than one byte shall be in network byte order\n(as illustrated in Figure 17 ): the most significant byte comes first, then\nthe less significant bytes in descending order of significance (MSB LSB for\ntwo-byte integers, MSB B2 B1 LSB for four-byte integers).<\/p>\n<p><a href=\"https:\/\/www.w3.org\/TR\/png-3\/#7Integers-and-byte-order\">Source<\/a><\/p>\n<\/blockquote>\n<p>Network byte order is the same as <a href=\"https:\/\/en.wikipedia.org\/wiki\/Endianness\">big-endian<\/a>,\nand is how us humans write numbers. For example, the <code>pHYs<\/code> length field, which\nhas a value of 9, is encoded as <code>00 00 00 09<\/code>.<\/p>\n<p>With this knowledge, let's write some code.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">binascii<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">create_phys_chunk<\/span><span class=\"p\">(<\/span><span class=\"n\">dots_per_inch<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span><span class=\"p\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nb\">bytes<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">length_field<\/span> <span class=\"o\">=<\/span> <span class=\"sa\">b<\/span><span class=\"s2\">\"<\/span><span class=\"se\">\\x00\\x00\\x00\\x09<\/span><span class=\"s2\">\"<\/span>\n    <span class=\"n\">type_field<\/span> <span class=\"o\">=<\/span> <span class=\"sa\">b<\/span><span class=\"s2\">\"pHYs\"<\/span>\n\n    <span class=\"n\">inches_per_meter<\/span> <span class=\"o\">=<\/span> <span class=\"mf\">39.37008<\/span>\n    <span class=\"n\">dots_per_meter<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">int<\/span><span class=\"p\">(<\/span><span class=\"n\">dots_per_inch<\/span> <span class=\"o\">*<\/span> <span class=\"n\">inches_per_meter<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">pixels_per_meter_field<\/span> <span class=\"o\">=<\/span> <span class=\"n\">dots_per_meter<\/span><span class=\"o\">.<\/span><span class=\"n\">to_bytes<\/span><span class=\"p\">(<\/span><span class=\"n\">length<\/span><span class=\"o\">=<\/span><span class=\"mi\">4<\/span><span class=\"p\">,<\/span> <span class=\"n\">byteorder<\/span><span class=\"o\">=<\/span><span class=\"s2\">\"big\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">unit_field<\/span> <span class=\"o\">=<\/span> <span class=\"sa\">b<\/span><span class=\"s2\">\"<\/span><span class=\"se\">\\x01<\/span><span class=\"s2\">\"<\/span>\n\n    <span class=\"n\">type_and_data<\/span> <span class=\"o\">=<\/span> <span class=\"n\">type_field<\/span> <span class=\"o\">+<\/span> <span class=\"n\">pixels_per_meter_field<\/span> <span class=\"o\">+<\/span> <span class=\"n\">pixels_per_meter_field<\/span> <span class=\"o\">+<\/span> <span class=\"n\">unit_field<\/span>\n    <span class=\"n\">checksum<\/span> <span class=\"o\">=<\/span> <span class=\"n\">binascii<\/span><span class=\"o\">.<\/span><span class=\"n\">crc32<\/span><span class=\"p\">(<\/span><span class=\"n\">type_and_data<\/span><span class=\"p\">)<\/span><span class=\"o\">.<\/span><span class=\"n\">to_bytes<\/span><span class=\"p\">(<\/span><span class=\"n\">length<\/span><span class=\"o\">=<\/span><span class=\"mi\">4<\/span><span class=\"p\">,<\/span> <span class=\"n\">byteorder<\/span><span class=\"o\">=<\/span><span class=\"s2\">\"big\"<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"k\">return<\/span> <span class=\"n\">length_field<\/span> <span class=\"o\">+<\/span> <span class=\"n\">type_and_data<\/span> <span class=\"o\">+<\/span> <span class=\"n\">checksum<\/span>\n<\/code><\/pre><\/div>\n\n<p>That's actually all there is to creating the <code>pHYs<\/code> chunk. Putting this\ntogether with the previous code snippet, we have a fully functioning <em>addition<\/em>\nof a <code>pHYs<\/code> chunk to a PNG file!<\/p>\n<h2 id=\"validating-the-results\">Validating the results<\/h2>\n<p>While most image viewers will display the DPI of a PNG image somewhere, it can\nbe useful to have more deliberate tooling for the job.\n<a href=\"http:\/\/www.libpng.org\/pub\/png\/apps\/pngcheck.html\">pngcheck<\/a>, whose homepage is\none of the last remaining bastions of plain <code>http<\/code> on the web, is a useful tool\nfor inspecting the chunks of a PNG file.<\/p>\n<p>Inspecting the original <code>qrcode_without_dpi.png<\/code>, we get the following output.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pngcheck<span class=\"w\"> <\/span>-v<span class=\"w\"> <\/span>qrcode_without_dpi.png\nFile:<span class=\"w\"> <\/span>qrcode_without_dpi.png<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">484<\/span><span class=\"w\"> <\/span>bytes<span class=\"o\">)<\/span>\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>IHDR<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x0000c,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">13<\/span>\n<span class=\"w\">    <\/span><span class=\"m\">116<\/span><span class=\"w\"> <\/span>x<span class=\"w\"> <\/span><span class=\"m\">116<\/span><span class=\"w\"> <\/span>image,<span class=\"w\"> <\/span><span class=\"m\">1<\/span>-bit<span class=\"w\"> <\/span>grayscale,<span class=\"w\"> <\/span>non-interlaced\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>cHRM<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x00025,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">32<\/span>\n<span class=\"w\">    <\/span>White<span class=\"w\"> <\/span><span class=\"nv\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.3127<span class=\"w\"> <\/span><span class=\"nv\">y<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.329,<span class=\"w\">  <\/span>Red<span class=\"w\"> <\/span><span class=\"nv\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.64<span class=\"w\"> <\/span><span class=\"nv\">y<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.33\n<span class=\"w\">    <\/span>Green<span class=\"w\"> <\/span><span class=\"nv\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.3<span class=\"w\"> <\/span><span class=\"nv\">y<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.6,<span class=\"w\">  <\/span>Blue<span class=\"w\"> <\/span><span class=\"nv\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.15<span class=\"w\"> <\/span><span class=\"nv\">y<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.06\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>bKGD<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x00051,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">2<\/span>\n<span class=\"w\">    <\/span><span class=\"nv\">gray<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>0x0000\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>tIME<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x0005f,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">7<\/span>:<span class=\"w\">  <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>Nov<span class=\"w\"> <\/span><span class=\"m\">2024<\/span><span class=\"w\"> <\/span><span class=\"m\">17<\/span>:25:43<span class=\"w\"> <\/span>UTC\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>IDAT<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x00072,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">200<\/span>\n<span class=\"w\">    <\/span>zlib:<span class=\"w\"> <\/span>deflated,<span class=\"w\"> <\/span>2K<span class=\"w\"> <\/span>window,<span class=\"w\"> <\/span>maximum<span class=\"w\"> <\/span>compression\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>tEXt<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x00146,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">37<\/span>,<span class=\"w\"> <\/span>keyword:<span class=\"w\"> <\/span>date:create\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>tEXt<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x00177,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">37<\/span>,<span class=\"w\"> <\/span>keyword:<span class=\"w\"> <\/span>date:modify\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>tEXt<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x001a8,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">40<\/span>,<span class=\"w\"> <\/span>keyword:<span class=\"w\"> <\/span>date:timestamp\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>IEND<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x001dc,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">0<\/span>\nNo<span class=\"w\"> <\/span>errors<span class=\"w\"> <\/span>detected<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>qrcode_without_dpi.png<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">9<\/span><span class=\"w\"> <\/span>chunks,<span class=\"w\"> <\/span><span class=\"m\">72<\/span>.2%<span class=\"w\"> <\/span>compression<span class=\"o\">)<\/span>.\n<\/code><\/pre><\/div>\n\n<p>It reports the chunks in the order it scans them, and some details about each,\nand summarizes with a status line about any errors (of which there should be\nnone), the total number of chunks as well as the overall compression of the\nfile.<\/p>\n<p>If we do the same with the modified <code>qrcode_50_dpi.png<\/code>, we can see the added\n<code>pHYs<\/code> chunk just after the <code>IHDR<\/code> chunk.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pngcheck<span class=\"w\"> <\/span>-v<span class=\"w\"> <\/span>qrcode_50_dpi.png\nFile:<span class=\"w\"> <\/span>qrcode_50_dpi.png<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">505<\/span><span class=\"w\"> <\/span>bytes<span class=\"o\">)<\/span>\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>IHDR<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x0000c,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">13<\/span>\n<span class=\"w\">    <\/span><span class=\"m\">116<\/span><span class=\"w\"> <\/span>x<span class=\"w\"> <\/span><span class=\"m\">116<\/span><span class=\"w\"> <\/span>image,<span class=\"w\"> <\/span><span class=\"m\">1<\/span>-bit<span class=\"w\"> <\/span>grayscale,<span class=\"w\"> <\/span>non-interlaced\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>pHYs<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x00025,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">9<\/span>:<span class=\"w\"> <\/span>1968x1968<span class=\"w\"> <\/span>pixels\/meter<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">50<\/span><span class=\"w\"> <\/span>dpi<span class=\"o\">)<\/span>\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>cHRM<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x0003a,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">32<\/span>\n<span class=\"w\">    <\/span>White<span class=\"w\"> <\/span><span class=\"nv\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.3127<span class=\"w\"> <\/span><span class=\"nv\">y<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.329,<span class=\"w\">  <\/span>Red<span class=\"w\"> <\/span><span class=\"nv\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.64<span class=\"w\"> <\/span><span class=\"nv\">y<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.33\n<span class=\"w\">    <\/span>Green<span class=\"w\"> <\/span><span class=\"nv\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.3<span class=\"w\"> <\/span><span class=\"nv\">y<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.6,<span class=\"w\">  <\/span>Blue<span class=\"w\"> <\/span><span class=\"nv\">x<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.15<span class=\"w\"> <\/span><span class=\"nv\">y<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.06\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>bKGD<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x00066,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">2<\/span>\n<span class=\"w\">    <\/span><span class=\"nv\">gray<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>0x0000\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>tIME<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x00074,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">7<\/span>:<span class=\"w\">  <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>Nov<span class=\"w\"> <\/span><span class=\"m\">2024<\/span><span class=\"w\"> <\/span><span class=\"m\">17<\/span>:25:43<span class=\"w\"> <\/span>UTC\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>IDAT<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x00087,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">200<\/span>\n<span class=\"w\">    <\/span>zlib:<span class=\"w\"> <\/span>deflated,<span class=\"w\"> <\/span>2K<span class=\"w\"> <\/span>window,<span class=\"w\"> <\/span>maximum<span class=\"w\"> <\/span>compression\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>tEXt<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x0015b,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">37<\/span>,<span class=\"w\"> <\/span>keyword:<span class=\"w\"> <\/span>date:create\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>tEXt<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x0018c,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">37<\/span>,<span class=\"w\"> <\/span>keyword:<span class=\"w\"> <\/span>date:modify\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>tEXt<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x001bd,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">40<\/span>,<span class=\"w\"> <\/span>keyword:<span class=\"w\"> <\/span>date:timestamp\n<span class=\"w\">  <\/span>chunk<span class=\"w\"> <\/span>IEND<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>offset<span class=\"w\"> <\/span>0x001f1,<span class=\"w\"> <\/span>length<span class=\"w\"> <\/span><span class=\"m\">0<\/span>\nNo<span class=\"w\"> <\/span>errors<span class=\"w\"> <\/span>detected<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>qrcode_50_dpi.png<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">10<\/span><span class=\"w\"> <\/span>chunks,<span class=\"w\"> <\/span><span class=\"m\">71<\/span>.0%<span class=\"w\"> <\/span>compression<span class=\"o\">)<\/span>.\n<\/code><\/pre><\/div>\n\n<p><code>pngcheck<\/code> is kind enough to report both the literal value, 1968x1968\npixels\/meter, as well as the more industry standard 50 DPI. Note also how the\nfinal status line still reports no errors, and that there are now 10 chunks in\ntotal.<\/p>\n<p>If you just want to check the integrity of the PNG file, running <code>pngcheck<\/code>\nwithout the <code>-v<\/code> returns only a single, summarized status line.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pngcheck<span class=\"w\"> <\/span>-v<span class=\"w\"> <\/span>qrcode_50_dpi.png\nOK:<span class=\"w\"> <\/span>qrcode_50_dpi.png<span class=\"w\"> <\/span><span class=\"o\">(<\/span>116x116,<span class=\"w\"> <\/span><span class=\"m\">1<\/span>-bit<span class=\"w\"> <\/span>grayscale,<span class=\"w\"> <\/span>non-interlaced,<span class=\"w\"> <\/span><span class=\"m\">71<\/span>.0%<span class=\"o\">)<\/span>.\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p><strong>Note:<\/strong> For a more comprehensive set of image inspection and manipulation\ncommands, I recommend <a href=\"https:\/\/imagemagick.org\/\">ImageMagick<\/a>. Its <a href=\"https:\/\/imagemagick.org\/script\/identify.php\">identify\ncommand<\/a> can do many of the same\nthings as <code>pngcheck<\/code>, and is also more general purpose and can work with a\nwide variety of image formats. I chose not to use it for this article as it's\na significantly more complicated tool than <code>pngcheck<\/code>.<\/p>\n<\/blockquote>\n<h2 id=\"caveat-what-if-there-already-is-a-phys-chunk-in-the-file\">Caveat - what if there already is a <code>pHYs<\/code> chunk in the file?<\/h2>\n<p>As you may have noted, this implementation relies on the fact that there isn't\nalready a <code>pHYs<\/code> chunk in the PNG file, and therefore we can simply add one\nafter the <code>IHDR<\/code> chunk. For a more generalized solution, we should parse the PNG\nfile and replace any existing <code>pHYs<\/code> chunk. That's really not very difficult,\ngiven how all the chunks start with the data chunk length and are therefore easy\nto skip over<sup id=\"sf-set-png-dpi-4-back\"><a href=\"#sf-set-png-dpi-4\" class=\"simple-footnote\" title=\"The length of a chunk is always 12 + len(data), due to the fixed size of the length, type and checksum fields.\">4<\/a><\/sup>, but it was still\nwell beyond what was needed for my implementation.<\/p>\n<h1 id=\"and-now-you-know-how-to-set-the-dpi-on-a-png\">And now you know how to set the DPI on a PNG!<\/h1>\n<p>Working with binary formats may seem daunting if you're not used to it, but most\noften, it really isn't that difficult. In fact, the PNG format is <em>very<\/em> easy to\nwork with due to the consistent layout of the chunks. I think the challenge lies\nprimarily in reading and understanding specifications, and that's something that\ntakes a bit of practice.<\/p>\n<p>Some may still think that I should have just pulled in a library for this, but I\nstrongly disagree. Not only is the final solution <a href=\"#putting-it-all-together\">both fairly short and\nsimple<\/a>, but I also now have a solid understanding for\nthe fundamentals of the PNG file format and have improved my understanding of\nimage formats in general.<\/p>\n<h1 id=\"putting-it-all-together\">Putting it all together<\/h1>\n<p>Putting this all together in a fully functioning Python script, it could look\nlike this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">binascii<\/span>\n<span class=\"kn\">import<\/span> <span class=\"nn\">pathlib<\/span>\n\n<span class=\"n\">PNG_SIGNATURE<\/span> <span class=\"o\">=<\/span> <span class=\"sa\">b<\/span><span class=\"s1\">'<\/span><span class=\"se\">\\x89\\x50\\x4e\\x47\\x0D\\x0A\\x1A\\x0A<\/span><span class=\"s1\">'<\/span>\n\n<span class=\"c1\"># the IHDR field is 25 bytes: [ length | 4 bytes ] [ type | 4 bytes ] [ data | 13 bytes ] [ checksum | 4 bytes ]<\/span>\n<span class=\"n\">IHDR_SIZE<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">25<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">main<\/span><span class=\"p\">():<\/span>\n    <span class=\"n\">qrcode_path<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pathlib<\/span><span class=\"o\">.<\/span><span class=\"n\">Path<\/span><span class=\"p\">(<\/span><span class=\"s2\">\"qrcode.png\"<\/span><span class=\"p\">)<\/span><span class=\"o\">.<\/span><span class=\"n\">absolute<\/span><span class=\"p\">()<\/span>\n    <span class=\"n\">qrcode_data<\/span> <span class=\"o\">=<\/span> <span class=\"n\">qrcode_path<\/span><span class=\"o\">.<\/span><span class=\"n\">read_bytes<\/span><span class=\"p\">()<\/span>\n    <span class=\"n\">qrcode_data_with_adjusted_dpi<\/span> <span class=\"o\">=<\/span> <span class=\"n\">with_dpi<\/span><span class=\"p\">(<\/span><span class=\"n\">qrcode_data<\/span><span class=\"p\">,<\/span> <span class=\"n\">dots_per_inch<\/span><span class=\"o\">=<\/span><span class=\"mi\">100<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">pathlib<\/span><span class=\"o\">.<\/span><span class=\"n\">Path<\/span><span class=\"p\">(<\/span><span class=\"s2\">\"qrcode_with_dpi.png\"<\/span><span class=\"p\">)<\/span><span class=\"o\">.<\/span><span class=\"n\">write_bytes<\/span><span class=\"p\">(<\/span><span class=\"n\">qrcode_data_with_adjusted_dpi<\/span><span class=\"p\">)<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">with_dpi<\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span> <span class=\"nb\">bytes<\/span><span class=\"p\">,<\/span> <span class=\"n\">dots_per_inch<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span><span class=\"p\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nb\">bytes<\/span><span class=\"p\">:<\/span>\n    <span class=\"k\">if<\/span> <span class=\"ow\">not<\/span> <span class=\"n\">data<\/span><span class=\"o\">.<\/span><span class=\"n\">startswith<\/span><span class=\"p\">(<\/span><span class=\"n\">PNG_SIGNATURE<\/span><span class=\"p\">):<\/span>\n        <span class=\"k\">raise<\/span> <span class=\"ne\">ValueError<\/span><span class=\"p\">(<\/span><span class=\"s2\">\"Not a PNG image\"<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"n\">signature_and_ihdr<\/span> <span class=\"o\">=<\/span> <span class=\"n\">data<\/span><span class=\"p\">[:<\/span><span class=\"nb\">len<\/span><span class=\"p\">(<\/span><span class=\"n\">PNG_SIGNATURE<\/span><span class=\"p\">)<\/span> <span class=\"o\">+<\/span> <span class=\"n\">IHDR_SIZE<\/span><span class=\"p\">]<\/span>\n    <span class=\"n\">rest<\/span> <span class=\"o\">=<\/span> <span class=\"n\">data<\/span><span class=\"p\">[<\/span><span class=\"nb\">len<\/span><span class=\"p\">(<\/span><span class=\"n\">signature_and_ihdr<\/span><span class=\"p\">):]<\/span>\n\n    <span class=\"n\">phys_chunk<\/span> <span class=\"o\">=<\/span> <span class=\"n\">create_phys_chunk<\/span><span class=\"p\">(<\/span><span class=\"n\">dots_per_inch<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"k\">return<\/span> <span class=\"n\">signature_and_ihdr<\/span> <span class=\"o\">+<\/span> <span class=\"n\">phys_chunk<\/span> <span class=\"o\">+<\/span> <span class=\"n\">rest<\/span>\n\n\n<span class=\"k\">def<\/span> <span class=\"nf\">create_phys_chunk<\/span><span class=\"p\">(<\/span><span class=\"n\">dots_per_inch<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span><span class=\"p\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nb\">bytes<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">\"\"\"Create a pHYs chunk with the specified dots per inch, converted to the<\/span>\n<span class=\"sd\">    PNG native pixels per meter.<\/span>\n<span class=\"sd\">    \"\"\"<\/span>\n    <span class=\"n\">length_field<\/span> <span class=\"o\">=<\/span> <span class=\"sa\">b<\/span><span class=\"s2\">\"<\/span><span class=\"se\">\\x00\\x00\\x00\\x09<\/span><span class=\"s2\">\"<\/span>\n    <span class=\"n\">type_field<\/span> <span class=\"o\">=<\/span> <span class=\"sa\">b<\/span><span class=\"s2\">\"pHYs\"<\/span>\n\n    <span class=\"n\">inches_per_meter<\/span> <span class=\"o\">=<\/span> <span class=\"mf\">39.37008<\/span>\n    <span class=\"n\">dots_per_meter<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">int<\/span><span class=\"p\">(<\/span><span class=\"n\">dots_per_inch<\/span> <span class=\"o\">*<\/span> <span class=\"n\">inches_per_meter<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">pixels_per_meter_field<\/span> <span class=\"o\">=<\/span> <span class=\"n\">dots_per_meter<\/span><span class=\"o\">.<\/span><span class=\"n\">to_bytes<\/span><span class=\"p\">(<\/span><span class=\"n\">length<\/span><span class=\"o\">=<\/span><span class=\"mi\">4<\/span><span class=\"p\">,<\/span> <span class=\"n\">byteorder<\/span><span class=\"o\">=<\/span><span class=\"s2\">\"big\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">unit_field<\/span> <span class=\"o\">=<\/span> <span class=\"sa\">b<\/span><span class=\"s2\">\"<\/span><span class=\"se\">\\x01<\/span><span class=\"s2\">\"<\/span>\n\n    <span class=\"n\">type_and_data<\/span> <span class=\"o\">=<\/span> <span class=\"n\">type_field<\/span> <span class=\"o\">+<\/span> <span class=\"n\">pixels_per_meter_field<\/span> <span class=\"o\">+<\/span> <span class=\"n\">pixels_per_meter_field<\/span> <span class=\"o\">+<\/span> <span class=\"n\">unit_field<\/span>\n    <span class=\"n\">checksum<\/span> <span class=\"o\">=<\/span> <span class=\"n\">binascii<\/span><span class=\"o\">.<\/span><span class=\"n\">crc32<\/span><span class=\"p\">(<\/span><span class=\"n\">type_and_data<\/span><span class=\"p\">)<\/span><span class=\"o\">.<\/span><span class=\"n\">to_bytes<\/span><span class=\"p\">(<\/span><span class=\"n\">length<\/span><span class=\"o\">=<\/span><span class=\"mi\">4<\/span><span class=\"p\">,<\/span> <span class=\"n\">byteorder<\/span><span class=\"o\">=<\/span><span class=\"s2\">\"big\"<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"k\">return<\/span> <span class=\"n\">length_field<\/span> <span class=\"o\">+<\/span> <span class=\"n\">type_and_data<\/span> <span class=\"o\">+<\/span> <span class=\"n\">checksum<\/span>\n\n\n<span class=\"k\">if<\/span> <span class=\"vm\">__name__<\/span> <span class=\"o\">==<\/span> <span class=\"s2\">\"__main__\"<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">main<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div><ol class=\"simple-footnotes\"><li id=\"sf-set-png-dpi-1\">That's\nfancy speak for \"optional\" <a href=\"#sf-set-png-dpi-1-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-set-png-dpi-2\">The PNG chunk types\nare readable as plaintext. Open a PNG in any text editor that isn't afraid to\nread a file that isn't entirely plaintext, and you'll most often be able to tell\nif a chunk is present or not. <a href=\"#sf-set-png-dpi-2-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-set-png-dpi-3\">There are some ordering rules. For example, if there are multiple\n<code>IDAT<\/code> chunks, <a href=\"https:\/\/www.w3.org\/TR\/png-3\/#11IDAT\">they must appear consecutively, with no other kinds of chunks in\nbetween<\/a>. <a href=\"#sf-set-png-dpi-3-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-set-png-dpi-4\">The length of a chunk is always <code>12 + len(data)<\/code>, due to the\nfixed size of the length, type and checksum fields. <a href=\"#sf-set-png-dpi-4-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><\/ol>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"python"}},{"@attributes":{"term":"png"}},{"@attributes":{"term":"dpi"}}]},{"title":"Developer PSA: Learn to type!","link":{"@attributes":{"href":"https:\/\/slar.se\/learn-to-type.html","rel":"alternate"}},"published":"2024-10-19T00:00:00+02:00","updated":"2024-10-19T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2024-10-19:\/learn-to-type.html","summary":"<p>Humans aren't great at multitasking. You can focus on just about one thing at a\ntime. This doesn't mean that you can only <em>do<\/em> one thing at a time, because not\nall things you do require your full attention. For example, try walking around,\nbut before taking each step, really \u2026<\/p>","content":"<p>Humans aren't great at multitasking. You can focus on just about one thing at a\ntime. This doesn't mean that you can only <em>do<\/em> one thing at a time, because not\nall things you do require your full attention. For example, try walking around,\nbut before taking each step, really focus on moving that foot forward. Think\neach step out loud like you haven't walked before. It will probably work out\nfine: the movement is itself the end goal and holds all of your attention.\nHowever, what if you turn that movement into a means to an end, where that end\nis to do something far more complex, such as playing soccer? You will find that\nit is near impossible to focus on the individual steps while at the same time\nachieving that higher goal. But, clearly, people play soccer just fine, because\nthey aren't actually <em>focusing<\/em> on moving their body. It's so engrained in their\nmuscle memory that it just kind of happens. Like an auto pilot.<\/p>\n<p>Programming is similar. The higher goal is to build a program, while the means\nto an end is typing on a keyboard. To be able to fully focus on the former, the\nlatter needs to be on auto pilot. Many programmers that I've worked with or\ntrained have not had typing on auto pilot. They frequently need to pause what\nthey're doing to search for the <code>$<\/code> symbol for the umpteenth time, or struggle\nto get a pair of brackets in place. The typing requires some amount of focus,\nwhich detracts focus from actually building the program. They are effectively\nmultitasking on something that should be a single activity. This is further\nexasperated by pair-programming situations, where there's also a level of\ncommunication involved.<\/p>\n<p>You need to get the typing on auto pilot. It should just happen. Some will make\na counterpoint in saying that the vast majority of time in programming is spent\nreading code rather than writing code, and so becoming faster at typing\ndoesn't really gain you that many benefits. Except it's not about becoming\nfaster, it's about reducing mental strain while programming, so that\ncounterpoint completely misses the mark. The fact that becoming a more\nproficient typist also makes you faster is simply a neat side effect. And\nbecoming proficient really isn't very difficult. Let me tell you how I did it.<\/p>\n<h1 id=\"learning-finger-placement\">Learning finger placement<\/h1>\n<p>The first thing to learn about typing is the very basics: finger placement. You\nshouldn't be using your right index finger to do 90% of the typing, and your\nleft pinky shouldn't be completely unutilized. They all need to contribute.<\/p>\n<p>A good place to start is <a href=\"https:\/\/thetypingcat.com\/typing-speed-test\">TypingCat<\/a>.\nIt shows you where to position your fingers while typing each character. I used\nit frequently when learning the Colemak layout and it worked great for\nme<sup id=\"sf-learn-to-type-1-back\"><a href=\"#sf-learn-to-type-1\" class=\"simple-footnote\" title=\"You do not need to switch to another keyboard layout. The scientific evidence for the superiority of alternate layouts is dubious at best. I did it only because I like to try new things.\">1<\/a><\/sup>. You very likely have some nasty\nhabits to unlearn when it comes to finger placement, so be judicious about\nusing the fingers indicated. Go very slow until you feel like you're starting to\nutilize all fingers at your disposal.<\/p>\n<p><img alt=\"The TypingCat online typing tutor\" src=\"https:\/\/slar.se\/photos\/learn_to_type\/typingcata.jpg\"><\/p>\n<p>Practice this 10-15 minutes every day before you start work, and you should see\nimprovements to your typing fairly quickly. Keep in mind that accuracy and\ncomfort are more important than speed. The end goal is not to become blazingly\nfast, but to reduce the amount of focus you need to put into the typing.<\/p>\n<p>Speed will however come with time, and combined with accuracy, you have two easy\nto measure metrics to gauge your improvements. Seeing such concrete improvements\ncan be a fun motivator to keep you practicing. I will however refrain from\nproviding any hard numbers about what speeds you should reach as it's fairly\narbitrary. But in terms of accuracy, you should aim for near perfect scores at\nall times. If you are inaccurate, you are typing too fast and need to slow down.<\/p>\n<p>At this stage, you will also likely be looking at your keyboard quite\nfrequently. However, you should be <a href=\"https:\/\/en.wikipedia.org\/wiki\/Touch_typing\">touch\ntyping<\/a> comfortably and accurately\nbefore you graduate to the next level of practice.<\/p>\n<h1 id=\"leveling-up\">Leveling up<\/h1>\n<p>Once you've gotten the basics down and can touch type comfortably, I would\nsuggest proceeding to <a href=\"https:\/\/monkeytype.com\/\">monkeytype<\/a> as it's a lot more\ncustomizable. Use the basic configuration in the beginning, and practice 10-15\nminutes a day until you start to feel comfortable and get near perfect accuracy.<\/p>\n<p>Then start adding in punctuation and numbers<sup id=\"sf-learn-to-type-2-back\"><a href=\"#sf-learn-to-type-2\" class=\"simple-footnote\" title=\"There is a toolbar above the typing area where you can adjust such things\">2<\/a><\/sup>. Finally, you can change the\n\"language\" to whatever programming language you're currently using and you'll\nget words and symbols drafted from it<sup id=\"sf-learn-to-type-3-back\"><a href=\"#sf-learn-to-type-3\" class=\"simple-footnote\" title=\"The language can be selected just above the typing area. All programming languages are called code <language>, e.g. code javascript.\">3<\/a><\/sup>. This will allow you to practice the special\ncharacters that are relevant to your programming language of choice.<\/p>\n<p>You can even go so far as to upload your own custom text (perhaps some code) by\nclicking <code>custom<\/code> and then <code>change<\/code> to the very far right of the toolbar! It's\nnot something I ever did as, at that point, I think it's better to practice\ntyping in your editor instead, but it's an option if you really like monkeytype.<\/p>\n<blockquote>\n<p>Even though I consider myself a highly proficient typist, I still practice on\nmonkeytype every now and then.<\/p>\n<\/blockquote>\n<h1 id=\"some-words-about-keyboard-layout\">Some words about keyboard layout<\/h1>\n<p>While I don't think there's good reason for most people to switch from the\nstandard QWERTY keyboard layout, there <em>is<\/em> good reason to choose a variant of\nthat layout that's well suited for programming. A layout that I find absolutely\natrocious for programming is the Swedish and Finnish multilingual layout (both\nvery similar).<\/p>\n<p><img alt=\"The Finnish multilingual keyboard layout\" src=\"\/images\/learn_to_type\/KB_Finnish_Multilingual.svg\" style=\"max-width: 95%;\"><\/p>\n<blockquote>\n<p>The Finnish multilingual keyboard layout, sourced from Wikipedia<sup id=\"sf-learn-to-type-4-back\"><a href=\"#sf-learn-to-type-4\" class=\"simple-footnote\" title=\"By KB_Sweden.svg: adapted by StuartBrady from File:KB United Kingdom.svgderivative work: Simo Kaupinm\u00e4ki (talk) (created in Inkscape; text converted to paths due to use of the uncommon FreeSans font) - KB_Sweden.svg, CC BY-SA 3.0, https:\/\/commons.wikimedia.org\/w\/index.php?curid=10276924\">4<\/a><\/sup><\/p>\n<\/blockquote>\n<p>The big problem with this layout is that the hard brackets (<code>[]<\/code>) and curly\nbraces (<code>{}<\/code>) require some real hand acrobatics, where you hold down <code>alt gr<\/code>\nand press one of 7, 8, 9 or 0. I personally started getting some wrist pain from\ndoing that very awkward movement over and over again. I found relief in the US\nANSI QWERTY layout, where the same characters are conveniently located just\nabove the home row, and hard brackets don't even require pressing a modifier\nkey.<\/p>\n<p><img alt=\"The US ANSI QWERTY layout\" src=\"\/images\/learn_to_type\/KB_United_States.svg\" style=\"max-width: 95%;\"><\/p>\n<blockquote>\n<p>The US ANSI QWERTY layout, sourced from Wikipedia<sup id=\"sf-learn-to-type-5-back\"><a href=\"#sf-learn-to-type-5\" class=\"simple-footnote\" title=\"By No machine-readable author provided. Denelson83 assumed (based on copyright claims). - No machine-readable source provided. Own work assumed (based on copyright claims)., CC BY-SA 3.0, https:\/\/commons.wikimedia.org\/w\/index.php?curid=508928\">5<\/a><\/sup><\/p>\n<\/blockquote>\n<p>It made quite the difference for me. So if you live in a country with a quirky\nlayout, where some frequently used programming characters are in awkward\npositions, consider adopting a layout that is more appropriate for programming.<\/p>\n<h1 id=\"closing-words\">Closing words<\/h1>\n<p>Trust me when I say that learning to type properly will really benefit you in\nthe long run. I'm not advocating that you practice for hours a day and become\nthe fastest typist in town, but that you become proficient enough with typing\nthat it's not something you have to think about when you're working on complex\nproblems. All your focus should be toward solving the problem at hand, and\nhaving to divert attention to the typing is such an unnecessary distraction to\nhave. If I could switch keyboard layout from QWERTY to Colemak within a couple\nof months and without too much effort spent, you can become proficient with the\nlayout you're already using without too much effort as well.<\/p><ol class=\"simple-footnotes\"><li id=\"sf-learn-to-type-1\">You do not need to switch to another keyboard layout. The scientific\nevidence for the superiority of alternate layouts is dubious at best. I did it\nonly because I like to try new things. <a href=\"#sf-learn-to-type-1-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-learn-to-type-2\">There is a toolbar above the\ntyping area where you can adjust such things <a href=\"#sf-learn-to-type-2-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-learn-to-type-3\">The language can be selected just\nabove the typing area. All programming languages are called <code>code &lt;language&gt;<\/code>,\ne.g. <code>code javascript<\/code>. <a href=\"#sf-learn-to-type-3-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-learn-to-type-4\">By KB_Sweden.svg: adapted by StuartBrady from File:KB United Kingdom.svgderivative work: Simo Kaupinm\u00e4ki (talk) (created in Inkscape; text converted to paths due to use of the uncommon FreeSans font) - KB_Sweden.svg, CC BY-SA 3.0, https:\/\/commons.wikimedia.org\/w\/index.php?curid=10276924 <a href=\"#sf-learn-to-type-4-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-learn-to-type-5\">By No machine-readable author provided. Denelson83 assumed (based on copyright claims). - No machine-readable source provided. Own work assumed (based on copyright claims)., CC BY-SA 3.0, https:\/\/commons.wikimedia.org\/w\/index.php?curid=508928 <a href=\"#sf-learn-to-type-5-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><\/ol>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"software engineering"}}]},{"title":"Taking a step back from open source development","link":{"@attributes":{"href":"https:\/\/slar.se\/taking-a-step-back-from-open-source-development.html","rel":"alternate"}},"published":"2024-08-18T00:00:00+02:00","updated":"2024-08-18T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2024-08-18:\/taking-a-step-back-from-open-source-development.html","summary":"<p>Over the past couple of years, I've half-heartedly tried to keep up with the\nbar I set for open source contributions back when I was in university. It has\nnot been easy, and ultimately I haven't been able to align my current projects\nwith where I'm taking my career. I's \u2026<\/p>","content":"<p>Over the past couple of years, I've half-heartedly tried to keep up with the\nbar I set for open source contributions back when I was in university. It has\nnot been easy, and ultimately I haven't been able to align my current projects\nwith where I'm taking my career. I's time for me to take a step back.<\/p>\n<blockquote>\n<p>tl;dr. I am taking a step back from open source development. Response times on\nmy open source repositories will be slow. Sometimes I may not respond at all.\nOpen source development is not one of my current focus points; my free time is\nspent elsewhere.<\/p>\n<\/blockquote>\n<h1 id=\"open-source-development-got-me-to-where-i-am\">Open source development got me to where I am<\/h1>\n<p>From creating <a href=\"https:\/\/repobee.org\">RepoBee<\/a> to maintaining\n<a href=\"https:\/\/github.com\/inria\/spoon\">Spoon<\/a>, I've spent thousands upon\nthousands of hours of my free time contributing to projects and putting them out\nthere for the world to see and use. It served me well in developing my skills,\nbut also in more unexpected ways such as opening doors to <a href=\"https:\/\/slar.se\/pages\/publications-and-essays.html\">publishing articles\nat academic conferences<\/a> and\nmentoring more junior developers well before I had a full time\njob<sup id=\"sf-taking-a-step-back-from-open-source-development-1-back\"><a href=\"#sf-taking-a-step-back-from-open-source-development-1\" class=\"simple-footnote\" title=\"Sadly, I never managed to find someone to mentor me.\">1<\/a><\/sup>. I am fully\nconvinced that I would not be nearly as skilled a software engineer as I am\ntoday had I not had these experiences. Given the choice, I would take the exact\nsame path all over again.<\/p>\n<h1 id=\"but-things-have-changed\">But things have changed<\/h1>\n<p>I loved open source development as a university student because it gave me the\nopportunity to collaborate with other developers on <em>real<\/em> and <em>long-term<\/em>\nprojects, honing skills that were not being honed in the predominantly\ntheoretical computer science program I attended<sup id=\"sf-taking-a-step-back-from-open-source-development-2-back\"><a href=\"#sf-taking-a-step-back-from-open-source-development-2\" class=\"simple-footnote\" title=\"I still think that studying computer science was well worth my time, but that's a topic for another blog post.\">2<\/a><\/sup>. I needed to ground the theoretical learnings in practical\napplication, and open source development gave me an outlet where I could do just\nthat.<\/p>\n<p>However, I must now recognize that those circumstances are in the past, and new\ncircumstances surround my day-to-day. A lot of what I got out of open source\ndevelopment as a student, such as collaboration and real-world application, I'm\nnow getting from my job. This greatly lessens the appeal of open source\ndevelopment for me, as it was never about some altruistic notion of helping\nothers, but about what I could learn from the experience. It was all part of my\nskills development process.<\/p>\n<p>What I <em>now<\/em> desire from my skills development in my free time is to explore new\ntechnologies and concepts that I don't have time or reason to work with on the\njob. This leads to a lot of <a href=\"https:\/\/slar.se\/syntax-highlight-anything-with-tree-sitter.html\">doing a little bit of\nthis<\/a> and <a href=\"content\/blog\/Programming\/postgresql\/basic_indexing.md\">a little\nbit of that<\/a>. While this\nmay still translate to the odd <a href=\"https:\/\/github.com\/slarse\/rut\">open source repository with some half-finished\nproject<\/a>, it does not mesh well with long-term\nmaintenance of established projects.<\/p>\n<h1 id=\"so-whats-up-now\">So what's up now?<\/h1>\n<p>This disconnect between my own needs and open source development has been\nweighing on me for years. I've felt guilty for neglecting the projects I\nmaintain, but at the same time haven't been able to do anything about it.\nA little while back, I decided that it wasn't a healthy way to go about it, and\ndecided to more officially scale down my open source involvement. I started out\nby <a href=\"https:\/\/github.com\/INRIA\/spoon\/pull\/5863\">resigning as a maintainer of Spoon<\/a>,\nand am finishing up with this blog post as a statement of my intentions.<\/p>\n<p>I will still attempt to respond to issues and PRs on my existing open source\nprojects. I will attempt to fix critical bugs in any project I maintain. But the\nkeyword is <em>attempt<\/em>. I make no promises about anything, responses from me will\nlikely be few and far between. Complex issues may never be investigated, and\nmajor PRs with difficult to integrate code will likely not be integrated.<\/p>\n<p>Things may change in the future. I may find that spark for open source\ndevelopment again and dive back into it. But now is not that time. Right now, I\njust want time for myself to tinker with things that interest me, but are of\nlittle use to others in the state that I leave them.<\/p><ol class=\"simple-footnotes\"><li id=\"sf-taking-a-step-back-from-open-source-development-1\">Sadly, I never managed to find someone to mentor <em>me<\/em>. <a href=\"#sf-taking-a-step-back-from-open-source-development-1-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-taking-a-step-back-from-open-source-development-2\">I still think that studying\ncomputer science was well worth my time, but that's a topic for another blog\npost. <a href=\"#sf-taking-a-step-back-from-open-source-development-2-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><\/ol>","category":[{"@attributes":{"term":"Blog"}},{"@attributes":{"term":"blog"}},{"@attributes":{"term":"open source"}},{"@attributes":{"term":"software engineering"}}]},{"title":"Book Review: Cybersecurity Myths and Misconceptions","link":{"@attributes":{"href":"https:\/\/slar.se\/book-review-cybersecurity-myths-and-misconceptions.html","rel":"alternate"}},"published":"2024-07-05T00:00:00+02:00","updated":"2024-07-05T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2024-07-05:\/book-review-cybersecurity-myths-and-misconceptions.html","summary":"<p>The world of cybersecurity is full of perils. Many of those perils stem from\nmisconceptions about the nature of cybersecurity. If you come to the insight\nthat perfect security is unachievable, you may reach the conclusion that\nbeing concerned with cybersecurity at all is a waste of your time. After \u2026<\/p>","content":"<p>The world of cybersecurity is full of perils. Many of those perils stem from\nmisconceptions about the nature of cybersecurity. If you come to the insight\nthat perfect security is unachievable, you may reach the conclusion that\nbeing concerned with cybersecurity at all is a waste of your time. After all,\nthe bad guys will get in anyway. Or you may have the notion that your particular\ncompany is too small of a target for anyone to bother with, and so you don't\nbother to defend yourself appropriately. Or perhaps you experience a security\nbreach and take action before you even know what's going on, because surely,\nsome action is better than no action. If reading about 175 statements of this\nkind and why they're flawed, then <em>Cybersecurity Myths and\nMisconceptions: Avoiding the Hazards and Pitfalls that Derail Us<\/em> may be the\nbook for you.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>Cybersecurity Myths and Misconceptions: Avoiding the Hazards and Pitfalls that Derail Us\nby Eugene Spafford, Josiah Dykstra, Leigh Metcalf\nReleased January 2023\nPublisher(s): Pearson Education (US)\nISBN: 9780137929238\n<\/code><\/pre><\/div>\n\n<h1 id=\"the-book-in-a-nutshell\">The book in a nutshell<\/h1>\n<p>The book covers 175 myths and misconceptions in cybersecurity. These are divided\ninto 16 chapters covering different topics ranging from faulty assumptions\n(e.g. \"I am too small to be a target\"<sup id=\"sf-book-review-cybersecurity-myths-and-misconceptions-1-back\"><a href=\"#sf-book-review-cybersecurity-myths-and-misconceptions-1\" class=\"simple-footnote\" title=\"You are not. A lot of cyber mischief isn't even targeted, but rather automated processes scanning vast amounts of the Internet to find servers with known vulnerabilities.\">1<\/a><\/sup>) to misconceptions\nabout digital forensics (e.g. \"Incidents are discovered as soon as they\noccur\"<sup id=\"sf-book-review-cybersecurity-myths-and-misconceptions-2-back\"><a href=\"#sf-book-review-cybersecurity-myths-and-misconceptions-2\" class=\"simple-footnote\" title=\"They are not. In 2022, the average time to discovery of a breach was 207 days.\">2<\/a><\/sup>).<\/p>\n<p>The vast majority of the myths are presented in the following format.<\/p>\n<ol>\n<li>Present some background information for the topic to make sense.<\/li>\n<li>Make a bold statement (the myth or misconception)<\/li>\n<li>Dismantle the statement and show how it does not hold water<ul>\n<li>Although some myths are acknowledge to be partially true, given the right\n  circumstances<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p>In some cases, there's also a small fictitious case study of a manager wanting\nto apply some technology or rule motivated by the myth. These can be a bit on\nthe nose, but also occasionally hit too close to home to be comfortable.<\/p>\n<p>For the most part, this is not a technical book. Most myths are presented on high\nenough a level that you do not need to be a software engineer to appreciate it.\nThere are some things that may fly over your head if you're not a software\nengineer, such as talk about the OSI network model and interprocess\ncommunication, but such technical dives are so infrequent that they barely need\nmention.<\/p>\n<h1 id=\"what-i-liked\">What I liked<\/h1>\n<p>This book is a leisure read. It does not require you to sit at a computer and\napply concepts to benefit from it, all you need to do is read the book and\nponder its implications. At the same time, it will surely grant you insights\nthat will have tangible effects on your ability to perform in a technical role.<\/p>\n<p>As a concrete example, there is a section about cognitive biases. One such bias\nis so-called <em>action bias<\/em>, where you are prone to take action as a response to\na cybersecurity threat, even before you have understood the situation well\nenough to make a qualified decision about <em>what<\/em> action to take. In reality,\nsometimes no action is the best solution, and rather often I'd say that no\naction is better than the <em>wrong<\/em> action. While I have experience enough to know\nnot to act prematurely, and sometimes not to act at all, I am definitely\npredisposed with an action bias. As, I think, are a lot of software engineers.\nWe want to <em>fix<\/em> things, not just wait for them to resolve themselves. Reading\nabout action bias in the way it is framed in this book has caused me to reflect\non how I act, especially in incident response, and I think it will help me take\nan even more measured approach in the future.<\/p>\n<p>In addition to expanding my own mind, I also found that the book framed a whole\nlot of the complaints that I've had to managers and peers over the years. For\nexample, the notion that \"I'm to small to be a target\" is something I've seen a\nlot, and the next time I come across it I very well may use this book as a\nreference to attempt to dissuade it.<\/p>\n<p>A lot of what is covered in the book is also applicable to software engineering\nas a whole (or even business as a whole), rather than just cybersecurity. The\nsunk cost fallacy<sup id=\"sf-book-review-cybersecurity-myths-and-misconceptions-3-back\"><a href=\"#sf-book-review-cybersecurity-myths-and-misconceptions-3\" class=\"simple-footnote\" title=\"The idea that an existing investment in something warrants further investment into the same thing (see Wikipedia)\">3<\/a><\/sup> is\nuniversally applicable when it comes to any costly investment, as is the fact\nthat basing decisions on anecdotal evidence isn't necessarily the best idea.\nThere's also this really insightful chapter on how analogies and abstractions\ncan be damaging to understanding when they don't fit well enough. For example,\nthe name <em>firewall<\/em> comes from physical walls intended to impede the spread of\nfire. A firewall in computing is built to stop some traffic (\"fire\"), but also\nlet some traffic through. The latter does not fit the analogy, a physical\nfirewall shouldn't let <em>any<\/em> fire through.<\/p>\n<p>As a final note on what I liked, there is a running theme in the book that\ninsulting people for their lack of cybersecurity awareness serves no purpose,\nand that guiding others to better decisions rather than berating bad ones is\noften the most effective path. However, there is also an undertone that\nat least some cybersecurity issues stem from software engineers with\ninsufficient skills. When discussing cross-platform compatibility in high-level\nprogramming languages, one footnote reads as follows.<\/p>\n<blockquote>\n<p>We are glossing over many things such as numerical precision, interprocess\ncommunication, and character sets. For this discussion, assume those things do\nnot matter, although they certainly do in real life. If you do not know what\nwe mean by that <strong>and<\/strong> you are writing production software, then you need to\nstudy more software engineering.<\/p>\n<\/blockquote>\n<p>This makes it clear that even though the authors believe in helping and\neducating your peers to the best of your abilities, a base level of\nunderstanding is to be expected from your peers. And that understanding is, at\nleast in part, their responsibility to attain.<\/p>\n<h1 id=\"what-i-didnt-like\">What I didn't like<\/h1>\n<p>There's a large amount of footnotes throughout the book, a lot of which contain\nuseful and interesting snippets of information as well as sources for\nstatements. These, I do not mind at all. But, unfortunately, there is a bit of\nan oversaturation of footnotes that only contain jokes, puns and witty remarks.\nWhile they are all well written and give the book a lighter tone, there are at\ntimes simply too many of them.<\/p>\n<p>Don't get me wrong, I don't mind light-hearted writing, and a few of these kinds\nof footnotes would only have made the book more enjoyable to read. But when you\ninterrupt your reading flow to read a footnote only to be greeted by your third\nwitty remark in a row, it does get a bit annoying.<\/p>\n<h1 id=\"conclusions\">Conclusions<\/h1>\n<p>This book widened my view of software engineering and cybersecurity. While most\nof the topics were familiar to me from my education and professional experience,\nsome were forgotten, some brand new, and many were simply framed in a way I had\npreviously not considered them in. Given the rather limited amount of effort I\nput into reading the book, I got a whole lot of value out of it.<\/p>\n<p>If you're a practicing software engineer, you should read this book, especially\nif you feel like your grasp of cybersecurity topics isn't where it should be. It\nwon't teach you what you need to know on a technical level, but it will help\nbuild up the basic mindset you ought to adopt as well as illuminate a lot of\nwhat you don't yet know.<\/p>\n<p>If you're a technical manager in charge of software engineers, you should read\nthis book. It will give you better insight into why software engineers sometimes\nsay \"no\" and hopefully allow you to make more measured decisions when it comes\nto acquiring new or retaining existing software.<\/p><ol class=\"simple-footnotes\"><li id=\"sf-book-review-cybersecurity-myths-and-misconceptions-1\">You are not. A lot of cyber mischief\nisn't even targeted, but rather automated processes scanning vast amounts of the\nInternet to find servers with known vulnerabilities. <a href=\"#sf-book-review-cybersecurity-myths-and-misconceptions-1-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-book-review-cybersecurity-myths-and-misconceptions-2\">They are not. In 2022, the average time to discovery of a breach was\n207 days. <a href=\"#sf-book-review-cybersecurity-myths-and-misconceptions-2-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-book-review-cybersecurity-myths-and-misconceptions-3\">The idea that an existing investment in something warrants\nfurther investment into the same thing <a href=\"https:\/\/en.wikipedia.org\/wiki\/Sunk_cost#Fallacy_effect\">(see\nWikipedia)<\/a> <a href=\"#sf-book-review-cybersecurity-myths-and-misconceptions-3-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><\/ol>","category":[{"@attributes":{"term":"Reviews"}},{"@attributes":{"term":"book review"}},{"@attributes":{"term":"software engineering"}},{"@attributes":{"term":"cybersecurity"}}]},{"title":"PostgreSQL indexing: The basics","link":{"@attributes":{"href":"https:\/\/slar.se\/postgresql-indexing-basics.html","rel":"alternate"}},"published":"2024-04-02T00:00:00+02:00","updated":"2024-04-02T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2024-04-02:\/postgresql-indexing-basics.html","summary":"<p>Back when I was in university, I had a teacher in database systems who also did\ncontract work as a database administrator. He told me that 90% of his work was\nto just add and reorganize indexes to speed up queries. That was almost 10 years\nago, and I'm now \u2026<\/p>","content":"<p>Back when I was in university, I had a teacher in database systems who also did\ncontract work as a database administrator. He told me that 90% of his work was\nto just add and reorganize indexes to speed up queries. That was almost 10 years\nago, and I'm now inclined to believe him. Having worked on three different\nsystems backed by PostgreSQL databases over the past four years, I've seen my\nfair share of queries missing indexes. The fallout has ranged from a poor end\nuser experience due to slow responses to entire systems becoming unresponsive\nas databases grind to a halt under the load of unindexed queries.<\/p>\n<p>Needless to say, indexing is important. I would go as far as to say that if you\ndon't understand the basics of indexing, you shouldn't be writing queries\nagainst a relational database in a production system. In this article, I'll walk\nyou through the basics of indexing in PostgreSQL, including how an index\nactually works. While this is targeted at PostgreSQL and contains a lot of\nspecifics about it, the general principles of indexing presented here are\napplicable to relational databases in general.<\/p>\n<p>Let's get started.<\/p>\n<blockquote>\n<p>Note: This article is based on PostgreSQL 16, but the vast majority of the\ncontent should be accurate for PostgreSQL 9.6 and newer.<\/p>\n<\/blockquote>\n<div class=\"toc\"><span class=\"toctitle\">Table of Contents<\/span><ul>\n<li><a href=\"#the-incredible-impact-of-indexes\">The incredible impact of indexes<\/a><\/li>\n<li><a href=\"#indexing-in-theory\">Indexing in theory<\/a><ul>\n<li><a href=\"#the-b-tree\">The B-tree<\/a><\/li>\n<li><a href=\"#selecting-ranges-is-almost-as-fast-as-single-values\">Selecting ranges is almost as fast as single values<\/a><\/li>\n<li><a href=\"#indexes-greatly-speed-up-order-by\">Indexes greatly speed up ORDER BY<\/a><\/li>\n<\/ul>\n<\/li>\n<li><a href=\"#indexing-pitfalls\">Indexing pitfalls<\/a><ul>\n<li><a href=\"#the-query-planner-can-choose-not-to-use-an-index\">The query planner can choose not to use an index<\/a><\/li>\n<li><a href=\"#an-index-is-for-an-exact-expression\">An index is for an exact expression<\/a><\/li>\n<li><a href=\"#indexes-optimize-reads-but-slow-down-writes\">Indexes optimize reads but slow down writes<\/a><\/li>\n<\/ul>\n<\/li>\n<li><a href=\"#summary\">Summary<\/a><\/li>\n<\/ul>\n<\/div>\n<h1 id=\"the-incredible-impact-of-indexes\">The incredible impact of indexes<\/h1>\n<p>To sell you on the fact that indexes are important, let's do a quick experiment.\nBelow I define a simple data model and fill it with some sample data.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">CREATE<\/span><span class=\"w\"> <\/span><span class=\"k\">TABLE<\/span><span class=\"w\"> <\/span><span class=\"k\">IF<\/span><span class=\"w\"> <\/span><span class=\"k\">NOT<\/span><span class=\"w\"> <\/span><span class=\"k\">EXISTS<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span>\n<span class=\"w\">  <\/span><span class=\"n\">id<\/span><span class=\"w\"> <\/span><span class=\"nb\">SERIAL<\/span><span class=\"w\"> <\/span><span class=\"k\">PRIMARY<\/span><span class=\"w\"> <\/span><span class=\"k\">KEY<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">  <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"nb\">INT<\/span><span class=\"w\"> <\/span><span class=\"k\">NOT<\/span><span class=\"w\"> <\/span><span class=\"k\">NULL<\/span>\n<span class=\"p\">);<\/span>\n\n<span class=\"c1\">-- seed with 10 million rows where 0 &lt;= value &lt;= 1,000,000<\/span>\n<span class=\"k\">INSERT<\/span><span class=\"w\"> <\/span><span class=\"k\">INTO<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"p\">)<\/span>\n<span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">RANDOM<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"mi\">1000000<\/span><span class=\"p\">)::<\/span><span class=\"nb\">INT<\/span>\n<span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"n\">generate_series<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">10000000<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>This gives us 10 million rows, where the value is between 0 and 1 million, thus\non average giving us 10 duplicates of each value. To be very clear, the data\nlooks like this.<\/p>\n<blockquote>\n<p>Note: <code>test=#<\/code> is my <code>psql<\/code> prompt. I'm using <code>psql<\/code> throughout this article\nto execute queries.<\/p>\n<\/blockquote>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">LIMIT<\/span><span class=\"w\"> <\/span><span class=\"mi\">5<\/span><span class=\"p\">;<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">id<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\">  <\/span>\n<span class=\"c1\">----+--------<\/span>\n<span class=\"w\">  <\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">602761<\/span>\n<span class=\"w\">  <\/span><span class=\"mi\">2<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">744515<\/span>\n<span class=\"w\">  <\/span><span class=\"mi\">3<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">725410<\/span>\n<span class=\"w\">  <\/span><span class=\"mi\">4<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">729718<\/span>\n<span class=\"w\">  <\/span><span class=\"mi\">5<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">783837<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Let's execute two queries, one where we search for a particular <code>id<\/code>, and one\nwhere we search for a particular <code>value<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"err\">\\<\/span><span class=\"n\">timing<\/span>\n<span class=\"n\">Timing<\/span><span class=\"w\"> <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"k\">on<\/span><span class=\"p\">.<\/span>\n<span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">WHERE<\/span><span class=\"w\"> <\/span><span class=\"n\">id<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">id<\/span><span class=\"w\">   <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\">  <\/span>\n<span class=\"c1\">--------+--------<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">650515<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"k\">row<\/span><span class=\"p\">)<\/span>\n\n<span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">845<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n\n<span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">WHERE<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">id<\/span><span class=\"w\">    <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\">  <\/span>\n<span class=\"c1\">---------+--------<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">2068259<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5013963<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">6894022<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">4305566<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">8455242<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">9020004<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">7313065<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">7<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n\n<span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">254<\/span><span class=\"p\">.<\/span><span class=\"mi\">458<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<\/code><\/pre><\/div>\n\n<p>Searching for the <code>id<\/code> took less than a millisecond, while searching for the\n<code>value<\/code> took a quarter of a second. While you could argue that the database had\nto do more work in compiling the results for the <code>value<\/code> search as there were\nmore hits, that shouldn't (and in fact, does not) account for a more than 250x\ntiming difference.<\/p>\n<p>So what's up? Let's have a look at the query plans to find out.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">EXPLAIN<\/span><span class=\"w\"> <\/span><span class=\"k\">ANALYZE<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">WHERE<\/span><span class=\"w\"> <\/span><span class=\"n\">id<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">                                                   <\/span><span class=\"n\">QUERY<\/span><span class=\"w\"> <\/span><span class=\"n\">PLAN<\/span><span class=\"w\">                                                   <\/span>\n<span class=\"c1\">----------------------------------------------------------------------------------------------------------------<\/span>\n<span class=\"w\"> <\/span><span class=\"k\">Index<\/span><span class=\"w\"> <\/span><span class=\"n\">Scan<\/span><span class=\"w\"> <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"n\">data_pkey<\/span><span class=\"w\"> <\/span><span class=\"k\">on<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">43<\/span><span class=\"p\">..<\/span><span class=\"mi\">8<\/span><span class=\"p\">.<\/span><span class=\"mi\">45<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">8<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">016<\/span><span class=\"p\">..<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">017<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">   <\/span><span class=\"k\">Index<\/span><span class=\"w\"> <\/span><span class=\"n\">Cond<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">id<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"p\">)<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Planning<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">058<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Execution<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">030<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">4<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n\n<span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">EXPLAIN<\/span><span class=\"w\"> <\/span><span class=\"k\">ANALYZE<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">WHERE<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">                                                     <\/span><span class=\"n\">QUERY<\/span><span class=\"w\"> <\/span><span class=\"n\">PLAN<\/span><span class=\"w\">                                                      <\/span>\n<span class=\"c1\">---------------------------------------------------------------------------------------------------------------------<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Gather<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">1000<\/span><span class=\"p\">.<\/span><span class=\"mi\">00<\/span><span class=\"p\">..<\/span><span class=\"mi\">97332<\/span><span class=\"p\">.<\/span><span class=\"mi\">43<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">11<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">8<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">74<\/span><span class=\"p\">.<\/span><span class=\"mi\">701<\/span><span class=\"p\">..<\/span><span class=\"mi\">257<\/span><span class=\"p\">.<\/span><span class=\"mi\">131<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">7<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">Workers<\/span><span class=\"w\"> <\/span><span class=\"n\">Planned<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">Workers<\/span><span class=\"w\"> <\/span><span class=\"n\">Launched<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span>\n<span class=\"w\">   <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\">  <\/span><span class=\"n\">Parallel<\/span><span class=\"w\"> <\/span><span class=\"n\">Seq<\/span><span class=\"w\"> <\/span><span class=\"n\">Scan<\/span><span class=\"w\"> <\/span><span class=\"k\">on<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">00<\/span><span class=\"p\">..<\/span><span class=\"mi\">96331<\/span><span class=\"p\">.<\/span><span class=\"mi\">33<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">5<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">8<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">114<\/span><span class=\"p\">.<\/span><span class=\"mi\">550<\/span><span class=\"p\">..<\/span><span class=\"mi\">231<\/span><span class=\"p\">.<\/span><span class=\"mi\">494<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">2<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">3<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">         <\/span><span class=\"n\">Filter<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">         <\/span><span class=\"k\">Rows<\/span><span class=\"w\"> <\/span><span class=\"n\">Removed<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">Filter<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">3333331<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Planning<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">046<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Execution<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">257<\/span><span class=\"p\">.<\/span><span class=\"mi\">164<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">8<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Going deep into query plans is beyond the scope of this article, but we don't\nneed to go deep here. We only need to see that the <code>id<\/code> query does an <em>index\nscan<\/em>, while the <code>value<\/code> query does a <em>seq(uential) scan<\/em>. The former means that\nthe sought value is looked up in an index, while the latter means that the\nentire table is scanned to find the value we're looking for. We can even see\nthat the query planner<sup id=\"sf-postgresql-indexing-basics-1-back\"><a href=\"#sf-postgresql-indexing-basics-1\" class=\"simple-footnote\" title=\"The query planner (or optimizer) is the part of PostgreSQL that's responsible for taking your high-level SQL query and figuring out the fastest way to execute it in the database (source).\">1<\/a><\/sup>\ndecided to do the sequential scan in parallel with two workers, indicating that\nit's a rather heavy query.<\/p>\n<p>Why was <code>id<\/code> indexed and not <code>value<\/code>, you ask? Because the primary key in a\nPostgreSQL table is always indexed, but that's also the only index you get for\nfree. Let's now add an index to <code>value<\/code> as well and see if we can make it a bit\nfaster.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">CREATE<\/span><span class=\"w\"> <\/span><span class=\"k\">INDEX<\/span><span class=\"w\"> <\/span><span class=\"n\">idx_data_value<\/span><span class=\"w\"> <\/span><span class=\"k\">ON<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"p\">);<\/span>\n<span class=\"k\">CREATE<\/span><span class=\"w\"> <\/span><span class=\"k\">INDEX<\/span>\n<span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">WHERE<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">id<\/span><span class=\"w\">    <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\">  <\/span>\n<span class=\"c1\">---------+--------<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">2068259<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">4305566<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5013963<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">6894022<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">7313065<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">8455242<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">9020004<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">7<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n\n<span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"p\">.<\/span><span class=\"mi\">058<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<\/code><\/pre><\/div>\n\n<p>Look at that, as fast as searching for the <code>id<\/code>! If we have a look at the query\nplan, we can see that we now do hit an index.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">EXPLAIN<\/span><span class=\"w\"> <\/span><span class=\"k\">ANALYZE<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">WHERE<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">                                                       <\/span><span class=\"n\">QUERY<\/span><span class=\"w\"> <\/span><span class=\"n\">PLAN<\/span><span class=\"w\">                                                       <\/span>\n<span class=\"c1\">------------------------------------------------------------------------------------------------------------------------<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Bitmap<\/span><span class=\"w\"> <\/span><span class=\"n\">Heap<\/span><span class=\"w\"> <\/span><span class=\"n\">Scan<\/span><span class=\"w\"> <\/span><span class=\"k\">on<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">4<\/span><span class=\"p\">.<\/span><span class=\"mi\">52<\/span><span class=\"p\">..<\/span><span class=\"mi\">48<\/span><span class=\"p\">.<\/span><span class=\"mi\">14<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">11<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">8<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">050<\/span><span class=\"p\">..<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">072<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">7<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">   <\/span><span class=\"k\">Recheck<\/span><span class=\"w\"> <\/span><span class=\"n\">Cond<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">Heap<\/span><span class=\"w\"> <\/span><span class=\"n\">Blocks<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">exact<\/span><span class=\"o\">=<\/span><span class=\"mi\">7<\/span>\n<span class=\"w\">   <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\">  <\/span><span class=\"n\">Bitmap<\/span><span class=\"w\"> <\/span><span class=\"k\">Index<\/span><span class=\"w\"> <\/span><span class=\"n\">Scan<\/span><span class=\"w\"> <\/span><span class=\"k\">on<\/span><span class=\"w\"> <\/span><span class=\"n\">idx_data_value<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">00<\/span><span class=\"p\">..<\/span><span class=\"mi\">4<\/span><span class=\"p\">.<\/span><span class=\"mi\">52<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">11<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">034<\/span><span class=\"p\">..<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">035<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">7<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">         <\/span><span class=\"k\">Index<\/span><span class=\"w\"> <\/span><span class=\"n\">Cond<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"p\">)<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Planning<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">189<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Execution<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">122<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">7<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>This looks a bit different with bitmap this and bitmap that. That's because\nthe query planner decided that it was going to read more data, and thus opted\nfor a slightly different strategy. We're still making good use of the index,\nthough, and if we simply put a limit on the amount of returned values we'll see\na pure index scan just like we did with the primary key.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">EXPLAIN<\/span><span class=\"w\"> <\/span><span class=\"k\">ANALYZE<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">WHERE<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"w\"> <\/span><span class=\"k\">LIMIT<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">                                                         <\/span><span class=\"n\">QUERY<\/span><span class=\"w\"> <\/span><span class=\"n\">PLAN<\/span><span class=\"w\">                                                          <\/span>\n<span class=\"c1\">-----------------------------------------------------------------------------------------------------------------------------<\/span>\n<span class=\"w\"> <\/span><span class=\"k\">Limit<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">43<\/span><span class=\"p\">..<\/span><span class=\"mi\">4<\/span><span class=\"p\">.<\/span><span class=\"mi\">82<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">8<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">041<\/span><span class=\"p\">..<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">042<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">   <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\">  <\/span><span class=\"k\">Index<\/span><span class=\"w\"> <\/span><span class=\"n\">Scan<\/span><span class=\"w\"> <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"n\">idx_data_value<\/span><span class=\"w\"> <\/span><span class=\"k\">on<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">43<\/span><span class=\"p\">..<\/span><span class=\"mi\">48<\/span><span class=\"p\">.<\/span><span class=\"mi\">63<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">11<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">8<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">038<\/span><span class=\"p\">..<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">039<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">         <\/span><span class=\"k\">Index<\/span><span class=\"w\"> <\/span><span class=\"n\">Cond<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span><span class=\"p\">)<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Planning<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">169<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Execution<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">077<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you only wanted to be sold on the fact that indexing is important, I think\nthat's been covered already. But just having the effect of something without\nunderstanding at least the principles on which it operates will still make it\nharder than it has to be to apply it in practice. So let's discuss the\nprinciples of indexing and work through an example of the most commonly used\nindex type: the B-tree.<\/p>\n<h1 id=\"indexing-in-theory\">Indexing in theory<\/h1>\n<p>If you've ever read a non-fiction book, you know in principle what an index is.\nBecause at the back of that book there's a section called \"index\", and it\ncontains an alphabetically sorted list of terms and phrases used throughout the\nbook and a reference to the page number(s) where you can find their use. It's\nfaster to find where \"the rule of three\" is defined in the book by looking it up\nin the index than by scanning through the entire book. Database indexes operate\non precisely that assumption; it's faster to look a value up in an index than it\nis to scan through the entire table.<\/p>\n<p>There are many different kinds of indexes in databases, but by far the most\ncommon type is the B-tree index. Inspecting the indexes of the 'data<code>table, we\ncan see that they are both of type<\/code>btree`.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"err\">\\<\/span><span class=\"n\">d<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span>\n<span class=\"w\">                            <\/span><span class=\"k\">Table<\/span><span class=\"w\"> <\/span><span class=\"ss\">\"public.data\"<\/span>\n<span class=\"w\"> <\/span><span class=\"k\">Column<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">  <\/span><span class=\"k\">Type<\/span><span class=\"w\">   <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"k\">Collation<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"k\">Nullable<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">             <\/span><span class=\"k\">Default<\/span><span class=\"w\">              <\/span>\n<span class=\"c1\">--------+---------+-----------+----------+----------------------------------<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">id<\/span><span class=\"w\">     <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"nb\">integer<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">           <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"k\">not<\/span><span class=\"w\"> <\/span><span class=\"k\">null<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"n\">nextval<\/span><span class=\"p\">(<\/span><span class=\"s1\">'data_id_seq'<\/span><span class=\"p\">::<\/span><span class=\"n\">regclass<\/span><span class=\"p\">)<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\">  <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"nb\">integer<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">           <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"k\">not<\/span><span class=\"w\"> <\/span><span class=\"k\">null<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span>\n<span class=\"n\">Indexes<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">    <\/span><span class=\"ss\">\"data_pkey\"<\/span><span class=\"w\"> <\/span><span class=\"k\">PRIMARY<\/span><span class=\"w\"> <\/span><span class=\"k\">KEY<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">btree<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">id<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"ss\">\"idx_data_value\"<\/span><span class=\"w\"> <\/span><span class=\"n\">btree<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>You may immediately think \"oh, a binary tree\", which is close, but no cigar. In\nthe following section I'll outline how a B-tree index works and its properties\nsuch that you can make effective use of it in your day to day work.<\/p>\n<h2 id=\"the-b-tree\">The B-tree<\/h2>\n<p>A B-tree is indeed a search tree, and it is in fact rather similar to a binary search\ntree. Each node, or <em>page<\/em><sup id=\"sf-postgresql-indexing-basics-2-back\"><a href=\"#sf-postgresql-indexing-basics-2\" class=\"simple-footnote\" title=\"In PostgreSQL, the nodes of a B-tree are called pages (source)\">2<\/a><\/sup>\nis a sorted list of references either to other pages of the tree, or to columns of the\nindexed table<sup id=\"sf-postgresql-indexing-basics-3-back\"><a href=\"#sf-postgresql-indexing-basics-3\" class=\"simple-footnote\" title=\"Pages in the B-tree are either internal pages or leaf pages. An internal page only contains references to other B-tree pages, while a leaf page only contains references to the indexed table. There are no hybrid internal\/leaf pages. The root can be either internal or a leaf depending on the size of the index. There is also a special metapage that keeps track of things like tree depth and which page is the root of the tree (source). A search in a B-tree index starts from the singular root page and then proceeds through internal pages in the tree until a leaf page containing references to the indexed table is found. From there, the references to the table can be resolved and the rows retrieved.\">3<\/a><\/sup><\/p>\n<p>Let's work through the example of searching for <code>value=560487<\/code> given the index\nstructure shown in the image below. We start from the root page and search\n<sup id=\"sf-postgresql-indexing-basics-4-back\"><a href=\"#sf-postgresql-indexing-basics-4\" class=\"simple-footnote\" title=\"The page is sorted, PostgreSQL makes effective use of binary search to quickly find a key\">4<\/a><\/sup>\nthrough it until we find the segment where <code>500000 &lt;= value<\/code>. Semantically, this\nsegment has an exclusive upper limit equal to the inclusive lower limit of the\nnext segment (i.e. <code>500000 &lt;= value &lt; 600000<\/code> in this example). Following the\nreference to the start of the next page, we search that until we find the\nsegment where <code>560000 &lt;= value &lt; 561000<\/code>. This segment refers to a leaf page,\nwhich again we search through until we find the desired key that in turn\ncontains references to the sought rows of the table. This search path is\nreflected in the below image with black lines, whereas the faint gray lines\nshow existing references that are not traversed.<\/p>\n<div class=\"graphviz\"><img src=\"data:image\/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIKICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPgo8IS0tIEdlbmVyYXRlZCBieSBncmFwaHZpeiB2ZXJzaW9uIDE0LjAuMiAoMCkKIC0tPgo8IS0tIFRpdGxlOiBHIFBhZ2VzOiAxIC0tPgo8c3ZnIHdpZHRoPSIxMDcycHQiIGhlaWdodD0iNzEzcHQiCiB2aWV3Qm94PSIwLjAwIDAuMDAgMTA3Mi4wMCA3MTMuMDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgo8ZyBpZD0iZ3JhcGgwIiBjbGFzcz0iZ3JhcGgiIHRyYW5zZm9ybT0ic2NhbGUoMSAxKSByb3RhdGUoMCkgdHJhbnNsYXRlKDQgNzA4LjUpIj4KPHRpdGxlPkc8L3RpdGxlPgo8cG9seWdvbiBmaWxsPSJ3aGl0ZSIgc3Ryb2tlPSJub25lIiBwb2ludHM9Ii00LDQgLTQsLTcwOC41IDEwNjguMjUsLTcwOC41IDEwNjguMjUsNCAtNCw0Ii8+CjxnIGlkPSJjbHVzdDEiIGNsYXNzPSJjbHVzdGVyIj4KPHRpdGxlPmNsdXN0ZXJfbGVnZW5kPC90aXRsZT4KPHBvbHlnb24gZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI0ODQuMjUsLTggNDg0LjI1LC02MCAxMDU2LjI1LC02MCAxMDU2LjI1LC04IDQ4NC4yNSwtOCIvPgo8L2c+CjwhLS0gTm9kZTEgLS0+CjxnIGlkPSJub2RlMSIgY2xhc3M9Im5vZGUiPgo8dGl0bGU+Tm9kZTE8L3RpdGxlPgo8cG9seWdvbiBmaWxsPSJsaWdodGJsdWUiIHN0cm9rZT0iYmxhY2siIHBvaW50cz0iNDA0LjEyLC02NjggNDA0LjEyLC03MDQgOTAwLjM4LC03MDQgOTAwLjM4LC02NjggNDA0LjEyLC02NjgiLz4KPHRleHQgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgeD0iNDE4Ljg4IiB5PSItNjgxLjMzIiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPi4uLjwvdGV4dD4KPHBvbHlsaW5lIGZpbGw9Im5vbmUiIHN0cm9rZT0iYmxhY2siIHBvaW50cz0iNDMzLjYyLC02NjggNDMzLjYyLC03MDQiLz4KPHRleHQgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgeD0iNTA2LjUiIHk9Ii02ODEuMzMiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+NDAwMDAwIOKJpCB2YWx1ZSAmbHQ7PC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI1NzkuMzgsLTY2OCA1NzkuMzgsLTcwNCIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI2NTIuMjUiIHk9Ii02ODEuMzMiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+NTAwMDAwIOKJpCB2YWx1ZSAmbHQ7PC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI3MjUuMTIsLTY2OCA3MjUuMTIsLTcwNCIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI3OTgiIHk9Ii02ODEuMzMiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+NjAwMDAwIOKJpCB2YWx1ZSAmbHQ7PC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI4NzAuODgsLTY2OCA4NzAuODgsLTcwNCIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI4ODUuNjIiIHk9Ii02ODEuMzMiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+Li4uPC90ZXh0Pgo8L2c+CjwhLS0gTm9kZTIgLS0+CjxnIGlkPSJub2RlMiIgY2xhc3M9Im5vZGUiPgo8dGl0bGU+Tm9kZTI8L3RpdGxlPgo8cG9seWdvbiBmaWxsPSJsaWdodHllbGxvdyIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSIwLC01NTkgMCwtNTk1IDM1MC41LC01OTUgMzUwLjUsLTU1OSAwLC01NTkiLz4KPHRleHQgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgeD0iMTQuNzUiIHk9Ii01NzIuMzMiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+Li4uPC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSIyOS41LC01NTkgMjkuNSwtNTk1Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjEwMi4zOCIgeT0iLTU3Mi4zMyIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj40MTAwMDAg4omkIHZhbHVlICZsdDs8L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjE3NS4yNSwtNTU5IDE3NS4yNSwtNTk1Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjI0OC4xMiIgeT0iLTU3Mi4zMyIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj40MjAwMDAg4omkIHZhbHVlICZsdDs8L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjMyMSwtNTU5IDMyMSwtNTk1Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjMzNS43NSIgeT0iLTU3Mi4zMyIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj4uLi48L3RleHQ+CjwvZz4KPCEtLSBOb2RlMSYjNDU7Jmd0O05vZGUyIC0tPgo8ZyBpZD0iZWRnZTEiIGNsYXNzPSJlZGdlIj4KPHRpdGxlPk5vZGUxOmYwJiM0NTsmZ3Q7Tm9kZTI6ZjA8L3RpdGxlPgo8cGF0aCBmaWxsPSJub25lIiBzdHJva2U9ImxpZ2h0Z3JheSIgZD0iTTUwNi41LC02NjcuNUM1MDYuNSwtNTYxLjE2IDUwLjU3LC02OTUuMjUgMTYuNzMsLTYwNi43NSIvPgo8cG9seWdvbiBmaWxsPSJsaWdodGdyYXkiIHN0cm9rZT0ibGlnaHRncmF5IiBwb2ludHM9IjIwLjE5LC02MDYuMjMgMTUuMDEsLTU5Ni45OSAxMy4zLC02MDcuNDUgMjAuMTksLTYwNi4yMyIvPgo8L2c+CjwhLS0gTm9kZTMgLS0+CjxnIGlkPSJub2RlMyIgY2xhc3M9Im5vZGUiPgo8dGl0bGU+Tm9kZTM8L3RpdGxlPgo8cG9seWdvbiBmaWxsPSJsaWdodHllbGxvdyIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSIzOTUsLTU1OSAzOTUsLTU5NSA3NDUuNSwtNTk1IDc0NS41LC01NTkgMzk1LC01NTkiLz4KPHRleHQgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgeD0iNDA5Ljc1IiB5PSItNTcyLjMzIiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPi4uLjwvdGV4dD4KPHBvbHlsaW5lIGZpbGw9Im5vbmUiIHN0cm9rZT0iYmxhY2siIHBvaW50cz0iNDI0LjUsLTU1OSA0MjQuNSwtNTk1Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjQ5Ny4zOCIgeT0iLTU3Mi4zMyIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj41NjAwMDAg4omkIHZhbHVlICZsdDs8L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjU3MC4yNSwtNTU5IDU3MC4yNSwtNTk1Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjY0My4xMiIgeT0iLTU3Mi4zMyIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj41NjEwMDAg4omkIHZhbHVlICZsdDs8L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjcxNiwtNTU5IDcxNiwtNTk1Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjczMC43NSIgeT0iLTU3Mi4zMyIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj4uLi48L3RleHQ+CjwvZz4KPCEtLSBOb2RlMSYjNDU7Jmd0O05vZGUzIC0tPgo8ZyBpZD0iZWRnZTIiIGNsYXNzPSJlZGdlIj4KPHRpdGxlPk5vZGUxOmYxJiM0NTsmZ3Q7Tm9kZTM6ZjA8L3RpdGxlPgo8cGF0aCBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBkPSJNNjUyLjI1LC02NjcuNUM2NTIuMjUsLTU1OS4yNCA0MjcuNDEsLTY5Ni45NSA0MTAuNzMsLTYwNi45NSIvPgo8cG9seWdvbiBmaWxsPSJibGFjayIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI0MTQuMjIsLTYwNi42NyA0MDkuODgsLTU5Ny4wMSA0MDcuMjQsLTYwNy4yNyA0MTQuMjIsLTYwNi42NyIvPgo8L2c+CjwhLS0gTm9kZTEmIzQ1OyZndDtOb2RlMyAtLT4KPCEtLSBOb2RlNSAtLT4KPGcgaWQ9Im5vZGU0IiBjbGFzcz0ibm9kZSI+Cjx0aXRsZT5Ob2RlNTwvdGl0bGU+Cjxwb2x5Z29uIGZpbGw9ImxpZ2h0Z3JlZW4iIHN0cm9rZT0iYmxhY2siIHBvaW50cz0iMjc3Ljg4LC00NTAgMjc3Ljg4LC00ODYgNzI0LjYyLC00ODYgNzI0LjYyLC00NTAgMjc3Ljg4LC00NTAiLz4KPHRleHQgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgeD0iMjkyLjYyIiB5PSItNDYzLjMyIiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPi4uLjwvdGV4dD4KPHBvbHlsaW5lIGZpbGw9Im5vbmUiIHN0cm9rZT0iYmxhY2siIHBvaW50cz0iMzA3LjM4LC00NTAgMzA3LjM4LC00ODYiLz4KPHRleHQgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgeD0iMzcyIiB5PSItNDYzLjMyIiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPnZhbHVlID0gNTYwNDg2PC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI0MzYuNjIsLTQ1MCA0MzYuNjIsLTQ4NiIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI1MDEuMjUiIHk9Ii00NjMuMzIiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+dmFsdWUgPSA1NjA0ODc8L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjU2NS44OCwtNDUwIDU2NS44OCwtNDg2Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjYzMC41IiB5PSItNDYzLjMyIiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPnZhbHVlID0gNTYwNDg4PC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI2OTUuMTIsLTQ1MCA2OTUuMTIsLTQ4NiIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI3MDkuODgiIHk9Ii00NjMuMzIiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+Li4uPC90ZXh0Pgo8L2c+CjwhLS0gTm9kZTEmIzQ1OyZndDtOb2RlNSAtLT4KPCEtLSBUYWJsZSAtLT4KPGcgaWQ9Im5vZGU1IiBjbGFzcz0ibm9kZSI+Cjx0aXRsZT5UYWJsZTwvdGl0bGU+CjxwYXRoIGZpbGw9IiNlYmViZWIiIHN0cm9rZT0iYmxhY2siIGQ9Ik00NzMuNzUsLTEyNC41QzQ3My43NSwtMTI0LjUgNTk4Ljc1LC0xMjQuNSA1OTguNzUsLTEyNC41IDYwNC43NSwtMTI0LjUgNjEwLjc1LC0xMzAuNSA2MTAuNzUsLTEzNi41IDYxMC43NSwtMTM2LjUgNjEwLjc1LC0zNjUgNjEwLjc1LC0zNjUgNjEwLjc1LC0zNzEgNjA0Ljc1LC0zNzcgNTk4Ljc1LC0zNzcgNTk4Ljc1LC0zNzcgNDczLjc1LC0zNzcgNDczLjc1LC0zNzcgNDY3Ljc1LC0zNzcgNDYxLjc1LC0zNzEgNDYxLjc1LC0zNjUgNDYxLjc1LC0zNjUgNDYxLjc1LC0xMzYuNSA0NjEuNzUsLTEzNi41IDQ2MS43NSwtMTMwLjUgNDY3Ljc1LC0xMjQuNSA0NzMuNzUsLTEyNC41Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjUwMS4yNSIgeT0iLTM1OS43IiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPmlkPC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI0NjEuNzUsLTM1MS43NSA1NDAuNzUsLTM1MS43NSIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI1MDEuMjUiIHk9Ii0zMzQuNDUiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+Li4uPC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI0NjEuNzUsLTMyNi41IDU0MC43NSwtMzI2LjUiLz4KPHRleHQgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgeD0iNTAxLjI1IiB5PSItMzA5LjIiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+NDU8L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjQ2MS43NSwtMzAxLjI1IDU0MC43NSwtMzAxLjI1Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjUwMS4yNSIgeT0iLTI4My45NSIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj4uLi48L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjQ2MS43NSwtMjc2IDU0MC43NSwtMjc2Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjUwMS4yNSIgeT0iLTI1OC43IiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPjIwNjgyNTk8L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjQ2MS43NSwtMjUwLjc1IDU0MC43NSwtMjUwLjc1Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjUwMS4yNSIgeT0iLTIzMy40NSIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj4uLi48L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjQ2MS43NSwtMjI1LjUgNTQwLjc1LC0yMjUuNSIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI1MDEuMjUiIHk9Ii0yMDguMiIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj41MDEzOTYzPC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI0NjEuNzUsLTIwMC4yNSA1NDAuNzUsLTIwMC4yNSIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI1MDEuMjUiIHk9Ii0xODIuOTUiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+Li4uPC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI0NjEuNzUsLTE3NSA1NDAuNzUsLTE3NSIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI1MDEuMjUiIHk9Ii0xNTcuNyIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj42MDAwMTM1PC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI0NjEuNzUsLTE0OS43NSA1NDAuNzUsLTE0OS43NSIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI1MDEuMjUiIHk9Ii0xMzIuNDUiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+Li4uPC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI1NDAuNzUsLTEyNC41IDU0MC43NSwtMzc3Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjU3NS43NSIgeT0iLTM1OS43IiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPnZhbHVlPC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI1NDAuNzUsLTM1MS43NSA2MTAuNzUsLTM1MS43NSIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI1NzUuNzUiIHk9Ii0zMzQuNDUiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+Li4uPC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI1NDAuNzUsLTMyNi41IDYxMC43NSwtMzI2LjUiLz4KPHRleHQgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgeD0iNTc1Ljc1IiB5PSItMzA5LjIiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+NTYwNDg4PC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI1NDAuNzUsLTMwMS4yNSA2MTAuNzUsLTMwMS4yNSIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI1NzUuNzUiIHk9Ii0yODMuOTUiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+Li4uPC90ZXh0Pgo8cG9seWxpbmUgZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI1NDAuNzUsLTI3NiA2MTAuNzUsLTI3NiIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI1NzUuNzUiIHk9Ii0yNTguNyIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj41NjA0ODc8L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjU0MC43NSwtMjUwLjc1IDYxMC43NSwtMjUwLjc1Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjU3NS43NSIgeT0iLTIzMy40NSIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj4uLi48L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjU0MC43NSwtMjI1LjUgNjEwLjc1LC0yMjUuNSIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI1NzUuNzUiIHk9Ii0yMDguMiIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj41NjA0ODc8L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjU0MC43NSwtMjAwLjI1IDYxMC43NSwtMjAwLjI1Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjU3NS43NSIgeT0iLTE4Mi45NSIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj4uLi48L3RleHQ+Cjxwb2x5bGluZSBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjU0MC43NSwtMTc1IDYxMC43NSwtMTc1Ii8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjU3NS43NSIgeT0iLTE1Ny43IiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPjU2MDQ4NjwvdGV4dD4KPHBvbHlsaW5lIGZpbGw9Im5vbmUiIHN0cm9rZT0iYmxhY2siIHBvaW50cz0iNTQwLjc1LC0xNDkuNzUgNjEwLjc1LC0xNDkuNzUiLz4KPHRleHQgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgeD0iNTc1Ljc1IiB5PSItMTMyLjQ1IiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPi4uLjwvdGV4dD4KPC9nPgo8IS0tIE5vZGUxJiM0NTsmZ3Q7VGFibGUgLS0+CjwhLS0gTm9kZTFfb21pdHRlZCAtLT4KPGcgaWQ9Im5vZGU2IiBjbGFzcz0ibm9kZSI+Cjx0aXRsZT5Ob2RlMV9vbWl0dGVkPC90aXRsZT4KPHBvbHlnb24gZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI4NTIuMjUsLTU1OSA4NTIuMjUsLTU5NSA5MDYuMjUsLTU5NSA5MDYuMjUsLTU1OSA4NTIuMjUsLTU1OSIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI4NzkiIHk9Ii01NzIuMzMiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+Li4uPC90ZXh0Pgo8L2c+CjwhLS0gTm9kZTEmIzQ1OyZndDtOb2RlMV9vbWl0dGVkIC0tPgo8ZyBpZD0iZWRnZTMiIGNsYXNzPSJlZGdlIj4KPHRpdGxlPk5vZGUxOmYyJiM0NTsmZ3Q7Tm9kZTFfb21pdHRlZDwvdGl0bGU+CjxwYXRoIGZpbGw9Im5vbmUiIHN0cm9rZT0ibGlnaHRncmF5IiBkPSJNNzk4LC02NjcuNUM3OTgsLTYzOC44IDgyMS4xOSwtNjE1LjIyIDg0Mi43OSwtNTk5LjQ4Ii8+Cjxwb2x5Z29uIGZpbGw9ImxpZ2h0Z3JheSIgc3Ryb2tlPSJsaWdodGdyYXkiIHBvaW50cz0iODQ0LjY5LC02MDIuNDMgODUwLjk1LC01OTMuODggODQwLjcyLC01OTYuNjYgODQ0LjY5LC02MDIuNDMiLz4KPC9nPgo8IS0tIE5vZGUyX29taXR0ZWRfMSAtLT4KPGcgaWQ9Im5vZGU3IiBjbGFzcz0ibm9kZSI+Cjx0aXRsZT5Ob2RlMl9vbWl0dGVkXzE8L3RpdGxlPgo8cG9seWdvbiBmaWxsPSJub25lIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9Ijc2LjI1LC00NTAgNzYuMjUsLTQ4NiAxMzAuMjUsLTQ4NiAxMzAuMjUsLTQ1MCA3Ni4yNSwtNDUwIi8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjEwMyIgeT0iLTQ2My4zMiIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj4uLi48L3RleHQ+CjwvZz4KPCEtLSBOb2RlMiYjNDU7Jmd0O05vZGUyX29taXR0ZWRfMSAtLT4KPGcgaWQ9ImVkZ2U0IiBjbGFzcz0iZWRnZSI+Cjx0aXRsZT5Ob2RlMjpmMSYjNDU7Jmd0O05vZGUyX29taXR0ZWRfMTwvdGl0bGU+CjxwYXRoIGZpbGw9Im5vbmUiIHN0cm9rZT0ibGlnaHRncmF5IiBkPSJNMTAyLjM4LC01NTguNUMxMDIuMzgsLTUzOC4yNyAxMDIuNiwtNTE1LjQ3IDEwMi44MiwtNDk3Ljk1Ii8+Cjxwb2x5Z29uIGZpbGw9ImxpZ2h0Z3JheSIgc3Ryb2tlPSJsaWdodGdyYXkiIHBvaW50cz0iMTA2LjMyLC00OTguMDUgMTAyLjk2LC00ODguMDEgOTkuMzIsLTQ5Ny45NiAxMDYuMzIsLTQ5OC4wNSIvPgo8L2c+CjwhLS0gTm9kZTJfb21pdHRlZF8yIC0tPgo8ZyBpZD0ibm9kZTgiIGNsYXNzPSJub2RlIj4KPHRpdGxlPk5vZGUyX29taXR0ZWRfMjwvdGl0bGU+Cjxwb2x5Z29uIGZpbGw9Im5vbmUiIHN0cm9rZT0iYmxhY2siIHBvaW50cz0iMjA2LjI1LC00NTAgMjA2LjI1LC00ODYgMjYwLjI1LC00ODYgMjYwLjI1LC00NTAgMjA2LjI1LC00NTAiLz4KPHRleHQgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgeD0iMjMzIiB5PSItNDYzLjMyIiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPi4uLjwvdGV4dD4KPC9nPgo8IS0tIE5vZGUyJiM0NTsmZ3Q7Tm9kZTJfb21pdHRlZF8yIC0tPgo8ZyBpZD0iZWRnZTUiIGNsYXNzPSJlZGdlIj4KPHRpdGxlPk5vZGUyOmYyJiM0NTsmZ3Q7Tm9kZTJfb21pdHRlZF8yPC90aXRsZT4KPHBhdGggZmlsbD0ibm9uZSIgc3Ryb2tlPSJsaWdodGdyYXkiIGQ9Ik0yNDguMTIsLTU1OC41QzI0OC4xMiwtNTM3LjkgMjQ0LjI0LC01MTQuOTggMjQwLjQ0LC00OTcuNDkiLz4KPHBvbHlnb24gZmlsbD0ibGlnaHRncmF5IiBzdHJva2U9ImxpZ2h0Z3JheSIgcG9pbnRzPSIyNDMuODcsLTQ5Ni43OCAyMzguMjEsLTQ4Ny44MyAyMzcuMDUsLTQ5OC4zNiAyNDMuODcsLTQ5Ni43OCIvPgo8L2c+CjwhLS0gTm9kZTMmIzQ1OyZndDtOb2RlNSAtLT4KPGcgaWQ9ImVkZ2U2IiBjbGFzcz0iZWRnZSI+Cjx0aXRsZT5Ob2RlMzpmMSYjNDU7Jmd0O05vZGU1OmYwPC90aXRsZT4KPHBhdGggZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgZD0iTTQ5Ny4zOCwtNTU4LjVDNDk3LjM4LC00NjYuMTggMzA5Ljg0LC01NzIuOTcgMjkzLjczLC00OTcuNzciLz4KPHBvbHlnb24gZmlsbD0iYmxhY2siIHN0cm9rZT0iYmxhY2siIHBvaW50cz0iMjk3LjIzLC00OTcuNjIgMjkyLjc3LC00ODguMDEgMjkwLjI2LC00OTguMyAyOTcuMjMsLTQ5Ny42MiIvPgo8L2c+CjwhLS0gTm9kZTNfb21pdHRlZCAtLT4KPGcgaWQ9Im5vZGU5IiBjbGFzcz0ibm9kZSI+Cjx0aXRsZT5Ob2RlM19vbWl0dGVkPC90aXRsZT4KPHBvbHlnb24gZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI3NDIuMjUsLTQ1MCA3NDIuMjUsLTQ4NiA3OTYuMjUsLTQ4NiA3OTYuMjUsLTQ1MCA3NDIuMjUsLTQ1MCIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI3NjkiIHk9Ii00NjMuMzIiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+Li4uPC90ZXh0Pgo8L2c+CjwhLS0gTm9kZTMmIzQ1OyZndDtOb2RlM19vbWl0dGVkIC0tPgo8ZyBpZD0iZWRnZTciIGNsYXNzPSJlZGdlIj4KPHRpdGxlPk5vZGUzOmYyJiM0NTsmZ3Q7Tm9kZTNfb21pdHRlZDwvdGl0bGU+CjxwYXRoIGZpbGw9Im5vbmUiIHN0cm9rZT0ibGlnaHRncmF5IiBkPSJNNjQzLjEyLC01NTguNUM2NDMuMTIsLTU0Ny40NyA2OTUuMDksLTUxMy43MyA3MzIuMzEsLTQ5MC45NyIvPgo8cG9seWdvbiBmaWxsPSJsaWdodGdyYXkiIHN0cm9rZT0ibGlnaHRncmF5IiBwb2ludHM9IjczMy44NiwtNDk0LjEzIDc0MC41OSwtNDg1Ljk0IDczMC4yMiwtNDg4LjE0IDczMy44NiwtNDk0LjEzIi8+CjwvZz4KPCEtLSBOb2RlNSYjNDU7Jmd0O1RhYmxlIC0tPgo8ZyBpZD0iZWRnZTgiIGNsYXNzPSJlZGdlIj4KPHRpdGxlPk5vZGU1OmYxJiM0NTsmZ3Q7VGFibGU6ZjY8L3RpdGxlPgo8cGF0aCBmaWxsPSJub25lIiBzdHJva2U9ImxpZ2h0Z3JheSIgZD0iTTM3MiwtNDQ5LjVDMzcyLC0zMTkuODQgMzI5Ljc3LC0xNzEuMzYgNDQ5LjQ2LC0xNjIuNzciLz4KPHBvbHlnb24gZmlsbD0ibGlnaHRncmF5IiBzdHJva2U9ImxpZ2h0Z3JheSIgcG9pbnRzPSI0NDkuMzYsLTE2Ni4yNyA0NTkuMjQsLTE2Mi40MyA0NDkuMTIsLTE1OS4yOCA0NDkuMzYsLTE2Ni4yNyIvPgo8L2c+CjwhLS0gTm9kZTUmIzQ1OyZndDtUYWJsZSAtLT4KPGcgaWQ9ImVkZ2U5IiBjbGFzcz0iZWRnZSI+Cjx0aXRsZT5Ob2RlNTpmMiYjNDU7Jmd0O1RhYmxlOmYyPC90aXRsZT4KPHBhdGggZmlsbD0ibm9uZSIgc3Ryb2tlPSJibGFjayIgZD0iTTUwMS4yNSwtNDQ5LjVDNTAxLjI1LC00MTMgNDcwLjk3LC00MTIuODIgNDYxLjc1LC0zNzcuNSA0NTAuMDQsLTMzMi42NCA0MTYuNTIsLTI3NC40NCA0NDkuNTksLTI2NC43NiIvPgo8cG9seWdvbiBmaWxsPSJibGFjayIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI0NDkuNzYsLTI2OC4yNyA0NTkuMjUsLTI2My41NiA0NDguODksLTI2MS4zMiA0NDkuNzYsLTI2OC4yNyIvPgo8L2c+CjwhLS0gTm9kZTUmIzQ1OyZndDtUYWJsZSAtLT4KPGcgaWQ9ImVkZ2UxMCIgY2xhc3M9ImVkZ2UiPgo8dGl0bGU+Tm9kZTU6ZjImIzQ1OyZndDtUYWJsZTpmNDwvdGl0bGU+CjxwYXRoIGZpbGw9Im5vbmUiIHN0cm9rZT0iYmxhY2siIGQ9Ik01MDEuMjUsLTQ0OS41QzUwMS4yNSwtNDEzIDQ3MC45MiwtNDEyLjgzIDQ2MS43NSwtMzc3LjUgNDQ0LjQxLC0zMTAuNjkgMzkzLjc4LC0yMjMuNDMgNDQ5LjUzLC0yMTMuNzYiLz4KPHBvbHlnb24gZmlsbD0iYmxhY2siIHN0cm9rZT0iYmxhY2siIHBvaW50cz0iNDQ5LjU1LC0yMTcuMjcgNDU5LjI0LC0yMTIuOTkgNDQ5LC0yMTAuMjkgNDQ5LjU1LC0yMTcuMjciLz4KPC9nPgo8IS0tIE5vZGU1JiM0NTsmZ3Q7VGFibGUgLS0+CjxnIGlkPSJlZGdlMTEiIGNsYXNzPSJlZGdlIj4KPHRpdGxlPk5vZGU1OmYzJiM0NTsmZ3Q7VGFibGU6ZjE8L3RpdGxlPgo8cGF0aCBmaWxsPSJub25lIiBzdHJva2U9ImxpZ2h0Z3JheSIgZD0iTTYzMC41LC00NDkuNUM2MzAuNSwtMzkyLjkzIDY2Ni44OSwtMzI0LjMyIDYyMy4xMSwtMzE0Ljk1Ii8+Cjxwb2x5Z29uIGZpbGw9ImxpZ2h0Z3JheSIgc3Ryb2tlPSJsaWdodGdyYXkiIHBvaW50cz0iNjIzLjU0LC0zMTEuNDggNjEzLjI2LC0zMTQuMDIgNjIyLjg4LC0zMTguNDUgNjIzLjU0LC0zMTEuNDgiLz4KPC9nPgo8IS0tIFJvb3QgLS0+CjxnIGlkPSJub2RlMTAiIGNsYXNzPSJub2RlIj4KPHRpdGxlPlJvb3Q8L3RpdGxlPgo8cG9seWdvbiBmaWxsPSJsaWdodGJsdWUiIHN0cm9rZT0iYmxhY2siIHBvaW50cz0iNTgwLjI1LC01MiA0OTIuMjUsLTUyIDQ5Mi4yNSwtMTYgNTgwLjI1LC0xNiA1ODAuMjUsLTUyIi8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9IjUzNi4yNSIgeT0iLTI5LjMyIiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPlJvb3QgUGFnZTwvdGV4dD4KPC9nPgo8IS0tIFRhYmxlJiM0NTsmZ3Q7Um9vdCAtLT4KPCEtLSBJbnRlcm5hbCAtLT4KPGcgaWQ9Im5vZGUxMSIgY2xhc3M9Im5vZGUiPgo8dGl0bGU+SW50ZXJuYWw8L3RpdGxlPgo8cG9seWdvbiBmaWxsPSJsaWdodHllbGxvdyIgc3Ryb2tlPSJibGFjayIgcG9pbnRzPSI3MTAuMjUsLTUyIDU5OC4yNSwtNTIgNTk4LjI1LC0xNiA3MTAuMjUsLTE2IDcxMC4yNSwtNTIiLz4KPHRleHQgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgeD0iNjU0LjI1IiB5PSItMjkuMzIiIGZvbnQtZmFtaWx5PSJUaW1lcyxzZXJpZiIgZm9udC1zaXplPSIxNC4wMCI+SW50ZXJuYWwgUGFnZTwvdGV4dD4KPC9nPgo8IS0tIExlYWYgLS0+CjxnIGlkPSJub2RlMTIiIGNsYXNzPSJub2RlIj4KPHRpdGxlPkxlYWY8L3RpdGxlPgo8cG9seWdvbiBmaWxsPSJsaWdodGdyZWVuIiBzdHJva2U9ImJsYWNrIiBwb2ludHM9IjgxNC4xMiwtNTIgNzI4LjM4LC01MiA3MjguMzgsLTE2IDgxNC4xMiwtMTYgODE0LjEyLC01MiIvPgo8dGV4dCB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiB4PSI3NzEuMjUiIHk9Ii0yOS4zMiIgZm9udC1mYW1pbHk9IlRpbWVzLHNlcmlmIiBmb250LXNpemU9IjE0LjAwIj5MZWFmIFBhZ2U8L3RleHQ+CjwvZz4KPCEtLSBUYWJsZU5vZGUgLS0+CjxnIGlkPSJub2RlMTMiIGNsYXNzPSJub2RlIj4KPHRpdGxlPlRhYmxlTm9kZTwvdGl0bGU+Cjxwb2x5Z29uIGZpbGw9IiNlYmViZWIiIHN0cm9rZT0iYmxhY2siIHBvaW50cz0iOTI0LjUsLTUyIDgzMiwtNTIgODMyLC0xNiA5MjQuNSwtMTYgOTI0LjUsLTUyIi8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9Ijg3OC4yNSIgeT0iLTI5LjMyIiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPkRhdGEgVGFibGU8L3RleHQ+CjwvZz4KPCEtLSBPbWl0dGVkIC0tPgo8ZyBpZD0ibm9kZTE0IiBjbGFzcz0ibm9kZSI+Cjx0aXRsZT5PbWl0dGVkPC90aXRsZT4KPHBvbHlnb24gZmlsbD0id2hpdGUiIHN0cm9rZT0iYmxhY2siIHBvaW50cz0iMTA0OC4yNSwtNTIgOTQyLjI1LC01MiA5NDIuMjUsLTE2IDEwNDguMjUsLTE2IDEwNDguMjUsLTUyIi8+Cjx0ZXh0IHhtbDpzcGFjZT0icHJlc2VydmUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHg9Ijk5NS4yNSIgeT0iLTI5LjMyIiBmb250LWZhbWlseT0iVGltZXMsc2VyaWYiIGZvbnQtc2l6ZT0iMTQuMDAiPi4uLiA9IG9taXR0ZWQ8L3RleHQ+CjwvZz4KPC9nPgo8L3N2Zz4K\"><\/div>\n<blockquote>\n<p>Note that this is just for illustrative purposes. The splitting into segments\nas shown here is completely made up by me to be easy to illustrate. It's very\nunlikely to actually be a good split and therefore not the one that PostgreSQL\nwould actually make.<\/p>\n<\/blockquote>\n<p>In addition to providing quick lookup to specific values, the fact that B-trees\nare sorted leads to some possibly unexpected benefits in queries that require\nsorted output.<\/p>\n<h2 id=\"selecting-ranges-is-almost-as-fast-as-single-values\">Selecting ranges is almost as fast as single values<\/h2>\n<p>Did you notice in the illustration above that the leaf page contained not only\nthe value we searched for, but also its closest neighbors? Because of this\nadjacency, an index lookup for a <em>range<\/em> of values is incredibly\nefficient<sup id=\"sf-postgresql-indexing-basics-5-back\"><a href=\"#sf-postgresql-indexing-basics-5\" class=\"simple-footnote\" title=\"Depending on the amount of hits, scanning the rows from the table may of course take longer, however.\">5<\/a><\/sup>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">WHERE<\/span><span class=\"w\"> <\/span><span class=\"mi\">560486<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;=<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"k\">AND<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"w\"> <\/span><span class=\"mi\">560489<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">id<\/span><span class=\"w\">    <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\">  <\/span>\n<span class=\"c1\">---------+--------<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">1061367<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">1451289<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">2068259<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">2250572<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">2298922<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560486<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">2998709<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560486<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">3149734<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560486<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">3385911<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560486<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">3552143<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">4123068<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">4305566<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">4599351<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5013963<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5490314<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5521774<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5715474<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560486<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5725443<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">6125940<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560486<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">6423931<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560486<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">6752395<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">6894022<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">7313065<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">7365878<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">7956607<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">8046840<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560486<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">8290267<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">8455242<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">8941102<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">9020004<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560487<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">9663961<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"mi\">560488<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">30<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n\n<span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"p\">.<\/span><span class=\"mi\">360<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<\/code><\/pre><\/div>\n\n<p>A very common use case for a range selection is on creation date, e.g. `WHERE\ncreated_at &gt;= '2024-04-01'.<\/p>\n<h2 id=\"indexes-greatly-speed-up-order-by\">Indexes greatly speed up <code>ORDER BY<\/code><\/h2>\n<p>Tacking on an <code>ORDER BY<\/code> to a query is commonplace and pretty much required if\nyou plan to do any kind of pagination on the result set<sup id=\"sf-postgresql-indexing-basics-6-back\"><a href=\"#sf-postgresql-indexing-basics-6\" class=\"simple-footnote\" title=\"The order in which rows are returned from a query is undefined unless ORDER BY is provided. A common bug in backend systems is that OFFSET and LIMIT are used for pagination either without explicit ordering or with ordering that is not unique.\">6<\/a><\/sup>. Without an index on <code>value<\/code>, ordering by it takes quite a bit of\ntime.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">DROP<\/span><span class=\"w\"> <\/span><span class=\"k\">INDEX<\/span><span class=\"w\"> <\/span><span class=\"k\">IF<\/span><span class=\"w\"> <\/span><span class=\"k\">EXISTS<\/span><span class=\"w\"> <\/span><span class=\"n\">idx_data_value<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">DROP<\/span><span class=\"w\"> <\/span><span class=\"k\">INDEX<\/span>\n<span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">DATA<\/span><span class=\"w\"> <\/span><span class=\"k\">ORDER<\/span><span class=\"w\"> <\/span><span class=\"k\">BY<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"k\">LIMIT<\/span><span class=\"w\"> <\/span><span class=\"mi\">10<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">id<\/span><span class=\"w\">    <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span>\n<span class=\"c1\">---------+-------<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">1453865<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">8150282<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">7796750<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">3782708<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">8571152<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">1650656<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">9165134<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\">  <\/span><span class=\"mi\">268472<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5889252<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">3330397<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n\n<span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">331<\/span><span class=\"p\">.<\/span><span class=\"mi\">239<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<\/code><\/pre><\/div>\n\n<p>But tacking on the index, it's again orders of magnitude faster.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">CREATE<\/span><span class=\"w\"> <\/span><span class=\"k\">INDEX<\/span><span class=\"w\"> <\/span><span class=\"n\">idx_data_value<\/span><span class=\"w\"> <\/span><span class=\"k\">ON<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"p\">);<\/span>\n<span class=\"k\">CREATE<\/span><span class=\"w\"> <\/span><span class=\"k\">INDEX<\/span>\n<span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">DATA<\/span><span class=\"w\"> <\/span><span class=\"k\">ORDER<\/span><span class=\"w\"> <\/span><span class=\"k\">BY<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"k\">LIMIT<\/span><span class=\"w\"> <\/span><span class=\"mi\">10<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">id<\/span><span class=\"w\">    <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span>\n<span class=\"c1\">---------+-------<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">1453865<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">3782708<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">7796750<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">8150282<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\">  <\/span><span class=\"mi\">268472<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">1650656<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">2191333<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">3330397<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5364764<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5889252<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n\n<span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"p\">.<\/span><span class=\"mi\">628<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is so fast because there's actually no ordering going on; PostgreSQL just\nscans the already sorted index.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">EXPLAIN<\/span><span class=\"w\"> <\/span><span class=\"k\">ANALYZE<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">DATA<\/span><span class=\"w\"> <\/span><span class=\"k\">ORDER<\/span><span class=\"w\"> <\/span><span class=\"k\">BY<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"k\">LIMIT<\/span><span class=\"w\"> <\/span><span class=\"mi\">10<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">                                                               <\/span><span class=\"n\">QUERY<\/span><span class=\"w\"> <\/span><span class=\"n\">PLAN<\/span><span class=\"w\">                                                               <\/span>\n<span class=\"c1\">----------------------------------------------------------------------------------------------------------------------------------------<\/span>\n<span class=\"w\"> <\/span><span class=\"k\">Limit<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">43<\/span><span class=\"p\">..<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">81<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">10<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">8<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">049<\/span><span class=\"p\">..<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">074<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">10<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">   <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\">  <\/span><span class=\"k\">Index<\/span><span class=\"w\"> <\/span><span class=\"n\">Scan<\/span><span class=\"w\"> <\/span><span class=\"k\">using<\/span><span class=\"w\"> <\/span><span class=\"n\">idx_data_value<\/span><span class=\"w\"> <\/span><span class=\"k\">on<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">43<\/span><span class=\"p\">..<\/span><span class=\"mi\">372326<\/span><span class=\"p\">.<\/span><span class=\"mi\">50<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">10000000<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">8<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">046<\/span><span class=\"p\">..<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">069<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">10<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Planning<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">161<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Execution<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">104<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">4<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n\n<span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"p\">.<\/span><span class=\"mi\">284<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<\/code><\/pre><\/div>\n\n<p>There is simply a lot of value to having an index that is already ordered<sup id=\"sf-postgresql-indexing-basics-7-back\"><a href=\"#sf-postgresql-indexing-basics-7\" class=\"simple-footnote\" title=\" Note that only the B-tree type of index has this property (source).\">7<\/a><\/sup>\nas so many common operations rely on ordering.<\/p>\n<h1 id=\"indexing-pitfalls\">Indexing pitfalls<\/h1>\n<p>Thus far, this article has mostly covered the happy path of indexing, when\neverything just works out. It may have given you the impression that indexing is\na silver bullet to any query running a bit slow. Unfortunately, that's far from\nthe case, so in this section I will outline a few scenarios that may cause\nconfusion among up and coming indexers.<\/p>\n<h2 id=\"the-query-planner-can-choose-not-to-use-an-index\">The query planner can choose not to use an index<\/h2>\n<p>Indexes are great, but sometimes the query planner may choose to ignore them and\njust scan the table instead. This is quite easy to show, take for example the\nfollowing query where we search for any <code>value &gt; 500000<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">EXPLAIN<\/span><span class=\"w\"> <\/span><span class=\"k\">ANALYZE<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">WHERE<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"mi\">500000<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">                                                   <\/span><span class=\"n\">QUERY<\/span><span class=\"w\"> <\/span><span class=\"n\">PLAN<\/span><span class=\"w\">                                                    <\/span>\n<span class=\"c1\">-----------------------------------------------------------------------------------------------------------------<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Seq<\/span><span class=\"w\"> <\/span><span class=\"n\">Scan<\/span><span class=\"w\"> <\/span><span class=\"k\">on<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">00<\/span><span class=\"p\">..<\/span><span class=\"mi\">169248<\/span><span class=\"p\">.<\/span><span class=\"mi\">00<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">5044664<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">8<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">5<\/span><span class=\"p\">.<\/span><span class=\"mi\">213<\/span><span class=\"p\">..<\/span><span class=\"mi\">653<\/span><span class=\"p\">.<\/span><span class=\"mi\">177<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">4998152<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">Filter<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"mi\">500000<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">   <\/span><span class=\"k\">Rows<\/span><span class=\"w\"> <\/span><span class=\"n\">Removed<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">Filter<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">5001848<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Planning<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">151<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">JIT<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">Functions<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span>\n<span class=\"w\">   <\/span><span class=\"k\">Options<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Inlining<\/span><span class=\"w\"> <\/span><span class=\"k\">false<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Optimization<\/span><span class=\"w\"> <\/span><span class=\"k\">false<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Expressions<\/span><span class=\"w\"> <\/span><span class=\"k\">true<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Deforming<\/span><span class=\"w\"> <\/span><span class=\"k\">true<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">Timing<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Generation<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">379<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Inlining<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">000<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Optimization<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">356<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Emission<\/span><span class=\"w\"> <\/span><span class=\"mi\">3<\/span><span class=\"p\">.<\/span><span class=\"mi\">469<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Total<\/span><span class=\"w\"> <\/span><span class=\"mi\">4<\/span><span class=\"p\">.<\/span><span class=\"mi\">204<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Execution<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">770<\/span><span class=\"p\">.<\/span><span class=\"mi\">366<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">9<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>The query planner chooses to forego the index and just scan the table (<code>Seq Scan\non data<\/code>). Why? Recall again the example trace of the B-tree index in the first\nsection of this article; it requires resolving a whole bunch of references and\naccessing data both from the index and the table<sup id=\"sf-postgresql-indexing-basics-8-back\"><a href=\"#sf-postgresql-indexing-basics-8\" class=\"simple-footnote\" title=\"Except for so-called index-only scans (source)\">8<\/a><\/sup>,\nwhich are stored separately. When accessing large parts of the table, it's often\nfaster to just scan through the entire table than it is to resolve all of those\nreferences. The condition <code>value &gt; 500000<\/code> corresponds to roughly half of the\ntable<sup id=\"sf-postgresql-indexing-basics-9-back\"><a href=\"#sf-postgresql-indexing-basics-9\" class=\"simple-footnote\" title=\"The query planner knows this as PostgreSQL keeps statistics on table contents (source).\">9<\/a><\/sup>,\nso the query planner does not use the index.<\/p>\n<p>If we increase the value, the query planner will re-evaluate and use the index\nas it estimates that a small enough part of the table needs to be scanned in the\nend.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\"> <\/span><span class=\"n\">Bitmap<\/span><span class=\"w\"> <\/span><span class=\"n\">Heap<\/span><span class=\"w\"> <\/span><span class=\"n\">Scan<\/span><span class=\"w\"> <\/span><span class=\"k\">on<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">49658<\/span><span class=\"p\">.<\/span><span class=\"mi\">83<\/span><span class=\"p\">..<\/span><span class=\"mi\">144439<\/span><span class=\"p\">.<\/span><span class=\"mi\">73<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">4042632<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">8<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">196<\/span><span class=\"p\">.<\/span><span class=\"mi\">822<\/span><span class=\"p\">..<\/span><span class=\"mi\">663<\/span><span class=\"p\">.<\/span><span class=\"mi\">746<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">4000401<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">   <\/span><span class=\"k\">Recheck<\/span><span class=\"w\"> <\/span><span class=\"n\">Cond<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"mi\">600000<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">Heap<\/span><span class=\"w\"> <\/span><span class=\"n\">Blocks<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">exact<\/span><span class=\"o\">=<\/span><span class=\"mi\">44248<\/span>\n<span class=\"w\">   <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\">  <\/span><span class=\"n\">Bitmap<\/span><span class=\"w\"> <\/span><span class=\"k\">Index<\/span><span class=\"w\"> <\/span><span class=\"n\">Scan<\/span><span class=\"w\"> <\/span><span class=\"k\">on<\/span><span class=\"w\"> <\/span><span class=\"n\">idx_data_value<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">00<\/span><span class=\"p\">..<\/span><span class=\"mi\">48648<\/span><span class=\"p\">.<\/span><span class=\"mi\">17<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">4042632<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">189<\/span><span class=\"p\">.<\/span><span class=\"mi\">479<\/span><span class=\"p\">..<\/span><span class=\"mi\">189<\/span><span class=\"p\">.<\/span><span class=\"mi\">479<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">4000401<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">         <\/span><span class=\"k\">Index<\/span><span class=\"w\"> <\/span><span class=\"n\">Cond<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"mi\">600000<\/span><span class=\"p\">)<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Planning<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">157<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">JIT<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">Functions<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span>\n<span class=\"w\">   <\/span><span class=\"k\">Options<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Inlining<\/span><span class=\"w\"> <\/span><span class=\"k\">false<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Optimization<\/span><span class=\"w\"> <\/span><span class=\"k\">false<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Expressions<\/span><span class=\"w\"> <\/span><span class=\"k\">true<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Deforming<\/span><span class=\"w\"> <\/span><span class=\"k\">true<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">Timing<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Generation<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">367<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Inlining<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">000<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Optimization<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">000<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Emission<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">000<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Total<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">367<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Execution<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">756<\/span><span class=\"p\">.<\/span><span class=\"mi\">080<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">11<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now the index is used, but the query runs almost precisely as fast at <code>756 ms<\/code>,\ncompared to <code>770 ms<\/code> for the full table scan. Considering it's also fetching\nfewer rows due to a narrower search, the fact that the query planner chose to\nrun the previous plan without touching the index seems justified.<\/p>\n<p>Note that this is all circumstantial, and that's entirely the point. The query\nplanner will come up with different query plans depending on the layout of the\ndata and the exact parameters of the query, even with all other server and\nclient settings being the same. A consequence of this is query plans can change\ndramatically as data in your tables accumulate. This also means that the <strong>query\nplans you get in your local development environment are often different from the\nones you get in production<\/strong>. As such, one can easily be fooled by a query that\ngets a terrible looking plan in your local environment but actually runs fine in\nproduction, and vice versa<sup id=\"sf-postgresql-indexing-basics-10-back\"><a href=\"#sf-postgresql-indexing-basics-10\" class=\"simple-footnote\" title=\"The query planner can also come up with terrible queries if table statistics are too outdated, but that's a topic for another time.\">10<\/a><\/sup>. Be aware of this when you add new indexes and are perplexed as to\nwhy they are not used; there may just not be enough data for it to be worth it.<\/p>\n<h2 id=\"an-index-is-for-an-exact-expression\">An index is for an exact expression<\/h2>\n<p>We have an index on <code>data(value)<\/code> and showed that ordering by <code>value<\/code> is super\nquick. Let's do it again so you don't have to scroll up too far.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">ORDER<\/span><span class=\"w\"> <\/span><span class=\"k\">BY<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"k\">LIMIT<\/span><span class=\"w\"> <\/span><span class=\"mi\">10<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">id<\/span><span class=\"w\">    <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span>\n<span class=\"c1\">---------+-------<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">1453865<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">3782708<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">7796750<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">8150282<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\">  <\/span><span class=\"mi\">268472<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">1650656<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">2191333<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">3330397<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5364764<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5889252<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n\n<span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">455<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<\/code><\/pre><\/div>\n\n<p>But what if we order by <code>value * 2<\/code>?<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">ORDER<\/span><span class=\"w\"> <\/span><span class=\"k\">BY<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"w\"> <\/span><span class=\"k\">LIMIT<\/span><span class=\"w\"> <\/span><span class=\"mi\">10<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">id<\/span><span class=\"w\">    <\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span>\n<span class=\"c1\">---------+-------<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">3782708<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">1453865<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">7796750<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">8150282<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">0<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5889252<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">3330397<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">9165134<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">5364764<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\"> <\/span><span class=\"mi\">8571152<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"w\">  <\/span><span class=\"mi\">268472<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"w\">     <\/span><span class=\"mi\">1<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n\n<span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">540<\/span><span class=\"p\">.<\/span><span class=\"mi\">665<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<\/code><\/pre><\/div>\n\n<p>It takes 1000 times as long. Looking at the query plan, we can see why.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">EXPLAIN<\/span><span class=\"w\"> <\/span><span class=\"k\">ANALYZE<\/span><span class=\"w\"> <\/span><span class=\"k\">SELECT<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"k\">FROM<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">ORDER<\/span><span class=\"w\"> <\/span><span class=\"k\">BY<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"w\"> <\/span><span class=\"k\">LIMIT<\/span><span class=\"w\"> <\/span><span class=\"mi\">10<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">                                                                 <\/span><span class=\"n\">QUERY<\/span><span class=\"w\"> <\/span><span class=\"n\">PLAN<\/span><span class=\"w\">                                                                 <\/span>\n<span class=\"c1\">--------------------------------------------------------------------------------------------------------------------------------------------<\/span>\n<span class=\"w\"> <\/span><span class=\"k\">Limit<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">187371<\/span><span class=\"p\">.<\/span><span class=\"mi\">53<\/span><span class=\"p\">..<\/span><span class=\"mi\">187372<\/span><span class=\"p\">.<\/span><span class=\"mi\">70<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">10<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">12<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">691<\/span><span class=\"p\">.<\/span><span class=\"mi\">290<\/span><span class=\"p\">..<\/span><span class=\"mi\">696<\/span><span class=\"p\">.<\/span><span class=\"mi\">029<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">10<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">   <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\">  <\/span><span class=\"n\">Gather<\/span><span class=\"w\"> <\/span><span class=\"n\">Merge<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">187371<\/span><span class=\"p\">.<\/span><span class=\"mi\">53<\/span><span class=\"p\">..<\/span><span class=\"mi\">1159661<\/span><span class=\"p\">.<\/span><span class=\"mi\">72<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">8333334<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">12<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">682<\/span><span class=\"p\">.<\/span><span class=\"mi\">579<\/span><span class=\"p\">..<\/span><span class=\"mi\">687<\/span><span class=\"p\">.<\/span><span class=\"mi\">316<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">10<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">         <\/span><span class=\"n\">Workers<\/span><span class=\"w\"> <\/span><span class=\"n\">Planned<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span>\n<span class=\"w\">         <\/span><span class=\"n\">Workers<\/span><span class=\"w\"> <\/span><span class=\"n\">Launched<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span>\n<span class=\"w\">         <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\">  <\/span><span class=\"n\">Sort<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">186371<\/span><span class=\"p\">.<\/span><span class=\"mi\">51<\/span><span class=\"p\">..<\/span><span class=\"mi\">196788<\/span><span class=\"p\">.<\/span><span class=\"mi\">18<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">4166667<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">12<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">659<\/span><span class=\"p\">.<\/span><span class=\"mi\">729<\/span><span class=\"p\">..<\/span><span class=\"mi\">659<\/span><span class=\"p\">.<\/span><span class=\"mi\">730<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">7<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">3<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">               <\/span><span class=\"n\">Sort<\/span><span class=\"w\"> <\/span><span class=\"k\">Key<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">((<\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">               <\/span><span class=\"n\">Sort<\/span><span class=\"w\"> <\/span><span class=\"k\">Method<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">top<\/span><span class=\"o\">-<\/span><span class=\"n\">N<\/span><span class=\"w\"> <\/span><span class=\"n\">heapsort<\/span><span class=\"w\">  <\/span><span class=\"n\">Memory<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">25<\/span><span class=\"n\">kB<\/span>\n<span class=\"w\">               <\/span><span class=\"n\">Worker<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">:<\/span><span class=\"w\">  <\/span><span class=\"n\">Sort<\/span><span class=\"w\"> <\/span><span class=\"k\">Method<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">top<\/span><span class=\"o\">-<\/span><span class=\"n\">N<\/span><span class=\"w\"> <\/span><span class=\"n\">heapsort<\/span><span class=\"w\">  <\/span><span class=\"n\">Memory<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">25<\/span><span class=\"n\">kB<\/span>\n<span class=\"w\">               <\/span><span class=\"n\">Worker<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"p\">:<\/span><span class=\"w\">  <\/span><span class=\"n\">Sort<\/span><span class=\"w\"> <\/span><span class=\"k\">Method<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">top<\/span><span class=\"o\">-<\/span><span class=\"n\">N<\/span><span class=\"w\"> <\/span><span class=\"n\">heapsort<\/span><span class=\"w\">  <\/span><span class=\"n\">Memory<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">25<\/span><span class=\"n\">kB<\/span>\n<span class=\"w\">               <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\">  <\/span><span class=\"n\">Parallel<\/span><span class=\"w\"> <\/span><span class=\"n\">Seq<\/span><span class=\"w\"> <\/span><span class=\"n\">Scan<\/span><span class=\"w\"> <\/span><span class=\"k\">on<\/span><span class=\"w\"> <\/span><span class=\"k\">data<\/span><span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"n\">cost<\/span><span class=\"o\">=<\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">00<\/span><span class=\"p\">..<\/span><span class=\"mi\">96331<\/span><span class=\"p\">.<\/span><span class=\"mi\">33<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">4166667<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"o\">=<\/span><span class=\"mi\">12<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">actual<\/span><span class=\"w\"> <\/span><span class=\"k\">time<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">.<\/span><span class=\"mi\">799<\/span><span class=\"p\">..<\/span><span class=\"mi\">312<\/span><span class=\"p\">.<\/span><span class=\"mi\">822<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"o\">=<\/span><span class=\"mi\">3333333<\/span><span class=\"w\"> <\/span><span class=\"n\">loops<\/span><span class=\"o\">=<\/span><span class=\"mi\">3<\/span><span class=\"p\">)<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Planning<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">250<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">JIT<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">Functions<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">7<\/span>\n<span class=\"w\">   <\/span><span class=\"k\">Options<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Inlining<\/span><span class=\"w\"> <\/span><span class=\"k\">false<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Optimization<\/span><span class=\"w\"> <\/span><span class=\"k\">false<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Expressions<\/span><span class=\"w\"> <\/span><span class=\"k\">true<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Deforming<\/span><span class=\"w\"> <\/span><span class=\"k\">true<\/span>\n<span class=\"w\">   <\/span><span class=\"n\">Timing<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Generation<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"p\">.<\/span><span class=\"mi\">026<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Inlining<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">000<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Optimization<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">.<\/span><span class=\"mi\">738<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Emission<\/span><span class=\"w\"> <\/span><span class=\"mi\">13<\/span><span class=\"p\">.<\/span><span class=\"mi\">207<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Total<\/span><span class=\"w\"> <\/span><span class=\"mi\">14<\/span><span class=\"p\">.<\/span><span class=\"mi\">971<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"w\"> <\/span><span class=\"n\">Execution<\/span><span class=\"w\"> <\/span><span class=\"k\">Time<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">696<\/span><span class=\"p\">.<\/span><span class=\"mi\">794<\/span><span class=\"w\"> <\/span><span class=\"n\">ms<\/span>\n<span class=\"p\">(<\/span><span class=\"mi\">16<\/span><span class=\"w\"> <\/span><span class=\"k\">rows<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Again, there is no need for a deep understanding of query plans to see that this\nis worse than the simple index scan shown before. Here we've both got sequential\nscanning of the entire table and a bunch of sorting going on, ending up taking a\nwhole lot of time. The reason the query plan looks like that is that <code>value * 2<\/code>\nis not indexed, only <code>value<\/code> is. It's the <em>exact<\/em> expression used in the index\ncreation that is actually indexed and can be used in <code>WHERE<\/code>, <code>ORDER BY<\/code>, <code>GROUP\nBY<\/code> etc. This should be fairly evident given how a B-tree index lookup works; we\ncannot quickly lookup an arbitrary expression using a column based on an index\nof the raw column.<\/p>\n<p>This example is of course silly, because ordering by a value or ordering by\ndouble that value results in the same order. In a more realistic scenario, there\nare many good reasons to use expressions in ordering or searching. For example,\nif you want to perform a case insensitive search on a text column that contains\nmixed casing, calling <code>LOWER()<\/code> on that column makes a whole lot of sense. Such\nsearches can be optimized using an <a href=\"https:\/\/www.postgresql.org\/docs\/16\/indexes-expressional.html\">expression index (a.k.a functional\nindex)<\/a>, but\nthat is something I plan to cover in an upcoming article. For the purposes of\nthis article, I only want to make it very clear that a column having an index on\nit does not imply that any search on that column can utilize said index.<\/p>\n<h2 id=\"indexes-optimize-reads-but-slow-down-writes\">Indexes optimize reads but slow down writes<\/h2>\n<p>Something to keep in mind with indexing is that an index is made to speed up\nreads. On the flip side, they slow down writes as every time a table is written\nto its indexes must also be written to<sup id=\"sf-postgresql-indexing-basics-11-back\"><a href=\"#sf-postgresql-indexing-basics-11\" class=\"simple-footnote\" title=\"Except for heap-only tuples (source). Indexes can also take up a significant amount of storage. I once worked with a production database where the largest table was around 2 terabytes in size, with an additional 3 terabytes of indexes. Adding a new index was something we thought long and hard about before actually doing.\">11<\/a><\/sup><\/p>\n<p>That said, you probably don't need to worry much about indexes taking up space\nor slowing down writes. I have personally only had to think about such things\nwith indexes for very large tables with billions of rows, or tables with very\nhigh throughput demands. The vast majority of applications have neither of\nthose, while the lack of indexes becomes problematic even for small amounts of\ndata. In other words, the benefits of indexing almost always outweighs the cons,\nbut it's good to be aware that cons exist.<\/p>\n<h1 id=\"summary\">Summary<\/h1>\n<p>In this article, we've covered the basics of indexing in PostgreSQL, had a\ntheoretical look at a B-tree index and its properties as well as how these can\nbe taken advantage of. In addition, we've looked at some common pitfalls with\nindexing and some things to keep in mind. That may seem like a lot more than\njust basics, but the unfortunate reality is that indexing is a complex subject.\nWe haven't delved into <a href=\"https:\/\/www.postgresql.org\/docs\/16\/indexes-types.html\">other types of\nindexes<\/a> or <a href=\"https:\/\/www.postgresql.org\/docs\/current\/indexes-multicolumn.html\">multicolumn\nindexes<\/a>.\nWe also haven't touched upon <a href=\"https:\/\/www.postgresql.org\/docs\/current\/indexes-partial.html\">partial\nindexes<\/a> or how\nindexes interact with more complex queries, such as joins. Simply put, there is\na lot more to cover.<\/p>\n<p>I plan to continue this article series with shorter articles that cover specific\nuse cases where these more advanced indexing techniques are useful. If you're\neager to learn more before I get around to that, the <a href=\"https:\/\/www.postgresql.org\/docs\/16\/indexes.html\">PostgreSQL index\ndocumentation<\/a> is a great place\nto start!<\/p><ol class=\"simple-footnotes\"><li id=\"sf-postgresql-indexing-basics-1\">The <em>query planner<\/em> (or <em>optimizer<\/em>) is the part of\nPostgreSQL that's responsible for taking your high-level SQL query and figuring\nout the fastest way to execute it in the database\n(<a href=\"https:\/\/www.postgresql.org\/docs\/current\/planner-optimizer.html\">source<\/a>). <a href=\"#sf-postgresql-indexing-basics-1-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-postgresql-indexing-basics-2\">In PostgreSQL, the nodes of a B-tree are called\npages\n<a href=\"https:\/\/www.postgresql.org\/docs\/current\/btree-implementation.html\">(source)<\/a> <a href=\"#sf-postgresql-indexing-basics-2-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-postgresql-indexing-basics-3\">Pages in the B-tree are either <em>internal<\/em> pages or <em>leaf<\/em>\npages. An internal page only contains references to other B-tree pages, while a\nleaf page only contains references to the indexed table. There are no hybrid\ninternal\/leaf pages. The root can be either internal or a leaf depending on the\nsize of the index. There is also a special metapage that keeps track of things\nlike tree depth and which page is the root of the tree\n<a href=\"https:\/\/www.postgresql.org\/docs\/current\/btree-implementation.html\">(source)<\/a>.\nA search in a B-tree index starts from the singular root page and then proceeds\nthrough <em>internal<\/em> pages in the tree until a <em>leaf<\/em> page containing references\nto the indexed table is found. From there, the references to the table can be\nresolved and the rows retrieved. <a href=\"#sf-postgresql-indexing-basics-3-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-postgresql-indexing-basics-4\">The page is sorted, <a href=\"https:\/\/github.com\/postgres\/postgres\/blob\/f4ad0021aface01ee74604355bd2e998e5f73320\/src\/backend\/access\/nbtree\/nbtsearch.c#L318\">PostgreSQL makes effective use of binary\nsearch to quickly find a\nkey<\/a> <a href=\"#sf-postgresql-indexing-basics-4-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-postgresql-indexing-basics-5\">Depending on the amount of hits, scanning the rows from the table\nmay of course take longer, however. <a href=\"#sf-postgresql-indexing-basics-5-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-postgresql-indexing-basics-6\">The order in which\nrows are returned from a query is undefined unless <code>ORDER BY<\/code> is provided. A\ncommon bug in backend systems is that <code>OFFSET<\/code> and <code>LIMIT<\/code> are used for\npagination either without explicit ordering or with ordering that is not\nunique. <a href=\"#sf-postgresql-indexing-basics-6-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-postgresql-indexing-basics-7\">\nNote that only the B-tree type of index has this property\n(<a href=\"https:\/\/www.postgresql.org\/docs\/16\/indexes-ordering.html\">source<\/a>). <a href=\"#sf-postgresql-indexing-basics-7-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-postgresql-indexing-basics-8\">Except for so-called <em>index-only scans<\/em>\n(<a href=\"https:\/\/www.postgresql.org\/docs\/current\/indexes-index-only-scans.html\">source<\/a>) <a href=\"#sf-postgresql-indexing-basics-8-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-postgresql-indexing-basics-9\">The query planner knows this as PostgreSQL keeps statistics on table\ncontents (<a href=\"https:\/\/www.postgresql.org\/docs\/16\/sql-analyze.html\">source<\/a>). <a href=\"#sf-postgresql-indexing-basics-9-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-postgresql-indexing-basics-10\">The query planner can also come up with terrible\nqueries if table statistics are too outdated, but that's a topic for another\ntime. <a href=\"#sf-postgresql-indexing-basics-10-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-postgresql-indexing-basics-11\">Except for heap-only tuples\n(<a href=\"https:\/\/www.postgresql.org\/docs\/16\/storage-hot.html\">source<\/a>). Indexes can\nalso take up a significant amount of storage. I once worked with a production\ndatabase where the largest table was around 2 terabytes in size, with an\nadditional 3 terabytes of indexes. Adding a new index was something we thought\nlong and hard about before actually doing. <a href=\"#sf-postgresql-indexing-basics-11-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><\/ol>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"postgresql"}},{"@attributes":{"term":"database"}},{"@attributes":{"term":"indexing"}},{"@attributes":{"term":"sql"}}]},{"title":"Configuring touchpad tap in Sway","link":{"@attributes":{"href":"https:\/\/slar.se\/configuring-touchpad-in-sway.html","rel":"alternate"}},"published":"2024-03-24T00:00:00+01:00","updated":"2024-03-24T00:00:00+01:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2024-03-24:\/configuring-touchpad-in-sway.html","summary":"<p>One thing that didn't carry over from my i3 setup <a href=\"https:\/\/slar.se\/wayland-one-month-later.html\">when moving over to\nSway (i.e. Wayland)<\/a> was the touchpad\nconfiguration. Input devices was a display server concern under X.Org, so the\nwindow manager had nothing to do with it. Notably, now click-on-tap is not\nworking for me \u2026<\/p>","content":"<p>One thing that didn't carry over from my i3 setup <a href=\"https:\/\/slar.se\/wayland-one-month-later.html\">when moving over to\nSway (i.e. Wayland)<\/a> was the touchpad\nconfiguration. Input devices was a display server concern under X.Org, so the\nwindow manager had nothing to do with it. Notably, now click-on-tap is not\nworking for me, which is massively annoying.<\/p>\n<p>If you're just here for the touchpad click-on-tap configuration, it looks like this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">input<\/span><span class=\"w\"> <\/span><span class=\"s\">\"type:touchpad\"<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">dwt<\/span><span class=\"w\"> <\/span><span class=\"nx\">enabled<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">dwtp<\/span><span class=\"w\"> <\/span><span class=\"nx\">enabled<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">tap<\/span><span class=\"w\"> <\/span><span class=\"nx\">enabled<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">tap_button_map<\/span><span class=\"w\"> <\/span><span class=\"nx\">lrm<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>But if you want to improve your understanding of how to configure input devices\nsuch as touchpads and mice in a Wayland compositor, then read on!<\/p>\n<h1 id=\"configuring-a-libinput-device-in-sway\">Configuring a libinput device in Sway<\/h1>\n<p>We need to add a libinput<sup id=\"sf-configuring-touchpad-in-sway-1-back\"><a href=\"#sf-configuring-touchpad-in-sway-1\" class=\"simple-footnote\" title=\"libinput is a stack for common input devices, such as keyboards, touchpads and mice. Read more in the Wayland wiki.\">1<\/a><\/sup>\nconfiguration into the Sway config file, which is usually located at\n<code>~\/.config\/sway\/config<\/code>. The Sway wiki <a href=\"https:\/\/github.com\/swaywm\/sway\/wiki#libinput-config-options\">has a small example for libinput\ndevices<\/a> but it\ndoesn't really say all that much. Generally, an input configuration should look\nlike this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>input &lt;selector&gt; {\n    option value\n}\n<\/code><\/pre><\/div>\n\n<p>For the selector, we can use either the device identifier, or the type of the\ndevice. I prefer the device type, i.e. <code>\"type:touchpad\"<\/code>, as I use the same\nconfiguration file for multiple devices that don't share touchpad\nidentifiers<sup id=\"sf-configuring-touchpad-in-sway-2-back\"><a href=\"#sf-configuring-touchpad-in-sway-2\" class=\"simple-footnote\" title=\"Note that the type selector will select all devices of that type. If you have multiple devices that identify as touchpads, you may want to be more specific and use the identifier.\">2<\/a><\/sup>.<\/p>\n<p>You can run <code>swaymsg -t get_inputs<\/code> to get information about your devices. You\nwill get a ton of output, but somewhere you'll find a device that has <code>Type:\nTouchpad<\/code>. Mine looks like this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>swaymsg<span class=\"w\"> <\/span>-t<span class=\"w\"> <\/span>get_inputs\n...\nInput<span class=\"w\"> <\/span>device:<span class=\"w\"> <\/span>SYNA1D31:00<span class=\"w\"> <\/span>06CB:CD48<span class=\"w\"> <\/span>Touchpad\n<span class=\"w\">  <\/span>Type:<span class=\"w\"> <\/span>Touchpad\n<span class=\"w\">  <\/span>Identifier:<span class=\"w\"> <\/span><span class=\"m\">1739<\/span>:52552:SYNA1D31:00_06CB:CD48_Touchpad\n<span class=\"w\">  <\/span>Product<span class=\"w\"> <\/span>ID:<span class=\"w\"> <\/span><span class=\"m\">52552<\/span>\n<span class=\"w\">  <\/span>Vendor<span class=\"w\"> <\/span>ID:<span class=\"w\"> <\/span><span class=\"m\">1739<\/span>\n<span class=\"w\">  <\/span>Libinput<span class=\"w\"> <\/span>Send<span class=\"w\"> <\/span>Events:<span class=\"w\"> <\/span>enabled\n...\n<\/code><\/pre><\/div>\n\n<p>We can however get a whole lot more information about each device with the\n<code>--raw<\/code> option<sup id=\"sf-configuring-touchpad-in-sway-3-back\"><a href=\"#sf-configuring-touchpad-in-sway-3\" class=\"simple-footnote\" title=\"When piping swaymsg output to another command, --raw is implicit. I use it here explicitly for clarity.\">3<\/a><\/sup>. Combining that with\n<code>jq<\/code><sup id=\"sf-configuring-touchpad-in-sway-4-back\"><a href=\"#sf-configuring-touchpad-in-sway-4\" class=\"simple-footnote\" title=\"If you don't know how to use jq, do yourself the biggest favor of the year and learn it.\">4<\/a><\/sup> we can get only touchpads out of the command. On all my\ndevices, I only have a single touchpad device. It should look something like\nthis.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>swaymsg<span class=\"w\"> <\/span>-t<span class=\"w\"> <\/span>get_inputs<span class=\"w\"> <\/span>--raw<span class=\"w\"> <\/span><span class=\"p\">|<\/span><span class=\"w\"> <\/span>jq<span class=\"w\"> <\/span><span class=\"s1\">'.[] | select(.type==\"touchpad\")'<\/span>\n<span class=\"o\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"s2\">\"identifier\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"1739:52552:SYNA1D31:00_06CB:CD48_Touchpad\"<\/span>,\n<span class=\"w\">  <\/span><span class=\"s2\">\"name\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"SYNA1D31:00 06CB:CD48 Touchpad\"<\/span>,\n<span class=\"w\">  <\/span><span class=\"s2\">\"vendor\"<\/span>:<span class=\"w\"> <\/span><span class=\"m\">1739<\/span>,\n<span class=\"w\">  <\/span><span class=\"s2\">\"product\"<\/span>:<span class=\"w\"> <\/span><span class=\"m\">52552<\/span>,\n<span class=\"w\">  <\/span><span class=\"s2\">\"type\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"touchpad\"<\/span>,\n<span class=\"w\">  <\/span><span class=\"s2\">\"scroll_factor\"<\/span>:<span class=\"w\"> <\/span><span class=\"m\">1<\/span>.0,\n<span class=\"w\">  <\/span><span class=\"s2\">\"libinput\"<\/span>:<span class=\"w\"> <\/span><span class=\"o\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"s2\">\"send_events\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"enabled\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"tap\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"disabled\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"tap_button_map\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"lrm\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"tap_drag\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"enabled\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"tap_drag_lock\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"disabled\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"accel_speed\"<\/span>:<span class=\"w\"> <\/span><span class=\"m\">0<\/span>.0,\n<span class=\"w\">    <\/span><span class=\"s2\">\"accel_profile\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"adaptive\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"natural_scroll\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"disabled\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"left_handed\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"disabled\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"click_method\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"button_areas\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"middle_emulation\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"disabled\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"scroll_method\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"two_finger\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"dwt\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"enabled\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"dwtp\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"enabled\"<\/span>\n<span class=\"w\">  <\/span><span class=\"o\">}<\/span>\n<span class=\"o\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This gives us everything we need to configure the touchpad, and we can also see\nif our configuration takes effect correctly. The options shown under <code>libinput<\/code>\nis what we have to play with. The names aren't necessarily self-explanatory, but\nyou can find decent descriptions of them in the <code>sway-input(5)<\/code><sup id=\"sf-configuring-touchpad-in-sway-5-back\"><a href=\"#sf-configuring-touchpad-in-sway-5\" class=\"simple-footnote\" title=\"Run man 5 sway-input to get the given page. See my article on man page sections if the 5 is confusing to you.\">5<\/a><\/sup>man\npage under the <code>LIBINPUT CONFIGURATION<\/code> section.<\/p>\n<p>I'm going to set the options that are crucial for how I use a touchpad,\nregardless of what their defaults are. These options are:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">input<\/span><span class=\"w\"> <\/span><span class=\"s\">\"type:touchpad\"<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">tap<\/span><span class=\"w\"> <\/span><span class=\"nx\">enabled<\/span><span class=\"w\">         <\/span><span class=\"err\">#<\/span><span class=\"w\"> <\/span><span class=\"nx\">enables<\/span><span class=\"w\"> <\/span><span class=\"nx\">click<\/span><span class=\"o\">-<\/span><span class=\"nx\">on<\/span><span class=\"o\">-<\/span><span class=\"nx\">tap<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">tap_button_map<\/span><span class=\"w\"> <\/span><span class=\"nx\">lrm<\/span><span class=\"w\">  <\/span><span class=\"err\">#<\/span><span class=\"w\"> <\/span><span class=\"nx\">tap<\/span><span class=\"w\"> <\/span><span class=\"nx\">with<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"nx\">finger<\/span><span class=\"w\"> <\/span><span class=\"p\">=<\/span><span class=\"w\"> <\/span><span class=\"nx\">left<\/span><span class=\"w\"> <\/span><span class=\"nx\">click<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"w\"> <\/span><span class=\"nx\">fingers<\/span><span class=\"w\"> <\/span><span class=\"p\">=<\/span><span class=\"w\"> <\/span><span class=\"nx\">right<\/span><span class=\"w\"> <\/span><span class=\"nx\">click<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">3<\/span><span class=\"w\"> <\/span><span class=\"nx\">fingers<\/span><span class=\"w\"> <\/span><span class=\"p\">=<\/span><span class=\"w\"> <\/span><span class=\"nx\">middle<\/span><span class=\"w\"> <\/span><span class=\"nx\">click<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">dwt<\/span><span class=\"w\"> <\/span><span class=\"nx\">enabled<\/span><span class=\"w\">         <\/span><span class=\"err\">#<\/span><span class=\"w\"> <\/span><span class=\"nx\">disable<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nx\">touchpad<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"k\">while<\/span><span class=\"w\"> <\/span><span class=\"nx\">typing<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">dwtp<\/span><span class=\"w\"> <\/span><span class=\"nx\">enabled<\/span><span class=\"w\">        <\/span><span class=\"err\">#<\/span><span class=\"w\"> <\/span><span class=\"nx\">disable<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nx\">touchpad<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"k\">while<\/span><span class=\"w\"> <\/span><span class=\"nx\">track<\/span><span class=\"w\"> <\/span><span class=\"nx\">pointing<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Putting this in my <code>~\/.config\/sway\/config<\/code><sup id=\"sf-configuring-touchpad-in-sway-6-back\"><a href=\"#sf-configuring-touchpad-in-sway-6\" class=\"simple-footnote\" title=\"To see exactly how I use this in my Sway config, refer to my config repository.\">6<\/a><\/sup>,\nreloading the environment and then checking the settings shows that <code>tap<\/code> is\nnow enabled.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>swaymsg<span class=\"w\"> <\/span>reload\n$<span class=\"w\"> <\/span>swaymsg<span class=\"w\"> <\/span>-t<span class=\"w\"> <\/span>get_inputs<span class=\"w\"> <\/span><span class=\"p\">|<\/span><span class=\"w\"> <\/span>jq<span class=\"w\"> <\/span><span class=\"s1\">'.[] | select(.type==\"touchpad\")'<\/span>\n<span class=\"o\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"s2\">\"identifier\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"1739:52552:SYNA1D31:00_06CB:CD48_Touchpad\"<\/span>,\n<span class=\"w\">  <\/span><span class=\"o\">[<\/span>...<span class=\"o\">]<\/span>\n<span class=\"w\">  <\/span><span class=\"s2\">\"libinput\"<\/span>:<span class=\"w\"> <\/span><span class=\"o\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"o\">[<\/span>...<span class=\"o\">]<\/span>\n<span class=\"w\">    <\/span><span class=\"s2\">\"tap\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"enabled\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"tap_button_map\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"lrm\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"o\">[<\/span>...<span class=\"o\">]<\/span>\n<span class=\"w\">    <\/span><span class=\"s2\">\"dwt\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"enabled\"<\/span>,\n<span class=\"w\">    <\/span><span class=\"s2\">\"dwtp\"<\/span>:<span class=\"w\"> <\/span><span class=\"s2\">\"enabled\"<\/span>\n<span class=\"w\">  <\/span><span class=\"o\">}<\/span>\n<span class=\"o\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>And that's that, click-on-tap now works again!<\/p>\n<h1 id=\"summary\">Summary<\/h1>\n<p>In this article, I outlined how to configure a touchpad in Sway. The principles\nshown here carry over to any kind of libinput device, and should also be\napplicable in most other Wayland compositors.<\/p><ol class=\"simple-footnotes\"><li id=\"sf-configuring-touchpad-in-sway-1\">libinput is a stack for common input devices, such\nas keyboards, touchpads and mice. Read more <a href=\"https:\/\/wayland.freedesktop.org\/libinput\/doc\/latest\/what-is-libinput.html\">in the Wayland\nwiki<\/a>. <a href=\"#sf-configuring-touchpad-in-sway-1-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-configuring-touchpad-in-sway-2\">Note that the type selector will select <em>all<\/em> devices of that\ntype. If you have multiple devices that identify as touchpads, you may want to\nbe more specific and use the identifier. <a href=\"#sf-configuring-touchpad-in-sway-2-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-configuring-touchpad-in-sway-3\">When piping <code>swaymsg<\/code> output to another command, <code>--raw<\/code> is\nimplicit. I use it here explicitly for clarity. <a href=\"#sf-configuring-touchpad-in-sway-3-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-configuring-touchpad-in-sway-4\">If you don't know how to use <code>jq<\/code>, do yourself the biggest favor of the\nyear and learn it. <a href=\"#sf-configuring-touchpad-in-sway-4-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-configuring-touchpad-in-sway-5\">Run <code>man 5\nsway-input<\/code> to get the given page. See my article on <a href=\"https:\/\/slar.se\/man-page-numbering.html\">man page\nsections<\/a> if the <code>5<\/code> is confusing to you. <a href=\"#sf-configuring-touchpad-in-sway-5-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><li id=\"sf-configuring-touchpad-in-sway-6\">To see exactly how I use this in\nmy Sway config, refer to <a href=\"https:\/\/github.com\/slarse\/config\/commit\/21b524a956bd942424aa944fa70cce01dd005ea8\">my config\nrepository<\/a>. <a href=\"#sf-configuring-touchpad-in-sway-6-back\" class=\"simple-footnote-back\">\u21a9<\/a><\/li><\/ol>","category":[{"@attributes":{"term":"Linux"}},{"@attributes":{"term":"linux"}},{"@attributes":{"term":"wayland"}},{"@attributes":{"term":"sway"}},{"@attributes":{"term":"libinput"}}]},{"title":"Syntax highlight anything with Tree-sitter","link":{"@attributes":{"href":"https:\/\/slar.se\/syntax-highlight-anything-with-tree-sitter.html","rel":"alternate"}},"published":"2024-03-11T00:00:00+01:00","updated":"2024-03-11T00:00:00+01:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2024-03-11:\/syntax-highlight-anything-with-tree-sitter.html","summary":"<p>As of my previous post on <a href=\"https:\/\/slar.se\/comment-and-uncomment-code-in-neovim.html\">extending NeoVim for commenting and uncommenting\ncode blocks<\/a>, I'm on something of a\nNeoVim extension streak. The flavor of the week is syntax highlighting. I've been\nusing the highly customizable\n<a href=\"https:\/\/github.com\/nvim-treesitter\/nvim-treesitter\">nvim-treesitter<\/a> for the\npast few years. This depends on there being a\n<a href=\"https:\/\/tree-sitter.github.io\/tree-sitter\/\">Tree-sitter<\/a> parser \u2026<\/p>","content":"<p>As of my previous post on <a href=\"https:\/\/slar.se\/comment-and-uncomment-code-in-neovim.html\">extending NeoVim for commenting and uncommenting\ncode blocks<\/a>, I'm on something of a\nNeoVim extension streak. The flavor of the week is syntax highlighting. I've been\nusing the highly customizable\n<a href=\"https:\/\/github.com\/nvim-treesitter\/nvim-treesitter\">nvim-treesitter<\/a> for the\npast few years. This depends on there being a\n<a href=\"https:\/\/tree-sitter.github.io\/tree-sitter\/\">Tree-sitter<\/a> parser for whatever\nlanguage you're working with. Usually there is, but sometimes you run into\nlanguages that are esoteric enough that there aren't any parsers available. And\nthen you're SOL on the whole syntax highlighting part. Unless, of course, you\nwrite a parser of your own. Which naturally is what we'll do.<\/p>\n<p>This is the first article in a series on working with Tree-sitter to syntax\nhighlight anything. Although this article series is intended for a\nNeoVim-inclined audience, this first part has nothing to do with NeoVim and can\nbe enjoyed by anyone interested in Tree-sitter or parsers in general. In the\nstill under construction second part, we'll dive into working with and utilizing\nTree-sitter in NeoVim.<\/p>\n<blockquote>\n<p><strong>Companion repository:<\/strong> The complete parser developed in this article is\navailable in a companion repository at\n<a href=\"https:\/\/github.com\/slarse\/tree-sitter-mds\">slarse\/tree-sitter-mds<\/a><\/p>\n<\/blockquote>\n<div class=\"toc\"><span class=\"toctitle\">Table of Contents<\/span><ul>\n<li><a href=\"#whats-this-tree-sitter-thing\">What's this Tree-sitter thing?<\/a><\/li>\n<li><a href=\"#working-example-markdown-simple\">Working example: Markdown Simple<\/a><\/li>\n<li><a href=\"#getting-started-with-creating-tree-sitter-parsers\">Getting started with creating Tree-sitter parsers<\/a><ul>\n<li><a href=\"#babys-first-grammar-rule\">Baby's first grammar rule<\/a><\/li>\n<li><a href=\"#let-there-be-color\">Let there be color<\/a><\/li>\n<\/ul>\n<\/li>\n<li><a href=\"#refining-the-grammar\">Refining the grammar<\/a><\/li>\n<li><a href=\"#capturing-inline-code-and-code-blocks\">Capturing inline code and code blocks<\/a><ul>\n<li><a href=\"#capturing-code-blocks\">Capturing code blocks<\/a><\/li>\n<li><a href=\"#paragraphs-with-text-and-inline-code\">Paragraphs with text and inline code<\/a><\/li>\n<li><a href=\"#resolving-a-conflict-in-the-grammar\">Resolving a conflict in the grammar<\/a><\/li>\n<li><a href=\"#improving-the-highlight-queries\">Improving the highlight queries<\/a><\/li>\n<li><a href=\"#injecting-a-javascript-parser\">Injecting a JavaScript parser<\/a><\/li>\n<\/ul>\n<\/li>\n<li><a href=\"#summary\">Summary<\/a><\/li>\n<\/ul>\n<\/div>\n<h1 id=\"whats-this-tree-sitter-thing\">What's this Tree-sitter thing?<\/h1>\n<p><a href=\"https:\/\/tree-sitter.github.io\/tree-sitter\/\">Tree-sitter<\/a> is a parser generator\ntool for the modern era. What's a parser generator, you ask? Well, it's exactly\nwhat it sounds like: a tool to generate a parser! By defining the syntax of a\nlanguage in a way the parser generator understands, it can generate a parser\nfor you that can take source code of that language and transform it into a\nsyntax tree.<\/p>\n<p>Parser generators aren't a new concept. <a href=\"https:\/\/en.wikipedia.org\/wiki\/GNU_Bison\">GNU\nBison<\/a> has been around for 38 years at\nthis point, and <a href=\"https:\/\/en.wikipedia.org\/wiki\/Yacc\">YACC<\/a> had been around for a\ndecade by the time Bison arrived. So, not at all a new concept. What's novel\nwith Tree-sitter is both how easy it is to define a grammar as long as you know\na little bit of JavaScript and the fact that <a href=\"https:\/\/tree-sitter.github.io\/tree-sitter\/syntax-highlighting\">syntax highlighting is a built-in\nfeature<\/a>.<\/p>\n<p>You can do a lot of cool things with Tree-sitter's syntax trees, but in this\narticle our focus is on syntax highlighting.<\/p>\n<blockquote>\n<p>This article assumes that you have access to a <code>bash<\/code>-like shell (such as\n<code>bash<\/code> or <code>zsh<\/code>). Commands intended to be executed in a shell are prefixed\nwith <code>$<\/code>. Lines that follow a <code>$<\/code>-prefixed line but are not prefixed are\noutput lines.<\/p>\n<\/blockquote>\n<h1 id=\"working-example-markdown-simple\">Working example: Markdown Simple<\/h1>\n<p>As a driving example for this article series, we'll look at a tiny subset of\nMarkdown, which should be familiar to most anyone in the target audience.\nSpecifically, we want to be able to highlight the following containing\nheadings, paragraphs, inline code and code blocks.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># This is a heading<\/span>\n<span class=\"n\">This<\/span><span class=\"w\"> <\/span><span class=\"n\">little<\/span><span class=\"w\"> <\/span><span class=\"n\">paragraph<\/span><span class=\"w\"> <\/span><span class=\"n\">of<\/span><span class=\"w\"> <\/span><span class=\"n\">text<\/span><span class=\"w\"> <\/span><span class=\"n\">with<\/span><span class=\"w\"> <\/span><span class=\"err\">`<\/span><span class=\"n\">inline<\/span><span class=\"w\"> <\/span><span class=\"n\">code<\/span><span class=\"err\">`<\/span>\n\n<span class=\"err\">```<\/span>\n<span class=\"k\">const<\/span><span class=\"w\"> <\/span><span class=\"n\">words<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"s2\">&quot;javascript&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;code&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;highlighting&quot;<\/span><span class=\"p\">];<\/span>\n\n<span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"k\">const<\/span><span class=\"w\"> <\/span><span class=\"n\">word<\/span><span class=\"w\"> <\/span><span class=\"n\">of<\/span><span class=\"w\"> <\/span><span class=\"n\">words<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">console<\/span><span class=\"o\">.<\/span><span class=\"n\">log<\/span><span class=\"p\">(<\/span><span class=\"n\">word<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"err\">```<\/span>\n\n<span class=\"c1\"># This is another heading<\/span>\n<span class=\"n\">Another<\/span><span class=\"w\"> <\/span><span class=\"n\">paragraph<\/span><span class=\"w\"> <\/span><span class=\"n\">with<\/span><span class=\"w\"> <\/span><span class=\"n\">a<\/span><span class=\"w\"> <\/span><span class=\"c1\"># in the middle.<\/span>\n<\/code><\/pre><\/div>\n\n<p><strong>Store these sample file contents in <code>test.mds<\/code> for later use<\/strong>!<\/p>\n<p>I call this subset <em>Markdown Simple<\/em> and choose to write it in files with the\n<code>.mds<\/code> file extension. At the end of this article, we'll have fully functioning\nsyntax highlighting for <code>.mds<\/code> files, including properly highlighted JavaScript\ncode in the multiline code blocks!<\/p>\n<h1 id=\"getting-started-with-creating-tree-sitter-parsers\">Getting started with creating Tree-sitter parsers<\/h1>\n<p>Tree-sitter's docs have a good <a href=\"https:\/\/tree-sitter.github.io\/tree-sitter\/creating-parsers#project-setup\">Project\nsetup<\/a>\nsection, but I found that it lacks a few key ingredients for our purposes. I\nwill offer an augmented version here.<\/p>\n<p>As a pre-requisite, you must have decently up-to-date versions <code>node<\/code> and <code>npm<\/code>\ninstalled. With that, we can get started creating a project directory.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>mkdir<span class=\"w\"> <\/span>tree-sitter-mds\n$<span class=\"w\"> <\/span><span class=\"nb\">cd<\/span><span class=\"w\"> <\/span>tree-sitter-mds\n$<span class=\"w\"> <\/span>npm<span class=\"w\"> <\/span>init\n<\/code><\/pre><\/div>\n\n<p>The <code>npm init<\/code> command will prompt you for a bunch of stuff. If you don't know\nwhat to choose, just go with the defaults, it hardly matters for the rest of\nthis article. Now, you need the <code>tree-sitter-cli<\/code> application, which you can\nalso get with <code>npm<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>npm<span class=\"w\"> <\/span>--save-dev<span class=\"w\"> <\/span>tree-sitter-cli\n<\/code><\/pre><\/div>\n\n<p>Then setup a configuration file for <code>tree-sitter-cli<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>npx<span class=\"w\"> <\/span>tree-sitter<span class=\"w\"> <\/span>init-config\n<\/code><\/pre><\/div>\n\n<p>Note where the configuration file is written to. You may need to edit it later\nfor your project to be located by Tree-sitter.<\/p>\n<h2 id=\"babys-first-grammar-rule\">Baby's first grammar rule<\/h2>\n<p>As previously mentioned, a parser generator reads a grammar that defines some\nlanguage and spits out a parser for it. In Tree-sitter, we define grammar rules\nin JavaScript, in a file called <code>grammar.js<\/code> in the root of your project. It\nshould have the following structure.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">module<\/span><span class=\"p\">.<\/span><span class=\"nx\">exports<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nx\">grammar<\/span><span class=\"p\">({<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">name<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"s1\">&#39;markdownsimple&#39;<\/span><span class=\"p\">,<\/span>\n\n<span class=\"w\">  <\/span><span class=\"nx\">rules<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">      <\/span><span class=\"c1\">\/\/ grammar rules go in here<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">});<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you now try to generate a parser you should get an error about there not being any rules.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>npx<span class=\"w\"> <\/span>tree-sitter<span class=\"w\"> <\/span>generate\n<span class=\"o\">[<\/span>stdin<span class=\"o\">]<\/span>:409\n<span class=\"w\">    <\/span>throw<span class=\"w\"> <\/span>new<span class=\"w\"> <\/span>Error<span class=\"o\">(<\/span><span class=\"s2\">&quot;Grammar must have at least one rule.&quot;<\/span><span class=\"o\">)<\/span><span class=\"p\">;<\/span>\n<\/code><\/pre><\/div>\n\n<p>Let's define a very simple grammar just to be able to parse the file.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">rules<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">source_file<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">text<\/span><span class=\"p\">,<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nx\">text<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">_<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"p\">(.<\/span><span class=\"o\">|<\/span><span class=\"err\">\\<\/span><span class=\"nx\">n<\/span><span class=\"p\">)<\/span><span class=\"o\">+<\/span><span class=\"err\">\/,<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Put the above rules into your <code>grammar.js<\/code> file and then generate and run the\nparser.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>npx<span class=\"w\"> <\/span>tree-sitter<span class=\"w\"> <\/span>generate\n$<span class=\"w\"> <\/span>npx<span class=\"w\"> <\/span>tree-sitter<span class=\"w\"> <\/span>parse<span class=\"w\"> <\/span>test.mds\n<\/code><\/pre><\/div>\n\n<p>This should produce a simple syntax tree.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">(<\/span><span class=\"nf\">source_file<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">13,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"nf\">text<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">13,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]))<\/span>\n<\/code><\/pre><\/div>\n\n<p>Let's dissect the grammar in detail so we can improve the syntax tree\ngranularity. The root node is the <code>source_file<\/code>. Every syntax tree is rooted in\nthis node, and there is only one of them for each parsed file. The rule\ndefinition may look a bit strange at first sight.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">source_file<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">text<\/span>\n<\/code><\/pre><\/div>\n\n<p>Any non-trivial grammar is built by composing rules. Any rule that references\nanother rule is a so-called\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Terminal_and_nonterminal_symbols\"><em>non-terminal<\/em><\/a>.\nThe above rule says that the <code>source_file<\/code> consists of precisely one <code>text<\/code>\nnode. So <code>source_file<\/code> is a non-terminal that references <code>text<\/code>.<\/p>\n<p>We then define the <code>text<\/code> rule using regex.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">_<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"p\">(.<\/span><span class=\"o\">+|<\/span><span class=\"err\">\\<\/span><span class=\"nx\">n<\/span><span class=\"p\">)<\/span><span class=\"o\">\/<\/span><span class=\"p\">,<\/span>\n<\/code><\/pre><\/div>\n\n<p>This regex just captures any character (<code>.<\/code>) or line feeds (<code>\\n<\/code>). As the rule\ndoes not reference any other rules, it is a so-called\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Terminal_and_nonterminal_symbols\"><em>terminal<\/em><\/a>.<\/p>\n<blockquote>\n<p>Note: Tree-sitter supports <a href=\"https:\/\/en.wikipedia.org\/wiki\/LR_parser\"><code>LR(1)<\/code>\ngrammars<\/a>, which <a href=\"https:\/\/tree-sitter.github.io\/tree-sitter\/creating-parsers#the-grammar-dsl\">limits the kinds of\nregex\nexpressions<\/a>\nthat can be used. The finer details of this is beyond the scope of this\narticle.<\/p>\n<\/blockquote>\n<p>In summary, our grammar currently defines a <code>source_file<\/code> as a single <code>text<\/code>\nnode. Of course, we could immediately define <code>source_file<\/code> as the regex that\ncurrently resides in <code>text<\/code> at this point; I just wanted to illustrate the\nconcept of terminal and non-terminal rules as it will become important in the\nnext part.<\/p>\n<h2 id=\"let-there-be-color\">Let there be color<\/h2>\n<p>The goal of this article is to achieve nice syntax highlighting, so let's get\nstarted immediately. We can highlight a file using the <code>highlight<\/code> command,\nbut it won't work out of the box.<\/p>\n<p>If you run the below command, you should get an error message.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>npx<span class=\"w\"> <\/span>tree-sitter<span class=\"w\"> <\/span>highlight<span class=\"w\"> <\/span>test.mds\nNo<span class=\"w\"> <\/span>language<span class=\"w\"> <\/span>found<span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span>path<span class=\"w\"> <\/span><span class=\"sb\">`<\/span>test.mds<span class=\"sb\">`<\/span>\n\nIf<span class=\"w\"> <\/span>a<span class=\"w\"> <\/span>language<span class=\"w\"> <\/span>should<span class=\"w\"> <\/span>be<span class=\"w\"> <\/span>associated<span class=\"w\"> <\/span>with<span class=\"w\"> <\/span>this<span class=\"w\"> <\/span>file<span class=\"w\"> <\/span>extension,<span class=\"w\"> <\/span>please<span class=\"w\"> <\/span>ensure<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>path<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span><span class=\"sb\">`<\/span>test.mds<span class=\"sb\">`<\/span><span class=\"w\"> <\/span>is<span class=\"w\"> <\/span>inside<span class=\"w\"> <\/span>one<span class=\"w\"> <\/span>of<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>following<span class=\"w\"> <\/span>directories<span class=\"w\"> <\/span>as<span class=\"w\"> <\/span>specified<span class=\"w\"> <\/span>by<span class=\"w\"> <\/span>your<span class=\"w\"> <\/span><span class=\"s1\">&#39;config.json&#39;<\/span>:\n\n<span class=\"w\">  <\/span><span class=\"m\">1<\/span>.<span class=\"w\"> <\/span>\/home\/slarse\/github<span class=\"w\">  <\/span>\n<span class=\"w\">  <\/span><span class=\"m\">2<\/span>.<span class=\"w\"> <\/span>\/home\/slarse\/src<span class=\"w\">  <\/span>\n<span class=\"w\">  <\/span><span class=\"m\">3<\/span>.<span class=\"w\"> <\/span>\/home\/slarse\/source<span class=\"w\">  <\/span>\n<span class=\"w\">  <\/span><span class=\"m\">4<\/span>.<span class=\"w\"> <\/span>\/home\/slarse\/projects<span class=\"w\">  <\/span>\n<span class=\"w\">  <\/span><span class=\"m\">5<\/span>.<span class=\"w\"> <\/span>\/home\/slarse\/dev<span class=\"w\">  <\/span>\n<span class=\"w\">  <\/span><span class=\"m\">6<\/span>.<span class=\"w\"> <\/span>\/home\/slarse\/git\n\nIf<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>directory<span class=\"w\"> <\/span>that<span class=\"w\"> <\/span>contains<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>relevant<span class=\"w\"> <\/span>grammar<span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"sb\">`<\/span>test.mds<span class=\"sb\">`<\/span><span class=\"w\"> <\/span>is<span class=\"w\"> <\/span>not<span class=\"w\"> <\/span>listed<span class=\"w\"> <\/span>above,<span class=\"w\"> <\/span>please<span class=\"w\"> <\/span>add<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>directory<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>list<span class=\"w\"> <\/span>of<span class=\"w\"> <\/span>directories<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>your<span class=\"w\"> <\/span>config<span class=\"w\"> <\/span>file,<span class=\"w\"> <\/span>located<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>\/home\/slarse\/.config\/tree-sitter\/config.json\n<\/code><\/pre><\/div>\n\n<p>To resolve this we need to add some information to <code>package.json<\/code>. Put the\nfollowing in there.<\/p>\n<blockquote>\n<p>Tip: It's easy to break the <code>package.json<\/code> file with a misplaced comma. To\nensure that you don't break the syntax of <code>package.json<\/code>, run <code>npm i<\/code> until it\ndoesn't complain anymore.<\/p>\n<\/blockquote>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">  <\/span><span class=\"nt\">&quot;tree-sitter&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&quot;scope&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;source.markdownsimple&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&quot;file-types&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span>\n<span class=\"w\">        <\/span><span class=\"s2\">&quot;mds&quot;<\/span>\n<span class=\"w\">      <\/span><span class=\"p\">],<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&quot;highlights&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span>\n<span class=\"w\">        <\/span><span class=\"s2\">&quot;queries\/highlights.scm&quot;<\/span>\n<span class=\"w\">      <\/span><span class=\"p\">]<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">],<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now run the <code>highlight<\/code> command again. If you get the <em>same<\/em> error as before,\nyou need to add the directory that contains you project's directory to\nTree-sitter's <code>config.json<\/code> file. For example, my project is located in\n<code>\/home\/slarse\/projects\/tree-sitter\/tree-sitter-mds<\/code>, so I add the path\n<code>\/home\/slarse\/projects\/tree-sitter<\/code> to the list of paths at the top of\n<code>\/home\/slarse\/.config\/tree-sitter\/config.json<\/code>.<\/p>\n<p>With that fixed, you should get a new error.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>npx<span class=\"w\"> <\/span>tree-sitter<span class=\"w\"> <\/span>highlight<span class=\"w\"> <\/span>test.mds\nFailed<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span><span class=\"nb\">read<\/span><span class=\"w\"> <\/span>query<span class=\"w\"> <\/span>file<span class=\"w\"> <\/span><span class=\"s2\">&quot;queries\/highlights.scm&quot;<\/span>\n\nCaused<span class=\"w\"> <\/span>by:\n<span class=\"w\">    <\/span>No<span class=\"w\"> <\/span>such<span class=\"w\"> <\/span>file<span class=\"w\"> <\/span>or<span class=\"w\"> <\/span>directory<span class=\"w\"> <\/span><span class=\"o\">(<\/span>os<span class=\"w\"> <\/span>error<span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"o\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>This means your project was correctly located. We now need to define <em>queries<\/em>\nfor our highlight. Queries allow us to select nodes in the syntax tree and\nassign pre-defined semantic meaning to them. Put the following content in the\nfile <code>queries\/highlights.scm<\/code> in your project directory.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">(<\/span><span class=\"nf\">text<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nv\">@string<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p>I won't go into detail on queries in this article. You can find all captures\n(e.g. <code>@string<\/code>) available <a href=\"https:\/\/github.com\/nvim-treesitter\/nvim-treesitter\/blob\/master\/CONTRIBUTING.md#highlights\">over\nhere<\/a>,\nand you can read more about queries as a whole <a href=\"https:\/\/tree-sitter.github.io\/tree-sitter\/using-parsers#pattern-matching-with-queries\">over\nhere<\/a>.<\/p>\n<\/blockquote>\n<p>This says that any <code>text<\/code> node should be considered a <code>string<\/code>. Running the\nhighlight command again, you ought to get some colored output.<\/p>\n<p><img alt=\"Simple syntax higlighting\" src=\"https:\/\/slar.se\/photos\/tree_sitter_highlighting\/first_highlighta.jpg\"><\/p>\n<p>Not all that impressive; as all nodes with any content are <code>text<\/code> nodes\neverything is just highlighted as a string. In my Tree-sitter configuration\nthe <code>string<\/code> color happens happens to be a shade of green, but it may be\ndifferent for you. For more granular highlighting, we need a more granular\nsyntax tree to perform queries against.<\/p>\n<h1 id=\"refining-the-grammar\">Refining the grammar<\/h1>\n<p>The basic pieces of the puzzle are now in place. We have a rudimentary syntax\ntree allowing for an equally rudimentary syntax highlighting. It's now time to\nstart refining the grammar to capture different components. With some crude\nannotations in <code>()<\/code>, we want a structure like this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">(<\/span><span class=\"n\">section<\/span><span class=\"p\">)<\/span>\n<span class=\"c1\"># This is a heading (heading)<\/span>\n<span class=\"n\">This<\/span><span class=\"w\"> <\/span><span class=\"n\">little<\/span><span class=\"w\"> <\/span><span class=\"n\">paragraph<\/span><span class=\"w\"> <\/span><span class=\"n\">of<\/span><span class=\"w\"> <\/span><span class=\"n\">text<\/span><span class=\"w\"> <\/span><span class=\"n\">with<\/span><span class=\"w\"> <\/span><span class=\"err\">`<\/span><span class=\"n\">inline<\/span><span class=\"w\"> <\/span><span class=\"n\">code<\/span><span class=\"err\">`<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">paragraph<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">text<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">inlineCode<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">codeText<\/span><span class=\"p\">)))<\/span>\n\n<span class=\"err\">```<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">codeBlock<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">codeText<\/span><span class=\"p\">))<\/span>\n<span class=\"k\">const<\/span><span class=\"w\"> <\/span><span class=\"n\">words<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"s2\">&quot;javascript&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;code&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;highlighting&quot;<\/span><span class=\"p\">];<\/span>\n\n<span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"k\">const<\/span><span class=\"w\"> <\/span><span class=\"n\">word<\/span><span class=\"w\"> <\/span><span class=\"n\">of<\/span><span class=\"w\"> <\/span><span class=\"n\">words<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">console<\/span><span class=\"o\">.<\/span><span class=\"n\">log<\/span><span class=\"p\">(<\/span><span class=\"n\">word<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"err\">```<\/span>\n\n<span class=\"c1\"># This is another heading (heading)<\/span>\n<span class=\"n\">And<\/span><span class=\"w\"> <\/span><span class=\"n\">this<\/span><span class=\"w\"> <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">another<\/span><span class=\"w\"> <\/span><span class=\"n\">little<\/span><span class=\"w\"> <\/span><span class=\"n\">paragraph<\/span><span class=\"o\">.<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">paragraph<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">text<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>\n\n<p>Let's start off only with capturing the additional <code>section<\/code> and <code>heading<\/code> nodes\nwith new rules.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">rules<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">source_file<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">repeat<\/span><span class=\"p\">(<\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">section<\/span><span class=\"p\">),<\/span>\n\n<span class=\"w\">  <\/span><span class=\"nx\">section<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">seq<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">heading<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">repeat<\/span><span class=\"p\">(<\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">text<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">),<\/span>\n\n<span class=\"w\">  <\/span><span class=\"nx\">heading<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">_<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"err\">#<\/span><span class=\"p\">.<\/span><span class=\"o\">+<\/span><span class=\"err\">\/,<\/span>\n\n<span class=\"w\">  <\/span><span class=\"nx\">text<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">_<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"p\">(.<\/span><span class=\"o\">|<\/span><span class=\"err\">\\<\/span><span class=\"nx\">n<\/span><span class=\"p\">)<\/span><span class=\"o\">+<\/span><span class=\"err\">\/,<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Our non-terminals <code>source_file<\/code> and <code>section<\/code> bring in ways of composing rules\nwith the <code>repeat()<\/code> and <code>seq()<\/code> composers. <code>repeat(rule)<\/code> means \"repeat rule\nzero or more times, while <code>seq(rules...)<\/code> means \"match these rules in this\norder\". So a <code>source_file<\/code> node is zero or more <code>section<\/code> nodes, and a <code>section<\/code>\nnode is a <code>heading<\/code> followed by zero or more <code>text<\/code> nodes.<\/p>\n<p>Generating and running the parser again, this lands us with a slightly more\ngranular syntax tree where we separately capture the section's heading.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">(<\/span><span class=\"nf\">source_file<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">13,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"nf\">section<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">13,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"nf\">heading<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">19<\/span><span class=\"p\">])<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"nf\">text<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">19<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">13,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">])))<\/span>\n<\/code><\/pre><\/div>\n\n<p>Clearly there's a bug here: we only have one section, yet our source file\ncontains two. The reason for this is that <code>text<\/code> is too liberal, it captures <code>#<\/code>\ncharacters anywhere on the line. We must adjust the regex to disallow <code>#<\/code>\ndirectly after line feeds.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">text<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">_<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"p\">([<\/span><span class=\"o\">^<\/span><span class=\"err\">#<\/span><span class=\"p\">]<\/span><span class=\"o\">|<\/span><span class=\"p\">[<\/span><span class=\"o\">^<\/span><span class=\"err\">\\<\/span><span class=\"nx\">n<\/span><span class=\"p\">]<\/span><span class=\"err\">#<\/span><span class=\"p\">)<\/span><span class=\"o\">+<\/span><span class=\"err\">\/,<\/span>\n<\/code><\/pre><\/div>\n\n<p>Here we say that <code>text<\/code> is either not a <code>#<\/code>, or it's a non-linefeed character\nfollowed by <code>#<\/code>. Generating and parsing again we should now have our basic\nsection structure mapped out.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">(<\/span><span class=\"nf\">source_file<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">13,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"nf\">section<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">11,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"nf\">heading<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">19<\/span><span class=\"p\">])<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"nf\">text<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">19<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">11,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]))<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"nf\">section<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">11,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">13,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"nf\">heading<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">11,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">11,<\/span><span class=\"w\"> <\/span><span class=\"mi\">25<\/span><span class=\"p\">])<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"nf\">text<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">11,<\/span><span class=\"w\"> <\/span><span class=\"mi\">25<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">13,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">])))<\/span>\n<\/code><\/pre><\/div>\n\n<p>Great! We can now also adjust the query in <code>queries\/highlights.scm<\/code> to only\nhighlight headings.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">(<\/span><span class=\"nf\">heading<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nv\">@string<\/span>\n<\/code><\/pre><\/div>\n\n<p>This should land you with the following highlighting.<\/p>\n<p><img alt=\"Syntax highlighting only on headings\" src=\"https:\/\/slar.se\/photos\/tree_sitter_highlighting\/second_highlighta.jpg\"><\/p>\n<p>Nice!<\/p>\n<h1 id=\"capturing-inline-code-and-code-blocks\">Capturing inline code and code blocks<\/h1>\n<p>The only thing left for us to capture is inline code and code blocks. This is\nhowever where it starts to get a little bit complicated, so let's take each of\nthese in turn.<\/p>\n<h2 id=\"capturing-code-blocks\">Capturing code blocks<\/h2>\n<p>Code blocks are relatively simple to capture in isolation. A rule for code\nblocks could look as follows.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">codeBlock<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">seq<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">  <\/span><span class=\"s1\">&#39;```&#39;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">codeText<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">  <\/span><span class=\"s1\">&#39;```&#39;<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">),<\/span>\n\n<span class=\"nx\">codeText<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">_<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"p\">[<\/span><span class=\"o\">^<\/span><span class=\"sb\">`]*\/,<\/span>\n<\/code><\/pre><\/div>\n\n<p>We could inline <code>codeText<\/code> into the <code>codeBlock<\/code>, but making it a separate rule\nwill make it easier for us to highlight the content of the code block without\naffecting the backticks around it. Note that <code>codeText<\/code> is not quite the same as\n<code>text<\/code>; the former allows any <em>zero or more<\/em> characters except for backticks.\nThis will of course make it impossible to use backticks inside of a <code>codeBlock<\/code>,\nwhich is a simplification we're going with here. Extending the rule to allow\nfor backticks within a <code>codeBlock<\/code> node is left as an exercise to the reader.<\/p>\n<p>We can now extend our <code>section<\/code> rule to contain <code>codeBlock<\/code>s.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">section<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">seq<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">heading<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">repeat<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">choice<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">      <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">text<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">codeBlock<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">)<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">),<\/span>\n<span class=\"p\">),<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you put this in and run it, you may be a bit surprised to see that the output\ndoesn't change from before. The syntax tree still consists of two <code>section<\/code>s\ncontaining one <code>heading<\/code> and <code>text<\/code> each. This is because <code>text<\/code> is consuming\nthe backticks that should delimit a <code>codeBlock<\/code>. We'll address this at the same\ntime as we define our paragraphs in the next part.<\/p>\n<h2 id=\"paragraphs-with-text-and-inline-code\">Paragraphs with text and inline code<\/h2>\n<p>We want to define grammar rules such that the parser can recognize <em>paragraphs<\/em>\nthat are composed of one or more <code>text<\/code> and\/or <code>inlineCode<\/code> nodes. The\n<code>inlineCode<\/code> rule is quite simple: a backtick, followed by zero or more\ncharacters that are anything but a backtick (i.e. <code>codeText<\/code>), followed by a\nbacktick.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">inlineCode<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">seq<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">  <\/span><span class=\"s1\">&#39;`&#39;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">codeText<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">  <\/span><span class=\"s1\">&#39;`&#39;<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">),<\/span>\n<\/code><\/pre><\/div>\n\n<p>We also need to alter the <code>text<\/code> terminal to not allow backticks, because\notherwise it will just consume them like it did the <code>#<\/code> before. This will also\nallow our <code>codeBlock<\/code> rule to actually consume something.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">text<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">_<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"p\">([<\/span><span class=\"o\">^<\/span><span class=\"err\">#<\/span><span class=\"sb\">`]|[^\\n]#)+\/,<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now we can define the <code>paragraph<\/code> non-terminal which, again, should be one or\nmore <code>inlineCode<\/code> or <code>text<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">paragraph<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">repeat1<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">choice<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">inlineCode<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">text<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">),<\/span>\n<span class=\"p\">),<\/span>\n<\/code><\/pre><\/div>\n\n<p>And then we update the <code>section<\/code> to repeat <code>paragraph<\/code> instead of <code>text<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">section<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">seq<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">heading<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">repeat<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">choice<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">      <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">paragraph<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">codeBlock<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">)<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">),<\/span>\n<span class=\"p\">),<\/span>\n<\/code><\/pre><\/div>\n\n<p>We end up with the following rule set.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">rules<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">source_file<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">repeat<\/span><span class=\"p\">(<\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">section<\/span><span class=\"p\">),<\/span>\n\n<span class=\"w\">  <\/span><span class=\"nx\">section<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">seq<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">heading<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">repeat<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">      <\/span><span class=\"nx\">choice<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">paragraph<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">codeBlock<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">),<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">),<\/span>\n\n<span class=\"w\">  <\/span><span class=\"nx\">paragraph<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">repeat1<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">choice<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">      <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">inlineCode<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">text<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">),<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">),<\/span>\n\n<span class=\"w\">  <\/span><span class=\"nx\">inlineCode<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">seq<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">    <\/span><span class=\"s1\">&#39;`&#39;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">codeText<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"s1\">&#39;`&#39;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">),<\/span>\n\n<span class=\"w\">  <\/span><span class=\"nx\">codeBlock<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">seq<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">    <\/span><span class=\"s1\">&#39;```&#39;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">codeText<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"s1\">&#39;```&#39;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">),<\/span>\n\n<span class=\"w\">  <\/span><span class=\"nx\">codeText<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">_<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"p\">[<\/span><span class=\"o\">^<\/span><span class=\"sb\">`]*\/,<\/span>\n\n<span class=\"sb\">  heading: _ =&gt; \/#.+\/,<\/span>\n\n<span class=\"sb\">  text: _ =&gt; \/([^#`<\/span><span class=\"p\">]<\/span><span class=\"o\">|<\/span><span class=\"p\">[<\/span><span class=\"o\">^<\/span><span class=\"err\">\\<\/span><span class=\"nx\">n<\/span><span class=\"p\">]<\/span><span class=\"err\">#<\/span><span class=\"p\">)<\/span><span class=\"o\">+<\/span><span class=\"err\">\/,<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you try this out, you'll find that it doesn't work, Tree-sitter won't even\ngenerate a parser for you. Instead, it complains about a conflict. Oh, dear.<\/p>\n<h2 id=\"resolving-a-conflict-in-the-grammar\">Resolving a conflict in the grammar<\/h2>\n<p>A conflict in the grammar occurs when there are multiple ways for Tree-sitter\nto interpret the rules you've provided it with. In the case of our <code>paragraph<\/code>\nrule, Tree-sitter has the following to say.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>npx<span class=\"w\"> <\/span>tree-sitter<span class=\"w\"> <\/span>generate\nUnresolved<span class=\"w\"> <\/span>conflict<span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span>symbol<span class=\"w\"> <\/span>sequence:\n\n<span class=\"w\">  <\/span>heading<span class=\"w\">  <\/span>paragraph_repeat1<span class=\"w\">  <\/span>\u2022<span class=\"w\">  <\/span><span class=\"s1\">&#39;`&#39;<\/span><span class=\"w\">  <\/span>\u2026\n\nPossible<span class=\"w\"> <\/span>interpretations:\n\n<span class=\"w\">  <\/span><span class=\"m\">1<\/span>:<span class=\"w\">  <\/span>heading<span class=\"w\">  <\/span><span class=\"o\">(<\/span>paragraph<span class=\"w\">  <\/span>paragraph_repeat1<span class=\"o\">)<\/span><span class=\"w\">  <\/span>\u2022<span class=\"w\">  <\/span><span class=\"s1\">&#39;`&#39;<\/span><span class=\"w\">  <\/span>\u2026\n<span class=\"w\">  <\/span><span class=\"m\">2<\/span>:<span class=\"w\">  <\/span>heading<span class=\"w\">  <\/span><span class=\"o\">(<\/span>paragraph_repeat1<span class=\"w\">  <\/span>paragraph_repeat1<span class=\"w\">  <\/span>\u2022<span class=\"w\">  <\/span>paragraph_repeat1<span class=\"o\">)<\/span>\n\nPossible<span class=\"w\"> <\/span>resolutions:\n\n<span class=\"w\">  <\/span><span class=\"m\">1<\/span>:<span class=\"w\">  <\/span>Specify<span class=\"w\"> <\/span>a<span class=\"w\"> <\/span>left<span class=\"w\"> <\/span>or<span class=\"w\"> <\/span>right<span class=\"w\"> <\/span>associativity<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"sb\">`<\/span>paragraph<span class=\"sb\">`<\/span>\n<span class=\"w\">  <\/span><span class=\"m\">2<\/span>:<span class=\"w\">  <\/span>Add<span class=\"w\"> <\/span>a<span class=\"w\"> <\/span>conflict<span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span>these<span class=\"w\"> <\/span>rules:<span class=\"w\"> <\/span><span class=\"sb\">`<\/span>paragraph<span class=\"sb\">`<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is a little bit hard to interpret if you haven't worked a lot with parsers\nbefore. The short of it is that our use of the <code>paragraph<\/code> rule is ambiguous due\nto the <code>paragraph<\/code> being repeated in the <code>section<\/code> rule, and then is itself a\nrepetition. For example, how should the first paragraph of the first section be\nparsed, as shown below, be parsed?<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>This little paragraph of text with `inline code`\n<\/code><\/pre><\/div>\n\n<p>Is it one paragraph containing <code>text<\/code> and <code>inlineCode<\/code>, i.e. <code>(paragraph (text)\n(inlineCode))<\/code>? Or is it perhaps two paragraphs, one with the <code>text<\/code> and one\nwith the <code>inlineCode<\/code>, i.e. <code>(paragraph (text))<\/code> and <code>(paragraph (inlineCode))<\/code>?\nIt's impossible to tell based on the rules we've defined.<\/p>\n<p>To get rid of this ambiguity, we can use\n<a href=\"https:\/\/tree-sitter.github.io\/tree-sitter\/creating-parsers#using-associativity\"><em>associativity<\/em><\/a>.\nAs associativity is a bit of a brain twister the first time around, we won't\nbother trying to fully understand it here. We'll just try both and see what\nhappens. We can make a rule left- or right-associative by wrapping it in\n<code>prec.left()<\/code> or <code>prec.right()<\/code>, respectively. Doing that in turn, we get the\nfollowing two parse results for this part of the tree.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">; left-associative result<\/span>\n<span class=\"p\">(<\/span><span class=\"nf\">paragraph<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nf\">text<\/span><span class=\"p\">))<\/span>\n<span class=\"p\">(<\/span><span class=\"nf\">paragraph<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nf\">inlineCode<\/span><span class=\"p\">))<\/span>\n\n<span class=\"c1\">; right-associative result<\/span>\n<span class=\"p\">(<\/span><span class=\"nf\">paragraph<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nf\">text<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nf\">inlineCode<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>\n\n<p>The right-associative version looks like what we sketched out before embarking\ndown this road, so we'll adjust the rule accordingly.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">paragraph<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">prec<\/span><span class=\"p\">.<\/span><span class=\"nx\">right<\/span><span class=\"p\">(<\/span><span class=\"nx\">repeat1<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">choice<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">inlineCode<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">text<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">),<\/span>\n<span class=\"p\">)),<\/span>\n<\/code><\/pre><\/div>\n\n<p>And with that, we can now create a syntax tree with a sufficient level of\ngranularity to achieve the highlighting we set out to. If you generate the\nparser again and run it, you should see a tree like this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">(<\/span><span class=\"nf\">source_file<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">13,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"nf\">section<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">9,<\/span><span class=\"w\"> <\/span><span class=\"mi\">3<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"nf\">heading<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">19<\/span><span class=\"p\">])<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"nf\">paragraph<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">19<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">1,<\/span><span class=\"w\"> <\/span><span class=\"mi\">48<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">      <\/span><span class=\"p\">(<\/span><span class=\"nf\">text<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">0,<\/span><span class=\"w\"> <\/span><span class=\"mi\">19<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">1,<\/span><span class=\"w\"> <\/span><span class=\"mi\">35<\/span><span class=\"p\">])<\/span>\n<span class=\"w\">      <\/span><span class=\"p\">(<\/span><span class=\"nf\">inlineCode<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">1,<\/span><span class=\"w\"> <\/span><span class=\"mi\">35<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">1,<\/span><span class=\"w\"> <\/span><span class=\"mi\">48<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">(<\/span><span class=\"nf\">codeText<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">1,<\/span><span class=\"w\"> <\/span><span class=\"mi\">36<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">1,<\/span><span class=\"w\"> <\/span><span class=\"mi\">47<\/span><span class=\"p\">])))<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"nf\">codeBlock<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">1,<\/span><span class=\"w\"> <\/span><span class=\"mi\">48<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">9,<\/span><span class=\"w\"> <\/span><span class=\"mi\">3<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">      <\/span><span class=\"p\">(<\/span><span class=\"nf\">codeText<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">3,<\/span><span class=\"w\"> <\/span><span class=\"mi\">3<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">9,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">])))<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"nf\">section<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">9,<\/span><span class=\"w\"> <\/span><span class=\"mi\">3<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">13,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"nf\">heading<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">9,<\/span><span class=\"w\"> <\/span><span class=\"mi\">3<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">11,<\/span><span class=\"w\"> <\/span><span class=\"mi\">25<\/span><span class=\"p\">])<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"nf\">paragraph<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">11,<\/span><span class=\"w\"> <\/span><span class=\"mi\">25<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">13,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n<span class=\"w\">      <\/span><span class=\"p\">(<\/span><span class=\"nf\">text<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">11,<\/span><span class=\"w\"> <\/span><span class=\"mi\">25<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"nb\">-<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"nv\">13,<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">]))))<\/span>\n<\/code><\/pre><\/div>\n\n<p>We still only have a single highlight query, though, so next up is improving\nthat.<\/p>\n<h2 id=\"improving-the-highlight-queries\">Improving the highlight queries<\/h2>\n<p>We now have a significantly more granular syntax tree to work with. As a first\nattempt, let's color inline code including backticks with one color, code block\nbackticks with one color and finally the code blocks themselves with another\ncolor.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">(<\/span><span class=\"nf\">heading<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nv\">@string<\/span>\n<span class=\"p\">(<\/span><span class=\"nf\">inlineCode<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nv\">@property<\/span>\n<span class=\"p\">(<\/span><span class=\"nf\">codeBlock<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nv\">@punctuation<\/span><span class=\"o\">.<\/span><span class=\"nv\">delimiter<\/span>\n<span class=\"p\">(<\/span><span class=\"nf\">codeBlock<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nf\">codeText<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nv\">@module<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Here we have our first non-trivial use of queries, as we have two queries\nreferencing the same type of node: <code>codeBlock<\/code>. The first query marks the\nentire <code>codeBlock<\/code> with <code>@punctuation.delimiter<\/code>, which is dark grey in my color\nscheme. Then we mark <code>codeText<\/code> <em>inside<\/em> the <code>codeBlock<\/code> as a <code>@module<\/code>, which\nis yellow in my color scheme. The latter query is more specific than the former,\nand so takes precedence. The result is a significant improvement over our\nstarting point.<\/p>\n<p><img alt=\"Syntax highlighting on headings, inline code and code blocks\" src=\"https:\/\/slar.se\/photos\/tree_sitter_highlighting\/third_highlighta.jpg\"><\/p>\n<p>But it's still not <em>great<\/em>. Having yellow JavaScript code is a marginal\nimprovement over just white code. This is where Tree-sitter's killer syntax\nhighlighting feature comes into play:\n<a href=\"https:\/\/tree-sitter.github.io\/tree-sitter\/syntax-highlighting#language-injection\">injections<\/a><\/p>\n<h2 id=\"injecting-a-javascript-parser\">Injecting a JavaScript parser<\/h2>\n<p>Injections are super cool. They allow us to succinctly state that certain nodes\nshould be parsed with some other parser than the one we're currently using. Just\nlike with highlights, injections are specified with queries. What makes this\neven cooler is that the author of some given parser doesn't need to have thought\nabout this; you can tack it on afterwards due to queries being completely\nseparate from the parser itself.<\/p>\n<p>First of all, we need to extend our <code>package.json<\/code> with an <code>injections<\/code> key.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">  <\/span><span class=\"nt\">&quot;tree-sitter&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&quot;scope&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;source.markdownsimple&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&quot;file-types&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span>\n<span class=\"w\">        <\/span><span class=\"s2\">&quot;mds&quot;<\/span>\n<span class=\"w\">      <\/span><span class=\"p\">],<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&quot;highlights&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span>\n<span class=\"w\">        <\/span><span class=\"s2\">&quot;queries\/highlights.scm&quot;<\/span>\n<span class=\"w\">      <\/span><span class=\"p\">],<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">&quot;injections&quot;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span>\n<span class=\"w\">        <\/span><span class=\"s2\">&quot;queries\/injections.scm&quot;<\/span>\n<span class=\"w\">      <\/span><span class=\"p\">]<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">],<\/span>\n<\/code><\/pre><\/div>\n\n<p>Then we add a file at <code>queries\/injections.scm<\/code> with the following query.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">(((<\/span><span class=\"nf\">codeBlock<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nf\">codeText<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nv\">@injection<\/span><span class=\"o\">.<\/span><span class=\"nv\">content<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">(<\/span><span class=\"o\">#<\/span><span class=\"k\">set!<\/span><span class=\"w\"> <\/span><span class=\"nv\">injection<\/span><span class=\"o\">.<\/span><span class=\"nv\">language<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;javascript&quot;<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>\n\n<p>Unfortunately, the highlight queries will interfere a bit with this injection,\nso we also need to reduce our <code>queries\/highlights.scm<\/code> file to the following.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">(<\/span><span class=\"nf\">heading<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nv\">@string<\/span>\n<span class=\"p\">(<\/span><span class=\"nf\">inlineCode<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nv\">@property<\/span>\n<\/code><\/pre><\/div>\n\n<p>But with that change, highlighting is now a lot more interesting. Although,\nadmittedly, the color scheme could definitely use some work.<\/p>\n<p><img alt=\"Syntax highlighting on headings, inline code and JavaScript injection in code blocks\" src=\"https:\/\/slar.se\/photos\/tree_sitter_highlighting\/final_highlighta.jpg\"><\/p>\n<p>With that, we've achieved the highlighting goals we set out to at the beginning\nof the article.<\/p>\n<h1 id=\"summary\">Summary<\/h1>\n<p>In this article, we explored the basics of Tree-sitter and how to apply it to\nprovide syntax highlighting for a simple markup language. The full source code\nfor the project can be found\n<a href=\"https:\/\/github.com\/slarse\/tree-sitter-mds\">in the companion repository<\/a>.\nThere are still numerous shortcomings with this implementation, such as the fact\nthat <code>codeBlock<\/code>s cannot contain backticks, or that empty lines between\nparagraphs don't actually produce multiple paragraphs in the syntax tree. But\nthe point of this article wasn't to produce a perfect Markdown Simple parser,\nbut rather illustrate some fundamental concepts of creating parsers with\nTree-sitter. And that, I think, has been achieved.<\/p>\n<p>In the next part of this article series, we'll explore working with Tree-sitter\nin NeoVim!<\/p>\n<p>The final versions of the grammar and queries are inlined below for your\nconvenience.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ grammar.js<\/span>\n<span class=\"nx\">module<\/span><span class=\"p\">.<\/span><span class=\"nx\">exports<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nx\">grammar<\/span><span class=\"p\">({<\/span>\n<span class=\"w\">  <\/span><span class=\"nx\">name<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"s1\">&#39;markdownsimple&#39;<\/span><span class=\"p\">,<\/span>\n\n<span class=\"w\">  <\/span><span class=\"nx\">rules<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">source_file<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">repeat<\/span><span class=\"p\">(<\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">section<\/span><span class=\"p\">),<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nx\">section<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">seq<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">      <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">heading<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"nx\">repeat<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">choice<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">          <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">paragraph<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">          <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">codeBlock<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">)<\/span>\n<span class=\"w\">      <\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">),<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nx\">paragraph<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">prec<\/span><span class=\"p\">.<\/span><span class=\"nx\">right<\/span><span class=\"p\">(<\/span><span class=\"nx\">repeat1<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">      <\/span><span class=\"nx\">choice<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">inlineCode<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">text<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">)),<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nx\">inlineCode<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">seq<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">      <\/span><span class=\"s1\">&#39;`&#39;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">codeText<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"s1\">&#39;`&#39;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">),<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nx\">codeBlock<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">$<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"nx\">seq<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">      <\/span><span class=\"s1\">&#39;```&#39;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">codeText<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">      <\/span><span class=\"s1\">&#39;```&#39;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">),<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nx\">codeText<\/span><span class=\"o\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">_<\/span><span class=\"w\"> <\/span><span class=\"p\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"p\">[<\/span><span class=\"o\">^<\/span><span class=\"sb\">`]*\/,<\/span>\n\n<span class=\"sb\">    heading: _ =&gt; \/#.+\/,<\/span>\n\n<span class=\"sb\">    text: _ =&gt; \/([^#`<\/span><span class=\"p\">]<\/span><span class=\"o\">|<\/span><span class=\"p\">[<\/span><span class=\"o\">^<\/span><span class=\"err\">\\<\/span><span class=\"nx\">n<\/span><span class=\"p\">]<\/span><span class=\"err\">#<\/span><span class=\"p\">)<\/span><span class=\"o\">+<\/span><span class=\"err\">\/,<\/span>\n<span class=\"w\">  <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">});<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">; queries\/highlights.scm<\/span>\n<span class=\"p\">(<\/span><span class=\"nf\">heading<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nv\">@string<\/span>\n<span class=\"p\">(<\/span><span class=\"nf\">inlineCode<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nv\">@property<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">; queries\/injections.scm<\/span>\n<span class=\"p\">(((<\/span><span class=\"nf\">codeBlock<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nf\">codeText<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nv\">@injection<\/span><span class=\"o\">.<\/span><span class=\"nv\">content<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">(<\/span><span class=\"o\">#<\/span><span class=\"k\">set!<\/span><span class=\"w\"> <\/span><span class=\"nv\">injection<\/span><span class=\"o\">.<\/span><span class=\"nv\">language<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;javascript&quot;<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"tree-sitter"}},{"@attributes":{"term":"parsing"}},{"@attributes":{"term":"syntax"}},{"@attributes":{"term":"neovim"}}]},{"title":"Extending NeoVim for commenting and uncommenting code blocks","link":{"@attributes":{"href":"https:\/\/slar.se\/comment-and-uncomment-code-in-neovim.html","rel":"alternate"}},"published":"2024-02-29T00:00:00+01:00","updated":"2024-02-29T00:00:00+01:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2024-02-29:\/comment-and-uncomment-code-in-neovim.html","summary":"<p>I've been using some variation of Vim for going on a decade now, yet I've never\nbothered with an efficient way of commenting out code. It just isn't something\nthat I do very often. But I saw a colleague comment out and uncomment lines of\ncode like a breeze in \u2026<\/p>","content":"<p>I've been using some variation of Vim for going on a decade now, yet I've never\nbothered with an efficient way of commenting out code. It just isn't something\nthat I do very often. But I saw a colleague comment out and uncomment lines of\ncode like a breeze in VS Code, so obviously I had to also have that capability.\nAnd then choose to not use it. Let's see how you can get that option, too.<\/p>\n<blockquote>\n<p>This article contains Lua code for configuring NeoVim. To follow along, paste\nthe Lua code presented into any <code>.lua<\/code> file and run <code>:luafile %<\/code> with the\nfile in the current buffer. This makes the commands defined within available\nin your current NeoVim session.<\/p>\n<\/blockquote>\n<h1 id=\"commenting-out-code-the-hard-way\">Commenting out code the hard way<\/h1>\n<p>A simple no-preparation way of commenting out code in any variation of Vim is to\nsimply select a few lines of code in visual mode and then make a substitution.\nLet's say we're writing Python where the inline comment character is <code>#<\/code>, then\ncommenting out a line would look like this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">:<\/span>s<span class=\"sr\">\/^\/<\/span>#\/\n<\/code><\/pre><\/div>\n\n<p>The <code>^<\/code> character is the \"start of line\" character, so here we're simply\nreplacing the start of line with <code>#<\/code>. And don't worry, the start of line isn't\nactually a character; there'll be a new start of line just in front of the <code>#<\/code>\nafter the substitution. Select a range of lines in visual mode and run the same\nsubstitution and you'll comment out the entire range.<\/p>\n<p>If you do this rarely it's fine. But if you do it regularly it becomes rather\ncumbersome. Luckily for us, NeoVim is easy to extend.<\/p>\n<h1 id=\"defining-a-command-to-comment-out-code\">Defining a command to comment out code<\/h1>\n<p>To make the above substitution a bit less of an effort, we can define a command\nfor it. First, we need to define a function that executes the code. A very\nsimple first effort would look like this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kr\">function<\/span> <span class=\"nf\">comment_out<\/span><span class=\"p\">()<\/span>\n    <span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;s:^:#:&quot;<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;noh&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"kr\">end<\/span>\n<\/code><\/pre><\/div>\n\n<p>There are a couple things to note about this function.<\/p>\n<ol>\n<li><code>vim.api.nvim_command<\/code> synchronously executes a command.<\/li>\n<li>We use <code>:<\/code> instead of <code>\/<\/code> as the substitution delimiter in anticipation of\n   the C-style <code>\/\/<\/code> inline comment.<\/li>\n<li>We clear the search highlight with <code>noh<\/code> after doing the substitution.<ul>\n<li>Figuring out what happens if you don't do that is left as an exercise to\n  the reader.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p>So that's our function for performing the substitution, and if we simply place\nour cursor on a line we wish to comment out we can execute it like so.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">:<\/span><span class=\"k\">lua<\/span> comment_out<span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>It should insert a <code>#<\/code> character at the start of the line. But this isn't\nterribly ergonomic, it'd be nicer if we could just call a native NeoVim command.\nFortunately, defining such a command is pretty simple.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_create_user_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;CommentOut&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">comment_out<\/span><span class=\"p\">,<\/span> <span class=\"p\">{})<\/span>\n<\/code><\/pre><\/div>\n\n<p>This exposes the <code>:CommentOut<\/code> command, and we can now invoke our commenting out\nfunction like so.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">:<\/span>CommentOut\n<\/code><\/pre><\/div>\n\n<p>Still, this feels like some amount of effort, so let's add a couple of handy\nkeybindings to do this. I like <code>&lt;leader&gt;co<\/code> which is a mnemonic for <strong>c<\/strong>omment\n<strong>o<\/strong>ut.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">keymap<\/span><span class=\"p\">.<\/span><span class=\"n\">set<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;v&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;&lt;leader&gt;co&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;:CommentOut&lt;CR&gt;&quot;<\/span><span class=\"p\">)<\/span> <span class=\"c1\">-- visual mode keymap<\/span>\n<span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">keymap<\/span><span class=\"p\">.<\/span><span class=\"n\">set<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;n&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;&lt;leader&gt;co&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;:CommentOut&lt;CR&gt;&quot;<\/span><span class=\"p\">)<\/span> <span class=\"c1\">-- normal mode keymap<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now we can simply invoke the commenting out routing with <code>&lt;leader&gt;co<\/code>, or\nwhatever else you've decided to put in there. There are however two big problems\nleft to address:<\/p>\n<ol>\n<li>The <code>:CommentOut<\/code> command doesn't work with a range<ul>\n<li>If you try to select a range of lines and run the function, you will\n  encounter an error saying <code>E481: No range allowed<\/code><\/li>\n<\/ul>\n<\/li>\n<li>The commenting character is hard-coded as <code>#<\/code><ul>\n<li>That approach works great if you only work with a single language, but if\n  you like me work daily with multiple languages that have different line\n  comment styles it's not ideal<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p>Let's address these in turn.<\/p>\n<h2 id=\"adding-support-for-range-selection\">Adding support for range selection<\/h2>\n<p>Being able to run our little <code>:CommentOut<\/code> command only on one line at a time\nis hardly useful, so let's make our command compatible with range selection.\nFirst we need to modify the creation of the command, which by default does\nnot allow ranges.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_create_user_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;CommentOut&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">comment_out<\/span><span class=\"p\">,<\/span> <span class=\"p\">{<\/span> <span class=\"n\">range<\/span> <span class=\"o\">=<\/span> <span class=\"kc\">true<\/span> <span class=\"p\">})<\/span>\n<\/code><\/pre><\/div>\n\n<p>With this modification, you'll be able to execute <code>:CommentOut<\/code> when a range is\nselected, but only the first line of the selection will actually be commented\nout. We need to add a few lines of code to the <code>comment_out()<\/code> function to\nactually act on the entire range. While we're at it, we'll also make the\nfunction <code>local<\/code> as it doesn't need to be accessible outside the module anymore.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">local<\/span> <span class=\"kr\">function<\/span> <span class=\"nf\">comment_out<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">)<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">start<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">math.min<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line1<\/span><span class=\"p\">,<\/span> <span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line2<\/span><span class=\"p\">)<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">math.max<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line1<\/span><span class=\"p\">,<\/span> <span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line2<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">(<\/span><span class=\"n\">start<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;,&quot;<\/span> <span class=\"o\">..<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;s:^:#:&quot;<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;noh&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"kr\">end<\/span>\n<\/code><\/pre><\/div>\n\n<p>Options for NeoVim commands are passed in via the <code>opts<\/code> table, and the line\nnumbers of the selection are stored in <code>line1<\/code> and <code>line2<\/code>. Other available\noptions are <a href=\"https:\/\/neovim.io\/doc\/user\/api.html#nvim_create_user_command()\">detailed in the NeoVim API\ndocs<\/a>.<\/p>\n<p>Note that depending on where you start the selection, either line may be the one\nat the top and bottom, respectively, so we do some rudimentary math to get the\nstart and finish of our substitution in the right order.<\/p>\n<p>Selecting a few lines of code and running <code>:CommentOut<\/code> (or using the\nkeybind for it) now actually comments out those lines! Let's now figure out how\nto select the correct kind of line comment for the given file type.<\/p>\n<h2 id=\"choosing-line-comment-style-by-filetype\">Choosing line comment style by filetype<\/h2>\n<p>While there's probably a super clever way of accomplishing this, I went with\nsomething really rudimentary: a table with line comment styles by filetype. It\nlooks something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">local<\/span> <span class=\"n\">non_c_line_comments_by_filetype<\/span> <span class=\"o\">=<\/span> <span class=\"p\">{<\/span>\n    <span class=\"n\">lua<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;--&quot;<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">python<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;#&quot;<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">sql<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;--&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"kd\">local<\/span> <span class=\"n\">default_line_comment<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;\/\/&quot;<\/span>\n\n<span class=\"kd\">local<\/span> <span class=\"kr\">function<\/span> <span class=\"nf\">comment_out<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">)<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">line_comment<\/span> <span class=\"o\">=<\/span> <span class=\"n\">non_c_line_comments_by_filetype<\/span><span class=\"p\">[<\/span><span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">bo<\/span><span class=\"p\">.<\/span><span class=\"n\">filetype<\/span><span class=\"p\">]<\/span> <span class=\"ow\">or<\/span> <span class=\"n\">default_line_comment<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">start<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">math.min<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line1<\/span><span class=\"p\">,<\/span> <span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line2<\/span><span class=\"p\">)<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">math.max<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line1<\/span><span class=\"p\">,<\/span> <span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line2<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">(<\/span><span class=\"n\">start<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;,&quot;<\/span> <span class=\"o\">..<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;s:^:&quot;<\/span> <span class=\"o\">..<\/span> <span class=\"n\">line_comment<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;:&quot;<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;noh&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"kr\">end<\/span>\n<\/code><\/pre><\/div>\n\n<p>Basically, we default to the <code>\/\/<\/code> line comment style <em>unless<\/em> we find a match in\nthe <code>non_c_line_comments_by_filetype<\/code> table. We use <code>vim.bo.filetype<\/code> to get the\ncurrent buffer's filetype. Then we do some more string concatenation in the\nsubstitution command, and that's pretty much that. If you need other line\ncomment styles, just add them to the table.<\/p>\n<p>If you now run the <code>:CommentOut<\/code> command in a Python file, it'll use <code>#<\/code> as the\ncomment style. But if you do it in a SQL file, it'll use <code>--<\/code>, and in a Go file\nit'll use <code>\/\/<\/code>.<\/p>\n<h1 id=\"uncommenting-code\">Uncommenting code<\/h1>\n<p>We now have a neat way of commenting out code, but what about <em>uncommenting<\/em>\ncode? Let's straight up copy <code>comment_out()<\/code> and just replace the substitution\nexpression with something that removes a line comment start.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">local<\/span> <span class=\"kr\">function<\/span> <span class=\"nf\">uncomment<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">)<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">line_comment<\/span> <span class=\"o\">=<\/span> <span class=\"n\">non_c_line_comments_by_filetype<\/span><span class=\"p\">[<\/span><span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">bo<\/span><span class=\"p\">.<\/span><span class=\"n\">filetype<\/span><span class=\"p\">]<\/span> <span class=\"ow\">or<\/span> <span class=\"s2\">&quot;\/\/&quot;<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">start<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">math.min<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line1<\/span><span class=\"p\">,<\/span> <span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line2<\/span><span class=\"p\">)<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">math.max<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line1<\/span><span class=\"p\">,<\/span> <span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line2<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">(<\/span><span class=\"n\">start<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;,&quot;<\/span> <span class=\"o\">..<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;s:^&quot;<\/span> <span class=\"o\">..<\/span> <span class=\"n\">line_comment<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;::&quot;<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;noh&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"kr\">end<\/span>\n\n<span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_create_user_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;Uncomment&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">uncomment<\/span><span class=\"p\">,<\/span> <span class=\"p\">{<\/span> <span class=\"n\">range<\/span> <span class=\"o\">=<\/span> <span class=\"kc\">true<\/span> <span class=\"p\">})<\/span>\n<span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">keymap<\/span><span class=\"p\">.<\/span><span class=\"n\">set<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;v&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;&lt;leader&gt;uc&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;:Uncomment&lt;CR&gt;&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">keymap<\/span><span class=\"p\">.<\/span><span class=\"n\">set<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;n&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;&lt;leader&gt;uc&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;:Uncomment&lt;CR&gt;&quot;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p>Note: The keybinding is a mnemonic for <strong>u<\/strong>n<strong>c<\/strong>omment.<\/p>\n<\/blockquote>\n<p>This mostly works. If you first run <code>:CommentOut<\/code> and then <code>:Uncomment<\/code>, the\nlatter cancels out the former. But there are two notable shortcomings.<\/p>\n<ol>\n<li>If you run <code>:Uncomment<\/code> on a line that deos not start with a line comment\n   start you encounter an error saying <code>Pattern not found:<\/code><\/li>\n<li>The line must <em>start<\/em> with a line comment start; leading whitespace causes\n   the substitution to fail<\/li>\n<li>If you have a formatter that indents line comments, you'll be in trouble!<\/li>\n<\/ol>\n<p>The first issue is simple to resolve: we wrap the call to <code>vim.api.nvim_comand<\/code>\nin a <em>protected call<\/em> using the <a href=\"https:\/\/www.lua.org\/pil\/8.4.html\">pcall() function<\/a>.\nThis allows us to handle errors, but in fact all we want is to prevent any error\nfrom bubbling up to the surface; we don't really care if the substitution fails\nor not as a failure simply indicates there was no comment to uncomment.<\/p>\n<p>The second issue requires a little bit more thought. We want to be able to\nuncomment lines even if there's leading whitespace to be give the command some\nmore flexibility. With <code>#<\/code> as the line comment, a first attempt could look like\nthis.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">:<\/span>s:^\\s\\{<span class=\"p\">-<\/span>\\}#::\n<\/code><\/pre><\/div>\n\n<p><code>^<\/code> is the line start meta character, <code>\\s<\/code> denotes any whitespace except for\nlinebreaks, and <code>\\{-\\}<\/code> means \"zero or more`. This mostly works, but it removes\nboth the leading whitespace and the comment character, effectively dedenting the\nline. We need to <em>capture<\/em> the whitespace and put it back after removing the\nline comment start.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">:<\/span>s:^\\<span class=\"p\">(<\/span>\\s\\{<span class=\"p\">-<\/span>\\}\\<span class=\"p\">)<\/span>#:\\<span class=\"m\">1<\/span>:\n<\/code><\/pre><\/div>\n\n<p>The escapes makes the pattern a bit difficult to read, but all we've done here\nis to wrap the \"zero or more whitespace\" in a capture group (denoted by\nparentheses), and then we reference that capture group in the replacement part\nof the expression with <code>\\1<\/code>.<\/p>\n<p>Putting all of this together, we end up with the following <code>uncomment()<\/code>\nfunction.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">local<\/span> <span class=\"kr\">function<\/span> <span class=\"nf\">uncomment<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">)<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">line_comment<\/span> <span class=\"o\">=<\/span> <span class=\"n\">non_c_line_comments_by_filetype<\/span><span class=\"p\">[<\/span><span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">bo<\/span><span class=\"p\">.<\/span><span class=\"n\">filetype<\/span><span class=\"p\">]<\/span> <span class=\"ow\">or<\/span> <span class=\"s2\">&quot;\/\/&quot;<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">start<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">math.min<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line1<\/span><span class=\"p\">,<\/span> <span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line2<\/span><span class=\"p\">)<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">math.max<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line1<\/span><span class=\"p\">,<\/span> <span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line2<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"nb\">pcall<\/span><span class=\"p\">(<\/span><span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">,<\/span> <span class=\"n\">start<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;,&quot;<\/span> <span class=\"o\">..<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;s:^<\/span><span class=\"se\">\\\\<\/span><span class=\"s2\">(<\/span><span class=\"se\">\\\\<\/span><span class=\"s2\">s<\/span><span class=\"se\">\\\\<\/span><span class=\"s2\">{-<\/span><span class=\"se\">\\\\<\/span><span class=\"s2\">}<\/span><span class=\"se\">\\\\<\/span><span class=\"s2\">)&quot;<\/span> <span class=\"o\">..<\/span> <span class=\"n\">line_comment<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;:<\/span><span class=\"se\">\\\\<\/span><span class=\"s2\">1:&quot;<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;noh&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"kr\">end<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now it should work pretty well!<\/p>\n<h1 id=\"summary-and-full-code\">Summary and full code<\/h1>\n<p>That's pretty much it for commenting and uncommenting code, at least as far as\nmy semi-imagined needs for it go. This represents among the first non-trivial\nextensions I've made to NeoVim using only its API and made me realise just how\nmuch power I've left untapped for so many years. I will undoubtedly return with\nmore blog posts on extending NeoVim in the future; it's just too much fun not\nto.<\/p>\n<p>The full code can be found below. You can just copy and paste it into your root\n<code>init.lua<\/code> file and it should work without any further tweaks. For a more\nsegregated placement, you can draw inspiration from <a href=\"https:\/\/github.com\/slarse\/config\/commit\/fe1ab5bcd24f4a1ad0a111b67a652de1c330a18d\">my NeoVim\nconfiguration<\/a>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">local<\/span> <span class=\"n\">non_c_line_comments_by_filetype<\/span> <span class=\"o\">=<\/span> <span class=\"p\">{<\/span>\n    <span class=\"n\">lua<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;--&quot;<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">python<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;#&quot;<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">sql<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;--&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">local<\/span> <span class=\"kr\">function<\/span> <span class=\"nf\">comment_out<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">)<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">line_comment<\/span> <span class=\"o\">=<\/span> <span class=\"n\">non_c_line_comments_by_filetype<\/span><span class=\"p\">[<\/span><span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">bo<\/span><span class=\"p\">.<\/span><span class=\"n\">filetype<\/span><span class=\"p\">]<\/span> <span class=\"ow\">or<\/span> <span class=\"s2\">&quot;\/\/&quot;<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">start<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">math.min<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line1<\/span><span class=\"p\">,<\/span> <span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line2<\/span><span class=\"p\">)<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">math.max<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line1<\/span><span class=\"p\">,<\/span> <span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line2<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">(<\/span><span class=\"n\">start<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;,&quot;<\/span> <span class=\"o\">..<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;s:^:&quot;<\/span> <span class=\"o\">..<\/span> <span class=\"n\">line_comment<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;:&quot;<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;noh&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"kr\">end<\/span>\n\n<span class=\"kd\">local<\/span> <span class=\"kr\">function<\/span> <span class=\"nf\">uncomment<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">)<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">line_comment<\/span> <span class=\"o\">=<\/span> <span class=\"n\">non_c_line_comments_by_filetype<\/span><span class=\"p\">[<\/span><span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">bo<\/span><span class=\"p\">.<\/span><span class=\"n\">filetype<\/span><span class=\"p\">]<\/span> <span class=\"ow\">or<\/span> <span class=\"s2\">&quot;\/\/&quot;<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">start<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">math.min<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line1<\/span><span class=\"p\">,<\/span> <span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line2<\/span><span class=\"p\">)<\/span>\n    <span class=\"kd\">local<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">math.max<\/span><span class=\"p\">(<\/span><span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line1<\/span><span class=\"p\">,<\/span> <span class=\"n\">opts<\/span><span class=\"p\">.<\/span><span class=\"n\">line2<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"nb\">pcall<\/span><span class=\"p\">(<\/span><span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">,<\/span> <span class=\"n\">start<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;,&quot;<\/span> <span class=\"o\">..<\/span> <span class=\"n\">finish<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;s:^<\/span><span class=\"se\">\\\\<\/span><span class=\"s2\">(<\/span><span class=\"se\">\\\\<\/span><span class=\"s2\">s<\/span><span class=\"se\">\\\\<\/span><span class=\"s2\">{-<\/span><span class=\"se\">\\\\<\/span><span class=\"s2\">}<\/span><span class=\"se\">\\\\<\/span><span class=\"s2\">)&quot;<\/span> <span class=\"o\">..<\/span> <span class=\"n\">line_comment<\/span> <span class=\"o\">..<\/span> <span class=\"s2\">&quot;:<\/span><span class=\"se\">\\\\<\/span><span class=\"s2\">1:&quot;<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;noh&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"kr\">end<\/span>\n\n<span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_create_user_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;CommentOut&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">comment_out<\/span><span class=\"p\">,<\/span> <span class=\"p\">{<\/span> <span class=\"n\">range<\/span> <span class=\"o\">=<\/span> <span class=\"kc\">true<\/span> <span class=\"p\">})<\/span>\n<span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">keymap<\/span><span class=\"p\">.<\/span><span class=\"n\">set<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;v&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;&lt;leader&gt;co&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;:CommentOut&lt;CR&gt;&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">keymap<\/span><span class=\"p\">.<\/span><span class=\"n\">set<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;n&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;&lt;leader&gt;co&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;:CommentOut&lt;CR&gt;&quot;<\/span><span class=\"p\">)<\/span>\n\n<span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">api<\/span><span class=\"p\">.<\/span><span class=\"n\">nvim_create_user_command<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;Uncomment&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">uncomment<\/span><span class=\"p\">,<\/span> <span class=\"p\">{<\/span> <span class=\"n\">range<\/span> <span class=\"o\">=<\/span> <span class=\"kc\">true<\/span> <span class=\"p\">})<\/span>\n<span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">keymap<\/span><span class=\"p\">.<\/span><span class=\"n\">set<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;v&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;&lt;leader&gt;uc&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;:Uncomment&lt;CR&gt;&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">vim<\/span><span class=\"p\">.<\/span><span class=\"n\">keymap<\/span><span class=\"p\">.<\/span><span class=\"n\">set<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;n&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;&lt;leader&gt;uc&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;:Uncomment&lt;CR&gt;&quot;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Happy editing!<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"neovim"}}]},{"title":"Adding guardrails to psql for PostgreSQL","link":{"@attributes":{"href":"https:\/\/slar.se\/psql-guardrails.html","rel":"alternate"}},"published":"2024-02-24T00:00:00+01:00","updated":"2024-02-24T00:00:00+01:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2024-02-24:\/psql-guardrails.html","summary":"<p>I've been using <code>psql<\/code> for many years to interface with PostgreSQL databases.\nIt's simple, pretty much always available as it's usually bundled with\nPostgreSQL and just does what it's supposed to. It does, however, have some\npretty dangerous defaults. Not only are writes allowed, but it also\nautomatically commits any \u2026<\/p>","content":"<p>I've been using <code>psql<\/code> for many years to interface with PostgreSQL databases.\nIt's simple, pretty much always available as it's usually bundled with\nPostgreSQL and just does what it's supposed to. It does, however, have some\npretty dangerous defaults. Not only are writes allowed, but it also\nautomatically commits any statements executed outside of explicit transactions.\nLet's fix that.<\/p>\n<h1 id=\"configuring-psql-with-psqlrc\">Configuring <code>psql<\/code> with <code>.psqlrc<\/code><\/h1>\n<p>The <a href=\"https:\/\/www.postgresql.org\/docs\/current\/app-psql.html#APP-PSQL-FILES-PSQLRC\"><code>.psqlrc<\/code>\nfile<\/a>\ncan be used to set defaults for new connections made with <code>psql<\/code>. It should be\nplaced in your home directory (i.e. <code>~\/.psqlrc<\/code>) and most often contains <code>\\set<\/code>\nand <code>SET<\/code> commands.<\/p>\n<p>The difference between <code>\\set<\/code> and <code>SET<\/code> commands is a bit subtle. A <a href=\"https:\/\/www.postgresql.org\/docs\/current\/sql-set.html\"><code>SET<\/code>\ncommand<\/a> sets a session\nvariable inside of the PostgreSQL server, whereas a <a href=\"https:\/\/www.postgresql.org\/docs\/current\/app-psql.html#APP-PSQL-META-COMMAND-SET\"><code>\\set<\/code>\ncommand<\/a>\nsets configuration in the <code>psql<\/code> client itself.<\/p>\n<h2 id=\"making-the-default-transaction-read-only\">Making the default transaction read-only<\/h2>\n<p>PostgreSQL executes all statements as transactions. If you don't start an\nexplicit transaction for a statement, <a href=\"https:\/\/www.postgresql.org\/docs\/current\/tutorial-transactions.html\">PostgreSQL automatically wraps the\nstatement in a\ntransaction<\/a>.\nBy default transactions are both readable and writable, which isn't necessarily\ndesirable. To make transactions read-only by default, you can set the following\nsession variable inside of PostgreSQL.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">SET<\/span><span class=\"w\"> <\/span><span class=\"n\">default_transaction_read_only<\/span><span class=\"o\">=<\/span><span class=\"ss\">&quot;on&quot;<\/span><span class=\"p\">;<\/span>\n<\/code><\/pre><\/div>\n\n<p>You can do this in any PostgreSQL session. It can also be configured on the\ndatabase server, but here we assume it isn't. If you after having done that try\nto execute a statement that writes to the database, you'll get an error.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test_db<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">CREATE<\/span><span class=\"w\"> <\/span><span class=\"k\">TABLE<\/span><span class=\"w\"> <\/span><span class=\"n\">test_table<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">id<\/span><span class=\"w\"> <\/span><span class=\"nb\">serial<\/span><span class=\"p\">);<\/span>\n<span class=\"n\">ERROR<\/span><span class=\"p\">:<\/span><span class=\"w\">  <\/span><span class=\"n\">cannot<\/span><span class=\"w\"> <\/span><span class=\"k\">execute<\/span><span class=\"w\"> <\/span><span class=\"k\">CREATE<\/span><span class=\"w\"> <\/span><span class=\"k\">TABLE<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">a<\/span><span class=\"w\"> <\/span><span class=\"k\">read<\/span><span class=\"o\">-<\/span><span class=\"k\">only<\/span><span class=\"w\"> <\/span><span class=\"k\">transaction<\/span>\n<\/code><\/pre><\/div>\n\n<p>However, it's still possible to create an explicit transaction that's allowed\nto write, so it doesn't hinder you if you do need to write.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test_db<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">BEGIN<\/span><span class=\"w\"> <\/span><span class=\"k\">READ<\/span><span class=\"w\"> <\/span><span class=\"k\">WRITE<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">BEGIN<\/span>\n<span class=\"n\">test_db<\/span><span class=\"o\">=*#<\/span><span class=\"w\"> <\/span><span class=\"k\">CREATE<\/span><span class=\"w\"> <\/span><span class=\"k\">TABLE<\/span><span class=\"w\"> <\/span><span class=\"n\">test_table<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">id<\/span><span class=\"w\"> <\/span><span class=\"nb\">serial<\/span><span class=\"p\">);<\/span>\n<span class=\"k\">CREATE<\/span><span class=\"w\"> <\/span><span class=\"k\">TABLE<\/span>\n<span class=\"n\">test_db<\/span><span class=\"o\">=*#<\/span><span class=\"w\"> <\/span><span class=\"k\">COMMIT<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">COMMIT<\/span>\n<\/code><\/pre><\/div>\n\n<p>To set this in <code>.psqlrc<\/code>, simply add the exact same line you'd use in an\ninteractive session to <code>~\/.psqlrc<\/code>. When you connect to a database, any <code>SET<\/code>\ncommand in <code>.psqlrc<\/code> is automatically executed.<\/p>\n<blockquote>\n<p><strong>Pitfall:<\/strong> <code>SET<\/code> commands in <code>.psqlrc<\/code> are only executed when you\nfirst establish a connection to the database server. If you <em>switch<\/em> database\nafter having connected with <code>\\c<\/code>, the <code>SET<\/code> command is <em>not<\/em> executed again.\nKeep that in mind.<\/p>\n<\/blockquote>\n<h2 id=\"disabling-autocommit\">Disabling autocommit<\/h2>\n<p><a href=\"https:\/\/www.postgresql.org\/docs\/current\/app-psql.html#APP-PSQL-FILES-PSQLRC\"><code>psql<\/code> automatically\ncommits<\/a>\nthe implicit transaction created when you execute a statement outside of an\nexplicit transaction. This can be altered such that <code>psql<\/code> implicitly creates a\ntransaction without automatically committing it by setting the <code>AUTOCIMMIT<\/code> variable to <code>off<\/code>. This is a <code>psql<\/code> variable, so we use <code>\\set<\/code> to set it.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"err\">\\<\/span><span class=\"k\">set<\/span><span class=\"w\"> <\/span><span class=\"n\">AUTOCOMMIT<\/span><span class=\"w\"> <\/span><span class=\"k\">false<\/span>\n<\/code><\/pre><\/div>\n\n<p>To validate that it's working as expected, you should look for the <code>*<\/code> in the\n<code>psql<\/code> prompt.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">test_db<\/span><span class=\"o\">=#<\/span><span class=\"w\"> <\/span><span class=\"k\">CREATE<\/span><span class=\"w\"> <\/span><span class=\"k\">TABLE<\/span><span class=\"w\"> <\/span><span class=\"n\">test_table<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">id<\/span><span class=\"w\"> <\/span><span class=\"nb\">serial<\/span><span class=\"p\">);<\/span>\n<span class=\"k\">CREATE<\/span><span class=\"w\"> <\/span><span class=\"k\">TABLE<\/span>\n<span class=\"n\">test_db<\/span><span class=\"o\">=*#<\/span><span class=\"w\"> <\/span><span class=\"k\">ROLLBACK<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"c1\">-- &lt;=== * in the prompt signifies transaction<\/span>\n<span class=\"k\">ROLLBACK<\/span>\n<\/code><\/pre><\/div>\n\n<p>Combined with <code>default_transaction_read_only<\/code>, this automatically creates a\nread-only transaction that's not immediately committed, putting two layers of\nprotection between you and an errenous write. Unlike setting\n<code>default_transaction_read_only<\/code> however, disabling <code>AUTOCOMMIT<\/code> persists even if\nyou switch database with <code>\\c<\/code>.<\/p>\n<h1 id=\"summary\">Summary<\/h1>\n<p>When connecting to any database that you for some reason don't want to\naccidentally write to, you should have guardrails. Many graphical PostgreSQL\nclients that I've seen my colleagues use have such guardrails by default in\nthat an explicit commit must be issued by clicking a button. <code>psql<\/code> does not, so\nsetting up some yourself is imperative.<\/p>\n<p>With <code>AUTOCOMMIT<\/code> disabled and <code>default_transaction_read_only<\/code> set to <code>on<\/code>, you\nshould however be about as safe as can be.<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"postgresql"}},{"@attributes":{"term":"psql"}},{"@attributes":{"term":"database"}}]},{"title":"First impressions of Wayland on Arch Linux","link":{"@attributes":{"href":"https:\/\/slar.se\/wayland-one-month-later.html","rel":"alternate"}},"published":"2024-02-04T00:00:00+01:00","updated":"2024-02-04T00:00:00+01:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2024-02-04:\/wayland-one-month-later.html","summary":"<p>Wayland appears to be the future of window systems in the world of Linux,\nreplacing the aging X.Org window system. The <a href=\"https:\/\/wiki.archlinux.org\/title\/Xorg\">Arch Wiki article on\nX.Org<\/a> refers to it as \"the alternative\nand successor [of X.Org]\" and Canonical even dropped its own <a href=\"https:\/\/wiki.ubuntu.com\/Wayland\">Mir display\nserver in favor \u2026<\/a><\/p>","content":"<p>Wayland appears to be the future of window systems in the world of Linux,\nreplacing the aging X.Org window system. The <a href=\"https:\/\/wiki.archlinux.org\/title\/Xorg\">Arch Wiki article on\nX.Org<\/a> refers to it as \"the alternative\nand successor [of X.Org]\" and Canonical even dropped its own <a href=\"https:\/\/wiki.ubuntu.com\/Wayland\">Mir display\nserver in favor of Wayland on Ubuntu<\/a>.\nSo when it became time for me to configure a new laptop in the beginning of\nJanuary, I decided to do give Wayland a go. Here's what I think of it so far.<\/p>\n<h1 id=\"what-the-heck-is-a-window-system\">What the heck is a window system?<\/h1>\n<p>First of all, what the heck is a window system? In short, it's the component\nthat renders graphical windows to your screen and communicates the user's input\nto the underlying operating system. The X Window System, or just X for short, is\nthe reigning king of window systems in UNIX-like operating systems (excepting\nmacOS which uses <a href=\"https:\/\/en.wikipedia.org\/wiki\/Quartz_Compositor\">Quartz<\/a>). You\nwill often see it referred to as X.Org; this is simply the most commonly used\n<a href=\"https:\/\/www.x.org\/wiki\/\">open source implementation of X<\/a>.<\/p>\n<p>I could try to outline what X.Org's problems are and how Wayland solves many of\nthem, but I simply don't have the level of understanding necessary to do so\nconfidently. One thing to note is that Wayland is first and foremost a\n<em>protocol<\/em> for the communication between a display server and applications. A\ndisplay server can implement the Wayland protocol and is then referred to as a\nWayland <em>compositor<\/em>.<\/p>\n<p>If you want to learn more, <a href=\"https:\/\/linuxiac.com\/xorg-x11-wayland-linux-display-servers-and-protocols-explained\/\">here's a brief article on the\nsubjecp<\/a>.<\/p>\n<h1 id=\"wayland-first-impressions-with-sway\">Wayland first impressions with Sway<\/h1>\n<p>I recently setup Wayland on a brand new work computer, and going from a clean\nslate setup was really effortless. I chose <a href=\"https:\/\/swaywm.org\/\">Sway<\/a> as my\ncompositor and started it. And it just kind of worked. Outside of <a href=\"https:\/\/github.com\/slarse\/config\/blob\/d8ba6671a2245be75c5fa3b4fdfef3df61cc93a0\/sway\/config\">configuring\nSway to my\nliking<\/a>,\nI didn't really have to do much of anything for it to work.<\/p>\n<p>On my private Dell XPS 15 <a href=\"https:\/\/slar.se\/xps-15-9520-arch-linux-intel-dri2.html\">where I'm already running\nX.Org<\/a>, setting up\nWayland was similarly effortless. I just installed Sway, and even though it\ndoesn't support <a href=\"https:\/\/github.com\/swaywm\/sway\/wiki#nvidia-users\">NVIDIA's proprietary\ndrivers<\/a>, running Sway with\nthe <code>--unsuported-gpu<\/code> option just worked.<\/p>\n<p>All-in-all, setup was a breeze and I did not encounter any problems at all.<\/p>\n<h2 id=\"upsides-of-sway\">Upsides of Sway<\/h2>\n<p>I immediately noticed some improvements in my desktop experience. The first came\nwhen connecting an external display, which Sway just found and started\noutputting an image to. In almost a decade of using X.Org on just shy of a half\ndozen devices, that has never happened before without effort on my part.<\/p>\n<p>I was also treated with a complete lack of screen tearing when scrolling\nwebsites and documents, which I had a lot of under X.Org. I'm sure there's a way\nto configure that away with X and I never bothered to look into it more than\nstating that it wasn't as easy as toggling a flag, but it was just for free with\nWayland. Now that it's gone I would have a hard time going back to it.<\/p>\n<p>Finally, most things just kind of work. It's a <em>big<\/em> accolade to note that over\na whole month of use, I haven't encountered a single show-stopping problem. But\nI have definitely encountered quite a few lesser ones.<\/p>\n<h2 id=\"downsites-of-sway\">Downsites of Sway<\/h2>\n<p>Pretty much all of the downsides I've encountered have to do with the fact that\na lot of applications I've used over the years were written for X.Org. This\nmeans that many applications run under the the \n<a href=\"https:\/\/wayland.freedesktop.org\/xserver.html\">XWayland<\/a> compatibility layer,\nwhich nullifies the performance improvements of Wayland's architecture. I've\nespecially noted that startup times for GUI apps that run under XWayland are\nslow compared to running X.Org directly.<\/p>\n<p>Another problem is that apps directly related to X.Org typically just do not\nfunction. For example, I've been using the <a href=\"https:\/\/imagemagick.org\/script\/import.php\"><code>import<\/code> command from\n<code>imagemagick<\/code><\/a> to grab snippeted\nscreenshots for nigh on a decade, and it doesn't work at all with Wayland as it\nexpects to work with an X.Org backend. Similarly,\n<a href=\"https:\/\/wiki.archlinux.org\/title\/Redshift\">Redshift<\/a> which I've been using for\nyears to adjust color temperature does not support Wayland. It results in a whole\nlot of <a href=\"https:\/\/www.reddit.com\/r\/wayland\/comments\/si49y1\/redshift_alternatives_for_wayland\/?rdt=39794\"><insert program> alternative for\nWayland<\/a>\nkinds of searches, but they usually bear fruit. I found <a href=\"https:\/\/sr.ht\/~emersion\/grim\/\"><code>grim<\/code> as a replacement\nfor <code>import<\/code><\/a> and <a href=\"https:\/\/gitlab.com\/chinstrap\/gammastep\"><code>gammastep<\/code> as a replacement\nfor <code>redshift<\/code><\/a> that way.<\/p>\n<p>The incompatibility with Redshift does bring up another interesting point,\nnamely that Wayland is still neither complete nor stable. <a href=\"https:\/\/gitlab.freedesktop.org\/wayland\/wayland-protocols\/-\/merge_requests\/14\">Color management is for\nexample still not\nstandardized<\/a>.\nIn some respects, stepping into the land of Way feels a bit like using a beta\nproduct.<\/p>\n<h1 id=\"conclusions\">Conclusions<\/h1>\n<p>Will I keep using Wayland? Definitely. I've only encountered a few very minor\nproblems with application compatibility, and most I've found alternatives for.\nI'm even a little bit excited to find some need completely unfulfilled in the\nland of Wayland applications, because that would give me a good reason to\nimplement it myself.<\/p>","category":[{"@attributes":{"term":"Linux"}},{"@attributes":{"term":"linux"}},{"@attributes":{"term":"wayland"}},{"@attributes":{"term":"xorg"}},{"@attributes":{"term":"x11"}}]},{"title":"Dependabot's dependency grouping is awesome","link":{"@attributes":{"href":"https:\/\/slar.se\/dependabots-dependency-grouping.html","rel":"alternate"}},"published":"2024-01-29T00:00:00+01:00","updated":"2024-01-29T00:00:00+01:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2024-01-29:\/dependabots-dependency-grouping.html","summary":"<p>I've been using GitHub's Dependabot since it was <a href=\"https:\/\/github.blog\/2020-06-01-keep-all-your-packages-up-to-date-with-dependabot\/\">released around 4 years\nago<\/a>,\nand to a large extent, it's been great. Except for one thing: the sheer amount\nof pull requests Dependabot would open for dependency updates. For some of my\nrepositories it became more of a chore to keep \u2026<\/p>","content":"<p>I've been using GitHub's Dependabot since it was <a href=\"https:\/\/github.blog\/2020-06-01-keep-all-your-packages-up-to-date-with-dependabot\/\">released around 4 years\nago<\/a>,\nand to a large extent, it's been great. Except for one thing: the sheer amount\nof pull requests Dependabot would open for dependency updates. For some of my\nrepositories it became more of a chore to keep up with Dependabot's pull request\nspamming than to just manually update dependencies every once in a while.<\/p>\n<p>Well. Turns out that's been fixed.<\/p>\n<h1 id=\"dependabots-big-problem-pull-request-spam\">Dependabot's big problem: Pull request spam<\/h1>\n<p>Since Dependabot was released, it's only mode of operation has been to open one\npull request per dependency update. As you can imagine, that leads to a whole\nbunch of pull requests being opened. I would routinely get dozens of dependency\npull requests a week for some of my more dependency heavy repositories. Needless\nto say, that's just not manageable.<\/p>\n<p>One of my projects, <a href=\"https:\/\/github.com\/kth-assert\/spork\">Spork<\/a>, which is\nmostly in maintenance mod is one such example where I just gave up on keeping up\nwith the updates. It ended up looking like this:<\/p>\n<p><img alt=\"Spork dependency spam\" src=\"https:\/\/slar.se\/photos\/dependabot_dependency_grouping\/pr-spama.jpg\"><\/p>\n<p>What a mess. But there's light at the end of the tunnel.<\/p>\n<h1 id=\"the-fix-grouped-dependencies\">The fix: Grouped dependencies<\/h1>\n<p>To address that problem GitHub recently released\n<a href=\"https:\/\/github.blog\/changelog\/2023-08-24-grouped-version-updates-for-dependabot-are-generally-available\/\">Grouped Version Updates<\/a>\nas a feature for Dependabot. In short, this means that you can get Dependabot\nto open pull requests containing multiple dependency updates, grouped in three\ndifferent ways.<\/p>\n<h2 id=\"a-configuration-example\">A configuration example<\/h2>\n<p>For my project <a href=\"https:\/\/github.com\/kth-assert\/spork\">Spork<\/a>, I decided to group\ndependencies in three groups:<\/p>\n<ol>\n<li>Updates to GitHub Actions dependencies<\/li>\n<li>Updates to production dependencies<\/li>\n<li>Updates to development dependencies<\/li>\n<\/ol>\n<p>Configuring this was really straightforward, all it took was <a href=\"https:\/\/github.com\/ASSERT-KTH\/spork\/commit\/ac3051e07bc6632c4f41f74feb60ffc555fce1cd\">this\ncommit<\/a>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\"> <\/span>    directory: &quot;\/&quot;\n<span class=\"w\"> <\/span>    schedule:\n<span class=\"w\"> <\/span>      interval: &quot;daily&quot;\n<span class=\"gi\">+    groups:<\/span>\n<span class=\"gi\">+      actions-deps:<\/span>\n<span class=\"gi\">+        patterns:<\/span>\n<span class=\"gi\">+          - &quot;*&quot;<\/span>\n\n<span class=\"w\"> <\/span>  - package-ecosystem: &quot;maven&quot;\n<span class=\"w\"> <\/span>    directory: &quot;\/&quot;\n<span class=\"w\"> <\/span>    schedule:\n<span class=\"w\"> <\/span>      interval: &quot;daily&quot;\n<span class=\"gi\">+    groups:<\/span>\n<span class=\"gi\">+      dev-deps:<\/span>\n<span class=\"gi\">+        dependency-type: &quot;development&quot;<\/span>\n<span class=\"gi\">+      prod-deps:<\/span>\n<span class=\"gi\">+        dependency-type: &quot;production&quot;<\/span>\n<\/code><\/pre><\/div>\n\n<p>In full, the configuration looks like so.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nt\">version<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"l l-Scalar l-Scalar-Plain\">2<\/span>\n<span class=\"nt\">updates<\/span><span class=\"p\">:<\/span>\n\n<span class=\"w\">  <\/span><span class=\"p p-Indicator\">-<\/span><span class=\"w\"> <\/span><span class=\"nt\">package-ecosystem<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;github-actions&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">directory<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;\/&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">schedule<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">interval<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;daily&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">groups<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">actions-deps<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">patterns<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">          <\/span><span class=\"p p-Indicator\">-<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;*&quot;<\/span>\n\n<span class=\"w\">  <\/span><span class=\"p p-Indicator\">-<\/span><span class=\"w\"> <\/span><span class=\"nt\">package-ecosystem<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;maven&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">directory<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;\/&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">schedule<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">interval<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;daily&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"nt\">groups<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">dev-deps<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">dependency-type<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;development&quot;<\/span>\n<span class=\"w\">      <\/span><span class=\"nt\">prod-deps<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">        <\/span><span class=\"nt\">dependency-type<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;production&quot;<\/span>\n<\/code><\/pre><\/div>\n\n<p>For each package ecosystem, you must group on <em>something<\/em>. For\n<code>github-actions<\/code>, I just wanted a single group, and the way to achieve such an\n\"everything group\" is to simply use a wildcard pattern. For <code>maven<\/code>, I ended up\nsplitting by the <code>dependency-type<\/code> attribute instead, which can be either\n<code>development<\/code> or <code>production<\/code>.<\/p>\n<p>But that's just two ways to group, you said there were three ways? Very\nattentive of you! In addition to the <code>pattern<\/code> and <code>dependency-type<\/code> groupings,\nyou can also group by <code>update-type<\/code>, which can be <code>patch<\/code>, <code>minor<\/code> or <code>major<\/code>\nand only really works for dependencies that comply with <a href=\"https:\/\/semver.org\/\">Semantic\nVersioning<\/a><\/p>\n<h2 id=\"effects-of-the-configuration\">Effects of the configuration<\/h2>\n<p>Within minutes, Dependabot had closed all* of the single dependency pull requests\nand created two new pull requests. One PR contained the GitHub Actions updates,\nwhich I could immediately merge.<\/p>\n<blockquote>\n<p>*For reasons I don't quite get at this point,\n<a href=\"https:\/\/github.com\/ASSERT-KTH\/spork\/pull\/458\">one single-dependency PR for <code>gumtree-spoon-ast-diff<\/code> remained\nopen<\/a><\/p>\n<\/blockquote>\n<p><img alt=\"Merged GitHub Actions dependencies\" src=\"https:\/\/slar.se\/photos\/dependabot_dependency_grouping\/actions_depsa.jpg\"><\/p>\n<p>Note that the <code>actions-deps<\/code> name, which is one of the keys in the YAML config\nfile, ends up being written out in the pull request title. Another PR was opened\nfor the grouped production dependencies, but it did not pass CI.<\/p>\n<p><img alt=\"Production dependencies PR\" src=\"https:\/\/slar.se\/photos\/dependabot_dependency_grouping\/prod-depsa.jpg\"><\/p>\n<p>This showcases the one downside with grouped dependency updates: there's no\nindication as to which dependency caused the CI failure. If you scroll up to the\nfirst image of this article, you'll similarly see the one benefit of single\ndependency pull requests: the update for <code>jgit<\/code> is failing.<\/p>\n<blockquote>\n<p>Note: As stated above, <code>gumtree-spoon-ast-diff<\/code> wasn't included in the grouped\ndependency update for some reason, so we'll ignore that it's also failing.<\/p>\n<\/blockquote>\n<p>So I decided to try to get Dependabot to open a new pull request without <code>jgit<\/code>.<\/p>\n<h2 id=\"ignoring-certain-dependencies-in-a-group\">Ignoring certain dependencies in a group<\/h2>\n<p>I knew that <code>jgit<\/code> was the issue in this case and decided to ignore it. It\nseemed like ignoring minor version updates was the best path forward, so I\nissued an <code>@dependabot ignore &lt;dependency_name&gt; minor version<\/code> command.<\/p>\n<p><img alt=\"Ignore minor version updates of jgit\" src=\"https:\/\/slar.se\/photos\/dependabot_dependency_grouping\/ignore_minora.jpg\"><\/p>\n<p>This didn't quite have the effect I was looking for, as Dependabot then\nproceeded to\n<a href=\"https:\/\/github.com\/ASSERT-KTH\/spork\/pull\/485\">open a new pull request<\/a>\nwith the previous minor version of <code>jgit<\/code>, which is also incompatible with\nSpork. At this point I decided to bring out the big guns and ignore <code>jgit<\/code>\naltoghether for now, as I knew I needed to put in some manual work to update it\nanyway.<\/p>\n<p><img alt=\"Ignore all version updates of jgit\" src=\"https:\/\/slar.se\/photos\/dependabot_dependency_grouping\/ignorea.jpg\"><\/p>\n<p>This finally resulted in what I wanted, a new PR without a bump to <code>jgit<\/code> that\ndoes not break the build. Thus, it's ready to merge.<\/p>\n<p><img alt=\"Production dependency PR now passing checks\" src=\"https:\/\/slar.se\/photos\/dependabot_dependency_grouping\/green-prod-pra.jpg\"><\/p>\n<p>Of course, this comes with the caveat that I need to remember to <a href=\"https:\/\/github.com\/ASSERT-KTH\/spork\/issues\/487\">unignore <code>jgit<\/code>\nwhen I get around to updating it<\/a>.\nBut I have 8 dependency updates with not too much effort, which is kind of cool!<\/p>\n<h1 id=\"closing-thoughts\">Closing thoughts<\/h1>\n<p>I had somewhat given up on keeping dependencies up to date in my lesser loved\nprojects. With grouped dependency updates, I feel like it will be possible for\nme to get back to keeping dependencies in good shape even for projects that I no\nlonger actively work on.<\/p>\n<p>The one downside is that it's no longer evident which dependency update breaks\nthe build. However, over many years of maintaining projects built in various\nlanguages and technologies, experience tells me that it's way more common for\ndependencies to update just fine than for them to break something, so I think\nit's a tradeoff well worth taking. As patterns of which dependencies break the\nbuild more often start to become apparent, one can also refine the groupings and\nseparate dependencies that break often from those that rarely or never do so.<\/p>\n<p>To summarize, grouped dependency updates is a killer feature that makes\nDependabot viable again. Everyone should use it, and it's honestly a shame that\nbackwards compatibility demands makes it such that groups will probably never be\nthe default.<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"dependabot"}},{"@attributes":{"term":"github"}},{"@attributes":{"term":"dependencies"}}]},{"title":"A new dark theme for the blog!","link":{"@attributes":{"href":"https:\/\/slar.se\/new-dark-theme.html","rel":"alternate"}},"published":"2023-10-25T00:00:00+02:00","updated":"2023-10-25T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2023-10-25:\/new-dark-theme.html","summary":"<p>If you've <em>ever<\/em> visited my blog before, you'll notice it looks a bit\ndifferent. I finally took the time to make a dark theme! Only 5 or so years late\nto the party. But late or not, I have a new theme to show off, so let's have a\nlook \u2026<\/p>","content":"<p>If you've <em>ever<\/em> visited my blog before, you'll notice it looks a bit\ndifferent. I finally took the time to make a dark theme! Only 5 or so years late\nto the party. But late or not, I have a new theme to show off, so let's have a\nlook!<\/p>\n<h1 id=\"before-and-after\">Before and after<\/h1>\n<p>I only put a couple of hours into trying out different colors and contrasts, so\nthis is still a bit of a work in progress. But I can't say I'm not pleased.\nLet's have a look at what it used to look like.<\/p>\n<p><img alt=\"The site with the old light theme\" src=\".\/images\/new_dark_theme\/before.png\" style=\"max-width: 95%;\"><\/p>\n<p>So, that doesn't look terrible in any way, but it doesn't fit the \"programmer\naesthetic\". It doesn't fit <em>my<\/em> aesthetic. The new theme is much more \"me\", and\nalthough you should already be seeing it all around here, here's the same image\nas above with the new theme.<\/p>\n<p><img alt=\"The site with the new dark theme\" src=\".\/images\/new_dark_theme\/after.png\" style=\"max-width: 95%;\"><\/p>\n<p>Much better! There are still a few rough edges, and I keep finding details where\nthe old theme isn't being overridden correctly (because this is all just <em>on top\nof<\/em> Bootstrap), but it's all mostly there.<\/p>\n<h1 id=\"parts-of-the-puzzle\">Parts of the puzzle<\/h1>\n<p>There are really only two parts to this. I'm still using the same\n<a href=\"https:\/\/github.com\/robulouski\/voidy-bootstrap\"><code>voidy-bootstrap<\/code> theme<\/a> as\nbefore, but I rewrote some of the CSS with the somewhat Halloween-looking\nexperience you're looking at right now. Which is fitting, considering Halloween\nis just around the corner!<\/p>\n<p>The second part is the fantastic\n<a href=\"https:\/\/draculatheme.com\/pygments\"><code>dracula<\/code> theme for Pygments<\/a>\nwhich gives the neat colorization of code snippets. That I find to be the single\nlargest improvement.<\/p>\n<h1 id=\"enjoy\">Enjoy!<\/h1>\n<p>That's all there is to it, enjoy the new theme!<\/p>","category":[{"@attributes":{"term":"Blog"}},{"@attributes":{"term":"blog"}}]},{"title":"What does the number in a man page mean?","link":{"@attributes":{"href":"https:\/\/slar.se\/man-page-numbering.html","rel":"alternate"}},"published":"2023-10-24T00:00:00+02:00","updated":"2023-10-24T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2023-10-24:\/man-page-numbering.html","summary":"<p>If you open a <code>man<\/code> page on a *NIX system (such as a Linux distro), you'll\nalways see a number next to the subject of the <code>man<\/code> page. Like <code>GIT(1)<\/code>,\n<code>SUDO(8)<\/code> or <code>open(n)<\/code>. What's that thing in parentheses? To cut a long\nstory short, it's the <em>section \u2026<\/em><\/p>","content":"<p>If you open a <code>man<\/code> page on a *NIX system (such as a Linux distro), you'll\nalways see a number next to the subject of the <code>man<\/code> page. Like <code>GIT(1)<\/code>,\n<code>SUDO(8)<\/code> or <code>open(n)<\/code>. What's that thing in parentheses? To cut a long\nstory short, it's the <em>section<\/em> the <code>man<\/code> page belongs to. Let's discover\nwhat that means.<\/p>\n<h1 id=\"man-pages-are-divided-into-sections\"><code>man<\/code> pages are divided into sections<\/h1>\n<p><code>man<\/code> pages act as a system reference manual on any *NIX system. All <code>man<\/code> pages\nhave a heading containing the name of the page, its section and a very short\ndescription. Something like this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>&lt;name&gt;(&lt;#section&gt;)     &lt;description&gt;     &lt;name&gt;(&lt;#section&gt;)\n<\/code><\/pre><\/div>\n\n<p>As a concrete example, here's the first line you get if you execute <code>man git<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>GIT(1)                         Git Manual                        GIT(1)\n<\/code><\/pre><\/div>\n\n<p>The name is self-explanatory, is is the short description, but the section\nnumber is not so transparent in its meaning. To find out what it means,\nwe can actually consult the <code>man<\/code> page for the <code>man<\/code> program itself.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">$<\/span><span class=\"w\"> <\/span><span class=\"n\">man<\/span><span class=\"w\"> <\/span><span class=\"n\">man<\/span>\n<span class=\"n\">MAN<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span><span class=\"w\">                     <\/span><span class=\"n\">Manual<\/span><span class=\"w\"> <\/span><span class=\"n\">pager<\/span><span class=\"w\"> <\/span><span class=\"n\">utils<\/span><span class=\"w\">                    <\/span><span class=\"n\">MAN<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">[...]<\/span>\n<span class=\"n\">The<\/span><span class=\"w\"> <\/span><span class=\"n\">table<\/span><span class=\"w\"> <\/span><span class=\"n\">below<\/span><span class=\"w\"> <\/span><span class=\"n\">shows<\/span><span class=\"w\"> <\/span><span class=\"n\">the<\/span><span class=\"w\"> <\/span><span class=\"n\">section<\/span><span class=\"w\"> <\/span><span class=\"n\">numbers<\/span><span class=\"w\"> <\/span><span class=\"n\">of<\/span><span class=\"w\"> <\/span><span class=\"n\">the<\/span><span class=\"w\"> <\/span><span class=\"n\">manual<\/span><span class=\"w\"> <\/span><span class=\"n\">followed<\/span>\n<span class=\"n\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">the<\/span><span class=\"w\"> <\/span><span class=\"n\">types<\/span><span class=\"w\"> <\/span><span class=\"n\">of<\/span><span class=\"w\"> <\/span><span class=\"n\">pages<\/span><span class=\"w\"> <\/span><span class=\"n\">they<\/span><span class=\"w\"> <\/span><span class=\"n\">contain<\/span><span class=\"p\">.<\/span>\n\n<span class=\"mi\">1<\/span><span class=\"w\">   <\/span><span class=\"n\">Executable<\/span><span class=\"w\"> <\/span><span class=\"n\">programs<\/span><span class=\"w\"> <\/span><span class=\"n\">or<\/span><span class=\"w\"> <\/span><span class=\"n\">shell<\/span><span class=\"w\"> <\/span><span class=\"n\">commands<\/span>\n<span class=\"mi\">2<\/span><span class=\"w\">   <\/span><span class=\"n\">System<\/span><span class=\"w\"> <\/span><span class=\"n\">calls<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">functions<\/span><span class=\"w\"> <\/span><span class=\"n\">provided<\/span><span class=\"w\"> <\/span><span class=\"n\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">the<\/span><span class=\"w\"> <\/span><span class=\"n\">kernel<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">3<\/span><span class=\"w\">   <\/span><span class=\"n\">Library<\/span><span class=\"w\"> <\/span><span class=\"n\">calls<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">functions<\/span><span class=\"w\"> <\/span><span class=\"n\">within<\/span><span class=\"w\"> <\/span><span class=\"n\">program<\/span><span class=\"w\"> <\/span><span class=\"n\">libraries<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">4<\/span><span class=\"w\">   <\/span><span class=\"n\">Special<\/span><span class=\"w\"> <\/span><span class=\"n\">files<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">usually<\/span><span class=\"w\"> <\/span><span class=\"n\">found<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"n\">dev<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">5<\/span><span class=\"w\">   <\/span><span class=\"n\">File<\/span><span class=\"w\"> <\/span><span class=\"n\">formats<\/span><span class=\"w\"> <\/span><span class=\"n\">and<\/span><span class=\"w\"> <\/span><span class=\"n\">conventions<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">e<\/span><span class=\"p\">.<\/span><span class=\"n\">g<\/span><span class=\"p\">.<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"n\">etc<\/span><span class=\"o\">\/<\/span><span class=\"n\">passwd<\/span>\n<span class=\"mi\">6<\/span><span class=\"w\">   <\/span><span class=\"n\">Games<\/span>\n<span class=\"mi\">7<\/span><span class=\"w\">   <\/span><span class=\"n\">Miscellaneous<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">including<\/span><span class=\"w\"> <\/span><span class=\"n\">macro<\/span><span class=\"w\">  <\/span><span class=\"n\">packages<\/span><span class=\"w\">  <\/span><span class=\"n\">and<\/span><span class=\"w\">  <\/span><span class=\"n\">conventions<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">e<\/span><span class=\"p\">.<\/span><span class=\"n\">g<\/span><span class=\"p\">.<\/span><span class=\"w\"> <\/span><span class=\"n\">man<\/span><span class=\"p\">(<\/span><span class=\"mi\">7<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">groff<\/span><span class=\"p\">(<\/span><span class=\"mi\">7<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">man<\/span><span class=\"o\">-<\/span><span class=\"n\">pages<\/span><span class=\"p\">(<\/span><span class=\"mi\">7<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">8<\/span><span class=\"w\">   <\/span><span class=\"n\">System<\/span><span class=\"w\"> <\/span><span class=\"n\">administration<\/span><span class=\"w\"> <\/span><span class=\"n\">commands<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">usually<\/span><span class=\"w\"> <\/span><span class=\"n\">only<\/span><span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"n\">root<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">9<\/span><span class=\"w\">   <\/span><span class=\"n\">Kernel<\/span><span class=\"w\"> <\/span><span class=\"n\">routines<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"n\">Non<\/span><span class=\"w\"> <\/span><span class=\"n\">standard<\/span><span class=\"p\">]<\/span>\n<span class=\"p\">[...]<\/span>\n<\/code><\/pre><\/div>\n\n<p>This sectioning makes it possible to have multiple <code>man<\/code> pages with the same\nname, but in different sections. By default, you'll get only one result when\nexecuting <code>man &lt;name&gt;<\/code>, and which one you get is dependent on a pre-defined\nsearch order. Which, of course, we can also find in the <code>man<\/code> page for <code>man<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">The<\/span><span class=\"w\">  <\/span><span class=\"n\">order<\/span><span class=\"w\">  <\/span><span class=\"n\">of<\/span><span class=\"w\"> <\/span><span class=\"n\">sections<\/span><span class=\"w\"> <\/span><span class=\"n\">to<\/span><span class=\"w\"> <\/span><span class=\"n\">search<\/span><span class=\"w\"> <\/span><span class=\"n\">may<\/span><span class=\"w\"> <\/span><span class=\"n\">be<\/span><span class=\"w\"> <\/span><span class=\"n\">overridden<\/span><span class=\"w\"> <\/span><span class=\"n\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">the<\/span><span class=\"w\"> <\/span><span class=\"n\">envi<\/span><span class=\"err\">\u2010<\/span>\n<span class=\"n\">ronment<\/span><span class=\"w\">  <\/span><span class=\"n\">variable<\/span><span class=\"w\">  <\/span><span class=\"o\">$<\/span><span class=\"n\">MANSECT<\/span><span class=\"w\">  <\/span><span class=\"ow\">or<\/span><span class=\"w\">  <\/span><span class=\"n\">by<\/span><span class=\"w\">  <\/span><span class=\"n\">the<\/span><span class=\"w\">  <\/span><span class=\"n\">SECTION<\/span><span class=\"w\">  <\/span><span class=\"n\">directive<\/span><span class=\"w\">  <\/span><span class=\"ow\">in<\/span>\n<span class=\"o\">\/<\/span><span class=\"n\">etc<\/span><span class=\"o\">\/<\/span><span class=\"n\">man_db<\/span><span class=\"o\">.<\/span><span class=\"n\">conf<\/span><span class=\"o\">.<\/span><span class=\"w\">  <\/span><span class=\"n\">By<\/span><span class=\"w\"> <\/span><span class=\"n\">default<\/span><span class=\"w\"> <\/span><span class=\"n\">it<\/span><span class=\"w\"> <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"n\">follows<\/span><span class=\"p\">:<\/span>\n\n<span class=\"w\">      <\/span><span class=\"mi\">1<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"n\">p<\/span><span class=\"w\"> <\/span><span class=\"n\">n<\/span><span class=\"w\"> <\/span><span class=\"n\">l<\/span><span class=\"w\"> <\/span><span class=\"mi\">8<\/span><span class=\"w\"> <\/span><span class=\"mi\">3<\/span><span class=\"w\"> <\/span><span class=\"mi\">3<\/span><span class=\"n\">p<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"n\">p<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"w\"> <\/span><span class=\"mi\">3<\/span><span class=\"n\">type<\/span><span class=\"w\"> <\/span><span class=\"mi\">5<\/span><span class=\"w\"> <\/span><span class=\"mi\">4<\/span><span class=\"w\"> <\/span><span class=\"mi\">9<\/span><span class=\"w\"> <\/span><span class=\"mi\">6<\/span><span class=\"w\"> <\/span><span class=\"mi\">7<\/span>\n<\/code><\/pre><\/div>\n\n<p>In my personal experience, the default search order most often gives you what\nyou want. But sometimes it doesn't, and then you need to figure out how to find\nthe man page you're after.<\/p>\n<h1 id=\"selecting-man-pages-from-different-sections\">Selecting man pages from different sections<\/h1>\n<p>To select a page from a particular section, you specify the section before the\nname. For example, as indicated by the excerpt from <code>MAN(1)<\/code> above, there's also\na <code>man(7)<\/code>. We can get it like so.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>man<span class=\"w\"> <\/span><span class=\"m\">7<\/span><span class=\"w\"> <\/span>man\nman<span class=\"o\">(<\/span><span class=\"m\">7<\/span><span class=\"o\">)<\/span><span class=\"w\">              <\/span>Miscellaneous<span class=\"w\"> <\/span>Information<span class=\"w\"> <\/span>Manual<span class=\"w\">             <\/span>man<span class=\"o\">(<\/span><span class=\"m\">7<\/span><span class=\"o\">)<\/span>\n<span class=\"o\">[<\/span>...<span class=\"o\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>But what if you don't actually know which section the man page you're looking\nfor is in, you only know that the one you're looking at isn't the one? Then you\ncan use <code>whatis<\/code>. For example, I have four different man pages named <code>open<\/code> on\nmy machine.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>whatis<span class=\"w\"> <\/span>open\nopen<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">2<\/span><span class=\"o\">)<\/span><span class=\"w\">             <\/span>-<span class=\"w\"> <\/span>open<span class=\"w\"> <\/span>and<span class=\"w\"> <\/span>possibly<span class=\"w\"> <\/span>create<span class=\"w\"> <\/span>a<span class=\"w\"> <\/span>file\nopen<span class=\"w\"> <\/span><span class=\"o\">(<\/span>3p<span class=\"o\">)<\/span><span class=\"w\">            <\/span>-<span class=\"w\"> <\/span>open<span class=\"w\"> <\/span>file\nopen<span class=\"w\"> <\/span><span class=\"o\">(<\/span>3perl<span class=\"o\">)<\/span><span class=\"w\">         <\/span>-<span class=\"w\"> <\/span>perl<span class=\"w\"> <\/span>pragma<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span><span class=\"nb\">set<\/span><span class=\"w\"> <\/span>default<span class=\"w\"> <\/span>PerlIO<span class=\"w\"> <\/span>layers<span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span>input<span class=\"w\"> <\/span>and<span class=\"w\"> <\/span>output\nopen<span class=\"w\"> <\/span><span class=\"o\">(<\/span>n<span class=\"o\">)<\/span><span class=\"w\">             <\/span>-<span class=\"w\"> <\/span>Open<span class=\"w\"> <\/span>a<span class=\"w\"> <\/span>file-based<span class=\"w\"> <\/span>or<span class=\"w\"> <\/span><span class=\"nb\">command<\/span><span class=\"w\"> <\/span>pipeline<span class=\"w\"> <\/span>channel\n<\/code><\/pre><\/div>\n\n<p>Here you can also see a couple of section numbers that look a bit different,\nnamely <code>3perl<\/code> and <code>n<\/code>. These don't belong to any of the standard sections, but\nyou can open them just the same. For example, <code>man 3perl open<\/code> would open the\n<code>open<\/code> page from the custom <code>3perl<\/code> section.<\/p>\n<blockquote>\n<p>Note: If you don't see all available man pages when running <code>whatis<\/code> for a\nparticular page, your <code>man<\/code> database is out-of-date, you may want to run\n<code>mandb<\/code> manually (or whatever is equivalent on your system) to rebuild the\nsearch index.<\/p>\n<\/blockquote>\n<h1 id=\"and-thats-all\">And that's all!<\/h1>\n<p>Now you should hopefully be a bit more confident in finding the man page you're\nlooking for. And if at any point you forget what I've written here, almost all\nof the information is available just a <code>man man<\/code> away!<\/p>","category":[{"@attributes":{"term":"Linux"}},{"@attributes":{"term":"linux"}},{"@attributes":{"term":"man"}}]},{"title":"The sheer insanity of interfaces and nil in Go","link":{"@attributes":{"href":"https:\/\/slar.se\/the-sheer-insanity-of-interfaces-and-nil-in-go.html","rel":"alternate"}},"published":"2023-10-21T00:00:00+02:00","updated":"2023-10-21T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2023-10-21:\/the-sheer-insanity-of-interfaces-and-nil-in-go.html","summary":"<p>If you've only dabbled briefly in Go, you might think that its <code>nil<\/code> is\nanalogous to the good ol' <a href=\"https:\/\/en.wikipedia.org\/wiki\/Tony_Hoare#Apologies_and_retractions\">\"billion dollar mistake\"<\/a>\nknown as <code>null<\/code>. I thought so, too, up until just a few weeks ago when I\ndecided to make a pass through Thorsten Ball's neat little book\n<a href=\"https:\/\/slar.se\/book-review-writing-an-interpreter-in-go.html\">Writing \u2026<\/a><\/p>","content":"<p>If you've only dabbled briefly in Go, you might think that its <code>nil<\/code> is\nanalogous to the good ol' <a href=\"https:\/\/en.wikipedia.org\/wiki\/Tony_Hoare#Apologies_and_retractions\">\"billion dollar mistake\"<\/a>\nknown as <code>null<\/code>. I thought so, too, up until just a few weeks ago when I\ndecided to make a pass through Thorsten Ball's neat little book\n<a href=\"https:\/\/slar.se\/book-review-writing-an-interpreter-in-go.html\">Writing an Interpreter in Go<\/a>.\nThat's when I first cut myself real bad on <code>nil<\/code>, or more specificaly, an\ninterface with a <code>nil<\/code> value.<\/p>\n<h1 id=\"the-sensible-kind-of-nil\">The sensible kind of <code>nil<\/code><\/h1>\n<p>First let's look at <code>nil<\/code> behaving like we'd expect. Here's a code snippet of a\n\"parser\" that somewhat shows the situation I had.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">package<\/span><span class=\"w\"> <\/span><span class=\"nx\">main<\/span>\n\n<span class=\"kn\">import<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span>\n<span class=\"w\">    <\/span><span class=\"s\">&quot;fmt&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"s\">&quot;strings&quot;<\/span>\n<span class=\"p\">)<\/span>\n\n<span class=\"kd\">type<\/span><span class=\"w\"> <\/span><span class=\"nx\">IfExpression<\/span><span class=\"w\"> <\/span><span class=\"kd\">struct<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">raw<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"nx\">parseIf<\/span><span class=\"p\">(<\/span><span class=\"nx\">s<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"nx\">IfExpression<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"nx\">strings<\/span><span class=\"p\">.<\/span><span class=\"nx\">HasPrefix<\/span><span class=\"p\">(<\/span><span class=\"nx\">s<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;if&quot;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"nx\">IfExpression<\/span><span class=\"p\">{<\/span><span class=\"nx\">raw<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">s<\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>So, we have a parse function that returns a pointer to an <code>IfExpression<\/code> struct\nif the input is an <code>if<\/code> expression (with an incredibly loose definition of what\nconstitutes an <code>if<\/code> expression). Let's add a <code>main<\/code> function and try it out.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"nx\">main<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">ifExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">parseIf<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;if a == b&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">fmt<\/span><span class=\"p\">.<\/span><span class=\"nx\">Println<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;ifExpr&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">ifExpr<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">ifExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"p\">)<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nx\">notIfExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">parseIf<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;not an expression&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">fmt<\/span><span class=\"p\">.<\/span><span class=\"nx\">Println<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;notIfExpr&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">notIfExpr<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">notIfExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Running this results in completely sensible output; <code>ifExpr<\/code> is not <code>nil<\/code> while\n<code>notIfExpr<\/code> is.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>go<span class=\"w\"> <\/span>run<span class=\"w\"> <\/span>main.go\n<span class=\"p\">&amp;<\/span><span class=\"o\">{<\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"nv\">a<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span>b<span class=\"o\">}<\/span><span class=\"w\"> <\/span><span class=\"nb\">false<\/span>\n&lt;nil&gt;<span class=\"w\"> <\/span><span class=\"nb\">true<\/span>\n<\/code><\/pre><\/div>\n\n<p>Say what you want about <code>nil<\/code>, this at least makes complete sense and is\nintuitively understandable. But when we throw interfaces into the mix,\nthat goes way out the window.<\/p>\n<h1 id=\"the-completely-insane-kind-of-nil\">The completely insane kind of <code>nil<\/code><\/h1>\n<p>As my parser came along, it turned out I needed multiple kinds of expressions,\nand so had to abstract the parse function to be able to return multiple kinds\nof expressions. So let's generalize the expression in an interface and add\nanother one.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">type<\/span><span class=\"w\"> <\/span><span class=\"nx\">Expression<\/span><span class=\"w\"> <\/span><span class=\"kd\">interface<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">Raw<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">type<\/span><span class=\"w\"> <\/span><span class=\"nx\">IfExpression<\/span><span class=\"w\"> <\/span><span class=\"kd\">struct<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">raw<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nx\">ie<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"nx\">IfExpression<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nx\">Raw<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"nx\">ie<\/span><span class=\"p\">.<\/span><span class=\"nx\">raw<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n\n<span class=\"kd\">type<\/span><span class=\"w\"> <\/span><span class=\"nx\">ForExpression<\/span><span class=\"w\"> <\/span><span class=\"kd\">struct<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">raw<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"nx\">fe<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"nx\">ForExpression<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nx\">Raw<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"nx\">fe<\/span><span class=\"p\">.<\/span><span class=\"nx\">raw<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>And then we adapt the parsing as well.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"nx\">parse<\/span><span class=\"p\">(<\/span><span class=\"nx\">s<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nx\">Expression<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"nx\">ifExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">parseIf<\/span><span class=\"p\">(<\/span><span class=\"nx\">s<\/span><span class=\"p\">);<\/span><span class=\"w\"> <\/span><span class=\"nx\">ifExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">!=<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"nx\">ifExpr<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"k\">else<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"nx\">parseFor<\/span><span class=\"p\">(<\/span><span class=\"nx\">s<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"nx\">parseFor<\/span><span class=\"p\">(<\/span><span class=\"nx\">s<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"nx\">ForExpression<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"nx\">strings<\/span><span class=\"p\">.<\/span><span class=\"nx\">HasPrefix<\/span><span class=\"p\">(<\/span><span class=\"nx\">s<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;for&quot;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"nx\">ForExpression<\/span><span class=\"p\">{<\/span><span class=\"nx\">raw<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">s<\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"nx\">parseIf<\/span><span class=\"p\">(<\/span><span class=\"nx\">s<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"nx\">IfExpression<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"nx\">strings<\/span><span class=\"p\">.<\/span><span class=\"nx\">HasPrefix<\/span><span class=\"p\">(<\/span><span class=\"nx\">s<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;if&quot;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"nx\">IfExpression<\/span><span class=\"p\">{<\/span><span class=\"nx\">raw<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"nx\">s<\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now, we have a more generalized <code>parse<\/code> function that tries to parse an <code>if<\/code>\nexpression, and falls back on parsing a <code>for<\/code> expression if it turns out not to\nbe an <code>if<\/code>. We then adapt our <code>main<\/code> function to make use of this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"nx\">main<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">ifExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">parse<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;if a == b&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">fmt<\/span><span class=\"p\">.<\/span><span class=\"nx\">Println<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;ifExpr&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">ifExpr<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">ifExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"p\">)<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nx\">forExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">parse<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;for a in b&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">fmt<\/span><span class=\"p\">.<\/span><span class=\"nx\">Println<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;forExpr&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">forExpr<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">forExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>And at first glance, this seems to work as expected.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>go<span class=\"w\"> <\/span>run<span class=\"w\"> <\/span>main.go<span class=\"w\"> <\/span>\nifExpr<span class=\"w\"> <\/span><span class=\"p\">&amp;<\/span><span class=\"o\">{<\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"nv\">a<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span>b<span class=\"o\">}<\/span><span class=\"w\"> <\/span><span class=\"nb\">false<\/span>\nforExpr<span class=\"w\"> <\/span><span class=\"p\">&amp;<\/span><span class=\"o\">{<\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span>a<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>b<span class=\"o\">}<\/span><span class=\"w\"> <\/span><span class=\"nb\">false<\/span>\n<\/code><\/pre><\/div>\n\n<p>But what happens when you try to parse something that is neither an <code>if<\/code> nor a\n<code>for<\/code>? We add the following to <code>main<\/code> to find out.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"nx\">notAnExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">parse<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;not an expression&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">fmt<\/span><span class=\"p\">.<\/span><span class=\"nx\">Println<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;notAnExpr&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">notAnExpr<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">notAnExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Clearly, as <code>\"not an expression\"<\/code> is neither an <code>if<\/code> expression nor a <code>for<\/code>\nexpression, both <code>parseIf<\/code> and <code>parseFor<\/code> will return <code>nil<\/code>, and as such <code>parse<\/code>\nshould return <code>nil<\/code>. But that's not <em>really<\/em> what happens.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>go<span class=\"w\"> <\/span>run<span class=\"w\"> <\/span>main.go<span class=\"w\"> <\/span>\nifExpr<span class=\"w\"> <\/span><span class=\"p\">&amp;<\/span><span class=\"o\">{<\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"nv\">a<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span>b<span class=\"o\">}<\/span><span class=\"w\"> <\/span><span class=\"nb\">false<\/span>\nforExpr<span class=\"w\"> <\/span><span class=\"p\">&amp;<\/span><span class=\"o\">{<\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span>a<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>b<span class=\"o\">}<\/span><span class=\"w\"> <\/span><span class=\"nb\">false<\/span>\nnotAnExpr<span class=\"w\"> <\/span>&lt;nil&gt;<span class=\"w\"> <\/span><span class=\"nb\">false<\/span>\n<\/code><\/pre><\/div>\n\n<p>What? <code>notAnExpr<\/code> is <code>&lt;nil&gt;<\/code>, but it does not compare true to a literal<code>nil<\/code>?\nWhat does that mean?<\/p>\n<h1 id=\"the-confusing-type-and-value-composition-of-interfaces\">The confusing type-and-value composition of interfaces<\/h1>\n<p>In Go, an interface is represented at runtime as a\n<a href=\"https:\/\/go.dev\/doc\/faq#nil_error\">type and a value<\/a>. You can think of it as a\nstruct with two fields.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">type<\/span><span class=\"w\"> <\/span><span class=\"nx\">Interface<\/span><span class=\"w\"> <\/span><span class=\"kd\">struct<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">type<\/span><span class=\"w\">  <\/span><span class=\"kt\">string<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">value<\/span><span class=\"w\"> <\/span><span class=\"kd\">interface<\/span><span class=\"p\">{}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>So, when <code>parseIf(s)<\/code> returns <code>nil<\/code>, the <code>parse(s)<\/code> function's return statement\nwraps the <code>nil<\/code> value into something like this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">Interface<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">Type<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;IfExpression&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">Value<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Armed with this knowledge, we can actually check for <code>nil<\/code> using\n<a href=\"https:\/\/pkg.go.dev\/reflect\">runtime reflection<\/a>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"nx\">IsNil<\/span><span class=\"p\">(<\/span><span class=\"nx\">value<\/span><span class=\"w\"> <\/span><span class=\"kd\">interface<\/span><span class=\"p\">{})<\/span><span class=\"w\"> <\/span><span class=\"kt\">bool<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"nx\">reflect<\/span><span class=\"p\">.<\/span><span class=\"nx\">ValueOf<\/span><span class=\"p\">(<\/span><span class=\"nx\">value<\/span><span class=\"p\">).<\/span><span class=\"nx\">IsNil<\/span><span class=\"p\">()<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"nx\">main<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">ifExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">parse<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;if a == b&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">fmt<\/span><span class=\"p\">.<\/span><span class=\"nx\">Println<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;ifExpr&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">ifExpr<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">IsNil<\/span><span class=\"p\">(<\/span><span class=\"nx\">ifExpr<\/span><span class=\"p\">))<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nx\">forExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">parse<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;for a in b&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">fmt<\/span><span class=\"p\">.<\/span><span class=\"nx\">Println<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;forExpr&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">forExpr<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">IsNil<\/span><span class=\"p\">(<\/span><span class=\"nx\">forExpr<\/span><span class=\"p\">))<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nx\">notAnExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">parse<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;a == b&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"nx\">fmt<\/span><span class=\"p\">.<\/span><span class=\"nx\">Println<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;notAnExpr&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">notAnExpr<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">IsNil<\/span><span class=\"p\">(<\/span><span class=\"nx\">notAnExpr<\/span><span class=\"p\">))<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>And running this, we now seem to have a functioning way to check for <code>nil<\/code>\ninterfaces.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nv\">ifExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span>{<span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"nv\">a<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"nv\">b<\/span>}<span class=\"w\"> <\/span><span class=\"nv\">false<\/span>\n<span class=\"nv\">forExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span>{<span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"nv\">a<\/span><span class=\"w\"> <\/span><span class=\"nv\">in<\/span><span class=\"w\"> <\/span><span class=\"nv\">b<\/span>}<span class=\"w\"> <\/span><span class=\"nv\">false<\/span>\n<span class=\"nv\">notAnExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"nv\">nil<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"nv\">true<\/span>\n<\/code><\/pre><\/div>\n\n<p>But do we really? Of course not.<\/p>\n<h1 id=\"actually-interfaces-can-also-be-completely-nil\">Actually, interfaces can also be \"completely\" <code>nil<\/code><\/h1>\n<p>Let's make this even more confusing, and refactor our <code>parse<\/code> function a bit.\nInstead of \"falling back\" on <code>parseFor<\/code>, we simply return <code>nil<\/code> explicitly if\nwe can't parse any known expression.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"nx\">parse<\/span><span class=\"p\">(<\/span><span class=\"nx\">s<\/span><span class=\"w\"> <\/span><span class=\"kt\">string<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"nx\">Expression<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"nx\">ifExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">parseIf<\/span><span class=\"p\">(<\/span><span class=\"nx\">s<\/span><span class=\"p\">);<\/span><span class=\"w\"> <\/span><span class=\"nx\">ifExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">!=<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"nx\">ifExpr<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"k\">else<\/span><span class=\"w\"> <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"nx\">forExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">parseFor<\/span><span class=\"p\">(<\/span><span class=\"nx\">s<\/span><span class=\"p\">);<\/span><span class=\"w\"> <\/span><span class=\"nx\">forExpr<\/span><span class=\"w\"> <\/span><span class=\"o\">!=<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"nx\">forExpr<\/span><span class=\"w\"> <\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now let's run it again.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>go<span class=\"w\"> <\/span>run<span class=\"w\"> <\/span>main.go<span class=\"w\"> <\/span>\nifExpr<span class=\"w\"> <\/span><span class=\"p\">&amp;<\/span><span class=\"o\">{<\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"nv\">a<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span>b<span class=\"o\">}<\/span><span class=\"w\"> <\/span><span class=\"nb\">false<\/span>\nforExpr<span class=\"w\"> <\/span><span class=\"p\">&amp;<\/span><span class=\"o\">{<\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span>a<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>b<span class=\"o\">}<\/span><span class=\"w\"> <\/span><span class=\"nb\">false<\/span>\npanic:<span class=\"w\"> <\/span>reflect:<span class=\"w\"> <\/span>call<span class=\"w\"> <\/span>of<span class=\"w\"> <\/span>reflect.Value.IsNil<span class=\"w\"> <\/span>on<span class=\"w\"> <\/span>zero<span class=\"w\"> <\/span>Value\n<\/code><\/pre><\/div>\n\n<p>Suddenly, <code>notAnExpr<\/code> <em>is<\/em> <code>nil<\/code>, causing our check to panic. What in the world\nis going on here? As it turns out, explicitly returning <code>nil<\/code> from a function\nthat returns an interface is semantically different to returning a <a href=\"https:\/\/go.dev\/doc\/faq#nil_error\">variable\ncontaning <code>nil<\/code> value, and typed with something implementing the\ninterface<\/a>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ actually returns nil<\/span>\n\n<span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"nx\">ForExpression<\/span><span class=\"w\"> <\/span><span class=\"p\">=<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span>\n<span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ returns an interface with type *ForExpression and value nil<\/span>\n<\/code><\/pre><\/div>\n\n<p>So a way around this is of course to always return <code>nil<\/code> in the form of a typed\nvariable. But I'm not satisfied with that, because even if I'm very strict\nabout it myself, others may not be. And I may also just make an honest mistake.\nSo let's tweak our <code>IsNil()<\/code> function to account for true <code>nil<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"nx\">IsNil<\/span><span class=\"p\">(<\/span><span class=\"nx\">value<\/span><span class=\"w\"> <\/span><span class=\"kd\">interface<\/span><span class=\"p\">{})<\/span><span class=\"w\"> <\/span><span class=\"kt\">bool<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"nx\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"w\"> <\/span><span class=\"o\">||<\/span><span class=\"w\"> <\/span><span class=\"nx\">reflect<\/span><span class=\"p\">.<\/span><span class=\"nx\">ValueOf<\/span><span class=\"p\">(<\/span><span class=\"nx\">value<\/span><span class=\"p\">).<\/span><span class=\"nx\">IsNil<\/span><span class=\"p\">()<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you run this, you'll see that the runtime panic is replaced with the\nfollowing.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>notAnExpr &lt;nil&gt; true\n<\/code><\/pre><\/div>\n\n<p>So we're done? Unfortunately, not quite.<\/p>\n<h1 id=\"structs-are-a-problem\">Structs are a problem<\/h1>\n<p>Our <code>IsNil()<\/code> handles true <code>nil<\/code> and interfaces with <code>nil<\/code> values. But,\nunfortunately, it does not handle structs.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">IfExpression<\/span><span class=\"p\">{<\/span><span class=\"nx\">raw<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;if&quot;<\/span><span class=\"p\">}<\/span>\n<span class=\"nx\">fmt<\/span><span class=\"p\">.<\/span><span class=\"nx\">Println<\/span><span class=\"p\">(<\/span><span class=\"nx\">IsNil<\/span><span class=\"p\">(<\/span><span class=\"nx\">value<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ panic: reflect: call of reflect.Value.IsNil on struct Value<\/span>\n<\/code><\/pre><\/div>\n\n<p>Poop. It appears we missed a critical part of\n<a href=\"https:\/\/pkg.go.dev\/reflect#Value.IsNil\"><code>IsNil()<\/code>'s documentation<\/a>.\nAnd by missed, I of course mean that we didn't read it, but here's the relevant\npart.<\/p>\n<blockquote>\n<p>IsNil reports whether its argument v is nil. The argument must be a chan,\nfunc, interface, map, pointer, or slice value; if it is not, IsNil panics.<\/p>\n<\/blockquote>\n<p>So, we need to check if the value is of any of these <code>nil<\/code>-able types,\nand otherwise assume that it is not <code>nil<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">func<\/span><span class=\"w\"> <\/span><span class=\"nx\">IsNil<\/span><span class=\"p\">(<\/span><span class=\"nx\">value<\/span><span class=\"w\"> <\/span><span class=\"kd\">interface<\/span><span class=\"p\">{})<\/span><span class=\"w\"> <\/span><span class=\"kt\">bool<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"nx\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"kc\">nil<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"kc\">true<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"nx\">reflected<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">reflect<\/span><span class=\"p\">.<\/span><span class=\"nx\">ValueOf<\/span><span class=\"p\">(<\/span><span class=\"nx\">value<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">switch<\/span><span class=\"w\"> <\/span><span class=\"nx\">reflected<\/span><span class=\"p\">.<\/span><span class=\"nx\">Kind<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">case<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">reflect<\/span><span class=\"p\">.<\/span><span class=\"nx\">Chan<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">reflect<\/span><span class=\"p\">.<\/span><span class=\"nx\">Func<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">reflect<\/span><span class=\"p\">.<\/span><span class=\"nx\">Interface<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">reflect<\/span><span class=\"p\">.<\/span><span class=\"nx\">Map<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">reflect<\/span><span class=\"p\">.<\/span><span class=\"nx\">Ptr<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">reflect<\/span><span class=\"p\">.<\/span><span class=\"nx\">Slice<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"nx\">reflected<\/span><span class=\"p\">.<\/span><span class=\"nx\">IsNil<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>And with this, the panic is abated.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nx\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">:=<\/span><span class=\"w\"> <\/span><span class=\"nx\">IfExpression<\/span><span class=\"p\">{<\/span><span class=\"nx\">raw<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;if&quot;<\/span><span class=\"p\">}<\/span>\n<span class=\"nx\">fmt<\/span><span class=\"p\">.<\/span><span class=\"nx\">Println<\/span><span class=\"p\">(<\/span><span class=\"nx\">IsNil<\/span><span class=\"p\">(<\/span><span class=\"nx\">value<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ false<\/span>\n<\/code><\/pre><\/div>\n\n<p>This will work so long as Go doesn't add some other <code>nil<\/code>-able type. Given how\nconservative the language is, such an addition to the core types seems an\nunlikely prospect. But of course, it could happen, and then this function would\nreturn <code>false<\/code> incorrectly in some cases.<\/p>\n<h1 id=\"footguns\">Footguns<\/h1>\n<p>All languages have <a href=\"https:\/\/en.wiktionary.org\/wiki\/footgun\">footguns<\/a>. Some\nlanguages, like C++ and JavaScript, are seemingly built exclusively of them.\nGo is a small-ish and conservative language, and so naturally has fewer such\ncontraptions. But how <code>nil<\/code> is handled differently in different contexts and how\nthe type of a variable can change the actual value that's returned from a\nfunction, is a big one.<\/p>\n<p>Of course, all of this may just be symptoms of my not knowing Go very well, and\nthis whole article could just be the frustrated ramblings of an apprentice. But,\nI'm an experienced programmer, and this confused me quite a bit. That alone\nshould be sufficient evidence that some design choices made here aren't optimal.<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"go"}},{"@attributes":{"term":"nil"}},{"@attributes":{"term":"null"}},{"@attributes":{"term":"software engineering"}}]},{"title":"Book Review: Writing an Interpreter in Go","link":{"@attributes":{"href":"https:\/\/slar.se\/book-review-writing-an-interpreter-in-go.html","rel":"alternate"}},"published":"2023-10-14T00:00:00+02:00","updated":"2023-10-14T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2023-10-14:\/book-review-writing-an-interpreter-in-go.html","summary":"<p>I love programming languages, both using them and implementing them. As such, I\nfound the concept of learning Go by creating a programming language to be just\ndelightful. And, to put it briefly, it was. Let's talk about Thorsten Ball's\nbook on interpreters. In Go.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">Writing<\/span><span class=\"w\"> <\/span><span class=\"n\">an<\/span><span class=\"w\"> <\/span><span class=\"n\">Interpreter<\/span><span class=\"w\"> <\/span><span class=\"ow\">in<\/span><span class=\"w\"> <\/span><span class=\"k\">Go \u2026<\/span><\/code><\/pre><\/div>","content":"<p>I love programming languages, both using them and implementing them. As such, I\nfound the concept of learning Go by creating a programming language to be just\ndelightful. And, to put it briefly, it was. Let's talk about Thorsten Ball's\nbook on interpreters. In Go.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">Writing<\/span><span class=\"w\"> <\/span><span class=\"n\">an<\/span><span class=\"w\"> <\/span><span class=\"n\">Interpreter<\/span><span class=\"w\"> <\/span><span class=\"ow\">in<\/span><span class=\"w\"> <\/span><span class=\"k\">Go<\/span>\n<span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">Thorsten<\/span><span class=\"w\"> <\/span><span class=\"n\">Ball<\/span>\n<span class=\"nl\">Publisher<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Thorsten<\/span><span class=\"w\"> <\/span><span class=\"n\">Ball<\/span>\n<span class=\"nl\">ISBN<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">9783982016115<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p>You can buy the book directly from Thorsten Ball's website at\n<a href=\"https:\/\/interpreterbook.com\/\">https:\/\/interpreterbook.com\/<\/a>.<\/p>\n<\/blockquote>\n<h1 id=\"the-book-in-a-nutshell\">The book in a nutshell<\/h1>\n<p><em>Writing an Interpreter in Go<\/em> is precisely what it sounds like; a practical\nguide to writing a fully functioning interpreter in Go. You go from source\ncode, to tokens, to abstract syntax tree and tree evaluation. The parser\nis based on the pretty fascinating\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Operator-precedence_parser#Pratt_parsing\"><em>Pratt parsing<\/em><\/a>\ntechnique, while the evaluation is based on simple tree-walking. This relative\nsimplicity allows Ball to cram a whole lot of functionality into a very concise\n200 pages worth of book. The result is impressive, and I am somewhat astonished\nby just how much content is actually in here, and how well written said content\nis.<\/p>\n<h1 id=\"what-i-liked\">What I liked<\/h1>\n<p>There is so much to like about this book. First of all, it is wonderfully\nstandalone. I wrote around 3500 lines of code based entirely on descriptions\nand code samples from the book's 200 printed pages. Although the source code\nfor the interpreter is available as part of the book, I never needed to\nreference it.<\/p>\n<p>Something else I just barely needed to reference was documentation for Go\nitself. While this book doesn't teach you programming and is therefore not for\ncomplete beginners, it does somewhat teach you Go by example. There are little\nto no explanations for how Go works, but due to how simple Go is I think the\nexamples speak for themselves. A caveat to that is that I have done some Go\nprogramming in the past, and I think that a complete beginner to Go should\nprobably go through the interactive <a href=\"https:\/\/go.dev\/tour\/\">A Tour of Go<\/a>\ntutorial first. The only thing that I personally needed to reference was some\ndetails around how interfaces and <code>nil<\/code> work together in Go (it's <a href=\"https:\/\/go.dev\/doc\/faq#nil_error\">really quite\nunintuitive<\/a>). It should also be noted that\nthere is nothing about concurrency in this book, which being a major selling\npoint of Go entails that this book omits some important parts of the language.\nI do however find that completely reasonable given the scope of the book.<\/p>\n<p>The book is also for the most part organized in a way that fit me very well.\nIn the first few parts of the book, the implementation is given up front and\nthen tests are added to verify the behavior. The majority of the later parts of\nthe book are however laid out in the opposite order, with descriptions of\nfunctionality and tests being followed by the actual implementation. This\nallowed me to read the tests and the descriptions to get a good idea of the\nintended behavior, and then try my own hand at coming up with a solution.\nComparing my solution to the author's after the fact was a great way to cement\nthe knowledge.<\/p>\n<p>The source code exhibits a splendid balance between proper design and being\nsimple enough to put into a book this short. There were several design decisions\nthat I did not fully agree with, especially with the parsing of strings, but I\ncan also see that certain simplifications had to be made to fit the format. For\nthe most part, I think these simplifications are well chosen.<\/p>\n<p>Concepts are explained clearly and intuitively. Pratt parsing is by far the most\ninvolved topic in the book, and I think Ball presents it in a very digestible\nfashion. I needed to run through it a couple of times and mentally step through\nthe code, but when it clicked I found no fault in how the concepts were\nexplained. At no point did I need to reference external sources to understand\nsomething.<\/p>\n<p>The last part of the book adds in a few extra features, such as arrays and hash\nmaps. All of these extra features are implemented in a very satisfying loop,\ngoing all the way from the lexing to the finished evaluation in one short\nchapter for each feature. Adding one feature at a time in this way really aids\nin understanding the workings of each part of the interpreter. And that, in\nfact, is a perfect segue to the one part of this book that I did not entirely\nlike.<\/p>\n<h1 id=\"what-i-didnt-like\">What I didn't like<\/h1>\n<p>I actually started this book around five years ago, but never finished it. In\nfact, I got just barely halfway due to what I perceive as the one flaw of this\notherwise fantastic piece of literature: it has a rather slow start. It's not\nuntil halfway through that you actually get to evaluation and thereby create a\ncomplete path from source code to output. The fantastic pacing of the last\nquarter of the book where you add features one at a time highlights that the\nfirst half isn't as satisfying as it probably could be. While I recognize that\nthe amount of groundwork to put down before getting to the exciting parts is a\ntough one to make, I think the book would have been better off closing the path\nfrom source code to evaluation earlier. For instance, I don't see any need to\nparse function definitions before evaluating arithmetic expressions.<\/p>\n<h1 id=\"conclusions\">Conclusions<\/h1>\n<p>This is a great book. It's clear, concise and packed full of learnings. Due to\nthe way the last quarter of the book is laid out, adding feature upon feature\nfrom start to finish, I was able to quite effortlessly add features completely\nof my own design by the time I finished the book. The only complaint I have\nabout the book is that not more of it is laid out in that fashion, because it's\njust so good.<\/p>\n<p>If you've dipped your toes in Go and want an exciting project to learn the\nlanguage better, I think this is a great way to do it. It takes a little while\nbefore the book gets going for real, but when it does, it really takes off.<\/p>","category":[{"@attributes":{"term":"Reviews"}},{"@attributes":{"term":"book review"}},{"@attributes":{"term":"software engineering"}},{"@attributes":{"term":"go"}}]},{"title":"Fix 3D graphics in Arch Linux on Dell XPS 15 9520","link":{"@attributes":{"href":"https:\/\/slar.se\/xps-15-9520-arch-linux-intel-dri2.html","rel":"alternate"}},"published":"2022-12-26T00:00:00+01:00","updated":"2022-12-26T00:00:00+01:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-12-26:\/xps-15-9520-arch-linux-intel-dri2.html","summary":"<p>I recently got myself a Dell XPS 15 9520 to replace my aging laptop. It's\nhighly Linux-compatible and just following the <a href=\"https:\/\/wiki.archlinux.org\/title\/Installation_guide\">official installation\nguide<\/a> got me 90% of the\nway of having a well-behaved Arch Linux laptop. One big thing wasn't working,\nthough: 3D graphics!<\/p>\n<h2 id=\"symptoms-glitchy-2d-graphics-and-unusable-3d-graphics\">Symptoms: glitchy 2D graphics and \u2026<\/h2>","content":"<p>I recently got myself a Dell XPS 15 9520 to replace my aging laptop. It's\nhighly Linux-compatible and just following the <a href=\"https:\/\/wiki.archlinux.org\/title\/Installation_guide\">official installation\nguide<\/a> got me 90% of the\nway of having a well-behaved Arch Linux laptop. One big thing wasn't working,\nthough: 3D graphics!<\/p>\n<h2 id=\"symptoms-glitchy-2d-graphics-and-unusable-3d-graphics\">Symptoms: glitchy 2D graphics and unusable 3D graphics<\/h2>\n<p>2D graphics worked mostly fine after installing <code>xf86-video-intel<\/code>, <code>nvidia<\/code> and\n<code>nvidia-prime<\/code>. Websites, most desktop applications as well as 2D games like\nTerraria worked without issue. Anything with the slightest hint of 3D would\nhowever glitch out terribly with Intel graphics and just be completely black\nwith 3D graphics.<\/p>\n<p>Some applications, such as Steam, wouldn't render properly unless in fullscreen.\n3D benchmark software like <code>fire<\/code> (from <code>mesa-demo<\/code>) and <code>glmark2<\/code> wouldn't\nupdate properly with Intel and would again be black with NVIDIA.<\/p>\n<h2 id=\"solution-using-dri2-for-the-intel-driver\">Solution: Using DRI2 for the Intel driver<\/h2>\n<p>The solution I found to this problem was to <a href=\"https:\/\/wiki.archlinux.org\/title\/Intel_graphics#DRI3_issues\">use\nDRI2 for the Intel\ndriver<\/a>. I have no\nidea of why this works, but it does. You can configure the Intel driver to use\nDRI2 by creating a configuration file for X.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code># \/etc\/X11\/xorg.conf.d\/20-intel.conf\nSection &quot;Device&quot;\n  Identifier &quot;Intel Graphics&quot;\n  Driver &quot;intel&quot;\n  Option &quot;DRI&quot; &quot;2&quot;\nEndSection\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p><strong>Note:<\/strong> The <a href=\"https:\/\/wiki.archlinux.org\/title\/Intel_graphics#Issues_with_selecting_Qt_elements_within_Plasma_Desktop_on_Alder_Lake.2FUHD_770\">modesetting driver also works<\/a>, but it interferes with PRIME offloading s.t. the NVIDIA GPU is always active. This butchers battery life and so wasn't acceptable to me.<\/p>\n<\/blockquote>\n<h2 id=\"need-more-tweaks\">Need more tweaks?<\/h2>\n<p>This wasn't the only tweak I put in to get my XPS 15 in tip-top shape, although\nit was the most crucial one. I've got a bunch of other tweaks listed <a href=\"https:\/\/slar.se\/pages\/wiki\/arch-linux-on-xps-15-9520.html\">over on\nmy Wiki page for the XPS 15<\/a>.<\/p>","category":[{"@attributes":{"term":"Blog"}},{"@attributes":{"term":"blog"}},{"@attributes":{"term":"linux"}},{"@attributes":{"term":"xps15"}}]},{"title":"Book Review: CPython Internals","link":{"@attributes":{"href":"https:\/\/slar.se\/book-review-cpython-internals.html","rel":"alternate"}},"published":"2022-11-20T00:00:00+01:00","updated":"2022-11-20T00:00:00+01:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-11-20:\/book-review-cpython-internals.html","summary":"<p>About a month ago I signed myself up to do a talk at a Python meetup hosted by\n<a href=\"https:\/\/hiq.se\/\">HiQ<\/a>. I brazenly set my topic as <em>Under the Hood of CPython<\/em>,\nthinking I had sufficient understanding of its inner workings to produce a\nriveting talk. As I started preparing the talk \u2026<\/p>","content":"<p>About a month ago I signed myself up to do a talk at a Python meetup hosted by\n<a href=\"https:\/\/hiq.se\/\">HiQ<\/a>. I brazenly set my topic as <em>Under the Hood of CPython<\/em>,\nthinking I had sufficient understanding of its inner workings to produce a\nriveting talk. As I started preparing the talk, I came to the gut-wrenching\nconclusion that my knowledge was too shallow, I simply didn't know enough of\nthe details to put together an in-depth talk on the subject. Thankfully, I knew\nwhere to turn to for the details I needed: Anthony Shaw's <em>CPython Internals<\/em>\nbook. Here's what I think of it.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>CPython Internals\nby Anthony Shaw\nReleased May 2021\nPublisher(s): Real Python (realpython.com)\nISBN: 9781775093344\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p>Confused about the difference between Python and CPython? See <a href=\"https:\/\/slar.se\/the-difference-between-python-and-cpython.html\">The difference\nbetween Python and\nCPython<\/a>.<\/p>\n<\/blockquote>\n<h1 id=\"the-book-in-a-nutshell\">The book in a nutshell<\/h1>\n<p><em>CPython Internals<\/em> gives you a guided tour of the CPython project, from\nparsing source code to compiling bytecode to interpreting said bytecode. The\nbook is meant to serve as a starting point for budding CPython contributors or\nPython developers that simply want to learn a bit more about the reference\nimplementation. It highlights the most important files in the project for each\nof the respective parts and guides you through their execution. Throughout the\nbook we also get to follow along with a worked example of extending the language\nwith an \"almost equal\" operator, written as <code>~=<\/code>.<\/p>\n<p>The book concludes with three concrete ways in which you can use the knowledge\nyou've attained: 1) creating C extensions, 2) improving existing Python programs\nby leveraging knowledge of the internals and 3) contributing to the CPython\nproject. While point 2) is potentially a little bit vague, points 1) and 3) are\nconcrete and well described.<\/p>\n<p>Before writing the book, Anthony wrote an in-depth article on the same topic.\nYou can find it over on <a href=\"https:\/\/realpython.com\/cpython-source-code-guide\/\">Real\nPython<\/a>. It is something of\nan appetizer for the book, but stands strong on its own. Having a brief look at\nthat article will give you a better understanding of what the book is about\nthan anything I could write here.<\/p>\n<h1 id=\"what-i-liked\">What I liked<\/h1>\n<p>I went from surface-level understanding of the CPython project to being pretty\nconfident about where to poke around to do what just from reading this book.\nIt's comprehensive in scope and the worked example of the <code>~=<\/code> operator helps <em>a\nlot<\/em> in facilitating an understanding for how to extend CPython with your own\nsilly things.<\/p>\n<p>I also appreciated the nods to other respectable sources. The <a href=\"https:\/\/devguide.python.org\/\">Python\nDeveloper's Guide<\/a> is a great resource for quickly\nrefreshing how to do something (but going from 0 knowledge about the project\nit's a bit to terse). Luciano Ramalho's book <a href=\"https:\/\/www.oreilly.com\/library\/view\/fluent-python-2nd\/9781492056348\/\">Fluent Python 2nd\ned<\/a> is\nalso noted as an excellent reference on the Python object model, which I\nabsolutely agree with.<\/p>\n<p>There is enough context in each chapter that you don't really need much\npre-existing understanding of any of the subjects. If you can read Python code\nand have a little bit of experience with reading C code, you're all good to go.\nConcepts relevant to the book such as parallelism and memory management are\nexplained both on an abstract level and in how they are implemented in CPython.\nThe book is to a great extent a standalone resource and it should be very\napproachable even to developers without much experience. There's even an\nappendix at the end to explain what little you need to know about the C\nprogramming language to be able to understand the code samples.<\/p>\n<h1 id=\"what-i-didnt-like\">What I didn't like<\/h1>\n<p>There was nothing about the book that I thought was <em>bad<\/em>, but for me\npersonally, I would have preferred less explanation of fundamental concepts\n(such as threading), and more in-depth details on CPython itself. That being\nsaid, I think Anthony overall has made good calls on the tradeoffs between depth\nand approachability. Given that the book is meant to be a starting point for\nCPython development as opposed to a complete reference, I think that this\nnit-pick of mine is nothing more than personal preference, and perhaps that I'm\nslightly outside the target audience of the book. It's clearly meant to contain\neverything you'd need to know to go from zero to hero, and it's a lot easier to\nskip over content you feel is redundant than it is to find content you didn't\nknow you needed.<\/p>\n<h1 id=\"conclusions\">Conclusions<\/h1>\n<p>CPython Internals saved my neck. I had three weeks to go from a shallow\nunderstanding of the CPython project to being able to explain it to others in a\n~30-minute talk, and <a href=\"https:\/\/github.com\/slarse\/talks\/tree\/80503786d4587abdadba9913c55c7d133269f3a2\/under-the-hood-of-cpython\">I made\nit<\/a>.\nWithout this book I wouldn't have. It was so approachable that I could use it\nfor \"Sunday reading\" before bedtime and in spare minutes on public transport.<\/p>\n<p>I highly recommend this book to anyone who's interested in the CPython project.\nIt's not necessary to have future CPython contributions as a goal to get a lot\nout of this book, I found it incredibly interesting in its own right. The fact\nthat Anthony has managed to pack so much information, with so much context\n(recall that I thought there was too much of that) in less than 400 pages is\nnothing short of spectacular.<\/p>","category":[{"@attributes":{"term":"Reviews"}},{"@attributes":{"term":"book review"}},{"@attributes":{"term":"software engineering"}},{"@attributes":{"term":"python"}}]},{"title":"The difference between Python and CPython","link":{"@attributes":{"href":"https:\/\/slar.se\/the-difference-between-python-and-cpython.html","rel":"alternate"}},"published":"2022-11-19T00:00:00+01:00","updated":"2022-11-19T00:00:00+01:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-11-19:\/the-difference-between-python-and-cpython.html","summary":"<p>At one point or another, every Python developer or hobbyist encounters the word\n<em>CPython<\/em>. For example, the <a href=\"https:\/\/docs.python.org\/3\/library\/dis.html\">dis\nmodule<\/a> states that it exposes an\n\"implementation detail of the CPython interpreter\". What does that mean?\nSome ask themselves how CPython differs from Python, and then\nthey move on with their lives \u2026<\/p>","content":"<p>At one point or another, every Python developer or hobbyist encounters the word\n<em>CPython<\/em>. For example, the <a href=\"https:\/\/docs.python.org\/3\/library\/dis.html\">dis\nmodule<\/a> states that it exposes an\n\"implementation detail of the CPython interpreter\". What does that mean?\nSome ask themselves how CPython differs from Python, and then\nthey move on with their lives without ever getting to the bottom of it. But if\nyou're one of the curious ones who couldn't put that thought down, this article\nis for you.<\/p>\n<h1 id=\"python-is-a-language-specification\">Python is a language specification<\/h1>\n<p>Python is a programming language. A programming language is an abstract concept.\nIt's fundamentally a set of rules saying what you're allowed to write in the\nlanguage, the <em>syntax<\/em> of the language, and another set of rules saying what\nshould happen if you execute some (syntactically valid) code, the <em>semantics<\/em> of\nthe language.<\/p>\n<p>For example, take the <a href=\"https:\/\/docs.python.org\/3\/reference\/simple_stmts.html#the-pass-statement\"><code>pass<\/code>\nstatement<\/a>.\nThe syntax of the <code>pass<\/code> statement is incredibly simple, it's just the keyword\n<code>pass<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nv\">pass_stmt<\/span><span class=\"w\"> <\/span><span class=\"o\">::=<\/span><span class=\"w\">  <\/span><span class=\"s\">&quot;pass&quot;<\/span>\n<\/code><\/pre><\/div>\n\n<p>The semantics are equally simple.<\/p>\n<blockquote>\n<p>pass is a null operation \u2014 when it is executed, nothing happens. It is useful\nas a placeholder when a statement is required syntactically, but no code needs\nto be executed, [...]<\/p>\n<\/blockquote>\n<p>For example:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">funtion_that_does_nothing<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">pass<\/span>\n<\/code><\/pre><\/div>\n\n<p>The pass statement could be <em>implemented<\/em> in any number of ways. It could\ncorrespond to a NOOP instruction that when executed does nothing. It could also\ncorrespond to <em>nothing<\/em>, i.e. no instruction is generated for it. There are\nreally endless possibilities in producing the semantic behavior described by the\nPython language reference.<\/p>\n<h1 id=\"cpython-is-an-implementation-of-the-python-language-specification\">CPython is an implementation of the Python language specification<\/h1>\n<p>CPython is an implementation of the Python language specification. In fact, it\nis the <a href=\"https:\/\/wiki.python.org\/moin\/CPython\"><em>reference<\/em> implementation<\/a>,\nmeaning that its runtime semantics are the law. It is necessarily the case that\nnot all runtime semantics are precisely described in the Python documentation,\nand then whatever CPython does is considered the desired behavior. Unless, of\ncourse, it is identified as a bug in the runtime.<\/p>\n<p>When it comes to the <code>pass<\/code> statement, CPython takes the \"nothing\" approach of\nnot generating an instruction. This has less overhead than generating and\nexecuting a NOOP instruction. However, as the <em>effect<\/em> of those two approaches\nare the same, it would be equally correct to take the NOOP instruction approach.\nSo CPython is a reference for what happens when you execute some code, not <em>how<\/em>\nthat happens.<\/p>\n<p>There are <a href=\"https:\/\/wiki.python.org\/moin\/PythonImplementations?action=show&amp;redirect=implementation\">other\nimplementations<\/a>\nof the Python programming language, such as <a href=\"https:\/\/www.pypy.org\/\">PyPy<\/a>. It is fundamentally different\nto CPython in a variety of ways. For one, PyPy is implemented in Python, whereas\nCPython is to a large extent implemented in C. PyPy also employs a JIT\n(just-in-time) compiler that can compile hot code to machine code to\nsubstantially speed up running times, often making it <a href=\"https:\/\/speed.pypy.org\/\">substantially faster than\nCPython<\/a>.<\/p>\n<h1 id=\"closing-words\">Closing words<\/h1>\n<p>The difference between Python and CPython is that the former is a language\nspecification while the latter is an implementation of said language\nspecification. However, in most everyday conversations among developers, they\nare one and the same. There is also the fact that CPython being the reference\nimplementation makes it part of the specification of the language. Python as a\nprogramming language and CPython as an implementation are to some extent\nmutually dependent: you can't really define one without the other.<\/p>\n<p>Distinguishing at all between the two may seem nit-picky, and in the vast\nmajority of cases I'd argue it is. But when module documentation mentions\nimplementation details of CPython or you find mentions of other implementations\naltogether, the distinction becomes important for it all to make sense.\nFor me personally, just the urge to understand why two different words were used\nfor seemingly the same thing was enough of a justification to dig into it, but\nI'm also hoping that this article brings more sense into the Python worlds of\nothers.<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"python"}}]},{"title":"The pre Python 2.5 ternary operator hack","link":{"@attributes":{"href":"https:\/\/slar.se\/python-24-ternary.html","rel":"alternate"}},"published":"2022-11-06T00:00:00+01:00","updated":"2022-11-06T00:00:00+01:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-11-06:\/python-24-ternary.html","summary":"<p>The modern day ternary operator is well-known to most Pythonistas:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&lt;<\/span><span class=\"n\">expr_if_true<\/span><span class=\"o\">&gt;<\/span> <span class=\"k\">if<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">condition<\/span><span class=\"o\">&gt;<\/span> <span class=\"k\">else<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">expr_if_false<\/span><span class=\"o\">&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>It's officially known as a <em>conditional expression<\/em> and was introduced\nback in Python 2.5 with <a href=\"https:\/\/www.regular-expressions.info\/atomic.html\">PEP\n308<\/a>. Some like it, some\ndon't, and while discussing it with a colleague of mine he mentioned that \u2026<\/p>","content":"<p>The modern day ternary operator is well-known to most Pythonistas:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&lt;<\/span><span class=\"n\">expr_if_true<\/span><span class=\"o\">&gt;<\/span> <span class=\"k\">if<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">condition<\/span><span class=\"o\">&gt;<\/span> <span class=\"k\">else<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">expr_if_false<\/span><span class=\"o\">&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>It's officially known as a <em>conditional expression<\/em> and was introduced\nback in Python 2.5 with <a href=\"https:\/\/www.regular-expressions.info\/atomic.html\">PEP\n308<\/a>. Some like it, some\ndon't, and while discussing it with a colleague of mine he mentioned that there\n\"used to be something a whole lot worse\" around the code bases written by\ndevelopers favoring ternary operators. He couldn't remember what it looked like\nas these events are <a href=\"https:\/\/peps.python.org\/pep-0356\/\">15 years in the past<\/a>,\nbut a few days later he came back to me with a code snippet like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">[<\/span><span class=\"s2\">&quot;nope&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;yep&quot;<\/span><span class=\"p\">][<\/span><span class=\"kc\">False<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>What?<\/p>\n<h2 id=\"no-ternary-operator-you-say\">No ternary operator you say?<\/h2>\n<p>Developers are creative and opinionated. Sometimes this mix leads to\nmonstrosities, such as when creative developers who really liked ternaries\ncreated this pattern:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">[<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">expr_if_false<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">,<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">expr_if_true<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">][<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">condition<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>You're reading that right. It's a list with two elements, the first of which\nis returned if the condition is <code>False<\/code> and the second if it's <code>True<\/code>. Here is\nan example:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">condition<\/span> <span class=\"o\">=<\/span> <span class=\"kc\">True<\/span>\n\n<span class=\"n\">message_modern<\/span> <span class=\"o\">=<\/span> <span class=\"s2\">&quot;success&quot;<\/span> <span class=\"k\">if<\/span> <span class=\"n\">condition<\/span> <span class=\"k\">else<\/span> <span class=\"s2\">&quot;failure&quot;<\/span>\n<span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"n\">message_modern<\/span><span class=\"p\">)<\/span>   <span class=\"c1\"># success<\/span>\n\n<span class=\"n\">message_old<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span><span class=\"s2\">&quot;failure&quot;<\/span><span class=\"p\">,<\/span> <span class=\"s2\">&quot;success&quot;<\/span><span class=\"p\">][<\/span><span class=\"n\">condition<\/span><span class=\"p\">]<\/span>\n<span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"n\">message_old<\/span><span class=\"p\">)<\/span>      <span class=\"c1\"># success<\/span>\n<\/code><\/pre><\/div>\n\n<p>This will make perfect sense to a C programmer: <code>True<\/code> and <code>1<\/code> are\ninterchangeable, as are <code>False<\/code> and <code>0<\/code>. And that's precisely how this works,\nthe underlying <a href=\"https:\/\/github.com\/python\/cpython\/blob\/2db55e0c0069a928775fa819973a76f840c5ab5a\/Objects\/listobject.c#L242-L255\">function that implements the list index\naccess<\/a>\nperforms some rudimentary checks and then just uses the provided index as an\noffset to the base pointer of the list.<\/p>\n<h2 id=\"but-the-hack-isnt-quite-the-same\">But the hack isn't quite the same<\/h2>\n<p>At first glance, it may seem like the old hack with the list is functionally\nequivalent to the modern ternary operator. It isn't quite, though, because it\nlacks one very important property: lazy evaluation of the branches. In short,\nthe ternary operator only evaluates the branch that it returns. Here's an\nexample:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">condition<\/span> <span class=\"o\">=<\/span> <span class=\"kc\">False<\/span>\n\n<span class=\"n\">result_modern<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">1<\/span> <span class=\"o\">\/<\/span> <span class=\"mi\">0<\/span> <span class=\"k\">if<\/span> <span class=\"n\">condition<\/span> <span class=\"k\">else<\/span> <span class=\"mi\">42<\/span>\n<span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"n\">result_modern<\/span><span class=\"p\">)<\/span> <span class=\"c1\"># 42<\/span>\n\n<span class=\"n\">result_old<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span><span class=\"mi\">42<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span> <span class=\"o\">\/<\/span> <span class=\"mi\">0<\/span><span class=\"p\">][<\/span><span class=\"n\">condition<\/span><span class=\"p\">]<\/span> <span class=\"c1\"># raises ZeroDivisionError: division by zero<\/span>\n<span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"n\">result_old<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>The ternary operator does not result in a crash on division by zero as it does\nnot evaluate the expression in the true-branch, whereas the old hack crashes\nimmediately as it first evaluates both expressions and then returns one of them.\nTo fully emulate the modern behavior we'd need something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">condition<\/span> <span class=\"o\">=<\/span> <span class=\"kc\">False<\/span>\n\n<span class=\"n\">result_old<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span><span class=\"k\">lambda<\/span><span class=\"p\">:<\/span> <span class=\"mi\">42<\/span><span class=\"p\">,<\/span> <span class=\"k\">lambda<\/span><span class=\"p\">:<\/span> <span class=\"mi\">1<\/span> <span class=\"o\">\/<\/span> <span class=\"mi\">0<\/span><span class=\"p\">][<\/span><span class=\"n\">condition<\/span><span class=\"p\">]()<\/span>\n<span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"n\">result_old<\/span><span class=\"p\">)<\/span> <span class=\"c1\"># 42<\/span>\n<\/code><\/pre><\/div>\n\n<p>Here we get lazy evaluation by virtue of wrapping the two branches in lambdas,\nand then executing the lambda that's returned. I think we can all agree that's\nnot a pretty sight.<\/p>\n<h2 id=\"conditional-expressions-are-a-good-thing\">Conditional expressions are a good thing<\/h2>\n<p>Regardless of your stance on using ternary operators (or conditional\nexpressions, as they're called in Python), it's probably a good thing they\nexist. Otherwise creative and opinionated programmers get around to hacks to\nemulate the behavior that end up being completely unreadable to others.<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"python"}}]},{"title":"Why I write a blog that nobody reads (and you should, too)","link":{"@attributes":{"href":"https:\/\/slar.se\/why-i-write-a-blog-that-nobody-reads-and-you-should-too.html","rel":"alternate"}},"published":"2022-10-29T00:00:00+02:00","updated":"2022-10-29T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-10-29:\/why-i-write-a-blog-that-nobody-reads-and-you-should-too.html","summary":"<p>I don't write this blog in hopes that it will get a lot of traction. I don't\nmarket it, I don't try to optimize it for SEO and I I don't even tell my\nfriends and coworkers about it. Although I would of course be delighted to hear\nsomeone who \u2026<\/p>","content":"<p>I don't write this blog in hopes that it will get a lot of traction. I don't\nmarket it, I don't try to optimize it for SEO and I I don't even tell my\nfriends and coworkers about it. Although I would of course be delighted to hear\nsomeone who found something useful in my blog, I really write it for myself.\nAnd what could I possibly get out of that? Glad you asked.<\/p>\n<h2 id=\"expressing-thoughts-and-ideas-is-hard\">Expressing thoughts and ideas is hard<\/h2>\n<p>I'm a software engineer. My job is mostly about coming up with neat solutions to\ntricky problems. Coming up with the solution in my head is however just part of\nthe fight as I also need to be able to concisely express the ideas to my\ncolleagues. Even harder is to convey the heart of a technical problem or\nsolution to a non-technical person, which happens more often than you might\nthink. For example, a manager might come around and inquire about why something\nstill isn't working as it should or why project X got so expensive.<\/p>\n<p>Writing a technical blog about helps me practice this skill. I put quite a bit\nof care into most blog posts I write and I also often look back at earlier posts\nto consider how I can improve the writing.<\/p>\n<h2 id=\"retaining-knowledge-is-also-hard\">Retaining knowledge is also hard<\/h2>\n<p>Another reason for why I write this blog is to retain knowledge. Writing about\nsomething you've just learned is a great way to further cement that knowledge.\nAs I put a large amount of care into my posts and want to be sure that I get\nthings right, I also often pick up bits and pieces that I missed when attaining\nthe knowledge I'm writing about.<\/p>\n<p>As I noted in <a href=\"https:\/\/slar.se\/introducing-my-wiki.html\">the post about my new\nWiki<\/a>, my strive toward high quality\nposts does unfortunately mean that I don't publish blog posts all that often.\nThat's where the <a href=\"https:\/\/slar.se\/pages\/wiki.html\">Wiki<\/a> comes in. In there I\nsimply write things down without any particular care about quality. I can\nthereby help myself retain knowledge about things that I don't yet understand\nwell enough to write a blog post about, or that I simply don't have the time\nto write about.<\/p>\n<h2 id=\"putting-yourself-out-there-is-perhaps-even-harder\">Putting yourself out there is perhaps even harder<\/h2>\n<p>Exposing your work to the public is not something most people are comfortable\nwith. It's easy to feel self-conscious about the things you create and be afraid\nof potential backlash or negative feedback. Putting up blog posts strengthens my\nconfidence when it comes to communicating and expressing myself, even if I don't\ntypically get any direct feedback (be that positive or negative) due to not\nhaving comments on this site. Similarly, putting up <a href=\"https:\/\/github.com\/slarse\">my projects on\nGitHub<\/a> strengthens my confidence in my technical\nskills.<\/p>\n<p>Having published my work for many years I now feel little to no anxiety about\npublishing my work. Rather, I find it enjoyable to put something out in the open\nwhere others may find it, even if few ever do.<\/p>","category":[{"@attributes":{"term":"Blog"}},{"@attributes":{"term":"blog"}}]},{"title":"Introducing my Wiki!","link":{"@attributes":{"href":"https:\/\/slar.se\/introducing-my-wiki.html","rel":"alternate"}},"published":"2022-10-24T00:00:00+02:00","updated":"2022-10-24T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-10-24:\/introducing-my-wiki.html","summary":"<p>A while ago, I decided that I wanted to have a low-effort way of recording what\nI learn out in the open. When I publish a blog post I feel compelled to keep\nthe standard of the writing on a fairly high level. I've started dozens of\narticles that I \u2026<\/p>","content":"<p>A while ago, I decided that I wanted to have a low-effort way of recording what\nI learn out in the open. When I publish a blog post I feel compelled to keep\nthe standard of the writing on a fairly high level. I've started dozens of\narticles that I never published because I couldn't massage them into a state\nthat meeting my own standards. And that's not even counting the hundreds\nof articles that I never even started because it seemed like too much of an\neffort to record a tiny learning experience.<\/p>\n<p>This strongly goes against the <em>Record What You Learn<\/em> an <em>Share What You\nLearn<\/em> patterns from <a href=\"https:\/\/slar.se\/book-review-apprenticeship-patterns.html\">Apprenticeship\nPatterns<\/a>; two patterns\nthat I value highly. Enter the Wiki!<\/p>\n<h1 id=\"my-public-wiki\">My public Wiki<\/h1>\n<p>The <a href=\"https:\/\/slar.se\/pages\/wiki.html\">Wiki<\/a> can be reached from the menu bar at the\ntop of the page. Here, I jot down quick notes about what I learn, what I have\nyet to learn and anything else that I feel is worth recording. The quality of\nthe writing will range from poor to worse, and it'll be haphazardly organized,\nat least initially. I hope to turn this into a wealth of knowledge both for\nmyself and for others in the coming years.<\/p>\n<h2 id=\"why-not-use-an-established-wiki-software\">Why not use an established Wiki software?<\/h2>\n<p>Although there are several open source Wikis out there, such as\n<a href=\"https:\/\/xwiki.org\">XWiki<\/a>, they're usually quite heavy and require a backend.\nThis site is a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Static_web_page\">static site<\/a>,\nwhich is very cheap to host and requires no particular security considerations\ndue to the lack of a backend. I quite like those properties, and I'm currently\nadapting the templates for this site to better suit my Wiki ambitions. This\nfirst rendition is <em>rough<\/em>, but it suits my current needs, and improving upon\nit as my Wiki grows wll be an interesting challenge.<\/p>\n<h2 id=\"searching-the-wiki\">Searching the Wiki<\/h2>\n<p>The <a href=\"https:\/\/slar.se\/pages\/wiki.html\">Wiki<\/a> is indexed along with the rest of the site\nand can be searched using the <a href=\"https:\/\/slar.se\/pelican-search.html\">search bar<\/a> on\nthe <a href=\"https:\/\/slar.se\/index.html\">home page<\/a>. In other words, you can search for anything on\nthis website through that single search bar!<\/p>\n<h2 id=\"going-forward\">Going forward<\/h2>\n<p>I intend to keep improving the wiki. As the amount of content grows, I expect to\nhave to improve the layout, cross-document linking and other related features.\nI'm very excited to finally get around to this as I've been thinking about it\nfor a long time. Even though I do hope others will find it useful, it's mostly\nfor my own gain, and I'm confident it will serve me well.<\/p>","category":[{"@attributes":{"term":"Blog"}},{"@attributes":{"term":"blog"}}]},{"title":"Book Review: The Rust Programming Language","link":{"@attributes":{"href":"https:\/\/slar.se\/book-review-the-rust-programming-language.html","rel":"alternate"}},"published":"2022-08-10T00:00:00+02:00","updated":"2022-08-10T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-08-10:\/book-review-the-rust-programming-language.html","summary":"<p>I've been learning Rust on and off for the past few months, and <em>The Rust\nProgramming Language<\/em> has been my <a href=\"https:\/\/slar.se\/learning-a-new-programming-language.html\">primary learning\nresource<\/a> during this time.\nIt's a great introduction to the language, and is even <a href=\"https:\/\/doc.rust-lang.org\/stable\/book\/\">freely available\nonline<\/a>.<\/p>\n<p>Here, I'm reviewing the 2018 print version. Although a little bit \u2026<\/p>","content":"<p>I've been learning Rust on and off for the past few months, and <em>The Rust\nProgramming Language<\/em> has been my <a href=\"https:\/\/slar.se\/learning-a-new-programming-language.html\">primary learning\nresource<\/a> during this time.\nIt's a great introduction to the language, and is even <a href=\"https:\/\/doc.rust-lang.org\/stable\/book\/\">freely available\nonline<\/a>.<\/p>\n<p>Here, I'm reviewing the 2018 print version. Although a little bit out of date by\nnow, there's nothing that's become obsolete, so I can still recommend even this\nversion. For the most up to date version, the online one is however the way to\ngo.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>The Rust Programming Language\nby Steve Klabnik, Carol Nichols\nReleased June 2018\nPublisher(s): No Starch Press\nISBN: 9781593278281\n<\/code><\/pre><\/div>\n\n<h1 id=\"the-book-in-a-nutshell\">The book in a nutshell<\/h1>\n<p><em>The Rust Programming Language<\/em> is really a book where the title perfectly\ncaptures what the book is about. It teaches Rust mostly by practical examples,\nand for the most part the examples are self-contained and executable. For some\nconcepts, examples are either missing or more illustrative than executable, but\nthese are few and far between.<\/p>\n<p>The book also to a large extent explains programming concepts, and has a rather\nelaborate section on concurrency. It however isn't on a beginner level, and\ndoesn't go out of its way to intuitively describe what a variable is, or how\nlooping works. I would rate this a great book for someone who is already\nsomewhat familiar with programming concepts, but it's not the best resource for\ngetting started with programming as a whole. It's the perfect \"second language\nbook\".<\/p>\n<h1 id=\"what-i-liked\">What I liked<\/h1>\n<p>This book is incredibly well written and organized. Concepts to be learned are\nfirst presented on a high level, and then the authors drill into the details.\nBut not too far into the details; at several points we are referred to other\nresources to acquire a deeper understanding for certain concepts. It's also a\ngreat standalone resource for learning Rust as it covers surrounding tooling\nlike <code>rustup<\/code> and <code>cargo<\/code> in addition to the language itself. You can learn Rust\nto a decent level of proficiency from this book alone.<\/p>\n<p>The well thought out pacing of the book carries over to the code samples, which\nare excellent through-and-through. There are some rather tricky concepts to get\nyour head around in Rust compared to other programming languages, and the code\nsamples are crucial in getting the point across. These are also presented in a\ntop down fashion. By that, I mean that the higher level code is presented first\ncontaining calls to yet to be defined functions that are presented later. <\/p>\n<p>As a crude example, imagine that we want to present a program that adds two\nnumbers and prints the result. That may look like so:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">fn<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">sum<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">add<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"fm\">println!<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;{}&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">sum<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>And then we define the <code>add<\/code> function after having presented the high-level idea\nwe want to implement:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">fn<\/span><span class=\"w\"> <\/span><span class=\"nf\">add<\/span><span class=\"p\">(<\/span><span class=\"n\">lhs<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">i32<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">rhs<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">i32<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kt\">i32<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">lhs<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"n\">rhs<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This top down approach to presenting code samples really helps in getting a good\nidea for <em>what<\/em> needs to be done before <em>how<\/em> it is actually implemented. I\nstrongly prefer this approach to a bottom up one, where you start with the low\nlevel <em>how<\/em> before getting to the high level <em>what<\/em>.<\/p>\n<p>The book ends with a project on building a multithreaded web server, which is\nmeant to solidify many of the concepts taught throughout the book. It's a great\nway to close out a great book.<\/p>\n<h1 id=\"what-i-didnt-like\">What I didn't like<\/h1>\n<p>This is my first book review where I can't come up with something that I overtly\ndid not like about a book. There are things the book lacks, such as more\nbeginner-friendly introductions to core programming concepts, but I feel that's\nby design rather than thoughtless omission. The book would simply be way too\nlong if it had to include such things as well.<\/p>\n<p>Perhaps I will find something to be annoyed with as I revisit this in the\nfuture, but as it stands I am completely pleased with my reading experience.<\/p>\n<h1 id=\"conclusions\">Conclusions<\/h1>\n<p>This is a great book to learn the Rust programming language. It's not\nappropriate for absolute beginners, but I think that may be simply a consequence\nof Rust being designed to tackle rather advanced problems. I would not\nrecommend a budding programmer to start out with Rust, and so it seems\ncompletely natural to me that the official learning resource doesn't cater toward\nsuch a crowd. That being said, you don't need to be a seasoned programmer\nto get value out of this book, as concepts are explained with quite a lot of\n\"backstory\". You don't need to be overly familiar with the problems Rust\nattempts to solve (memory safety, for example) as the book clearly exemplifies\nthe problems before outlining the solutions.<\/p>\n<p>As <em>The Rust Programming Language<\/em> is <a href=\"https:\/\/doc.rust-lang.org\/stable\/book\/\">freely available\nonline<\/a>, I whole-heartedly recommend it\nfor those looking to dive into Rust. I see no good reason to go looking\nelsewhere for resources when there's such a great one staring you right in the\nface. This is <em>the<\/em> starting place for a prospective Rustacean!<\/p>","category":[{"@attributes":{"term":"Reviews"}},{"@attributes":{"term":"book review"}},{"@attributes":{"term":"software engineering"}},{"@attributes":{"term":"rust"}}]},{"title":"Book Review: 97 Things Every Programmer Should Know","link":{"@attributes":{"href":"https:\/\/slar.se\/book-review-97-things.html","rel":"alternate"}},"published":"2022-07-11T21:00:48+02:00","updated":"2022-07-11T21:00:48+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-07-11:\/book-review-97-things.html","summary":"<p><em>97 Things Every Programmer Should Know<\/em> is a collection of short essays by\nexperienced programmers. And by short, I mean <em>short<\/em>: 1-3 fairly tiny pages a\npiece. If you're on a journey to become a software engineer then this book will\ngive you a crash course in terminology you should \u2026<\/p>","content":"<p><em>97 Things Every Programmer Should Know<\/em> is a collection of short essays by\nexperienced programmers. And by short, I mean <em>short<\/em>: 1-3 fairly tiny pages a\npiece. If you're on a journey to become a software engineer then this book will\ngive you a crash course in terminology you should be familiar with. Even as a\npracticing software engineer there is wisdom to be found in this book, but a\nnovice will undoubtedly get more out of reading it.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"mf\">97<\/span><span class=\"w\"> <\/span><span class=\"n\">Things<\/span><span class=\"w\"> <\/span><span class=\"n\">Every<\/span><span class=\"w\"> <\/span><span class=\"n\">Programmer<\/span><span class=\"w\"> <\/span><span class=\"n\">Should<\/span><span class=\"w\"> <\/span><span class=\"n\">Know<\/span>\n<span class=\"n\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">Kevlin<\/span><span class=\"w\"> <\/span><span class=\"n\">Henney<\/span>\n<span class=\"n\">Released<\/span><span class=\"w\"> <\/span><span class=\"n\">February<\/span><span class=\"w\"> <\/span><span class=\"mf\">2010<\/span>\n<span class=\"n\">Publisher<\/span><span class=\"p\">(<\/span><span class=\"n\">s<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"n\">O<\/span><span class=\"err\">&#39;<\/span><span class=\"n\">Reilly<\/span><span class=\"w\"> <\/span><span class=\"n\">Media<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Inc<\/span><span class=\"mf\">.<\/span>\n<span class=\"n\">ISBN<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mf\">9780596809485<\/span>\n<\/code><\/pre><\/div>\n\n<h1 id=\"the-book-in-a-nutshell\">The book in a nutshell<\/h1>\n<p>As I mentioned in the introduction, <em>97 Things Every Programmer Should Know<\/em> is\na collection of very short essays by practicing professionals. The essays treat\na wide variety of themes that are relevant to a practicing software engineer,\nranging from hard technical skills such as the <em>Don't Repeat Yourself<\/em> principle\nand <em>Single Responsibility Principle<\/em>, to softer skills such as interacting with\nmanagers and fostering good relationships with your colleagues. Most of the\nessays are focused on the technical side of things, however, and there is good\nvariety in the technical topics. While a lot of the essays are about how to\nwrite good code, there is also a healthy amount of recommendations for tooling\nto use, such as static code analysers, automated test suites, version control\nsystems and more.<\/p>\n<p>There really isn't much more to say regarding what the book is about. It's like\na collection of very well-written blog posts on programming-related topics. So\nif you're reading this blog, chances are good you're going to enjoy this book.<\/p>\n<h1 id=\"what-i-liked\">What I liked<\/h1>\n<p>In some ways, <em>97 Things<\/em> has a lot in common with <a href=\"https:\/\/slar.se\/book-review-apprenticeship-patterns.html\">Apprenticeship\nPatterns<\/a> that I reviewed last week.\nThey're both about how you improve as a software engineer. The difference is\nthat <em>97 Things<\/em> is a lot more to the point and more concrete. For the most\npart, it presents tips and tricks that you can apply immediately and see\nbenefits from just as fast. For the budding software engineer, it's an excellent\npool of topics to diversify your skill set. That's with an emphasis on <em>topics<\/em>,\nthough. This book presents a brief introduction to a wide variety of topics, but\nit dives deeply into none of them. I think this is a great strength of the book,\nas it means you will never get stuck on some \"boring\" topic that doesn't\ninterest you.<\/p>\n<p>While you can absolutely draw connections between the essays, they are written\nas standalone pieces of work. This makes <em>97 Things<\/em> a perfect book to read on\nthe go, when you might just have a few minutes or so to read.<\/p>\n<p>Out of all 97 things, I recall only a handful that I didn't find genuinely\nhelpful or insightful. Some essays even contradict each other, which actually\ngives a nice perspective on the fact that a <em>lot<\/em> of best practices are, to a\nlarge degree, opinions. A notable example I recall is about automatic code\nformatting, where one essay discourages its use and a few others encourage it.\nI think this is a great benefit of having so many different authors. You don't\njust get one person's opinion.<\/p>\n<h1 id=\"what-i-didnt-like\">What I didn't like<\/h1>\n<p>As with many other books on how to be a good software engineer, there is a slight\ntint of workaholism over some of the essays. I especially found an essay by\nRobert C. Martin on what it means to be a professional programmer to send this\nmessage. It's the same theme I found a little bit disturbing with\n<a href=\"https:\/\/slar.se\/book-review-apprenticeship-patterns.html\">Apprenticeship Patterns<\/a>. I can't say I\ndisagree with the message; I truly believe in the craftsmanship approach to\nsoftware engineering, the path of lifelong learning. But at the same time I\ndon't think it is for everyone, and I think it should be possible to treat\nprogramming as \"just a job\".<\/p>\n<p>A minor inconvenience is that the essays are ordered alphabetically, where I\nwould have preferred them to be ordered by theme. Finding a particular essay of\nwhich you recall the theme but not the title is needlessly difficult. I just now\nsuffered through it trying to find the aforementioned essay by Robert C. Martin.<\/p>\n<p>But as a package, I find little to dislike about the book. Even the workaholism\npart is effectively counteracted by an entire essay dedicated to sending the\nmessage \"work smarter not harder\".<\/p>\n<h1 id=\"conclusions\">Conclusions<\/h1>\n<p>This is another book that I wish I'd read years ago. I strongly recommend it as\na read for <em>any<\/em> software engineer at the beginning of their career or student\n(self-taught or at a seat of learning) who is preparing for their career. Being\nsuch a light and quick read, I find no good reason not to spend the few hours it\ntakes to read through the book and be exposed to a whole lot of different ideas.<\/p>","category":[{"@attributes":{"term":"Reviews"}},{"@attributes":{"term":"book review"}},{"@attributes":{"term":"software engineering"}}]},{"title":"Full text search with pelican-search!","link":{"@attributes":{"href":"https:\/\/slar.se\/pelican-search.html","rel":"alternate"}},"published":"2022-07-10T21:58:53+02:00","updated":"2022-07-10T21:58:53+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-07-10:\/pelican-search.html","summary":"<p>I've been meaning to take this blog into more of the Wiki direction. Or rather\nsome unholy mixture of a Wiki and a blog. An important step in that direction is\nfull text search, which I've now got!<\/p>\n<p>This blog is powered by <a href=\"https:\/\/blog.getpelican.com\/\">Pelican<\/a>, and quite\nrecently a new plugin \u2026<\/p>","content":"<p>I've been meaning to take this blog into more of the Wiki direction. Or rather\nsome unholy mixture of a Wiki and a blog. An important step in that direction is\nfull text search, which I've now got!<\/p>\n<p>This blog is powered by <a href=\"https:\/\/blog.getpelican.com\/\">Pelican<\/a>, and quite\nrecently a new plugin called\n<a href=\"https:\/\/github.com\/pelican-plugins\/search\">pelican-search<\/a> popped up.\nIt's quite simple: it adds the search bar you see on the <a href=\"https:\/\/slar.se\/index.html\">home\npage<\/a>, which taps into the powerful <a href=\"https:\/\/stork-search.net\/\">Stork<\/a>\nsearch library.<\/p>\n<p>It all sums up to the super fast search bar that all visitors of this website\nnow have at their disposal. Pretty neat!<\/p>","category":[{"@attributes":{"term":"Blog"}},{"@attributes":{"term":"blog"}}]},{"title":"The art of learning from the less experienced","link":{"@attributes":{"href":"https:\/\/slar.se\/learning-from-the-less-experienced.html","rel":"alternate"}},"published":"2022-07-07T22:31:50+02:00","updated":"2022-08-07T23:59:50+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-07-07:\/learning-from-the-less-experienced.html","summary":"<p>Software engineering is a lifelong journey of learning. Regardless of how\ndedicated you are in your learning, there will never come a point where you\nhave learned it all. As such, it's important to use all learning resources\navailable to us. As is evident from the themes on my blog \u2026<\/p>","content":"<p>Software engineering is a lifelong journey of learning. Regardless of how\ndedicated you are in your learning, there will never come a point where you\nhave learned it all. As such, it's important to use all learning resources\navailable to us. As is evident from the themes on my blog, I'm very partial to\nbooks and other written media. Indeed, this blog post is such written media.\nBut perhaps the best source of learning for a software engineer is simply other\n software engineers.<\/p>\n<p>Now, learning new things from those more experienced than you isn't that much a\nleap of the imagination. Of course you're going to try to soak up anything you\ncan learn from your seasoned team lead, or that database expert who does magical\nthings with SQL queries, or anyone else you identify as being highly proficient\nin something that interests you. No, there is no real challenge there, barring\nthe fact that these experienced engineers may not have the inclination to teach\nyou. But this blog post is about your disposition as a learner, so let's stick\nto the topic. And actually get to the topic to begin with: learning from the\nless experienced.<\/p>\n<h1 id=\"a-student-can-teach-their-teacher\">A student can teach their teacher<\/h1>\n<p>When I attended university, I worked many years as a teaching assistant in\nintroductory computer science classes. During one class I held, there was at\nsome point a part of an assignment that required flipping the value of a\nboolean variable. Something like: given a boolean variable <code>isOdd<\/code>, define a\nnew boolean variable <code>isEven<\/code> that is <code>true<\/code> if <code>isOdd<\/code> is <code>false<\/code>, and <code>false<\/code>\nif <code>isOdd<\/code> is <code>true<\/code>. One student presented a solution like the one below.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kt\">boolean<\/span><span class=\"w\"> <\/span><span class=\"n\">isEven<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">isOdd<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"kc\">true<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">isEven<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"k\">else<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">isEven<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"kc\">true<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Being an enthusiastic but still rather fresh teaching assistant with not all\nthat much programming experience, I said it was a viable solution but it would\nbe more concise to use a ternary operator.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kt\">boolean<\/span><span class=\"w\"> <\/span><span class=\"n\">isEven<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">isOdd<\/span><span class=\"w\"> <\/span><span class=\"o\">?<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kc\">true<\/span><span class=\"p\">;<\/span>\n<\/code><\/pre><\/div>\n\n<p>The students sat back in awe at my incredibly simple solution to the problem.\nThat is, until 5 seconds passed and another student had a bright idea: \"why not\njust negate <code>isOdd<\/code>?\". What the student meant was the following:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kt\">boolean<\/span><span class=\"w\"> <\/span><span class=\"n\">isEven<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"o\">!<\/span><span class=\"n\">isOdd<\/span><span class=\"p\">;<\/span>\n<\/code><\/pre><\/div>\n\n<p>Not only is this solution the most concise, it also more clearly represents the\nconcept the task asked for. Something is \"even\" precisely if it is \"not odd\",\nafter all. I managed to humble myself enough to commend the student for a well\nthought out solution.<\/p>\n<h1 id=\"first-year-students-routinely-taught-me-new-things\">First year students routinely taught me new things<\/h1>\n<p>I taught the first year computer science courses for four years. I expanded my\nskills exponentially during this time. And yet, every year there would be new\nfirst year students that knew something I did not, or had some insight I\nlacked. While these events definitely became less frequent as I gained more\nexperience, they never ceased. I'm confident that I could go back there now and\nteach the same courses again, and there would be a student or two with\nsomething to teach me.<\/p>\n<p>The great insight that I gained from this is that regardless of how far ahead\nyou are of someone else, you are doing both yourself and them a disservice by\nnot being open to let them teach you things. It's also incredibly hard to\ndetermine if someone is less experienced than you are. In the <code>!isOdd<\/code> scenario\noutlined above, I was in a position of authority relative to the student who\nhad the best solution, but it's not unlikely that student had done a lot more\nprogramming than I had, given that I didn't start until I was in university.<\/p>\n<h1 id=\"the-great-challenge-in-keeping-an-open-mind-in-disagreement\">The great challenge in keeping an open mind in disagreement<\/h1>\n<p>The reason I could so easily swallow my pride and commend the student with the\n<code>!isOdd<\/code> solution is not that I at that time was particularly humble. I simply\nagreed with the solution the student had in mind, it fit my mental model. I've\nsince been in situations where someone I've viewed as less experienced (and more\nimportantly, <em>less proficient<\/em>) than myself has come with a suggestion that I've\nfundamentally disagreed with. In such scenarios keeping an open mind is a\nlot more difficult, and all I can do is try to the best of my abilities. I will\nargue my point, and I can argue fiercely, but I also try my absolute hardest not\nto dismiss their point outright, and hear out their arguments. I also try not to\nlet my predetermined view of their experience and proficiency taint my\njudgement. Sometimes I succeed on the spot, and sometimes I succeed in hindsight\nwhen reflecting over a past conversation. And most assuredly, sometimes I\nsimply fail.<\/p>\n<p>My point with all of this storytelling really boils down to one piece of advise:\navoid leaning on your impressions of someone's experience and proficiency when\nevaluating their arguments for some point. I guarantee they know things you don't.\nLike me, you are unlikely to always succeed, but you'll benefit from the times\nyou do. Not to mention that the other party of the argument will most often\nappreciate you letting them make their case. Perhaps that's actually the more\nimportant part of thes story. But it sure does not hurt that there's something\nin it for you as well.<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"learning"}},{"@attributes":{"term":"software engineering"}}]},{"title":"Book Review: Apprenticeship Patterns","link":{"@attributes":{"href":"https:\/\/slar.se\/book-review-apprenticeship-patterns.html","rel":"alternate"}},"published":"2022-07-02T13:00:48+02:00","updated":"2022-07-02T13:27:48+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-07-02:\/book-review-apprenticeship-patterns.html","summary":"<p><em>Apprenticeship Patterns: Guidance for the Aspiring Software Craftsman<\/em> is\nfundamentally a book about lifelong learning. It is about treating software\nengineering as a craft you may never master; in fact it may never have been\nmastered before. Perhaps it simply cannot be mastered in the traditional sense\nof the word \u2026<\/p>","content":"<p><em>Apprenticeship Patterns: Guidance for the Aspiring Software Craftsman<\/em> is\nfundamentally a book about lifelong learning. It is about treating software\nengineering as a craft you may never master; in fact it may never have been\nmastered before. Perhaps it simply cannot be mastered in the traditional sense\nof the word. But that doesn't mean that we should not aspire to master it, that\nwe should not embark on <em>The Long Road<\/em>. So how can a book help with that?<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nv\">Apprenticeship<\/span><span class=\"w\"> <\/span><span class=\"nv\">Patterns<\/span>:<span class=\"w\"> <\/span><span class=\"nv\">Guidance<\/span><span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"nv\">the<\/span><span class=\"w\"> <\/span><span class=\"nv\">Aspiring<\/span><span class=\"w\"> <\/span><span class=\"nv\">Software<\/span><span class=\"w\"> <\/span><span class=\"nv\">Craftsman<\/span>\n<span class=\"nv\">by<\/span><span class=\"w\"> <\/span><span class=\"nv\">Dave<\/span><span class=\"w\"> <\/span><span class=\"nv\">Hoover<\/span>,<span class=\"w\"> <\/span><span class=\"nv\">Adewale<\/span><span class=\"w\"> <\/span><span class=\"nv\">Oshineye<\/span>\n<span class=\"nv\">Released<\/span><span class=\"w\"> <\/span><span class=\"nv\">October<\/span><span class=\"w\"> <\/span><span class=\"mi\">2009<\/span>\n<span class=\"nv\">Publisher<\/span><span class=\"ss\">(<\/span><span class=\"nv\">s<\/span><span class=\"ss\">)<\/span>:<span class=\"w\"> <\/span><span class=\"nv\">O<\/span><span class=\"err\">&#39;Reilly Media, Inc.<\/span>\n<span class=\"err\">ISBN: 9780596518387<\/span>\n<\/code><\/pre><\/div>\n\n<h1 id=\"the-book-in-a-nutshell\">The book in a nutshell<\/h1>\n<p>The core tenet of the book is that software engineering is a <em>craft<\/em>. A craft in\nthe same sense that blacksmithing is, or carpentry, or the construction of\nmusical instruments. The authors provide a concise reasoning for why this is so.<\/p>\n<blockquote>\n<p>Software engineering is a craft precisely because we don't understand it well\nenough to make it a codified discipline like science or engineering.<\/p>\n<\/blockquote>\n<p>One can agree or disagree with this statement, but it is hard to argue against\nthe notion that software engineering is something that requires a high degree of\n<em>skill<\/em>. That's not skill as in technical proficiency, although that is part of\nit. It's skill as in everything that encompasses a successful software engineer,\nof which technical proficiency is important but far from being the skill in it's\nown right.<\/p>\n<p>As the title suggests, <em>Apprenticeship Patterns<\/em> is comprised of a series of\n<em>patterns<\/em>. These are meant to help you hone your skill as a software craftsman.\nEach pattern is composed of four parts:<\/p>\n<ul>\n<li>Context: A generalized context to put the pattern in perspective.<\/li>\n<li>Problem: A concrete problem statement.<\/li>\n<li>Solution: One or more suggestions for solving or alleviating the problem.<\/li>\n<li>Action: A concrete exercise to practice the solution.<\/li>\n<\/ul>\n<p>The patterns are really <em>contextual habits<\/em>; given a situation X it is\nappropriate to do Y. A (perhaps <em>the<\/em>) core pattern is <em>The Long Road<\/em>, which\nboils down to the fact that mastering a craft is a lifelong process. It\nchallenges the notion that the quickest way to success as measured in notoriety\nor material wealth is what one should aspire for. The solution is a lengthy\naffair, but it importantly suggests that climbing the corporate ladder through\nquick promotions or similar easily takes you away from the actual crafting of\nsoftware, thus diverting you from The Long Road. You should be prepared to work\nas a developer for many years to come. Many of the other patterns of the book\ncomplement The Long Road, such as <em>Stay In The Trenches<\/em> which specifically\ndeals with the problem of success being rewarded with promotions.<\/p>\n<p>Another pattern that struck home with me is <em>Record What You Learn<\/em>. Quite\nunsurprisingly, it simply suggests that one should keep a record of the things\nyou have learned and plan to learn in the future. This book review is in fact a\ndirect application of that pattern.<\/p>\n<p>There are many, many more patterns in the book. Some of my favorite ones include:<\/p>\n<ul>\n<li><em>Be The Worst<\/em>: Place yourself in situations where you are surrounded by\n  craftsmen that are more skilled than you in some area, and that you can learn\n  from. Avoid becoming complacent.<\/li>\n<li><em>Share What You Learn<\/em>: Put your learning experiences out in the open, for\n  anyone to find.<\/li>\n<li><em>Kindred Spirits<\/em>: Surround yourself with others passionate to learn the\n  things you wish to dive into.<\/li>\n<li><em>Use The Source<\/em>: Read open source code. A lot.<\/li>\n<li><em>Read Constantly<\/em>: Read books. A lot.<\/li>\n<\/ul>\n<p>I'm not going to list all the patterns that resonated with me, and I can't even\ndo these few ones justice with just this brief explanation of them. You really\nneed to read the book with each context, problem, solution and action for the\nrespective patterns to get the full picture.<\/p>\n<h1 id=\"what-i-liked\">What I liked<\/h1>\n<p>This book is a very easy read. I like to have at least one <em>soft<\/em> book to read\nwhen my mind wanders too much for me to take in a technical book, and\n<em>Apprenticeship Patterns<\/em> perfectly fits that bill. It took me a couple of weeks\nwith a few pages a night to get through it. It's easy to pick it up, read about\na pattern or two, and then put it down. It's well organized and easy to refer\nback to after completion. The patterns are presented with just enough context to\nmake them understandable, yet the authors do not dwell on things for too long.\nIt is a concise book that is still easy to comprehend.<\/p>\n<p>I also found that it is a highly inspirational book, and approaching software\nengineering as a craft really speaks to me. Many of the patterns of this book\nare quite obvious to me and I practice several of them already, yet there are\nmany patterns I think I should practice that I don't. Record What You Learn is\nthe perfect example. I've been thinking for years that I should do so, but never\nreally got around to doing it other than a sporadic blog post once or twice a\nyear. After reading the book, I have newfound motivation to apply many of\nthe patterns, as this book review is tangible evidence of. In the future, I\nintend to always finish up a book with a book review. Hopefully I will improve\nin writing them with time, as I am not all that happy with how this review\nturned out. But Share What You Learn tells me I should post this anyway, and I\nreally do agree with that.<\/p>\n<p>I also think this is a terrific book to read as a budding software engineer. It\nis called <em>Apprenticeship Patterns<\/em>, after all. I wish I would have read it\nyears ago, and I wish I was already practicing many of the patterns. But better\nlate than never, and as I will discuss in the next section there is a reason for\nme to be somewhat thankful for not reading it earlier.<\/p>\n<h1 id=\"what-i-didnt-like\">What I didn't like<\/h1>\n<p>While I think this is a good handbook for mastering a craft, I also think the\napproach is potentially unhealthy if applied without moderation. I have\npersonally struggled a lot with finding a balance between improving my skills as\na software and just living a life separate from software engineering. Or\ncomputers and technology in general. I found the book truly inspirational, so\nmuch so that it prompted be to spend two hours of my Saturday morning writing\nthis book review. To be completely honest, I am still tweaking the\naforementioned balance. I would not say that I am struggling anymore, but I\ncannot deny that it is still a work in progress.<\/p>\n<h1 id=\"conclusions\">Conclusions<\/h1>\n<p>This book struck home with me, and I wholeheartedly recommend it. But that is a\nrecommendation with a caveat, as I don't think this is a book for everyone.\nIt's really all in the title, this book is for the aspiring software\n<em>craftsman<\/em>. I don't think you <em>have<\/em> to approach software engineering as a\ncraft that you devote yourself to, and the authors actually allude to this as\nwell. It's one approach, and it's a great boon to the field that some take it.\nBut for others, working with software can be \"just a job\", and not their\npassion. That is fine, a job can be just a means to provide for yourself. And\nif that's you, then I say skip this book. But if you do have a passion for\nbuilding great software, I think this is a book you don't want to miss.<\/p>","category":[{"@attributes":{"term":"Reviews"}},{"@attributes":{"term":"book review"}},{"@attributes":{"term":"software engineering"}}]},{"title":"Eleven Table Tennis: A VR masterpiece","link":{"@attributes":{"href":"https:\/\/slar.se\/eleven-table-tennis-a-vr-masterpiece.html","rel":"alternate"}},"published":"2022-06-12T00:00:00+02:00","updated":"2022-06-12T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-06-12:\/eleven-table-tennis-a-vr-masterpiece.html","summary":"<p>As a software engineer, I sit and stand still for large chunks of the day.\nUnfortunately, I'm also a big fan of playing video games, which traditionally\nfalls into the same category of physical exercise. Much to avoid repetitive\nstress injury and everything else that comes along with sitting at \u2026<\/p>","content":"<p>As a software engineer, I sit and stand still for large chunks of the day.\nUnfortunately, I'm also a big fan of playing video games, which traditionally\nfalls into the same category of physical exercise. Much to avoid repetitive\nstress injury and everything else that comes along with sitting at a computer\nday in and day out, I've in the past year started to devote more time to\nvirtual reality (VR) gaming. In some VR games you actually get to move around,\nand I'm writing this article to fawn over my favorite experience yet: <a href=\"https:\/\/elevenvr.com\/en\/\">Eleven\nTable Tennis<\/a>.<\/p>\n<h3 id=\"table-tennis-is-an-excellent-fit-for-vr\">Table tennis is an excellent fit for VR<\/h3>\n<p>There are two things about table tennis that makes it very well suited to\nVR. First, the playing field is small enough that it can fit into a\nfair-sized living room. Granted, fitting a full-sized table tennis table into\na smaller apartment can be somewhat inconvenient, but when playing in VR you\nactually only need the space for <em>half<\/em> of the table. That is not to say that\nI don't occasionally physically assault some furniture that was unfortunate\nenough to come in my way, but most of the time it works well even though my\nplaying space is only roughly 2.5x2.5 meters.<\/p>\n<p>Second, the real-life feedback of hitting a table tennis\nball with a racket is rather realistically reproduced by a vibration in a\nmotion controller. There's just not a lot of feedback from those tiny and\nhollow table tennis balls, so even though most motion controllers can't produce\nparticularly strong vibrations, it's still enough. I've played both with\na Valve Index and an Oculus Rift CV1, and both provide a perfectly serviceable\nexperience.<\/p>\n<h3 id=\"eleven-table-tennis-delivers-on-that-premise\">Eleven Table Tennis delivers on that premise<\/h3>\n<p>So the actual game of table tennis is really well suited to a VR treatment.\nEleven Table Tennis takes this premise and delivers an almost realistic physics\nengine that for the most part just <em>feels right<\/em>. Granted, there are the odd\n\"wait, what?...\" moments from time to time, and I especially feel like some\nserves can be delivered in a way that's not really possible in real life. But\noverall, it feels true to life.<\/p>\n<p>While playing against bots in Eleven Table Tennis is a perfectly fine challenge,\nwhat really sets the game apart is a stellar online multiplayer. I jump into the\ngame both in early mornings before work and in late evenings before bed, and\nit rarely takes me more than 30 seconds to find an opponent. While waiting,\nyou can keep playing against the bots as well, so there's never an idle moment.<\/p>\n<p>As icing on the cake, playing table tennis in VR is a really decent workout. I'm\nover the moon about how I can combine my love for video games with physical\nexercise. There are games that do that even better, such as <a href=\"https:\/\/www.beatsaber.com\/\">Beat\nSaber<\/a>, but I find the competitive nature of table\ntennis to be much more engaging and worthwhile.<\/p>\n<p>If you're a VR fan and don't have this game yet, do yourself a favor and get\nit. Just ensure that you don't have any expensive furniture in your immediate\nplay area.<\/p>","category":[{"@attributes":{"term":"Blog"}},{"@attributes":{"term":"blog"}}]},{"title":"Learning a new programming language as a practicing software engineer","link":{"@attributes":{"href":"https:\/\/slar.se\/learning-a-new-programming-language.html","rel":"alternate"}},"published":"2022-06-12T00:00:00+02:00","updated":"2022-06-12T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2022-06-12:\/learning-a-new-programming-language.html","summary":"<p>When it comes to programming languages, I consider myself something of a\npolyglot. To me, learning a new language is one of the most enjoyable\nthings in all of software engineering. This is especially true when you\nstart to venture into new paradigms; going from procedural to functional,\nfunctional to \u2026<\/p>","content":"<p>When it comes to programming languages, I consider myself something of a\npolyglot. To me, learning a new language is one of the most enjoyable\nthings in all of software engineering. This is especially true when you\nstart to venture into new paradigms; going from procedural to functional,\nfunctional to logical and logical to constraint-based. Exploring programming\nlanguages is one of the best way to improve your craft, even if you don't\nend up using that language in your daily work.<\/p>\n<p>Having learned (to varying degrees of proficiency) a good few languages over\nthe years, I figured it's about time I share my process for learning a new one.\nAnd when I say learn here, I mean <em>really<\/em> learn the language and become\nproficient in it, as opposed to learning just enough to become dangerous.\nThere is a time and place for the latter as well, but that is not the focus\nof this article. This article is also not about learning your <em>first<\/em>\nprogramming language, as that's a process where you need to also learn\nprogramming as a skill.<\/p>\n<p>I'm currently in the process of learning the Rust programming language, and in\nthis article I'll take you through how I go about learning it. My process, which\nI will detail throughout this article, is as follows:<\/p>\n<ol>\n<li>Identify learning resources<\/li>\n<li>Start learning<\/li>\n<li>Build a project<\/li>\n<li>Maintain knowledge<\/li>\n<\/ol>\n<h1 id=\"step-1-identify-learning-resources\">Step 1: Identify learning resources<\/h1>\n<p>The first thing I do is to identify the learning resources that I intend to use.\nThis does not have to be an exhaustive list of resources, as sometimes I stumble\nupon more of them as I go along, but I always put in some amount of research\ninto which learning resources are the most well received by others. I divide\nthese into <em>primary<\/em> and <em>secondary<\/em> learning resources, where the primary ones\nguide me through the learning experience while the secondary ones are\nsupplementary and can be skipped altogether if time is tight.<\/p>\n<h2 id=\"primary-learning-resources\">Primary learning resources<\/h2>\n<p>My primary learning resources are one or more structured overviews of the\nlanguage I'm about to learn. I usually only aim for one or two primary resources,\nand in the vast majority of cases I go with books. The reason I prefer books\nover things like video courses is that I find books to be better suited to\nactive learning. It is incredibly easy for me to watch a video and just start\nthinking about something else. In fact, that's something I do even when reading\na book, but to a lesser extent.<\/p>\n<p>Sometimes, finding a good primary learning resource is easy. In the case of\nRust, the community maintains a book called <a href=\"https:\/\/doc.rust-lang.org\/stable\/book\/\"><em>The Rust Programming\nLanguage<\/em><\/a>, which is the recommended\nstarting point for newcomers. After that, I intend to continue with\n<a href=\"https:\/\/www.oreilly.com\/library\/view\/programming-rust-2nd\/9781492052586\/\"><em>Programming\nRust<\/em><\/a>,\nwhich appears to be more in-depth. In some cases, identifying a good primary\nresource may be far from trivial, and requires a fair amount of looking around.\nBut for Rust it did not take me much time at all to find what I was looking for.<\/p>\n<p>I am aware that many prefer video resources over books nowadays. If that fits\nyour learning style, then that's all good. Books are just where it's at for me\npersonally. Sites like <a href=\"https:\/\/udemy.com\">Udemy<\/a> and\n<a href=\"https:\/\/pluralsight.com\">Pluralsight<\/a> provide an ample selection of courses\nsuitable as primary learning resources for most programming languages in use\ntoday. In my experience, such courses do however often cater to people learning\n<em>programming<\/em>, rather than software engineers just looking to add a new language\nto their repertoire.<\/p>\n<p>An important note on my primary learning resource is that I never follow more\nthan one at any one time. That's essentially what makes it a primary resource.\nSo right now, I'm going with <em>The Rust Programming Language<\/em> first and will then\nmove on to <em>Programming Rust<\/em>, but I don't read them at the same time.<\/p>\n<h2 id=\"secondary-learning-resources\">Secondary learning resources<\/h2>\n<p>Secondary learning resources are complementary, both to primary learning\nresources and other secondary learning resources. I most often have at one or\ntwo secondary resources that I utilize in parallel with a primary one. My\nfavourite sources of secondary learning resources are conference talks and\npodcasts.<\/p>\n<p>For Rust, I found a rather high-quality podcast called <a href=\"https:\/\/newrustacean.com\/\">New\nRustacean<\/a>, which features the host's journey of\nlearning the Rust programming language. It's a nice complement to my reading,\nand I enjoy being able to listen to it on the go. If you're about to learn\nPython, see my post on <a href=\"https:\/\/slar.se\/awesome-python-podcasts.html\">Awesome Python\nPodcasts<\/a> for some inspiration.<\/p>\n<p>Talks are most easily found on YouTube. Many of today's popular programming\nlanguages have at least one yearly conference, while a lot of them have many\nmore. Python as various incarnations of <a href=\"https:\/\/pycon.org\/\">PyCon<\/a>, Rust has\n<a href=\"https:\/\/rustconf.com\/\">RustConf<\/a> and C++ has <a href=\"https:\/\/cppcon.org\/\">CppCon<\/a>, and\nyou'll find that pretty much any language has a yearly conference named\n<code>&lt;Language&gt;Con(f)<\/code>. Some put all talks on YouTube, while others are a bit\nless easy to get a hold of.<\/p>\n<p>There is one more detail about secondary learning resources that I think is\nworth noting, namely that they keep being useful to me long after I've stopped\ninvesting time in primary learning resources. Secondary learning resources can\nalso enter my radar when I'm already a well-rounded programmer in a given\nlanguage. I will touch more on this when I discuss maintaining knowledge of a\nprogramming language.<\/p>\n<h1 id=\"step-2-start-to-learn\">Step 2: Start to learn<\/h1>\n<p>In the initial step of learning, I simply sit down with my chosen primary\nlearning resource and consume only that. As I'm a book person, this entails\nsitting down for a nice read. Although a very common advice is to learn actively\nby trying out examples and writing your own code as soon as possible, I\npersonally prefer to just read for a while before I start dabbling with code\nmyself. Sometimes I'll try a small example or other that looks extra\ninteresting, but I generally wait with any serious amount of programming until\nStep 3 of my learning process. The goal of Step 2 is not really to learn the\nlanguage, but to get a good overview of it.<\/p>\n<p>I often start using my chosen secondary resources immediately after my first\nsitting with a primary resource, at least if there's at least one podcast lined\nup. What I mostly seek from secondary resources is to get an idea of the\ncommunity surrounding the programming language, what the ecosystem (e.g\nlibraries and frameworks) looks like and keep up to date with the development of\nthe core language. More on this in Step 4.<\/p>\n<h1 id=\"step-3-build-a-project\">Step 3: Build a project<\/h1>\n<p>As soon as I feel like I have touched all subjects I need to sit down and start\nup a small project, that's exactly what I do. This point usually rolls around\nwhen I know how to create a project in the language, how to write unit tests and\nhow to write documentation. I'll often have a particular project in mind, and\nthen I may also know about a few additional things I need to learn about before\nI get going.<\/p>\n<p>My chosen project for learning Rust is to create a compiler and runtime\nenvironment for a statically typed Python-like programming language that I call\n<em>Rusthon<\/em>. This is an open source project and you can find it over at <a href=\"https:\/\/github.com\/slarse\/rusthon\">Rusthon's\nGitHub page<\/a> if you're interested.<\/p>\n<p>Like I mentioned in Step 2, this is where the advice of active learning comes\ninto play. It's virtually impossible to become proficient with a new language\nyou're confined to following along with examples and solving tiny problems\nwithout context. You need something larger to work on, I really do think this is\nessential.<\/p>\n<h1 id=\"step-4-maintain-knowledge\">Step 4: Maintain knowledge<\/h1>\n<p>Once I've learned a language well enough to become proficient in it, I need to\nmaintain that knowledge and also keep up-to-date with developments in the\ncommunity and ecosystem. These are two rather separate concerns. Maintaining a\nworking knowledge of the language requires one to write code in it. For this I\nkeep using my project, or find new things to do. I often try to get involved in\nopen source projects, such as <a href=\"https:\/\/github.com\/repobee\/repobee\">RepoBee<\/a>\n(Python) and <a href=\"https:\/\/github.com\/inria\/spoon\">Spoon<\/a> (Java) to make meaningful\ncontributions to the community.<\/p>\n<p>Keeping up-to-date with the community and ecosystem is where I mostly keep using\nsecondary learning resources, mostly podcasts but also talks from conferences.\nThis may be less important in older languages with less vibrant ecosystems, but\nin \"newer\" languages like Java, Python and Rust, knowing your way around the\npackage ecosystem and keeping up-to-date with new language features is rather\nimportant.<\/p>\n<h1 id=\"final-thoughts\">Final thoughts<\/h1>\n<p>Learning a new programming language is something I enjoy greatly. I go about it\nin a rather rigorous fashion where my goal is to become really proficient. I\n<em>immerse<\/em> myself in the language, its community and its ecosystem. This also\nentails that I spend some amount of effort in maintaining my knowledge and grasp\non the language, leading to the selection of languages I call myself proficient\nin being small. When I learn a new language it often effectively replaces\nsomething already in my repertoire. Rust is a contender to replace C, although I\ncan't say I've been all that thorough in maintaining my skills in C in the past\nfew years.<\/p>\n<p>It is also worth considering that learning a new language without maintaining\nyour skills in it for any considerable amount of time can still be worthwhile. I\nthink this is especially true when exploring different paradigms, as I alluded\nto in the introduction of this article. I learned Haskell many years back but\ndid not maintain a working knowledge of it for very long. Yet, the concepts that\nI learned from being forced to code in a purely functional fashion are valuable\nto me to this day. It was thanks to programming in Haskell that I really grasped\nthe concepts of recursion and higher-order functions, and understanding that has\ngreatly benefited me in all languages I've practiced since.<\/p>\n<p>To summarize, learning a new language can be greatly beneficial. Even if you\ndon't intend to add it to your repertoire, it can still be a worthwhile effort\nto step out of your comfort zone and explore new programming paradigms. The\nthings you learn from programming in one language can benefit your programming\nin another, and make you a more well-rounded software engineer.<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"rust"}},{"@attributes":{"term":"programming languages"}},{"@attributes":{"term":"learning"}}]},{"title":"RepoBee at ITiCSE and SIGCSE 2021!","link":{"@attributes":{"href":"https:\/\/slar.se\/repobee-at-iticse-and-sigcse-2021.html","rel":"alternate"}},"published":"2021-09-09T21:57:00+02:00","updated":"2021-09-09T21:57:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2021-09-09:\/repobee-at-iticse-and-sigcse-2021.html","summary":"<p>Another year, and a few new papers published on my favorite project:\n<a href=\"https:\/\/repobee.org\">RepoBee<\/a>. We made a hat-trick and appeared at\nITiCSE 2021 for a third year in a row (see <a href=\"https:\/\/slar.se\/repobee-and-simon-at-iticse-2019.html\">ITiCSE 2019<\/a>\nand <a href=\"https:\/\/slar.se\/repobee-at-iticse-2020.html\">ITiCSE 2020<\/a>), but this time we managed to sneak\nin two papers. One paper that I presented \u2026<\/p>","content":"<p>Another year, and a few new papers published on my favorite project:\n<a href=\"https:\/\/repobee.org\">RepoBee<\/a>. We made a hat-trick and appeared at\nITiCSE 2021 for a third year in a row (see <a href=\"https:\/\/slar.se\/repobee-and-simon-at-iticse-2019.html\">ITiCSE 2019<\/a>\nand <a href=\"https:\/\/slar.se\/repobee-at-iticse-2020.html\">ITiCSE 2020<\/a>), but this time we managed to sneak\nin two papers. One paper that I presented detailed <a href=\"https:\/\/doi.org\/10.1145\/3456565.3460031\">RepoBee's double-blind peer\nreview<\/a>, and the other paper that was\npresented by my colleague Tobias showcased the <a href=\"https:\/\/doi.org\/10.1145\/3456565.3460036\">repobee-sanitizer\nplugin<\/a>. Amazingly, the presentations\nwon <a href=\"https:\/\/iticse.acm.org\/best-paper-award\/\">both \"Best Presentation\" awards for their\ncategory<\/a>.<\/p>\n<p>We also made an appearance at SIGCSE with a 20-minute demo and Q&amp;A. The teaser\ntrailer for the demo <a href=\"https:\/\/repobee.org\/media\/repobee-demo.mp4\">is available\nhere<\/a>. The demo itself was\nessentially that, but less compressed and a little more elaborate.\nIt was followed by a nicely active Q&amp;A, where we made some new connections.<\/p>\n<p>All my publications can be found on the <a href=\"https:\/\/slar.se\/pages\/publications-and-essays.html\">Publications\npage<\/a>.<\/p>","category":[{"@attributes":{"term":"Blog"}},{"@attributes":{"term":"blog"}},{"@attributes":{"term":"repobee"}}]},{"title":"RepoBee at ITiCSE 2020!","link":{"@attributes":{"href":"https:\/\/slar.se\/repobee-at-iticse-2020.html","rel":"alternate"}},"published":"2020-10-04T09:20:00+02:00","updated":"2020-10-04T09:20:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2020-10-04:\/repobee-at-iticse-2020.html","summary":"<p>In 2019, <a href=\"https:\/\/slar.se\/repobee-and-simon-at-iticse-2019.html\">I presented RepoBee at the ITiCSE conference<\/a>\nin Aberdeen. This year, ITiCSE went virtual, but RepoBee still made an\nappearance in the new tools and tricks section with a small, two-page paper.\nAlthough I let my co-author Ric Glassey deal with the virtual presentation, I'm\nstill quite proud \u2026<\/p>","content":"<p>In 2019, <a href=\"https:\/\/slar.se\/repobee-and-simon-at-iticse-2019.html\">I presented RepoBee at the ITiCSE conference<\/a>\nin Aberdeen. This year, ITiCSE went virtual, but RepoBee still made an\nappearance in the new tools and tricks section with a small, two-page paper.\nAlthough I let my co-author Ric Glassey deal with the virtual presentation, I'm\nstill quite proud that I had another paper on RepoBee published at one of the\nmajor tech education conferences.<\/p>\n<p>If you're unaware, <a href=\"https:\/\/repobee.org\">RepoBee<\/a> is a tool for managing Git\nrepositories in an educational context. A basic use case is for a teacher to\nhave a template repository, and create copies of it for students or groups of\nstudents on GitHub or GitLab. If you've heard of <a href=\"https:\/\/classroom.github.com\">GitHub\nClassroom<\/a>, it's the same concept, but RepoBee is\nfar more powerful and customizable, at the expense of being a little more\nintricate to use.<\/p>\n<p>In the paper, Ric and I mostly discuss the need for customizable tools to tailor\nto different teaching methodologies and preferences, and how RepoBee makes this\npossible through plugins and by supporting both GitHub and GitLab. We also\ndiscuss the two primary modes of RepoBee, and how they can be combined. In\n<em>dictate<\/em> mode, RepoBee creates repositories for students based on template\nrepositories.  In <em>discovery<\/em> mode, RepoBee only sets up student teams\/groups,\nand then the students themselves are responsible for creating the repositories,\nwhich RepoBee can then \"discover\".<\/p>\n<p>The full paper <a href=\"https:\/\/doi.org\/10.1145\/3341525.3393999\">is available in the ACM digital\nlibrary<\/a>.<\/p>","category":[{"@attributes":{"term":"Blog"}},{"@attributes":{"term":"blog"}}]},{"title":"Essential pytest pt. 3: Rerunning failed tests (and the pytest cache)","link":{"@attributes":{"href":"https:\/\/slar.se\/essential-pytest-3.html","rel":"alternate"}},"published":"2020-10-03T19:00:00+02:00","updated":"2020-10-03T19:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2020-10-03:\/essential-pytest-3.html","summary":"<p>This is the third part of a series of small articles detailing some of the\nfunctionality of the <a href=\"https:\/\/docs.pytest.org\/en\/latest\/\">pytest<\/a> testing\nframework that I find most essential. The series assumes you know how to run\ntests with <code>pytest<\/code> already.<\/p>\n<p>In this third part, we'll take a super quick look at the \u2026<\/p>","content":"<p>This is the third part of a series of small articles detailing some of the\nfunctionality of the <a href=\"https:\/\/docs.pytest.org\/en\/latest\/\">pytest<\/a> testing\nframework that I find most essential. The series assumes you know how to run\ntests with <code>pytest<\/code> already.<\/p>\n<p>In this third part, we'll take a super quick look at the <code>--lf<\/code> flag that lets\nus rerun failed tests, as well as the caching mechanism that makes it possible.<\/p>\n<h2 id=\"using-lf-to-rerun-failed-tests\">Using <code>--lf<\/code> to rerun failed tests<\/h2>\n<p>In this article, we'll use the test suite from <a href=\"https:\/\/slar.se\/essential-pytest-1.html\">the first\narticle<\/a>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># test_mul.py<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">mul<\/span><span class=\"p\">(<\/span><span class=\"n\">lhs<\/span><span class=\"p\">,<\/span> <span class=\"n\">rhs<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">lhs<\/span> <span class=\"o\">*<\/span> <span class=\"n\">lhs<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_equal_numbers<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span> <span class=\"mi\">5<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">25<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_by_zero<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"mi\">0<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">0<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_different_numbers<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">15<\/span>\n<\/code><\/pre><\/div>\n\n<p>Just like in that article, the implementation of <code>mul<\/code> is broken.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>-v<span class=\"w\"> <\/span>--tb<span class=\"o\">=<\/span><span class=\"nv\">no<\/span>\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.5,<span class=\"w\"> <\/span>pytest-6.1.0,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\ncachedir:<span class=\"w\"> <\/span>.pytest_cache\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>items<span class=\"w\">                                                        <\/span>\n\ntest_mul.py::test_multiply_equal_numbers<span class=\"w\"> <\/span>PASSED<span class=\"w\">                    <\/span><span class=\"o\">[<\/span><span class=\"w\"> <\/span><span class=\"m\">33<\/span>%<span class=\"o\">]<\/span>\ntest_mul.py::test_multiply_by_zero<span class=\"w\"> <\/span>FAILED<span class=\"w\">                          <\/span><span class=\"o\">[<\/span><span class=\"w\"> <\/span><span class=\"m\">66<\/span>%<span class=\"o\">]<\/span>\ntest_mul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>FAILED<span class=\"w\">                <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">========================<\/span><span class=\"w\"> <\/span>short<span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>summary<span class=\"w\"> <\/span><span class=\"nv\">info<\/span><span class=\"w\"> <\/span><span class=\"o\">=========================<\/span>\nFAILED<span class=\"w\"> <\/span>test_mul.py::test_multiply_by_zero<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">1<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>\nFAILED<span class=\"w\"> <\/span>test_mul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">25<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"nv\">15<\/span>\n<span class=\"o\">======================<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>failed,<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>passed<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.05s<span class=\"w\"> <\/span><span class=\"o\">=======================<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note how 2 tests failed. <code>pytest<\/code> caches the failed tests from the last run,\nwhich enables us to rerun them with the <code>--lf|--last-failed<\/code> flag. So let's do\nthat, and show some more traceback information while we're at it. Note that\nonly the failing tests are executed.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>-v<span class=\"w\"> <\/span>--lf<span class=\"w\"> <\/span>--tb<span class=\"o\">=<\/span><span class=\"nv\">short<\/span>\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.5,<span class=\"w\"> <\/span>pytest-6.1.0,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\ncachedir:<span class=\"w\"> <\/span>.pytest_cache\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>items<span class=\"w\">                                                        <\/span>\nrun-last-failure:<span class=\"w\"> <\/span>rerun<span class=\"w\"> <\/span>previous<span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>failures\n\ntest_mul.py::test_multiply_by_zero<span class=\"w\"> <\/span>FAILED<span class=\"w\">                          <\/span><span class=\"o\">[<\/span><span class=\"w\"> <\/span><span class=\"m\">50<\/span>%<span class=\"o\">]<\/span>\ntest_mul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>FAILED<span class=\"w\">                <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">================================<\/span><span class=\"w\"> <\/span><span class=\"nv\">FAILURES<\/span><span class=\"w\"> <\/span><span class=\"o\">================================<\/span>\n_________________________<span class=\"w\"> <\/span>test_multiply_by_zero<span class=\"w\"> <\/span>__________________________\ntest_mul.py:8:<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>test_multiply_by_zero\n<span class=\"w\">    <\/span>assert<span class=\"w\"> <\/span>mul<span class=\"o\">(<\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"o\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>\nE<span class=\"w\">   <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">1<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>\nE<span class=\"w\">     <\/span>+1\nE<span class=\"w\">     <\/span>-0\n____________________<span class=\"w\"> <\/span>test_multiply_different_numbers<span class=\"w\"> <\/span>_____________________\ntest_mul.py:11:<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>test_multiply_different_numbers\n<span class=\"w\">    <\/span>assert<span class=\"w\"> <\/span>mul<span class=\"o\">(<\/span><span class=\"m\">5<\/span>,<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"o\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">15<\/span>\nE<span class=\"w\">   <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">25<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">15<\/span>\nE<span class=\"w\">     <\/span>+25\nE<span class=\"w\">     <\/span>-15\n<span class=\"o\">========================<\/span><span class=\"w\"> <\/span>short<span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>summary<span class=\"w\"> <\/span><span class=\"nv\">info<\/span><span class=\"w\"> <\/span><span class=\"o\">=========================<\/span>\nFAILED<span class=\"w\"> <\/span>test_mul.py::test_multiply_by_zero<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">1<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>\nFAILED<span class=\"w\"> <\/span>test_mul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">25<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"nv\">15<\/span>\n<span class=\"o\">===========================<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>failed<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.12s<span class=\"w\"> <\/span><span class=\"o\">============================<\/span>\n<\/code><\/pre><\/div>\n\n<p>My primary use case for <code>--lf<\/code> is for sorting out bugs. Every time a test\npasses, it is removed from the last-failed cache, and thus does not run the next\ntime <code>--lf<\/code> is specified. This way, it's easy to quickly target only failing\ntests, and systematically eliminate them one by one.<\/p>\n<blockquote>\n<p><strong>Pitfall:<\/strong> A common mistake is to use <code>--lf<\/code> to eliminate the failing tests\none by one, and then forget to run all tests when the last of the initially\nfailing tests passes. It's entirely possible to fix the implementation such\nthat a test <code>A<\/code> passes, and then subsequently reintroduce the same problem in\naddressing another test, but at that point <code>A<\/code> is no longer executing with\n<code>--lf<\/code>.<\/p>\n<\/blockquote>\n<h2 id=\"interacting-with-the-cache\">Interacting with the cache<\/h2>\n<p>I mentioned that the failed tests from the last run are stored in a cache. This\ncache is located in the <code>.pytest_cache<\/code> directory of the current working\ndirectory. There are a few flags to interact with said cache. First, you can\nexecute <code>pytest<\/code> with the <code>--cache-show<\/code> flag to show the current contents of\nthe cache.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>pytest<span class=\"w\"> <\/span>--cache-show\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.5,<span class=\"w\"> <\/span>pytest-6.1.0,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncachedir:<span class=\"w\"> <\/span>\/home\/slarse\/python\/.pytest_cache\n--------------------------<span class=\"w\"> <\/span>cache<span class=\"w\"> <\/span>values<span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"s1\">&#39;*&#39;<\/span><span class=\"w\"> <\/span>--------------------------\ncache\/lastfailed<span class=\"w\"> <\/span>contains:\n<span class=\"w\">  <\/span><span class=\"o\">{<\/span><span class=\"s1\">&#39;test_mul.py::test_multiply_by_zero&#39;<\/span>:<span class=\"w\"> <\/span>True,\n<span class=\"w\">   <\/span><span class=\"s1\">&#39;test_mul.py::test_multiply_different_numbers&#39;<\/span>:<span class=\"w\"> <\/span>True<span class=\"o\">}<\/span>\ncache\/nodeids<span class=\"w\"> <\/span>contains:\n<span class=\"w\">  <\/span><span class=\"o\">[<\/span><span class=\"s1\">&#39;test_mul.py::test_multiply_by_zero&#39;<\/span>,\n<span class=\"w\">   <\/span><span class=\"s1\">&#39;test_mul.py::test_multiply_different_numbers&#39;<\/span>,\n<span class=\"w\">   <\/span><span class=\"s1\">&#39;test_mul.py::test_multiply_equal_numbers&#39;<\/span><span class=\"o\">]<\/span>\ncache\/stepwise<span class=\"w\"> <\/span>contains:\n<span class=\"w\">  <\/span><span class=\"o\">[]<\/span>\n\n<span class=\"o\">=========================<\/span><span class=\"w\"> <\/span>no<span class=\"w\"> <\/span>tests<span class=\"w\"> <\/span>ran<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.00s<span class=\"w\"> <\/span><span class=\"o\">==========================<\/span>\n<\/code><\/pre><\/div>\n\n<p>Here, we can for example see the contents of the last-failed cache\n(<code>cache\/lastfailed<\/code>), and the tests currently known by <code>pytest<\/code>\n(<code>cache\/nodeids<\/code>). It's possible to supply <code>--cache-show<\/code> with an optional\nvalue, in order to show only some part of the cache. For example,\n<code>--cache-show=lastfailed<\/code> shows only the last-failed cache contents.<\/p>\n<p>On occasion, the cache may get into an inconsistent state, typically due to\nstrange interactions by the user. This has happened to me on several occasions,\nwith tests simply not executing as I expect them to. At that point, supplying\nthe <code>--cache-clear<\/code> flag to a test run will clear the cache. Alternatively, you\nmay simply remove the <code>.pytest_cache<\/code> directory.<\/p>\n<h2 id=\"summary\">Summary<\/h2>\n<p>Being able to execute only the failing tests from the previous test run is a\nvery handy feature when addressing bugs, both saving time in test execution and\nlimiting the amount of output shown to the user. It's however important to\nremember to execute all tests after the last failing test passes, so as to check\nfor regressions. One should also be aware that the functionality hinges on\ncaching in the <code>.pytest_cache<\/code> directory, which on rare occasions may need to be\ncleared.<\/p>","category":[{"@attributes":{"term":"Testing"}},{"@attributes":{"term":"python"}},{"@attributes":{"term":"pytest"}},{"@attributes":{"term":"testing"}}]},{"title":"Essential pytest pt. 2: Selecting tests to run","link":{"@attributes":{"href":"https:\/\/slar.se\/essential-pytest-2.html","rel":"alternate"}},"published":"2020-10-03T14:00:00+02:00","updated":"2020-10-03T14:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2020-10-03:\/essential-pytest-2.html","summary":"<p>This is the second part of a series of small articles detailing some of the\nfunctionality of the <a href=\"https:\/\/docs.pytest.org\/en\/latest\/\">pytest<\/a> testing\nframework that I find most essential. The series assumes you know how to run\ntests with <code>pytest<\/code> already.<\/p>\n<p>In this second part, we'll take a look at the <code>-k<\/code> and \u2026<\/p>","content":"<p>This is the second part of a series of small articles detailing some of the\nfunctionality of the <a href=\"https:\/\/docs.pytest.org\/en\/latest\/\">pytest<\/a> testing\nframework that I find most essential. The series assumes you know how to run\ntests with <code>pytest<\/code> already.<\/p>\n<p>In this second part, we'll take a look at the <code>-k<\/code> and <code>-m<\/code> options to control\nwhich tests in the test suite are executed.<\/p>\n<h2 id=\"the-test-suite\">The test suite<\/h2>\n<p>In this article, we'll use the test suite from <a href=\"https:\/\/slar.se\/essential-pytest-1.html\">the first\narticle<\/a>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># test_mul.py<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">mul<\/span><span class=\"p\">(<\/span><span class=\"n\">lhs<\/span><span class=\"p\">,<\/span> <span class=\"n\">rhs<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">lhs<\/span> <span class=\"o\">*<\/span> <span class=\"n\">rhs<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_equal_numbers<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span> <span class=\"mi\">5<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">25<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_by_zero<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"mi\">0<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">0<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_different_numbers<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">15<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that <code>mul<\/code> is now correctly implemented, so all tests will pass.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>-v\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.5,<span class=\"w\"> <\/span>pytest-6.1.0,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\ncachedir:<span class=\"w\"> <\/span>.pytest_cache\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>items<span class=\"w\">                                                        <\/span>\n\nmul.py::test_multiply_equal_numbers<span class=\"w\"> <\/span>PASSED<span class=\"w\">                         <\/span><span class=\"o\">[<\/span><span class=\"w\"> <\/span><span class=\"m\">33<\/span>%<span class=\"o\">]<\/span>\nmul.py::test_multiply_by_zero<span class=\"w\"> <\/span>PASSED<span class=\"w\">                               <\/span><span class=\"o\">[<\/span><span class=\"w\"> <\/span><span class=\"m\">66<\/span>%<span class=\"o\">]<\/span>\nmul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>PASSED<span class=\"w\">                     <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">===========================<\/span><span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>passed<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.01s<span class=\"w\"> <\/span><span class=\"o\">============================<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now, let's learn how to run subsets of these tests, without modifying the\nsource code.<\/p>\n<h2 id=\"using-the-k-option-to-select-tests-by-substring-matching\">Using the <code>-k<\/code> option to select tests by substring matching<\/h2>\n<p>The <code>-k<\/code> option is wonderful, and allows us to select a subset of tests to\nexecute based on simple substring matching. The simplest use of <code>-k<\/code> is to\nprovide it with a whitespace-less string. Any test with a name that <em>contains<\/em>\nthat string will be executed. To be clear, the name of a test is e.g.\n<code>mul.py::test_multiply_equal_numbers<\/code>, that is to say, the qualified path to it.<\/p>\n<p>As a simple example, we can select only the test that multiplies by zero like\nso.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>-v<span class=\"w\"> <\/span>-k<span class=\"w\"> <\/span><span class=\"nv\">zero<\/span>\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.5,<span class=\"w\"> <\/span>pytest-6.1.0,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\ncachedir:<span class=\"w\"> <\/span>.pytest_cache\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>items<span class=\"w\"> <\/span>\/<span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>deselected<span class=\"w\"> <\/span>\/<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>selected<span class=\"w\">                            <\/span>\n\ntest_mul.py::test_multiply_by_zero<span class=\"w\"> <\/span>PASSED<span class=\"w\">                          <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">====================<\/span><span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>passed,<span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>deselected<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.05s<span class=\"w\"> <\/span><span class=\"o\">=====================<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that 2 tests were deselected. It is also possible to create logical\nexpressions using <code>not<\/code>, <code>or<\/code> and <code>and<\/code>.  <code>not<\/code> simply inverts the condition:\nany test that does <em>not<\/em> match the substring is executed.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>-v<span class=\"w\"> <\/span>-k<span class=\"w\"> <\/span><span class=\"s1\">&#39;not zero&#39;<\/span>\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.5,<span class=\"w\"> <\/span>pytest-6.1.0,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\ncachedir:<span class=\"w\"> <\/span>.pytest_cache\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>items<span class=\"w\"> <\/span>\/<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>deselected<span class=\"w\"> <\/span>\/<span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>selected<span class=\"w\">                            <\/span>\n\ntest_mul.py::test_multiply_equal_numbers<span class=\"w\"> <\/span>PASSED<span class=\"w\">                    <\/span><span class=\"o\">[<\/span><span class=\"w\"> <\/span><span class=\"m\">50<\/span>%<span class=\"o\">]<\/span>\ntest_mul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>PASSED<span class=\"w\">                <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">====================<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>passed,<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>deselected<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.05s<span class=\"w\"> <\/span><span class=\"o\">=====================<\/span>\n<\/code><\/pre><\/div>\n\n<p>With <code>or<\/code>, we can select tests that match any of a number of substrings.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>-v<span class=\"w\"> <\/span>-k<span class=\"w\"> <\/span><span class=\"s1\">&#39;equal or different&#39;<\/span>\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.5,<span class=\"w\"> <\/span>pytest-6.1.0,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\n\/usr\/bin\/python\ncachedir:<span class=\"w\"> <\/span>.pytest_cache\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>items<span class=\"w\"> <\/span>\/<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>deselected<span class=\"w\"> <\/span>\/<span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>selected<span class=\"w\">                            <\/span>\n\ntest_mul.py::test_multiply_equal_numbers<span class=\"w\"> <\/span>PASSED<span class=\"w\">                    <\/span><span class=\"o\">[<\/span><span class=\"w\"> <\/span><span class=\"m\">50<\/span>%<span class=\"o\">]<\/span>\ntest_mul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>PASSED<span class=\"w\">                <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">====================<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>passed,<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>deselected<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.06s<span class=\"w\"> <\/span><span class=\"o\">=====================<\/span>\n<\/code><\/pre><\/div>\n\n<p>Finally, <code>and<\/code> allows us to select tests that match multiple substrings.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>-v<span class=\"w\"> <\/span>-k<span class=\"w\"> <\/span><span class=\"s1\">&#39;multiply and equal&#39;<\/span>\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.5,<span class=\"w\"> <\/span>pytest-6.1.0,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\n\/usr\/bin\/python\ncachedir:<span class=\"w\"> <\/span>.pytest_cache\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>items<span class=\"w\"> <\/span>\/<span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>deselected<span class=\"w\"> <\/span>\/<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>selected<span class=\"w\">                            <\/span>\n\ntest_mul.py::test_multiply_equal_numbers<span class=\"w\"> <\/span>PASSED<span class=\"w\">                    <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">====================<\/span><span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>passed,<span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>deselected<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.05s<span class=\"w\"> <\/span><span class=\"o\">=====================<\/span>\n<\/code><\/pre><\/div>\n\n<p>And that's pretty much all there is to the <code>-k<\/code> option. It's extremely useful\nwhen test suites grow in size, and I use it daily.<\/p>\n<h2 id=\"using-the-m-option-to-select-by-marker\">Using the <code>-m<\/code> option to select by marker<\/h2>\n<p>With <code>-m<\/code>, we can select tests by <em>markers<\/em>. You can mark a test function (or\nclass) by placing a decorator above it.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># test_mul.py<\/span>\n<span class=\"kn\">import<\/span> <span class=\"nn\">pytest<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">mul<\/span><span class=\"p\">(<\/span><span class=\"n\">lhs<\/span><span class=\"p\">,<\/span> <span class=\"n\">rhs<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">lhs<\/span> <span class=\"o\">*<\/span> <span class=\"n\">rhs<\/span>\n\n<span class=\"nd\">@pytest<\/span><span class=\"o\">.<\/span><span class=\"n\">mark<\/span><span class=\"o\">.<\/span><span class=\"n\">normcase<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_equal_numbers<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span> <span class=\"mi\">5<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">25<\/span>\n\n<span class=\"nd\">@pytest<\/span><span class=\"o\">.<\/span><span class=\"n\">mark<\/span><span class=\"o\">.<\/span><span class=\"n\">edgecase<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_by_zero<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"mi\">0<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">0<\/span>\n\n<span class=\"nd\">@pytest<\/span><span class=\"o\">.<\/span><span class=\"n\">mark<\/span><span class=\"o\">.<\/span><span class=\"n\">normcase<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_different_numbers<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">15<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that we must actually import the <code>pytest<\/code> module to be able to mark tests\nwith <code>@pytest.mark.x<\/code>. Now, we can run all tests marked with e.g. <code>normcase<\/code>\nlike so.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>-v<span class=\"w\"> <\/span>-m<span class=\"w\"> <\/span><span class=\"nv\">normcase<\/span>\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.5,<span class=\"w\"> <\/span>pytest-6.1.0,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\ncachedir:<span class=\"w\"> <\/span>.pytest_cache\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>items<span class=\"w\"> <\/span>\/<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>deselected<span class=\"w\"> <\/span>\/<span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>selected<span class=\"w\">                            <\/span>\n\ntest_mul.py::test_multiply_equal_numbers<span class=\"w\"> <\/span>PASSED<span class=\"w\">                    <\/span><span class=\"o\">[<\/span><span class=\"w\"> <\/span><span class=\"m\">50<\/span>%<span class=\"o\">]<\/span>\ntest_mul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>PASSED<span class=\"w\">                <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">============================<\/span><span class=\"w\"> <\/span>warnings<span class=\"w\"> <\/span><span class=\"nv\">summary<\/span><span class=\"w\"> <\/span><span class=\"o\">============================<\/span>\ntest_mul.py:6\n<span class=\"w\">  <\/span>\/home\/slarse\/python\/test_mul.py:6:<span class=\"w\"> <\/span>PytestUnknownMarkWarning:<span class=\"w\"> <\/span>Unknown<span class=\"w\"> <\/span>pytest.mark.normcase<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>is<span class=\"w\"> <\/span>this<span class=\"w\"> <\/span>a<span class=\"w\"> <\/span>typo?<span class=\"w\">  <\/span>You<span class=\"w\"> <\/span>can<span class=\"w\"> <\/span>register<span class=\"w\"> <\/span>custom<span class=\"w\"> <\/span>marks<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span>avoid<span class=\"w\"> <\/span>this<span class=\"w\"> <\/span>warning<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span>details,<span class=\"w\"> <\/span>see<span class=\"w\"> <\/span>https:\/\/docs.pytest.org\/en\/stable\/mark.html\n<span class=\"w\">    <\/span>@pytest.mark.normcase\n\n<span class=\"o\">[<\/span>...<span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>WARNINGS<span class=\"w\"> <\/span>OMITTED<span class=\"w\"> <\/span>...<span class=\"o\">]<\/span>\n\n--<span class=\"w\"> <\/span>Docs:<span class=\"w\"> <\/span>https:\/\/docs.pytest.org\/en\/stable\/warnings.html\n<span class=\"o\">==============<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>passed,<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>deselected,<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>warnings<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.01s<span class=\"w\"> <\/span><span class=\"o\">===============<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that this resulted in 3 warnings, one for each of the markings. The reason\nfor this is that newer versions of <code>pytest<\/code> want you to <em>register<\/em> markers, <a href=\"https:\/\/docs.pytest.org\/en\/stable\/example\/markers.html#registering-markers\">as\ndescribed\nhere<\/a>.\nThe purpose of this is to avoid users misspelling markers, and registering them\nwill make the warnings go away.<\/p>\n<p>As might be expected, the <code>-m<\/code> option also accepts logical expressions using\n<code>not<\/code>, <code>and<\/code> and <code>or<\/code>, just like the <code>-k<\/code> option does. Personally, I very rarely\nuse <code>-m<\/code> when using <code>pytest<\/code>, but some people swear by it, which is why I wanted\nto include it in this article.<\/p>\n<h2 id=\"trick-grouping-related-tests-into-classes-makes-selection-easier\">Trick: Grouping related tests into classes makes selection easier<\/h2>\n<p>A trick that I like to employ is to group related tests into classes. The class\nname is then incorporated into the test's name, and it becomes very easy to\nselect tests that are part of the same class. Here's a simple example, where I'm\ntesting two functions in the same module <code>test_arithmetics.py<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># test_arithmetics.py<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">mul<\/span><span class=\"p\">(<\/span><span class=\"n\">lhs<\/span><span class=\"p\">,<\/span> <span class=\"n\">rhs<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">lhs<\/span> <span class=\"o\">*<\/span> <span class=\"n\">rhs<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">div<\/span><span class=\"p\">(<\/span><span class=\"n\">lhs<\/span><span class=\"p\">,<\/span> <span class=\"n\">rhs<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">lhs<\/span> <span class=\"o\">\/<\/span> <span class=\"n\">rhs<\/span>\n\n<span class=\"k\">class<\/span> <span class=\"nc\">TestMul<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;Tests for the mul function.&quot;&quot;&quot;<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_equal_numbers<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n        <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span> <span class=\"mi\">5<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">25<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_by_zero<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n        <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"mi\">0<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">0<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_different_numbers<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n        <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">15<\/span>\n\n<span class=\"k\">class<\/span> <span class=\"nc\">TestDiv<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;Tests for the div function.&quot;&quot;&quot;<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">test_divide_equal_numbers<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n        <span class=\"k\">assert<\/span> <span class=\"n\">div<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">,<\/span> <span class=\"mi\">10<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">1<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that in grouping test functions into test classes, the <code>self<\/code> argument\nmust be added. This is a little bit annoying, as I rarely if ever use the\n<code>self<\/code> argument in a test case, but it's something that has to be done.<\/p>\n<p>Now, I can for example run only the tests in <code>TestDiv<\/code> like so.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>-v<span class=\"w\"> <\/span>-k<span class=\"w\"> <\/span><span class=\"nv\">TestDiv<\/span>\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.5,<span class=\"w\"> <\/span>pytest-6.1.0,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\ncachedir:<span class=\"w\"> <\/span>.pytest_cache\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">4<\/span><span class=\"w\"> <\/span>items<span class=\"w\"> <\/span>\/<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>deselected<span class=\"w\"> <\/span>\/<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>selected<span class=\"w\">                            <\/span>\n\ntest_arithmetics.py::TestDiv::test_divide_equal_numbers<span class=\"w\"> <\/span>PASSED<span class=\"w\">      <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">====================<\/span><span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>passed,<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>deselected<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.05s<span class=\"w\"> <\/span><span class=\"o\">=====================<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that the test name that's printed above includes the class name, which is\nwhy it is possible to select it with <code>-k<\/code>. Of course, grouping related tests\ninto modules is equally viable, as the module name (here, <code>test_arithmetics.py<\/code>)\nis also part of the test name. I typically do both by creating one test module\nper module of production code, and one test class per production code function.\nThis allows me to easily select tests at two levels of granularity, which comes\nin very handy.<\/p>\n<h2 id=\"summary\">Summary<\/h2>\n<p>Selecting a subset of test cases to run is crucial to my development workflow.\nWhen there are 100s or even 1000s of tests to run, running all of them is often\nnot what you want to do. My preferred way of selecting test cases is by using\nthe <code>-k<\/code> option to match substrings of test names, but the <code>-m<\/code> option is also\nthere for those that like to put marker decorators in their code. Finally,\ngrouping related tests into modules and classes allows for easy selection of\ntests on two levels of granularity, which is something that I exploit daily.<\/p>","category":[{"@attributes":{"term":"Testing"}},{"@attributes":{"term":"python"}},{"@attributes":{"term":"pytest"}},{"@attributes":{"term":"testing"}}]},{"title":"Thoughts on graduating with an MSc in Computer Science and Engineering","link":{"@attributes":{"href":"https:\/\/slar.se\/thoughts-on-graduating-with-an-msc-in-computer-science-and-engineering.html","rel":"alternate"}},"published":"2020-09-29T00:00:00+02:00","updated":"2020-09-29T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2020-09-29:\/thoughts-on-graduating-with-an-msc-in-computer-science-and-engineering.html","summary":"<p>After five long years of studies (seven if you include the two years of\nmaterials science), I've finally graduated with an <em>MSc in Computer Science and\nEngineering<\/em> from KTH Royal Institute of Technology. I'm still awaiting my\ndegree certificates, but the <a href=\"http:\/\/urn.kb.se\/resolve?urn=urn:nbn:se:kth:diva-281960\">thesis is\npublished<\/a> and I don't\nhave to do \u2026<\/p>","content":"<p>After five long years of studies (seven if you include the two years of\nmaterials science), I've finally graduated with an <em>MSc in Computer Science and\nEngineering<\/em> from KTH Royal Institute of Technology. I'm still awaiting my\ndegree certificates, but the <a href=\"http:\/\/urn.kb.se\/resolve?urn=urn:nbn:se:kth:diva-281960\">thesis is\npublished<\/a> and I don't\nhave to do anything but wait. I have two weeks left of my one month off before I\nstart working, and I found that now would be a good time to reflect a bit on my\neducation.<\/p>\n<h2 id=\"a-cs-degree-does-not-an-engineer-make\">A CS degree does not an engineer make<\/h2>\n<p>Early on in my education, it became abundantly clear to me that my CS degree\nwould be highly theoretical, and the practical elements were mostly toy\nprojects. I needed side projects, both to practice applying the theory I learned\nin class, and to get experience with common software development practices such\nas version control (Git) and issue management.<\/p>\n<p>While my first few projects were toy projects, such as\n<a href=\"https:\/\/github.com\/slarse\/clanim\/commits\/master\">clanim<\/a>, I started my grail\nproject in <a href=\"https:\/\/github.com\/repobee\/repobee\">RepoBee<\/a> fairly early during my\nbachelor's (technically, I started its predecessor). This was a \"real\" project\nfor me, that I used daily and was also used by others. This gave me great\nincentive to create a good product and keep working on it. As RepoBee is a\nmanagement tool for version control in education, it also came naturally to\nadopt proper version control practices, as opposed to just winging it.<\/p>\n<p>The takeaway from this is that in order to be well-equipped for work after\nschool, side projects are really invaluable. Not only are side projects\ninvaluable, but I think it's important to work on real projects. It creates\nincentive to keep going, and also gives you something to show off to future\nemployers. If you can't come up with something yourself, then there are a\nborderline innumerable amount of open-source software projects out there that\nneed all the help they can get. Such as RepoBee :)<\/p>\n<h2 id=\"a-cs-degree-gives-you-an-exceptional-theoretical-foundation-in-computing\">A CS degree gives you an exceptional theoretical foundation in computing<\/h2>\n<p>Although I think the engineering aspects were lacking in my education, the\ntheoretical foundation that I now possess is nothing short of incredible. I\nnever thought I could learn so much about mathematics, algorithms, operating\nsystems, network protocols, computer security etc in only five short years. I\nalso learned <em>how<\/em> to learn, and how to do so efficiently. This is probably the\nmost important thing you can take with you from university.<\/p>\n<p>I think that a lot of the theory would have been very hard for me to learn on my\nown, whereas the practical engineering practices were not. As such, in\nhindsight, I appreciate the heavy emphasis on theory. I've had a large amount of\nuse for my knowledge of algorithms, data structures and time complexities\nalready, and given my interest in programming languages and version control\nsystems, I expect this trend will carry on.<\/p>\n<p>A lot of people will tell you that a CS degree is not worth it, that you don't\neven learn the practical skills you need for engineering. This is true to an\nextent, but I think it's an oversimplification and whether or not it's worth it\nis highly individual. For me, the degree was <em>entirely<\/em> worth it. I was exposed\nto subjects I would not have found on my own and was taught concepts I would\nhave struggled to grasp without a tutor. I also greatly enjoy learning for the\nsake of it, and I like to dive deep. I like to understand how things work,\nrather than just understand how to use them. A CS degree is definitely not for\neveryone, but the blanket statement that it isn't worth it is simply false. For\nthose that enjoy learning and have a deep interest in programming, CS is the way\nto go. If you want to learn the practical skills you need to land a job as fast\nas possible, then it probably isn't.<\/p>\n<h2 id=\"teaching-is-learning\">Teaching is learning<\/h2>\n<p>After finishing the first year of my studies, I applied and was accepted to a\nposition as a teaching assistant. I would go on to work as a TA during The\nremaining four years of my studies, year-round. I held exercises, worked labs,\ncorrected student submissions, developed coursework, and much more. This greatly\naccelerated my own learning, for two reasons. First, in order to teach a\nsubject, you really must learn it well, and students' questions inevitably\nhighlight the shortcomings in your own knowledge. I received so many questions\nthat I could not answer that I likely would not have known I could not answer\nhad those questions not been asked. Second, in working as a TA I was introduced\nto other more senior TAs, who were much more knowledgable than I was.\nDiscussions with them would lead to my learning things that I would not have\nfound out on my own.<\/p>\n<p>Another benefit of working as a TA was that I got the opportunity to develop\nRepoBee as a paid project, giving me another source of income during the summer\nand winter breaks. I also got the opportunity to write some short research\npapers, attend conferences, and connect with other faculty. If I wanted to, I\ncould easily launch an academic career at this point. However, even though I\nenjoy science, I am more interested in practical engineering, and so an academic\ncareer seems unlikely at this point.<\/p>\n<p>My point here is simple: if you have the opportunity to teach, then do so! I\nattribute a lot of my success to my experience as a TA, and many doors have been\nopened for me as a result of working with other academics. I can't recommend it\nenough.<\/p>\n<h2 id=\"closing-thoughts\">Closing thoughts<\/h2>\n<p>My education has overall been a great experience. I've met a lot of interesting\npeople and done a lot of interesting things. I've taken classes, taught classes,\nwritten software, theses and conference papers, and despaired in the face of\nthe odd inordinately difficult exam. Although I greatly enjoyed my time at\nuniversity, I don't want to continue with a PhD. I feel done with studies. For\nthe time being, I'll be working as a research engineer developing experimental\nsoftware at KTH, which seems like a nice middle ground between academics and\nindustry. After that, I don't really know, which is pretty exciting in\nand of itself.<\/p>","category":[{"@attributes":{"term":"Blog"}},{"@attributes":{"term":"blog"}}]},{"title":"The Linux \/etc\/passwd file, and why it doesn't contain passwords","link":{"@attributes":{"href":"https:\/\/slar.se\/etc-passwd.html","rel":"alternate"}},"published":"2020-08-02T11:51:33+00:00","updated":"2020-08-02T12:15:33+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2020-08-02:\/etc-passwd.html","summary":"<p>On any Linux distribution, there's a file located at <code>\/etc\/passwd<\/code>. This file\ncontains information about users that exist on the system, including their\nusername, user id, group id and more. In this short article, I'll outline the\nstructure of the <code>\/etc\/passwd<\/code> file, and also illuminate why it doesn't \u2026<\/p>","content":"<p>On any Linux distribution, there's a file located at <code>\/etc\/passwd<\/code>. This file\ncontains information about users that exist on the system, including their\nusername, user id, group id and more. In this short article, I'll outline the\nstructure of the <code>\/etc\/passwd<\/code> file, and also illuminate why it doesn't\ntypically contain any passwords.<\/p>\n<h2 id=\"layout-of-the-etcpasswd-file\">Layout of the <code>\/etc\/passwd<\/code> file<\/h2>\n<p>The layout of the <code>\/etc\/passwd<\/code> file is fairly simple. Each line represents a\nuser on the system, with different fields being separated by colons as follows:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">name<\/span><span class=\"o\">:<\/span><span class=\"n\">password<\/span><span class=\"o\">:<\/span><span class=\"n\">UID<\/span><span class=\"o\">:<\/span><span class=\"n\">GID<\/span><span class=\"o\">:<\/span><span class=\"n\">GECOS<\/span><span class=\"o\">:<\/span><span class=\"n\">directory<\/span><span class=\"o\">:<\/span><span class=\"n\">shell<\/span>\n<\/code><\/pre><\/div>\n\n<p><code>name<\/code> and <code>password<\/code> are the username and password of the user, <code>UID<\/code> is the\nuser's numerical id, <code>GID<\/code> is the id of the <em>first<\/em> group the user belongs to,\n<code>GECOS<\/code> is an optional comment, <code>directory<\/code> is the user's home directory, and\n<code>shell<\/code> is the path to the executable that launches the user's preferred\nshell. As an example, a part of my <code>\/etc\/passwd<\/code> file looks like this:<\/p>\n<blockquote>\n<p><strong>Note:<\/strong> You can find the groups users belong to in the <code>\/etc\/group<\/code> file.<\/p>\n<\/blockquote>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">root<\/span><span class=\"o\">:<\/span><span class=\"n\">x<\/span><span class=\"o\">:<\/span><span class=\"mi\">0<\/span><span class=\"o\">:<\/span><span class=\"mi\">0<\/span><span class=\"o\">::\/<\/span><span class=\"n\">root<\/span><span class=\"o\">:\/<\/span><span class=\"n\">bin<\/span><span class=\"o\">\/<\/span><span class=\"n\">bash<\/span>\n<span class=\"n\">slarse<\/span><span class=\"o\">:<\/span><span class=\"n\">x<\/span><span class=\"o\">:<\/span><span class=\"mi\">1000<\/span><span class=\"o\">:<\/span><span class=\"mi\">985<\/span><span class=\"o\">::\/<\/span><span class=\"n\">home<\/span><span class=\"sr\">\/slarse:\/bin\/<\/span><span class=\"n\">bash<\/span>\n<span class=\"n\">mysql<\/span><span class=\"o\">:<\/span><span class=\"n\">x<\/span><span class=\"o\">:<\/span><span class=\"mi\">970<\/span><span class=\"o\">:<\/span><span class=\"mi\">970<\/span><span class=\"o\">:<\/span><span class=\"n\">MariaDB<\/span><span class=\"o\">:\/<\/span><span class=\"n\">var<\/span><span class=\"sr\">\/lib\/mysql:\/sbin\/<\/span><span class=\"n\">nologin<\/span>\n<\/code><\/pre><\/div>\n\n<p>We can see that the root user has the fields set as follows:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nv\">password<\/span><span class=\"o\">=<\/span>x\n<span class=\"nv\">UID<\/span><span class=\"o\">=<\/span><span class=\"m\">0<\/span>\n<span class=\"nv\">GID<\/span><span class=\"o\">=<\/span><span class=\"m\">0<\/span>\n<span class=\"nv\">GECOS<\/span><span class=\"o\">=<\/span>\n<span class=\"nv\">directory<\/span><span class=\"o\">=<\/span>\/root\n<span class=\"nv\">shell<\/span><span class=\"o\">=<\/span>\/bin\/bash\n<\/code><\/pre><\/div>\n\n<p>The user and group IDs of the root user are always 0, and it typically has its\nhome directory in <code>\/root<\/code>. But is the password of root user really <code>x<\/code>? No, it\nisn't. An <code>x<\/code> in the password field means that the password is located in the\n<em>shadow<\/em> file. More on that in the next section. The entry for my own user,\nslarse, is largely similar to that of the root user.<\/p>\n<p>The entry for the mysql user is however a bit different. For starters, it has a\ncomment in the <code>GECOS<\/code> field saying <em>MariaDB<\/em>, which indicates that the mysql\nuser is actually used by the <code>MariaDB<\/code> fork of the <code>MySQL<\/code> database system. It\nalso has in interesting login shell, namely <code>\/sbin\/nologin<\/code>. The description of\nthe <code>nologin<\/code> program from its manpage simply reads: <em>nologin - politely refuse\na login<\/em>. This program simply refuses a login, regardless of what credentials\nare supplied.<\/p>\n<p>And that's pretty much it for what the <code>\/etc\/passwd<\/code> file contains. For more\ndetails, you can read the <code>passwd (5)<\/code> manpage. Now, what about that shadow\nfile?<\/p>\n<blockquote>\n<p><strong>Hint:<\/strong> To access section <code>Y<\/code> of a manpage <code>PAGE<\/code>, type <code>man PAGE.Y<\/code> into a\nterminal. For example, to access <code>passwd (5)<\/code>, you type <code>man passwd.5<\/code>.<\/p>\n<\/blockquote>\n<h2 id=\"the-etcshadow-file\">The <code>\/etc\/shadow<\/code> file<\/h2>\n<p>The <code>\/etc\/passwd<\/code> file is a so-called <em>world-readable<\/em>, meaning that any user on\nthe system can read it. Many programs use this file to map users to their ids,\nfor example, and so its broad accessibility is necessary. A side effect is that\nstoring encrypted passwords in the <code>\/etc\/passwd<\/code> file lets any user that has\naccess to the system read the encrypted password of any other user. In times\nlong past, when cracking encrypted passwords was computationally infeasible,\nthis wasn't really a problem. Nowadays however, cracking an encrypted password\nis only a matter of (feasible) time.<\/p>\n<blockquote>\n<p><strong>Note:<\/strong> The <code>\/etc\/passwd<\/code> file is word-readable, but it's only writeable by\nroot to avoid other users tampering with it, such as by replacing an <code>x<\/code> with\nan actual password.<\/p>\n<\/blockquote>\n<p>The <code>\/etc\/shadow<\/code> file presents a solution to this problem. It is readable only\nby the root user, and contains the encrypted passwords of users with an <code>x<\/code> in\nthe password field of their <code>\/etc\/passwd<\/code> entry. The shadow file is technically\noptional, but you will probably never find a system that doesn't use it.<\/p>\n<p>I won't go into detail on how the shadow file is structured, as it's not a file\nthat's typically accessed by user space programs. If you want to know more about\nit, you can read the manpage of <code>shadow (5)<\/code>.<\/p>\n<p>And that's it for this article, hope you learned something!<\/p>","category":[{"@attributes":{"term":"Linux"}},{"@attributes":{"term":"linux"}}]},{"title":"Essential pytest pt. 1: Controlling the verbosity of output","link":{"@attributes":{"href":"https:\/\/slar.se\/essential-pytest-1.html","rel":"alternate"}},"published":"2020-07-31T20:07:56+00:00","updated":"2020-07-31T20:07:56+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2020-07-31:\/essential-pytest-1.html","summary":"<p>This is the first part of a series of small articles detailing some of the\nfunctionality of the <a href=\"https:\/\/docs.pytest.org\/en\/latest\/\">pytest<\/a> testing\nframework that I find most essential. The series assumes you know how to run\ntests with <code>pytest<\/code> already.<\/p>\n<p>In this first part, we'll take a look at the <code>-v<\/code> and \u2026<\/p>","content":"<p>This is the first part of a series of small articles detailing some of the\nfunctionality of the <a href=\"https:\/\/docs.pytest.org\/en\/latest\/\">pytest<\/a> testing\nframework that I find most essential. The series assumes you know how to run\ntests with <code>pytest<\/code> already.<\/p>\n<p>In this first part, we'll take a look at the <code>-v<\/code> and <code>--tb<\/code> options to control\nthe verbosity of the output.<\/p>\n<h2 id=\"the-test-suite\">The test suite<\/h2>\n<p>For the purposes of this article, I've implemented a very simple multiplication\nfunction called <code>mul<\/code>, along with a few tests. Here's the entire thing, in a\nfile called <code>test_mul.py<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># test_mul.py<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">mul<\/span><span class=\"p\">(<\/span><span class=\"n\">lhs<\/span><span class=\"p\">,<\/span> <span class=\"n\">rhs<\/span><span class=\"p\">):<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">lhs<\/span> <span class=\"o\">*<\/span> <span class=\"n\">lhs<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_equal_numbers<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span> <span class=\"mi\">5<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">25<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_by_zero<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"mi\">0<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">0<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">test_multiply_different_numbers<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"n\">mul<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"mi\">15<\/span>\n<\/code><\/pre><\/div>\n\n<p>Obviously, the implementation of <code>mul<\/code> is broken, and running <code>pytest<\/code> gives\nthe following output.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span><span class=\"nv\">pytest<\/span>\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.3,<span class=\"w\"> <\/span>pytest-5.4.3,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>items<span class=\"w\">                                                        <\/span>\n\ntest_mul.py<span class=\"w\"> <\/span>.FF<span class=\"w\">                                                         <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">================================<\/span><span class=\"w\"> <\/span><span class=\"nv\">FAILURES<\/span><span class=\"w\"> <\/span><span class=\"o\">================================<\/span>\n_________________________<span class=\"w\"> <\/span>test_multiply_by_zero<span class=\"w\"> <\/span>__________________________\n\n<span class=\"w\">    <\/span>def<span class=\"w\"> <\/span>test_multiply_by_zero<span class=\"o\">()<\/span>:\n&gt;<span class=\"w\">       <\/span>assert<span class=\"w\"> <\/span>mul<span class=\"o\">(<\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"o\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>\nE<span class=\"w\">       <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">1<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>\nE<span class=\"w\">        <\/span>+<span class=\"w\">  <\/span>where<span class=\"w\"> <\/span><span class=\"nv\">1<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>mul<span class=\"o\">(<\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"o\">)<\/span>\n\ntest_mul.py:8:<span class=\"w\"> <\/span>AssertionError\n____________________<span class=\"w\"> <\/span>test_multiply_different_numbers<span class=\"w\"> <\/span>_____________________\n\n<span class=\"w\">    <\/span>def<span class=\"w\"> <\/span>test_multiply_different_numbers<span class=\"o\">()<\/span>:\n&gt;<span class=\"w\">       <\/span>assert<span class=\"w\"> <\/span>mul<span class=\"o\">(<\/span><span class=\"m\">5<\/span>,<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"o\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">15<\/span>\nE<span class=\"w\">       <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">25<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">15<\/span>\nE<span class=\"w\">        <\/span>+<span class=\"w\">  <\/span>where<span class=\"w\"> <\/span><span class=\"nv\">25<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>mul<span class=\"o\">(<\/span><span class=\"m\">5<\/span>,<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"o\">)<\/span>\n\ntest_mul.py:11:<span class=\"w\"> <\/span><span class=\"nv\">AssertionError<\/span>\n<span class=\"o\">========================<\/span><span class=\"w\"> <\/span>short<span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>summary<span class=\"w\"> <\/span><span class=\"nv\">info<\/span><span class=\"w\"> <\/span><span class=\"o\">=========================<\/span>\nFAILED<span class=\"w\"> <\/span>test_mul.py::test_multiply_by_zero<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">1<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>\nFAILED<span class=\"w\"> <\/span>test_mul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">25<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"nv\">15<\/span>\n<span class=\"o\">======================<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>failed,<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>passed<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.08s<span class=\"w\"> <\/span><span class=\"o\">=======================<\/span>\n<\/code><\/pre><\/div>\n\n<p>Let's learn how to control how much of what we see here.<\/p>\n<h2 id=\"using-the-tb-option-to-control-traceback-verbosity\">Using the <code>--tb<\/code> option to control traceback verbosity<\/h2>\n<p>Most of what you're seeing in the output of the previous section is the\n<em>traceback<\/em> information. While the traceback shown above is manageable as is,\nconsider that it stems from a single-line function and single-line tests. With\nthat in mind, it's actually pretty freaking verbose. We can show less of it by\nusing the <code>--tb<\/code> option. We can even shut it off completely.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>--tb<span class=\"o\">=<\/span><span class=\"nv\">no<\/span>\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.3,<span class=\"w\"> <\/span>pytest-5.4.3,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>items<span class=\"w\">                                                        <\/span>\n\ntest_mul.py<span class=\"w\"> <\/span>.FF<span class=\"w\">                                                         <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">========================<\/span><span class=\"w\"> <\/span>short<span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>summary<span class=\"w\"> <\/span><span class=\"nv\">info<\/span><span class=\"w\"> <\/span><span class=\"o\">=========================<\/span>\nFAILED<span class=\"w\"> <\/span>test_mul.py::test_multiply_by_zero<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">1<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>\nFAILED<span class=\"w\"> <\/span>test_mul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">25<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"nv\">15<\/span>\n<span class=\"o\">======================<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>failed,<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>passed<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.02s<span class=\"w\"> <\/span><span class=\"o\">=======================<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is useful when you're just trying to figure out what tests are failing, and\nwhen test output is just entirely overwhelming. I find myself using it quite\nfrequently. Another useful traceback value is <code>line<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>--tb<span class=\"o\">=<\/span><span class=\"nv\">line<\/span>\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.3,<span class=\"w\"> <\/span>pytest-5.4.3,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>items<span class=\"w\">                                                        <\/span>\n\ntest_mul.py<span class=\"w\"> <\/span>.FF<span class=\"w\">                                                         <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">================================<\/span><span class=\"w\"> <\/span><span class=\"nv\">FAILURES<\/span><span class=\"w\"> <\/span><span class=\"o\">================================<\/span>\n\/home\/slarse\/python\/test_mul.py:8:<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">1<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>\n\/home\/slarse\/python\/test_mul.py:11:<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">25<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"nv\">15<\/span>\n<span class=\"o\">========================<\/span><span class=\"w\"> <\/span>short<span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>summary<span class=\"w\"> <\/span><span class=\"nv\">info<\/span><span class=\"w\"> <\/span><span class=\"o\">=========================<\/span>\nFAILED<span class=\"w\"> <\/span>test_mul.py::test_multiply_by_zero<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">1<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>\nFAILED<span class=\"w\"> <\/span>test_mul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">25<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"nv\">15<\/span>\n<span class=\"o\">======================<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>failed,<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>passed<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.03s<span class=\"w\"> <\/span><span class=\"o\">=======================<\/span>\n<\/code><\/pre><\/div>\n\n<p>This lets us see the exact lines where the test failures occurred. In this case,\nit shows the lines of the assertions, but it could also for example show the\nline where an exception was raised.<\/p>\n<p>Another one that I find really useful is <code>--tb=short<\/code>. It shows the full\ntraceback, but with much less context around each function call. It won't\nmake much of a difference for this short a traceback, but it makes a world of\ndifference for deeply nested function calls.<\/p>\n<p>There are more ways to manipulate the traceback, but these are the two I use the\nmost, aside from the default. To see the other options, refer to <code>pytest -h<\/code> and\nlook for the <code>--tb<\/code> option.<\/p>\n<h2 id=\"using-v-to-show-more-verbose-test-output\">Using <code>-v<\/code> to show more verbose test output<\/h2>\n<p>The <code>-v<\/code> option controls the verbosity of test output while the tests are\nrunning, and also the verbosity of single items in the traceback. It's really\nuseful when tests take a long time to run, and you want to know approximately\nwhere you're at.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>--tb<span class=\"o\">=<\/span>no<span class=\"w\"> <\/span>-v\n<span class=\"o\">==========================<\/span><span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>session<span class=\"w\"> <\/span><span class=\"nv\">starts<\/span><span class=\"w\"> <\/span><span class=\"o\">===========================<\/span>\nplatform<span class=\"w\"> <\/span>linux<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>Python<span class=\"w\"> <\/span><span class=\"m\">3<\/span>.8.3,<span class=\"w\"> <\/span>pytest-5.4.3,<span class=\"w\"> <\/span>py-1.9.0,<span class=\"w\"> <\/span>pluggy-0.13.1<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>\/usr\/bin\/python\ncachedir:<span class=\"w\"> <\/span>.pytest_cache\nrootdir:<span class=\"w\"> <\/span>\/home\/slarse\/python\ncollected<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span>items<span class=\"w\">                                                        <\/span>\n\ntest_mul.py::test_multiply_equal_numbers<span class=\"w\"> <\/span>PASSED<span class=\"w\">                         <\/span><span class=\"o\">[<\/span><span class=\"w\"> <\/span><span class=\"m\">33<\/span>%<span class=\"o\">]<\/span>\ntest_mul.py::test_multiply_by_zero<span class=\"w\"> <\/span>FAILED<span class=\"w\">                               <\/span><span class=\"o\">[<\/span><span class=\"w\"> <\/span><span class=\"m\">66<\/span>%<span class=\"o\">]<\/span>\ntest_mul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>FAILED<span class=\"w\">                     <\/span><span class=\"o\">[<\/span><span class=\"m\">100<\/span>%<span class=\"o\">]<\/span>\n\n<span class=\"o\">========================<\/span><span class=\"w\"> <\/span>short<span class=\"w\"> <\/span><span class=\"nb\">test<\/span><span class=\"w\"> <\/span>summary<span class=\"w\"> <\/span><span class=\"nv\">info<\/span><span class=\"w\"> <\/span><span class=\"o\">=========================<\/span>\nFAILED<span class=\"w\"> <\/span>test_mul.py::test_multiply_by_zero<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">1<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>\nFAILED<span class=\"w\"> <\/span>test_mul.py::test_multiply_different_numbers<span class=\"w\"> <\/span>-<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"nv\">25<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"nv\">15<\/span>\n<span class=\"o\">======================<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"w\"> <\/span>failed,<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>passed<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">0<\/span>.03s<span class=\"w\"> <\/span><span class=\"o\">=======================<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note how each test is now shown on a line of its own, as opposed to just <code>.<\/code> and\n<code>F<\/code> in the previous runs. The lines show up as the tests are running, and I find\nit useful to track long-running tests.<\/p>\n<p>But what about that \"single-item\" verbosity that I mentioned? When there are\nsingle items in the traceback that are very large, such as a list of say 1000\nelements, then pytest will truncate them by default. To demnstrate, consider\nthis single (pointless) test:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># test_truncation.py<\/span>\n<span class=\"kn\">import<\/span> <span class=\"nn\">pytest<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">test_truncation_demonstration<\/span><span class=\"p\">():<\/span>\n    <span class=\"k\">assert<\/span> <span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">,<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"mi\">2<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">]<\/span> <span class=\"o\">==<\/span> <span class=\"nb\">list<\/span><span class=\"p\">(<\/span><span class=\"nb\">range<\/span><span class=\"p\">(<\/span><span class=\"mi\">1000<\/span><span class=\"p\">))<\/span>\n<\/code><\/pre><\/div>\n\n<p>Running this test will yield a traceback that looks something like this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest\n<span class=\"o\">[<\/span>...<span class=\"w\"> <\/span>OMITTED<span class=\"w\"> <\/span>...<span class=\"o\">]<\/span>\n______________________<span class=\"w\"> <\/span>test_truncation_demonstration<span class=\"w\"> <\/span>_____________________\n\n<span class=\"w\">    <\/span>def<span class=\"w\"> <\/span>test_truncation_demonstration<span class=\"o\">()<\/span>:\n<span class=\"w\">    <\/span>&gt;<span class=\"w\">       <\/span>assert<span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"m\">0<\/span>,<span class=\"w\"> <\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">2<\/span>,<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span>list<span class=\"o\">(<\/span>range<span class=\"o\">(<\/span><span class=\"m\">1000<\/span><span class=\"o\">))<\/span>\n<span class=\"w\">    <\/span>E<span class=\"w\">       <\/span>assert<span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"m\">0<\/span>,<span class=\"w\"> <\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">2<\/span>,<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"m\">0<\/span>,<span class=\"w\"> <\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">2<\/span>,<span class=\"w\"> <\/span><span class=\"m\">3<\/span>,<span class=\"w\"> <\/span><span class=\"m\">4<\/span>,<span class=\"w\"> <\/span><span class=\"m\">5<\/span>,<span class=\"w\"> <\/span>...<span class=\"o\">]<\/span>\n<span class=\"w\">    <\/span>E<span class=\"w\">         <\/span>Right<span class=\"w\"> <\/span>contains<span class=\"w\"> <\/span><span class=\"m\">996<\/span><span class=\"w\"> <\/span>more<span class=\"w\"> <\/span>items,<span class=\"w\"> <\/span>first<span class=\"w\"> <\/span>extra<span class=\"w\"> <\/span>item:<span class=\"w\"> <\/span><span class=\"m\">4<\/span>\n<span class=\"w\">    <\/span>E<span class=\"w\">         <\/span>Use<span class=\"w\"> <\/span>-v<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span>get<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>full<span class=\"w\"> <\/span>diff\n\n<span class=\"w\">    <\/span>truncation.py:4:<span class=\"w\"> <\/span>AssertionError\n<\/code><\/pre><\/div>\n\n<p>Note how the long list has been truncated such that only the first few items are\nshown. Note also how pytest is suggesting the use of <code>-v<\/code>. If we supply <code>-v<\/code>, it\nactually still doesn't show the whole list.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>pytest<span class=\"w\"> <\/span>-v\n<span class=\"o\">[<\/span>...<span class=\"w\"> <\/span>OMITTED<span class=\"w\"> <\/span>...<span class=\"o\">]<\/span>\n______________________<span class=\"w\"> <\/span>test_truncation_demonstration<span class=\"w\"> <\/span>_____________________\n\n<span class=\"w\">    <\/span>def<span class=\"w\"> <\/span>test_truncation_demonstration<span class=\"o\">()<\/span>:\n<span class=\"w\">    <\/span>&gt;<span class=\"w\">       <\/span>assert<span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"m\">0<\/span>,<span class=\"w\"> <\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">2<\/span>,<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span>list<span class=\"o\">(<\/span>range<span class=\"o\">(<\/span><span class=\"m\">1000<\/span><span class=\"o\">))<\/span>\n<span class=\"w\">    <\/span>E<span class=\"w\">       <\/span>AssertionError:<span class=\"w\"> <\/span>assert<span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"m\">0<\/span>,<span class=\"w\"> <\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">2<\/span>,<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"o\">]<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"m\">0<\/span>,<span class=\"w\"> <\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">2<\/span>,<span class=\"w\"> <\/span><span class=\"m\">3<\/span>,<span class=\"w\"> <\/span><span class=\"m\">4<\/span>,<span class=\"w\"> <\/span><span class=\"m\">5<\/span>,<span class=\"w\"> <\/span>...<span class=\"o\">]<\/span>\n<span class=\"w\">    <\/span>E<span class=\"w\">         <\/span>Right<span class=\"w\"> <\/span>contains<span class=\"w\"> <\/span><span class=\"m\">996<\/span><span class=\"w\"> <\/span>more<span class=\"w\"> <\/span>items,<span class=\"w\"> <\/span>first<span class=\"w\"> <\/span>extra<span class=\"w\"> <\/span>item:<span class=\"w\"> <\/span><span class=\"m\">4<\/span>\n<span class=\"w\">    <\/span>E<span class=\"w\">         <\/span>Full<span class=\"w\"> <\/span>diff:\n<span class=\"w\">    <\/span>E<span class=\"w\">           <\/span><span class=\"o\">[<\/span>\n<span class=\"w\">    <\/span>E<span class=\"w\">            <\/span><span class=\"m\">0<\/span>,\n<span class=\"w\">    <\/span>E<span class=\"w\">            <\/span><span class=\"m\">1<\/span>,\n<span class=\"w\">    <\/span>E<span class=\"w\">            <\/span><span class=\"m\">2<\/span>,\n<span class=\"w\">    <\/span>E<span class=\"w\">            <\/span><span class=\"m\">3<\/span>,...\n<span class=\"w\">    <\/span>E<span class=\"w\">         <\/span>\n<span class=\"w\">    <\/span>E<span class=\"w\">         <\/span>...Full<span class=\"w\"> <\/span>output<span class=\"w\"> <\/span>truncated<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">998<\/span><span class=\"w\"> <\/span>lines<span class=\"w\"> <\/span>hidden<span class=\"o\">)<\/span>,<span class=\"w\"> <\/span>use<span class=\"w\"> <\/span><span class=\"s1\">&#39;-vv&#39;<\/span><span class=\"w\"> <\/span>to<span class=\"w\"> <\/span>show\n\n<span class=\"w\">    <\/span>truncation.py:4:<span class=\"w\"> <\/span>AssertionError\n<\/code><\/pre><\/div>\n\n<p>In fact, pytest isn't even showing more output here, it just shows the same\nthings more verbosely. If we stack <code>-v<\/code> twice, i.e. <code>-vv<\/code> or <code>-v -v<\/code>, then we\nget the full output. I find <code>-v<\/code> on its own to be rather useless, and typically\nalways supply <code>-vv<\/code> if I want verbose output. For obvious reasons, I will not\nshow what that output looks like.<\/p>\n<h2 id=\"summary\">Summary<\/h2>\n<p>In this article, we had a look at the <code>--tb<\/code> and <code>-v<\/code> options to control output\nverbosity in pytest. <code>--tb<\/code> controls the overall size of the traceback, and can\nbe supplied with values like <code>no<\/code> for no output at all, <code>line<\/code> for just a single\nline of traceback, or <code>short<\/code> for complete traceback with shortened context.\n<code>-v<\/code> controls the verbosity of running tests and single items in the traceback,\nsuch as very long lists which are truncated by default. Typically, <code>-vv<\/code> is\nrequired to get fully verbose output.<\/p>\n<p>And that's about it, I hope you learned something!<\/p>","category":[{"@attributes":{"term":"Testing"}},{"@attributes":{"term":"python"}},{"@attributes":{"term":"pytest"}},{"@attributes":{"term":"testing"}}]},{"title":"Don't use String for method options, use an enum!","link":{"@attributes":{"href":"https:\/\/slar.se\/dont-use-string-for-method-options-use-an-enum.html","rel":"alternate"}},"published":"2019-11-10T18:56:00+01:00","updated":"2019-11-10T18:56:00+01:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-11-10:\/dont-use-string-for-method-options-use-an-enum.html","summary":"<p>In this article, we are going to have a look at a method that accepts an option.\nThat is to say, it accepts an argument that somehow decides how it operates. If\nyou use a lot of libraries in your day-to-day programming, you're bound to come\nacross methods that accept \u2026<\/p>","content":"<p>In this article, we are going to have a look at a method that accepts an option.\nThat is to say, it accepts an argument that somehow decides how it operates. If\nyou use a lot of libraries in your day-to-day programming, you're bound to come\nacross methods that accept <code>String<\/code> values as such options, and you've probably\nbeen infuriated by you misspelling the options, or just trying to figure out\nwhat options there are in the first place. That suggests that there must be a\nbetter solution, and as you may have figured out by now,\n<a href=\"https:\/\/docs.oracle.com\/javase\/tutorial\/java\/javaOO\/enum.html\">enums<\/a> is that\nsolution.<\/p>\n<blockquote>\n<p><strong>Note:<\/strong> This article discusses enums in Java, but the very same arguments\nare valid for any language that has support for enum types, or something\ncomparable.<\/p>\n<\/blockquote>\n<h2 id=\"the-problem-what-options-do-i-have\">The problem: What options do I have?<\/h2>\n<p>Consider the following method that formats a <code>String<\/code> according to an option\nsupplied as another <code>String<\/code>:<\/p>\n<blockquote>\n<p>Yes, this is a somewhat contrived example, but bear with me!<\/p>\n<\/blockquote>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"nf\">format<\/span><span class=\"p\">(<\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">str<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">option<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">switch<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">option<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;upper&quot;<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">str<\/span><span class=\"p\">.<\/span><span class=\"na\">toUpperCase<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;lower&quot;<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">str<\/span><span class=\"p\">.<\/span><span class=\"na\">toLowerCase<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">default<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">throw<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">IllegalStateException<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Internal errror, unmatched option &quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"n\">option<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>We could then use the method something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">format<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;hello&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;upper&quot;<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>Can you see any problems with this? Well first of all, if you don't have access\nto the source, how do you know which options can be passed? There are an\ninfinite amount of strings, after all. At best, the Javadoc will say precisely\nwhich values are valid options, <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/nio\/file\/Files.html#getAttribute-java.nio.file.Path-java.lang.String-java.nio.file.LinkOption...-\">but that is not always the case even in the\nJava standard\nlibrary<\/a>.\nBut even if all of the options are clearly documented at one point, it would be\nso easy for a developer to add or remove an option, and forget to enact the\ncorresponding change in the Javadoc. It is also difficult to have automatic\nchecks that actually verify that all possible options are documented. And even\nassuming that all options are properly documented at all times, the compiler\ncan't distinguish which <code>String<\/code> values are valid and which are not, so a user\nmisspelling an option won't know until runtime.<\/p>\n<h2 id=\"the-solution-enums\">The solution: enums!<\/h2>\n<p>My goal here is not to explain the ins and outs of what enums are, but rather\nshow a use case. In short, an enum is a data type with a (typically very)\nlimited amount of possible values (<a href=\"https:\/\/docs.oracle.com\/javase\/tutorial\/java\/javaOO\/enum.html\">you can read more about it\nhere<\/a>).\nNow, let's instead define this enum type:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">enum<\/span><span class=\"w\"> <\/span><span class=\"n\">FormatOption<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">UPPER<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">LOWER<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>And refactor the method with it:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"nf\">format<\/span><span class=\"p\">(<\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">str<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">FormatOption<\/span><span class=\"w\"> <\/span><span class=\"n\">option<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">switch<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">option<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"n\">UPPER<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">str<\/span><span class=\"p\">.<\/span><span class=\"na\">toUpperCase<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"n\">LOWER<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">str<\/span><span class=\"p\">.<\/span><span class=\"na\">toLowerCase<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">default<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">throw<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">IllegalStateException<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Internal errror, unmatched option &quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"n\">option<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This method can then be used like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">format<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;hello&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">FormatOption<\/span><span class=\"p\">.<\/span><span class=\"na\">UPPER<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>With this small alteration, we have eliminated <em>all<\/em> of the problems mentioned\nbefore. The possible values for the <code>option<\/code> argument are now self-documented\nin the <code>FormatOption<\/code> enum. Additionally, any modern IDE will kindly list the\npossible values when you type <code>FormatOption.<\/code>, such that a programmer does not\neven necessarily need to consult the documentation, assuming that the enum\nvalues have descriptive enough names. The compiler can also distinguish between\n<code>FormatOption.UPPER<\/code> and a misspelling such as <code>FormatOption.UPER<\/code>, as the\nlatter is not defined, so runtime errors due to invalid options is no longer a\nproblem.<\/p>\n<h2 id=\"whats-the-catch\">What's the catch?<\/h2>\n<p>So what's the catch? Well, if you have many methods like this, you'll end up\nwith a lot of enum types. Personally, I think that's totally worth it, and you\ncould also nest the enums inside the classes that use them to reduce their\noverall footprint in the project. The whole thing could then look like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span> <span class=\"nc\">Formatter<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"kd\">enum<\/span><span class=\"w\"> <\/span><span class=\"n\">Option<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">UPPER<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">LOWER<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"kd\">static<\/span><span class=\"w\"> <\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"nf\">format<\/span><span class=\"p\">(<\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">str<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Option<\/span><span class=\"w\"> <\/span><span class=\"n\">option<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">result<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">switch<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">option<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"n\">UPPER<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">                <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">str<\/span><span class=\"p\">.<\/span><span class=\"na\">toUpperCase<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">case<\/span><span class=\"w\"> <\/span><span class=\"n\">LOWER<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">                <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">str<\/span><span class=\"p\">.<\/span><span class=\"na\">toLowerCase<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">default<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">                <\/span><span class=\"k\">throw<\/span><span class=\"w\"> <\/span><span class=\"k\">new<\/span><span class=\"w\"> <\/span><span class=\"n\">IllegalStateException<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Internal errror, unmatched option &quot;<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"n\">option<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Didn't add that much complexity now, did it?<\/p>\n<h2 id=\"summary\">Summary<\/h2>\n<p>If you have a method that you want to pass options to, <em>use enums<\/em>.\nThat's really all there is to it. Enums are quite widely used in the Java\nstandard library as well, such as\n<a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/nio\/file\/StandardCopyOption.html\">StandardCopyOption<\/a>,\n<a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/nio\/file\/StandardOpenOption.html\">StandardOpenOption<\/a> and\n<a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/nio\/file\/LinkOption.html\">LinkOption<\/a>\nin the <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/nio\/file\/package-summary.html\"><code>java.nio.file<\/code>\nAPI<\/a>,\nwhich are used much in the same way as I used the enum in this article.\nHopefully, having read this article, you won't be creating any more APIs that\naccept <code>String<\/code> options!<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"java"}},{"@attributes":{"term":"enums"}}]},{"title":"Java's Optional: Why you should prefer it over null","link":{"@attributes":{"href":"https:\/\/slar.se\/javas-optional-why-you-should-prefer-it-over-null.html","rel":"alternate"}},"published":"2019-10-11T16:57:00+02:00","updated":"2019-10-11T16:57:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-10-11:\/javas-optional-why-you-should-prefer-it-over-null.html","summary":"<p>Null references are problematic, to say the least. Tony Hoare (inventor of the\nnull reference) even went as far to say call them his <a href=\"https:\/\/en.wikipedia.org\/wiki\/Tony_Hoare#Apologies_and_retractions\">\"billion dollar\nmistake\"<\/a>.\nIn this article, I first make a cursory exploration of why null references are\nso problematic, and then have a look at Java's \u2026<\/p>","content":"<p>Null references are problematic, to say the least. Tony Hoare (inventor of the\nnull reference) even went as far to say call them his <a href=\"https:\/\/en.wikipedia.org\/wiki\/Tony_Hoare#Apologies_and_retractions\">\"billion dollar\nmistake\"<\/a>.\nIn this article, I first make a cursory exploration of why null references are\nso problematic, and then have a look at Java's proposed solution: the\n<a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Optional.html\"><code>Optional&lt;T&gt;<\/code> class<\/a>.<\/p>\n<h1 id=\"why-null-is-problematic\">Why null is problematic<\/h1>\n<p>There are many reasons why null is problematic, but there are a few that are\nparticularly easy to illustrate. I will be using the\n<a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Map.html#get(java.lang.Object)\"><code>Map.get<\/code><\/a>\nmethod as an example, as it returns null if the key provided to it is not in\nthe map. For all of the examples, assume that there is a variable <code>Map&lt;Integer,\nString&gt; map<\/code> in the current scope.<\/p>\n<h2 id=\"null-circumvents-the-type-system\">null circumvents the type system<\/h2>\n<p>Java has a fairly rigorous type system (although it's not entirely sound, I may\ndo an article on that later!). The type system can't help with null, however.\nAny variable of reference type can either contain a reference to an object of\nthat type, or null. This leads to a whole lot of code that looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">map<\/span><span class=\"p\">.<\/span><span class=\"na\">get<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">);<\/span>\n<span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">valueUpper<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">!=<\/span><span class=\"w\"> <\/span><span class=\"kc\">null<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">valueUpper<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"p\">.<\/span><span class=\"na\">toUpperCase<\/span><span class=\"p\">();<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"c1\">\/\/ else do something different with the knowledge that value is null<\/span>\n<\/code><\/pre><\/div>\n\n<p>While you may argue that null checks are pretty ugly, the real problem is that\nthey are not enforced by the type system. The above might just as well have\nbeen written like this, and the type checker would have been none the wiser:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">map<\/span><span class=\"p\">.<\/span><span class=\"na\">get<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">);<\/span>\n<span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">valueUpper<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"p\">.<\/span><span class=\"na\">toUpperCase<\/span><span class=\"p\">();<\/span>\n<\/code><\/pre><\/div>\n\n<p>This program could crash with a <code>NullPointerException<\/code>. That's not great. But\nit can be even worse. What if the call to <code>value.toUpperCase()<\/code> occurs in an\nentirely different part of the program, perhaps hours or even days after\n<code>Map.get<\/code> returned null? Then, not only do you have a crash, but a crash that\ncan potentially be very difficult to diagnose.<\/p>\n<h2 id=\"its-easy-to-miss-that-a-method-can-return-null\">It's easy to miss that a method can return null<\/h2>\n<p>The cause of the previous problem is often that it's not always obvious that a\nmethod may return null. If you have a look at the <a href=\"https:\/\/github.com\/openjdk\/jdk\/blob\/0dbfc97c05218ffd10242901d73c0715ccb53bf3\/src\/java.base\/share\/classes\/java\/util\/Map.java#L217-L242\">documentation for\nMap.get<\/a>,\nyou'll see that it says that it may return null a little here and there, and\nit's pretty clear about that. But still, a careless developer might miss this,\nand there's also the fact that many methods are <em>not<\/em> this well documented.<\/p>\n<h2 id=\"why-not-just-throw-an-exception-instead\">Why not just throw an exception instead?<\/h2>\n<p>One question you may ask is, why even return null, why not just throw an\nexception? Indeed, throwing an exception may be a good solution in many cases,\nbut sometimes it just isn't desirable. In the case of <code>Map.get<\/code>, it's mostly\nabout efficiency. If <code>Map.get<\/code> were to throw an exception when the key was\nmissing, you'd essentially have two alternatives. <\/p>\n<h3 id=\"ask-for-forgiveness-catch-the-exception\">Ask for forgiveness (catch the exception)<\/h3>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">try<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">map<\/span><span class=\"p\">.<\/span><span class=\"na\">get<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span><span class=\"w\"> <\/span><span class=\"k\">catch<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">NoSuchElementException<\/span><span class=\"w\"> <\/span><span class=\"n\">e<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ handle error<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>That's both ugly, and very inefficient if it is often the case that the key is\nmissing. Catching an exception involves a whole lot of work for the JVM, so you\nreally do not want to do this for an operation that you often perform.<\/p>\n<h3 id=\"look-before-you-leap\">Look before you leap<\/h3>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">map<\/span><span class=\"p\">.<\/span><span class=\"na\">containsKey<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">map<\/span><span class=\"p\">.<\/span><span class=\"na\">get<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"c1\">\/\/ else handle missing keys<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is not too ugly, but it is inefficient as the map has to be traversed twice:\nonce to check if it contains the key, and once more to fetch the value\nassociated with the key. Throwing an exception becomes even more undesirable if\nyou're using\n<a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/stream\/Stream.html\">Streams<\/a>.\nSo, I think we can safely conclude that throwing an exception is not the\nbe-all-end-all solution.<\/p>\n<h1 id=\"optionalt-to-the-rescue\"><code>Optional&lt;T&gt;<\/code> to the rescue<\/h1>\n<p>Using the <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Optional.html\"><code>Optional&lt;T&gt;<\/code>\nclass<\/a>, we\nsolve the issues discussed previously. <code>Optional<\/code> is simply a container for\nanother object that may or may not be null.\n<a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Optional.html#get--\"><code>Optional.get<\/code><\/a>\nreturns the contained object if present, or throws a <code>NoSuchElementException<\/code> if\nit is not (i.e. it is null).\n<a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Optional.html#isPresent--\"><code>Optional.isPresent<\/code><\/a>\nlets us check first if the value is present, to avoid an exception if it is not.\n<strong>Let's pretend<\/strong> like there's a method <code>Map.getOptional<\/code> that returns an\n<code>Optional&lt;T&gt;<\/code> instead of just <code>T<\/code>. We then have several options.<\/p>\n<blockquote>\n<p><strong>Important:<\/strong> There is no <code>Map.getOptional<\/code> method, this is just\nhypothetical. We'll see toward the end of the article how one can wrap\n<code>Map.get<\/code> to create a <code>getOptional<\/code> method.<\/p>\n<\/blockquote>\n<h2 id=\"retrieve-the-value-without-checking-if-it-is-present\">Retrieve the value without checking if it is present<\/h2>\n<p>If you're certain that the value will be present, you may simply retrieve it\nimmediately.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">Optional<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">String<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">opt<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">map<\/span><span class=\"p\">.<\/span><span class=\"na\">getOptional<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">);<\/span>\n<span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">opt<\/span><span class=\"p\">.<\/span><span class=\"na\">get<\/span><span class=\"p\">();<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ `value` will either be non-null, or we crash<\/span>\n<\/code><\/pre><\/div>\n\n<p>This may at first glance just look like more work than previously, two <code>get<\/code>\ncalls instead of one. The benefit here is that the programmer is extremely\nunlikely to miss the fact that the returned value may not be present, as the\nreturn value itself has the type <code>Optional&lt;String&gt;<\/code>, and the type system will\nscream bloody murder if they try to use the <code>Optional&lt;String&gt;<\/code> value like a\n<code>String<\/code>. Requiring that extra <code>get<\/code> <em>forces<\/em> the programmer to make a conscious\nchoice of how to handle errors. Now, this may crash with a\n<code>NoSuchElementException<\/code>, but as <code>Optional<\/code> values typically are not passed\naround, the is unlikely to happen far from where the <code>Optional<\/code> was produced.<\/p>\n<h2 id=\"check-if-the-object-is-present\">Check if the object is present<\/h2>\n<p>If you're uncertain whether the value will be present, you may simply check for\nit:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">Optional<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">String<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">opt<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">map<\/span><span class=\"p\">.<\/span><span class=\"na\">getOptional<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">);<\/span>\n<span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">opt<\/span><span class=\"p\">.<\/span><span class=\"na\">isPresent<\/span><span class=\"p\">())<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">opt<\/span><span class=\"p\">.<\/span><span class=\"na\">get<\/span><span class=\"p\">();<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is very much like the null check we had before, but it's supported by the\ntype system.<\/p>\n<h2 id=\"use-a-fallback-value\">Use a fallback value<\/h2>\n<p>Often when we don't want the code to crash, we have a fallback value. <code>Optional<\/code>\nhas a method to handle that.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">map<\/span><span class=\"p\">.<\/span><span class=\"na\">getOptional<\/span><span class=\"p\">(<\/span><span class=\"mi\">10<\/span><span class=\"p\">).<\/span><span class=\"na\">orElse<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Nothing here :)&quot;<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>If the value is present, it is returned. Otherwise, we get <code>\"Nothing here :)\"<\/code>.\nThis, I think, is one of the cleanest and tidiest uses of <code>Optional<\/code>.<\/p>\n<h2 id=\"what-about-drawbacks\">What about drawbacks?<\/h2>\n<p>Of course, <code>Optional<\/code> has drawbacks. As every single object is wrapped in\nanother object, there will be an increase in memory consumption. The extra\nmethod call <em>may<\/em> result in a noticeable performance penalty, but I don't dare\nsay anything concrete about that without running some tests (the JVM is pretty\ndarn good at inlining and optimizing). Perhaps, your most performance critical\nsegments of code should not use <code>Optional<\/code>. But the vast majority of your code\nis not performance critical, so most often it will be a moot point. Finally,\nthere's also a little bit of extra boilerplate to deal with, which also may not\nbe desirable.<\/p>\n<h1 id=\"alright-im-sold-how-do-i-optional\">Alright, I'm sold, how do I <code>Optional<\/code>?<\/h1>\n<p>We've already had a look at how to consume <code>Optional<\/code>s. But how do we produce\nthem? It's really quite easy. The three most important methods are:<\/p>\n<ol>\n<li><a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Optional.html#of-T-\"><code>static &lt;T&gt; Optional.of(T value)<\/code><\/a><ul>\n<li>A static method that wraps a value in an <code>Optional<\/code> instance. Throws an\n  exception if <code>value<\/code> is <code>null<\/code>.<\/li>\n<\/ul>\n<\/li>\n<li><a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Optional.html#empty--\"><code>static &lt;T&gt; Optional.empty()<\/code><\/a><ul>\n<li>A static method that returns an empty <code>Optional<\/code> instance.<\/li>\n<\/ul>\n<\/li>\n<li><a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Optional.html#ofNullable-T-\"><code>static &lt;T&gt; Optional.ofNullable(T value)<\/code><\/a><ul>\n<li>A static method that wraps a value in an <code>Optional<\/code>. The value may be\n  <code>null<\/code>, which essentially produces an empty <code>Optional<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p>The <code>of<\/code> and <code>empty<\/code> methods are the ones you want to produce <code>Optional<\/code> values\nfrom scratch. Here's a useless but simple example: an identity function for\ninteger values that is only defined for <code>n &gt;= 0<\/code>. Using null, it would look\nlike this.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"cm\">\/**<\/span>\n<span class=\"cm\"> * @param n An Integer value.<\/span>\n<span class=\"cm\"> * @return n iff n &gt;= 0, otherwise null<\/span>\n<span class=\"cm\"> *\/<\/span>\n<span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">Integer<\/span><span class=\"w\"> <\/span><span class=\"nf\">id<\/span><span class=\"p\">(<\/span><span class=\"n\">Integer<\/span><span class=\"w\"> <\/span><span class=\"n\">n<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">n<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;=<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">n<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"kc\">null<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This comes with all of the previously discussed problems associated with null\nreturn values. Here's the equivalent method using <code>Optional<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"cm\">\/**<\/span>\n<span class=\"cm\"> * @param n An Integer value.<\/span>\n<span class=\"cm\"> * @return An Optional with n iff n &gt;= 0, otherwise an empty Optional.<\/span>\n<span class=\"cm\"> *\/<\/span>\n<span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"n\">Optional<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Integer<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"nf\">id<\/span><span class=\"p\">(<\/span><span class=\"n\">Integer<\/span><span class=\"w\"> <\/span><span class=\"n\">n<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">if<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">n<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;=<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">Optional<\/span><span class=\"p\">.<\/span><span class=\"na\">of<\/span><span class=\"p\">(<\/span><span class=\"n\">n<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">Optional<\/span><span class=\"p\">.<\/span><span class=\"na\">empty<\/span><span class=\"p\">();<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Notice how both the documentation, and the return value itself, clearly states\nthat the value returned from the method may not be present. It is more or less\nimpossible to miss that this method may return an empty value (as long as you\nknow what <code>Optional<\/code> is, that is).<\/p>\n<p>The <code>ofNullable<\/code> method is great for wrapping existing methods that may return\nnull. For example, assuming that we have the <code>Map&lt;Integer, String&gt; map<\/code> field\nfrom earlier, we can wrap its <code>get<\/code> method in our own <code>getOptional<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">public<\/span><span class=\"w\"> <\/span><span class=\"nf\">getOptional<\/span><span class=\"p\">(<\/span><span class=\"n\">Integer<\/span><span class=\"w\"> <\/span><span class=\"n\">key<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">String<\/span><span class=\"w\"> <\/span><span class=\"n\">value<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">map<\/span><span class=\"p\">.<\/span><span class=\"na\">get<\/span><span class=\"p\">(<\/span><span class=\"n\">key<\/span><span class=\"p\">);<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ might be null!<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"n\">Optional<\/span><span class=\"p\">.<\/span><span class=\"na\">ofNullable<\/span><span class=\"p\">(<\/span><span class=\"n\">value<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This lets us easily create APIs that contain two versions of, for example, a\ngetter method: one that returns <code>T<\/code>, and one that returns <code>Optional&lt;T&gt;<\/code>. And\nthat's all the essentials. Not that hard, right?<\/p>\n<h1 id=\"summary\">Summary<\/h1>\n<p><code>Optional<\/code> solves most of the problems with null references in a mostly\nelegant way. The most important thing with <code>Optional<\/code> is that it is a strong\nform of documentation, which states both to the programmer and to the compiler\nthat the value asked for may be present. There's also the fact that\n<code>Optional<\/code> provides both the null-check approach using <code>isPresent<\/code>, and the\nexception-throwing approach by calling <code>get<\/code> without checking for presence. As\nsuch, the caller of a method gets to decide which of these approaches to use,\nincreasing flexibility. <code>Optional<\/code> is also a critical part of the <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/stream\/Stream.html\">Stream\nAPI<\/a>,\nwhich would be forced to throw exceptions left and right without it (and you'd\nbe forced to catch them!). Although the use of <code>Optional<\/code> may incur a\nperformance penalty, it is trivial to provide two versions of performance\ncritical methods: one that returns an <code>Optional&lt;T&gt;<\/code> and one that just returns\n<code>T<\/code>. If you want to learn more about <code>Optional<\/code>, I recommend first checking out\n<a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Optional.html\">the API\ndocumentation<\/a>.\nI also encourage having a look at the <a href=\"https:\/\/github.com\/openjdk\/jdk\/blob\/a95a39a04e066548764e15bfc793a6c242a22bb7\/src\/java.base\/share\/classes\/java\/util\/Optional.java\">source\ncode for\n<code>Optional<\/code><\/a>,\nit's a surprisingly simple class that provides all of this functionality!<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"java"}}]},{"title":"RepoBee (and Simon) at ITiCSE 2019!","link":{"@attributes":{"href":"https:\/\/slar.se\/repobee-and-simon-at-iticse-2019.html","rel":"alternate"}},"published":"2019-07-22T23:02:00+02:00","updated":"2019-04-10T23:20:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-07-22:\/repobee-and-simon-at-iticse-2019.html","summary":"<p>I just got home from the <em>Innovation and Technology in Computer Science<\/em>\n(ITiCSE) conference in lovely Aberdeen, Scotland. I was there to present a small\nexperience paper on developing and using <a href=\"https:\/\/repobee.org\">RepoBee<\/a>, an open\nsource tool for generating and managing large amounts of Git repositories for\nstudents in higher education \u2026<\/p>","content":"<p>I just got home from the <em>Innovation and Technology in Computer Science<\/em>\n(ITiCSE) conference in lovely Aberdeen, Scotland. I was there to present a small\nexperience paper on developing and using <a href=\"https:\/\/repobee.org\">RepoBee<\/a>, an open\nsource tool for generating and managing large amounts of Git repositories for\nstudents in higher education. The paper is available over in the <a href=\"https:\/\/doi.org\/10.1145\/3304221.3319784\">ACM Digital\nLibrary<\/a>, and it's my very first\npublication outside of school, so I'm quite proud of it!<\/p>\n<p>The conference itself was also terrific. The atmosphere was very friendly, there\nwere many interesting talks and social activities, and I have a hard time\nimagining how a conference could be more inviting to a first-time\nconference-goer like me. If you have a chance to attend it, I highly recommend\ndoing so.<\/p>","category":[{"@attributes":{"term":"Blog"}},{"@attributes":{"term":"blog"}}]},{"title":"Git worktrees: work in parallel on multiple versions of a project","link":{"@attributes":{"href":"https:\/\/slar.se\/git-worktrees-work-in-parallel-on-multiple-versions-of-a-project.html","rel":"alternate"}},"published":"2019-07-22T22:01:00+02:00","updated":"2019-07-22T22:01:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-07-22:\/git-worktrees-work-in-parallel-on-multiple-versions-of-a-project.html","summary":"<p>I've been AWOL for a month due to injury, sickness and conference-going. But\nwith all that finally out of the way, I have another Tip of the Week, this time\nrelating to Git: the <code>git worktree<\/code> command. With <code>git worktree<\/code>, you can check\nout <em>multiple<\/em> branches at once, which is \u2026<\/p>","content":"<p>I've been AWOL for a month due to injury, sickness and conference-going. But\nwith all that finally out of the way, I have another Tip of the Week, this time\nrelating to Git: the <code>git worktree<\/code> command. With <code>git worktree<\/code>, you can check\nout <em>multiple<\/em> branches at once, which is super useful for when working on major\nchanges where you need to view multiple versions, or maybe you're just trying a\nfew different solutions to a single prodlem. If you've ever found yourself\nfrantically switching branches, stashing changes to be able to switch branches,\nand even creating copies of the repository you're working in, then this article\nis for you.<\/p>\n<h3 id=\"an-example-repo\">An example repo<\/h3>\n<p>Let's first create an example repo. Here's a little terminal session where I\ncreate a repository, add a README to it on the master branch, add another line\nto the readme on a branch called other, and finally checking out to master.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">[<\/span>~<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>mkdir<span class=\"w\"> <\/span>repo\n<span class=\"o\">[<\/span>~<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span><span class=\"nb\">cd<\/span><span class=\"w\"> <\/span>repo\n<span class=\"o\">[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>init\nInitialized<span class=\"w\"> <\/span>empty<span class=\"w\"> <\/span>Git<span class=\"w\"> <\/span>repository<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>\/home\/slarse\/repo\/.git\/\n<span class=\"o\">[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span><span class=\"nb\">echo<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;Hello!&quot;<\/span><span class=\"w\"> <\/span>&gt;<span class=\"w\"> <\/span>README.md\n<span class=\"o\">[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>add<span class=\"w\"> <\/span>README.md<span class=\"w\"> <\/span><span class=\"o\">&amp;&amp;<\/span><span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>commit<span class=\"w\"> <\/span>-m<span class=\"w\"> <\/span><span class=\"s1\">&#39;Add README&#39;<\/span>\n<span class=\"o\">[<\/span>master<span class=\"w\"> <\/span><span class=\"o\">(<\/span>root-commit<span class=\"o\">)<\/span><span class=\"w\"> <\/span>6094baf<span class=\"o\">]<\/span><span class=\"w\"> <\/span>Add<span class=\"w\"> <\/span>README\n<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>file<span class=\"w\"> <\/span>changed,<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>insertion<span class=\"o\">(<\/span>+<span class=\"o\">)<\/span>\n<span class=\"w\"> <\/span>create<span class=\"w\"> <\/span>mode<span class=\"w\"> <\/span><span class=\"m\">100644<\/span><span class=\"w\"> <\/span>README.md\n<span class=\"o\">(<\/span>master<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>checkout<span class=\"w\"> <\/span>-b<span class=\"w\"> <\/span>other\nSwitched<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span>a<span class=\"w\"> <\/span>new<span class=\"w\"> <\/span>branch<span class=\"w\"> <\/span><span class=\"s1\">&#39;other&#39;<\/span>\n<span class=\"o\">(<\/span>other<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span><span class=\"nb\">echo<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;There!&quot;<\/span><span class=\"w\"> <\/span>&gt;&gt;<span class=\"w\"> <\/span>README.md<span class=\"w\"> <\/span>\n<span class=\"o\">(<\/span>other<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>commit<span class=\"w\"> <\/span>-am<span class=\"w\"> <\/span><span class=\"s1\">&#39;Add new line to README&#39;<\/span>\n<span class=\"o\">[<\/span>other<span class=\"w\"> <\/span>b779dfb<span class=\"o\">]<\/span><span class=\"w\"> <\/span>Add<span class=\"w\"> <\/span>new<span class=\"w\"> <\/span>line<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span>README\n<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>file<span class=\"w\"> <\/span>changed,<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>insertion<span class=\"o\">(<\/span>+<span class=\"o\">)<\/span>\n<span class=\"o\">(<\/span>other<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>checkout<span class=\"w\"> <\/span>master\nSwitched<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span>branch<span class=\"w\"> <\/span><span class=\"s1\">&#39;master&#39;<\/span>\n<span class=\"o\">(<\/span>master<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>\n<\/code><\/pre><\/div>\n\n<p>It's not super important how you do it, just make sure to have two branches.<\/p>\n<h3 id=\"adding-a-new-worktree\">Adding a new worktree<\/h3>\n<p>First of all: what is a <em>worktree<\/em>? Usually, you only have <em>the<\/em> worktree, which\nis the part of a repository where you actually do your work (edit files etc).\nRunning <code>git worktree list<\/code> on most repos will show the location of this single\nworktree, and what commit\/branch it is checked out to.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">(<\/span>master<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span><span class=\"nb\">pwd<\/span><span class=\"w\"> <\/span><span class=\"c1\"># just checking the current working directory<\/span>\n\/home\/slarse\/repo\n<span class=\"o\">(<\/span>master<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>worktree<span class=\"w\"> <\/span>list\n\/home\/slarse\/repo<span class=\"w\">  <\/span>6094baf<span class=\"w\"> <\/span><span class=\"o\">[<\/span>master<span class=\"o\">]<\/span><span class=\"w\">  <\/span><span class=\"c1\"># points to the cwd, checked out to master<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p><strong>Note:<\/strong> When I run <code>git worktree list<\/code> after this point, it's just to show\nthe results of commands.<\/p>\n<\/blockquote>\n<p>With <code>git worktree add<\/code>, you can add additional worktrees checked out to\ndifferent commits. The most basic usage is <code>git worktree add &lt;path&gt;\n&lt;commit-ish&gt;<\/code>, where <code>path<\/code> is a path to the new worktree (i.e. where you want\nto put it), and <code>commit-ish<\/code> is something like a commit or branch (or a few\nother things that are not important for every-day use). Let's check out <code>other<\/code>\nin a new worktree. <\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">(<\/span>master<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>worktree<span class=\"w\"> <\/span>add<span class=\"w\"> <\/span>..\/repo-other<span class=\"w\"> <\/span>other\nPreparing<span class=\"w\"> <\/span>worktree<span class=\"w\"> <\/span><span class=\"o\">(<\/span>checking<span class=\"w\"> <\/span>out<span class=\"w\"> <\/span><span class=\"s1\">&#39;other&#39;<\/span><span class=\"o\">)<\/span>\nHEAD<span class=\"w\"> <\/span>is<span class=\"w\"> <\/span>now<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>b779dfb<span class=\"w\"> <\/span>Add<span class=\"w\"> <\/span>new<span class=\"w\"> <\/span>line<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span>README\n<span class=\"o\">(<\/span>master<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>worktree<span class=\"w\"> <\/span>list\n\/home\/slarse\/repo<span class=\"w\">        <\/span>6094baf<span class=\"w\"> <\/span><span class=\"o\">[<\/span>master<span class=\"o\">]<\/span>\n\/home\/slarse\/repo-other<span class=\"w\">  <\/span>b779dfb<span class=\"w\"> <\/span><span class=\"o\">[<\/span>other<span class=\"o\">]<\/span>\n<span class=\"o\">(<\/span>master<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>ls<span class=\"w\"> <\/span>-a<span class=\"w\"> <\/span>..\/repo-other<span class=\"w\"> <\/span><span class=\"c1\"># have a look in the new working tree<\/span>\n.<span class=\"w\">  <\/span>..<span class=\"w\">  <\/span>.git<span class=\"w\">  <\/span>README.md\n<\/code><\/pre><\/div>\n\n<p>As you can see, the new worktree has been created, and can be seen in the list\nof worktrees. <code>.git<\/code> is usually a directory, but in the case of a non-primary\nworktree, it's actually just a file with a path to the original <code>.git<\/code>\ndirectory.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">(<\/span>master<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>..\/repo-other\/.git<span class=\"w\"> <\/span>\ngitdir:<span class=\"w\"> <\/span>\/home\/slarse\/repo\/.git\/worktrees\/repo-other\n<\/code><\/pre><\/div>\n\n<p>Like many things in Git, it's brilliantly simple. You can start working in your\nnew worktree like it's an entirely separate repository, with the caveat that you\ncan't check out to a branch that is checked out in some other worktree. That\nincludes checking out to other commits or branches, and even creating entirely\nnew branches.<\/p>\n<h3 id=\"moving-a-worktree\">Moving a worktree<\/h3>\n<p>If for some reason you need to move a worktree, you should use <code>git worktree\nmove<\/code> to make sure that all of the references are correctly changed. It's very\nsimple, just type <code>git worktree move &lt;src&gt; &lt;dst&gt;<\/code>. For example, if I want to\nmove <code>..\/repo-other<\/code> to <code>..\/repo-work<\/code>, I do:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">(<\/span>master<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>worktree<span class=\"w\"> <\/span>move<span class=\"w\"> <\/span>..\/repo-other<span class=\"w\"> <\/span>..\/repo-work\n<span class=\"o\">(<\/span>master<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>worktree<span class=\"w\"> <\/span>list\n\/home\/slarse\/repo<span class=\"w\">       <\/span>6094baf<span class=\"w\"> <\/span><span class=\"o\">[<\/span>master<span class=\"o\">]<\/span>\n\/home\/slarse\/repo-work<span class=\"w\">  <\/span>b779dfb<span class=\"w\"> <\/span><span class=\"o\">[<\/span>other<span class=\"o\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>That's all there is to moving worktrees. Not very exciting, and I can't recall\never actually doing it, but I can see how it could be useful.<\/p>\n<h3 id=\"removing-a-worktree\">Removing a worktree<\/h3>\n<p>To remove a worktree, run <code>git worktree remove &lt;path&gt;<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">(<\/span>master<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>worktree<span class=\"w\"> <\/span>remove<span class=\"w\"> <\/span>..\/repo-work\/\n<span class=\"o\">(<\/span>master<span class=\"o\">)[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>worktree<span class=\"w\"> <\/span>list\n\/home\/slarse\/repo<span class=\"w\">  <\/span>6094baf<span class=\"w\"> <\/span><span class=\"o\">[<\/span>master<span class=\"o\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>You can also just remove the directory with the worktree and the reference to it\nwill be removed automatically (but not necessarily immediately). Run <code>git\nworktree prune<\/code> to trigger this removal process.<\/p>\n<h3 id=\"the-other-worktree-commands\">The other worktree commands<\/h3>\n<p>There are a few more <code>git worktree<\/code> commands that I've never felt the need to\nuse. Have a look at them\n<a href=\"https:\/\/git-scm.com\/docs\/git-worktree\">in the git-worktree documentation<\/a>.<\/p>\n<h3 id=\"summary\">Summary<\/h3>\n<p>In this short article I showcased <code>git worktree<\/code>. It's super useful to work in\nparallel on different versions of the same project, without having to create\ncopies of the repository and thereby having to deal with synchronizing multiple\nlocal copies (which can quickly get hard to manage). I find myself using this\nmore and more, and if you find it useful yourself I highly recommend reading up\non it more in its man-page (either with <code>man git-worktree<\/code> or\n<a href=\"https:\/\/git-scm.com\/docs\/git-worktree\">online<\/a>).<\/p>","category":[{"@attributes":{"term":"Tip of the Week"}},{"@attributes":{"term":"totw"}},{"@attributes":{"term":"bash"}},{"@attributes":{"term":"git"}}]},{"title":"Redirecting stdout and stderr in bash","link":{"@attributes":{"href":"https:\/\/slar.se\/redirecting-stdout-and-stderr-in-bash.html","rel":"alternate"}},"published":"2019-06-23T21:37:00+02:00","updated":"2019-06-23T21:37:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-06-23:\/redirecting-stdout-and-stderr-in-bash.html","summary":"<p>A couple of weeks ago I covered some basic I\/O redirection in bash (see\n<a href=\"https:\/\/slar.se\/io-redirection-in-bash.html\">I\/O redirection in bash<\/a>). Well, there's actually\na lot more to it, so for this TOTW I thought I'd touch on a few more advanced\nusages.<\/p>\n<h2 id=\"redirecting-stderr\">Redirecting stderr<\/h2>\n<p>Sometimes, you may find that part \u2026<\/p>","content":"<p>A couple of weeks ago I covered some basic I\/O redirection in bash (see\n<a href=\"https:\/\/slar.se\/io-redirection-in-bash.html\">I\/O redirection in bash<\/a>). Well, there's actually\na lot more to it, so for this TOTW I thought I'd touch on a few more advanced\nusages.<\/p>\n<h2 id=\"redirecting-stderr\">Redirecting stderr<\/h2>\n<p>Sometimes, you may find that part or all of the output of a command isn't\nproperly redirected. As a quick example, navigate to any directory that is <em>not<\/em>\na Git repository, and run <code>git status<\/code>. You should see something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>status\nfatal:<span class=\"w\"> <\/span>not<span class=\"w\"> <\/span>a<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>repository<span class=\"w\"> <\/span><span class=\"o\">(<\/span>or<span class=\"w\"> <\/span>any<span class=\"w\"> <\/span>of<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>parent<span class=\"w\"> <\/span>directories<span class=\"o\">)<\/span>:<span class=\"w\"> <\/span>.git\n<\/code><\/pre><\/div>\n\n<p>Yet, if you try to redirect it with a standard redirect, the output\nis still displayed, and the file you redirect to remains empty.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>status<span class=\"w\"> <\/span>&gt;<span class=\"w\"> <\/span>output\nfatal:<span class=\"w\"> <\/span>not<span class=\"w\"> <\/span>a<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>repository<span class=\"w\"> <\/span><span class=\"o\">(<\/span>or<span class=\"w\"> <\/span>any<span class=\"w\"> <\/span>of<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>parent<span class=\"w\"> <\/span>directories<span class=\"o\">)<\/span>:<span class=\"w\"> <\/span>.git\n$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>output\n$<span class=\"w\"> <\/span>\n<\/code><\/pre><\/div>\n\n<p>The reason is quite simple: the output from <code>git status<\/code> is an error message,\nwhich is typically output on <em>standard error<\/em> (stderr), while I\/O redirection\noperates on <em>standard output<\/em> (stdout) by default. When redirecting output (or\ninput, for that matter), one can optionally provide a file descriptor specifying\nwhich output stream to redirect. On a typical UNIX-like system, stdout is file\ndescriptor 1, and stderr is file descriptor 2. So if we want to catch that\nstderr output, we just need to prepend  a 2 to the redirection operator.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>status<span class=\"w\"> <\/span><span class=\"m\">2<\/span>&gt;<span class=\"w\"> <\/span>output\n$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>output\nfatal:<span class=\"w\"> <\/span>not<span class=\"w\"> <\/span>a<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>repository<span class=\"w\"> <\/span><span class=\"o\">(<\/span>or<span class=\"w\"> <\/span>any<span class=\"w\"> <\/span>of<span class=\"w\"> <\/span>the<span class=\"w\"> <\/span>parent<span class=\"w\"> <\/span>directories<span class=\"o\">)<\/span>:<span class=\"w\"> <\/span>.git\n<\/code><\/pre><\/div>\n\n<p>You can probably guess that if you leave the file descriptor out, it will\ndefault to 1. In some cases, you may want to redirect both stderr and stdout to\nthe same file. But many programs output both on stderr and stdout, and we may\nwant to redirect both of them.<\/p>\n<h2 id=\"redirecting-stderr-and-stdout\">Redirecting stderr and stdout<\/h2>\n<p>So, we can specify a file descriptor to redirect stdout or stderr (or any other\nfile descriptor, really), but many programs output on both stderr and stdout,\nand it's often useful to redirect both. Here's a small Python script <code>print.py<\/code>\nthat outputs on line on stdout and one on stderr.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kn\">import<\/span> <span class=\"nn\">sys<\/span>\n\n<span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;some standard output&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">file<\/span><span class=\"o\">=<\/span><span class=\"n\">sys<\/span><span class=\"o\">.<\/span><span class=\"n\">stdout<\/span><span class=\"p\">)<\/span>\n<span class=\"nb\">print<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;some error output&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">file<\/span><span class=\"o\">=<\/span><span class=\"n\">sys<\/span><span class=\"o\">.<\/span><span class=\"n\">stderr<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p><strong>Note:<\/strong> That's Python as in Python 3.<\/p>\n<\/blockquote>\n<p>If we redirect stdout only, then the stderr line is still printed to the\nterminal.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>python3<span class=\"w\"> <\/span>print.py<span class=\"w\"> <\/span><span class=\"m\">1<\/span>&gt;<span class=\"w\"> <\/span>stdout_output<span class=\"w\"> <\/span><span class=\"c1\"># recall that the 1 can be omitted<\/span>\nsome<span class=\"w\"> <\/span>error<span class=\"w\"> <\/span>output\n$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>stdout_output\nsome<span class=\"w\"> <\/span>standard<span class=\"w\"> <\/span>output\n<\/code><\/pre><\/div>\n\n<p>Similarly, redirecting only stderr leaves the stdout output on the terminal.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>python3<span class=\"w\"> <\/span>print.py<span class=\"w\"> <\/span><span class=\"m\">2<\/span>&gt;<span class=\"w\"> <\/span>stderr_output\nsome<span class=\"w\"> <\/span>standard<span class=\"w\"> <\/span>output\n$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>stderr_output\nsome<span class=\"w\"> <\/span>error<span class=\"w\"> <\/span>output\n<\/code><\/pre><\/div>\n\n<p>Quite intuitively, if we want to redirect both stderr and stdout to one file\neach, we can simply do two redirections following one another.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>python3<span class=\"w\"> <\/span>print.py<span class=\"w\"> <\/span><span class=\"m\">1<\/span>&gt;<span class=\"w\"> <\/span>stdout_output<span class=\"w\"> <\/span><span class=\"m\">2<\/span>&gt;<span class=\"w\"> <\/span>stderr_output\n$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>stdout_output\nsome<span class=\"w\"> <\/span>standard<span class=\"w\"> <\/span>output\n$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>stderr_output\nsome<span class=\"w\"> <\/span>error<span class=\"w\"> <\/span>output\n<\/code><\/pre><\/div>\n\n<p>There's also the possibility to redirect both stdout and stderr to the same file\nusing the special <code>&amp;<\/code> character in place of a file descriptor.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>python3<span class=\"w\"> <\/span>print.py<span class=\"w\"> <\/span><span class=\"p\">&amp;<\/span>&gt;<span class=\"w\"> <\/span>output\n$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>output\nsome<span class=\"w\"> <\/span>standard<span class=\"w\"> <\/span>output\nsome<span class=\"w\"> <\/span>error<span class=\"w\"> <\/span>output\n<\/code><\/pre><\/div>\n\n<p>And with that and the previous article, I've shared pretty much everything I\nfeel is useful with output redirection. In some future Tip of the Week, I'm sure\nI'll get into input redirecton as well, as it's much the same.<\/p>","category":[{"@attributes":{"term":"Tip of the Week"}},{"@attributes":{"term":"totw"}},{"@attributes":{"term":"bash"}}]},{"title":"Technical e-books from Humble Bundle","link":{"@attributes":{"href":"https:\/\/slar.se\/technical-e-books-from-humble-bundle.html","rel":"alternate"}},"published":"2019-06-13T09:12:00+02:00","updated":"2019-06-13T09:12:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-06-13:\/technical-e-books-from-humble-bundle.html","summary":"<p>Another Tip of the Week, in the same week as the previous one (because I've\nbeen slacking off). This one is very simple, and rather non-technical. I simply\nwant to direct attention toward\n<a href=\"https:\/\/www.humblebundle.com\/\">humblebundle.com<\/a>, and their quite frequent book\nbundles. Many of these book bundles include or are entirely \u2026<\/p>","content":"<p>Another Tip of the Week, in the same week as the previous one (because I've\nbeen slacking off). This one is very simple, and rather non-technical. I simply\nwant to direct attention toward\n<a href=\"https:\/\/www.humblebundle.com\/\">humblebundle.com<\/a>, and their quite frequent book\nbundles. Many of these book bundles include or are entirely centered around\nprogramming topics. I've gotten tons of great books from there over the years,\nand it can really pay off to keep an eye on the new bundles. Typically, the top\ntier of a book bundle is around 15-20 EUR, while most books in it cost more\nalone. There have been general programming bundles, hacking\/security bundles,\nPython bundles (a lot of them), Linux bundles, and much more. A few of the best\nbooks I've gotten from Humble include:<\/p>\n<ul>\n<li><a href=\"https:\/\/www.amazon.com\/Linux-Programming-Interface-System-Handbook\/dp\/1593272200\">The Linux Programming Interface<\/a><ul>\n<li>Got it in a 20 EUR bundle, while this book alone costs somewhere around 70.<\/li>\n<\/ul>\n<\/li>\n<li><a href=\"https:\/\/www.amazon.com\/Fluent-Python-Concise-Effective-Programming-dp-1491946008\/dp\/1491946008\/ref=mt_paperback?_encoding=UTF8&amp;me=&amp;qid=\">Fluent Python<\/a><ul>\n<li>I actually already owned this book at the time of acquiring it from a\n  bundle, but it's by far the best book on Python I've ever read.<\/li>\n<\/ul>\n<\/li>\n<li><a href=\"https:\/\/www.amazon.com\/Flask-Web-Development-Developing-Applications-dp-1491991739\/dp\/1491991739\/ref=mt_paperback?_encoding=UTF8&amp;me=&amp;qid=1560410372\">Flask Web Development<\/a><\/li>\n<li><a href=\"https:\/\/www.amazon.com\/CSS-Definitive-Guide-Visual-Presentation-dp-1449393195\/dp\/1449393195\/ref=mt_paperback?_encoding=UTF8&amp;me=&amp;qid=1560410482\">CSS: The Definitive Guide<\/a><\/li>\n<\/ul>\n<p>And many, many more! Really, all I want to get said with this TOTW is that you\nshould really keep an eye on Humble Bundle, as their book bundles contain\ntremendous value, and you can choose to put some (or all) of the money you pay\ntoward charity. And that's all there is to it!<\/p>\n<blockquote>\n<p><strong>Disclaimer:<\/strong> I am not sponsored by Humble in any way, I am simply a\nlong-time user of the service.<\/p>\n<\/blockquote>","category":[{"@attributes":{"term":"Tip of the Week"}},{"@attributes":{"term":"totw"}}]},{"title":"I\/O redirection in bash","link":{"@attributes":{"href":"https:\/\/slar.se\/io-redirection-in-bash.html","rel":"alternate"}},"published":"2019-06-11T23:16:00+02:00","updated":"2019-06-11T23:16:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-06-11:\/io-redirection-in-bash.html","summary":"<p>Alright, so Tip of the Week has turned somewhat into \"tip every two or three\nweeks\". It turns out that it's pretty difficult to find the time to actually\nwrite something every week. but I'll keep trying. With that out of the way,\nlet's head into the subject matter of \u2026<\/p>","content":"<p>Alright, so Tip of the Week has turned somewhat into \"tip every two or three\nweeks\". It turns out that it's pretty difficult to find the time to actually\nwrite something every week. but I'll keep trying. With that out of the way,\nlet's head into the subject matter of this post: <em>I\/O redirection<\/em>. \nWe'll just have a look at the most basic but also most generally applicable use\nof redirection: taking the output from a program and storing it in a file.<\/p>\n<blockquote>\n<p><strong>Important:<\/strong> Files will both be created and clobbered in this TOTW. When\ntrying this stuff out, first create a new directory and do everything in\nthere, so you don't litter your filesystem with strange files, or\naccidentally overwrite something important.<\/p>\n<\/blockquote>\n<h2 id=\"redirecting-output\">Redirecting output<\/h2>\n<p>To set the stage, I'll be working in a directory with the following contents:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">[<\/span>tmp<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>ls\nfile1.txt<span class=\"w\">  <\/span>file2.txt<span class=\"w\">  <\/span>image1.png<span class=\"w\"> <\/span>file2.txt\n<\/code><\/pre><\/div>\n\n<p>Redirecting output is fairly simple, and useful when you want to save the\noutput of some command in a file. There are two primary ways of redirecting\noutput: <em>appending<\/em> and <em>truncating<\/em>. Appending is the one I use the most,\nso let's start with that one.<\/p>\n<h3 id=\"appending-output-redirection\">Appending output redirection<\/h3>\n<p>With <code>&gt;&gt;<\/code>, we can make an appending redirect.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">[<\/span>tmp<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>ls<span class=\"w\"> <\/span>&gt;&gt;<span class=\"w\"> <\/span>ls_output.txt<span class=\"w\">  <\/span><span class=\"c1\"># output from ls saved to output.txt<\/span>\n<span class=\"o\">[<\/span>tmp<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>ls_output.txt<span class=\"w\">    <\/span><span class=\"c1\"># let&#39;s have a look... <\/span>\nfile1.txt\nfile2.txt\nimage1.png\nimage2.png\nls_output.txt\n<span class=\"o\">[<\/span>tmp<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>ls<span class=\"w\"> <\/span>&gt;&gt;<span class=\"w\"> <\/span>ls_output.txt<span class=\"w\">  <\/span><span class=\"c1\"># append new output<\/span>\n<span class=\"o\">[<\/span>tmp<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>ls_output.txt<span class=\"w\">    <\/span><span class=\"c1\"># let&#39;s have a look again<\/span>\nfile1.txt\nfile2.txt\nimage1.png\nimage2.png\nls_output.txt\nfile1.txt\nfile2.txt\nimage1.png\nimage2.png\nls_output.txt\n<\/code><\/pre><\/div>\n\n<p>There are three things to note here. First, the <code>ls_output.txt<\/code> file does not\nexist in the initial directory, and so it is created with the first redirect.\nNote however that <code>ls_output.txt<\/code> is present in the first redirected output\nfrom <code>ls<\/code>: <code>ls_output.txt<\/code> is actually created <em>before<\/em> <code>ls<\/code> is run as there\nneeds to be an open\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/File_descriptor\">file descriptor<\/a>* to the file\npass along. <\/p>\n<blockquote>\n<p>** * ** A file descriptor can simply be thought of as a pointer to a file.\nThere is no need to understand file descriptors intimately to use basic I\/O\nredirection efficiently.<\/p>\n<\/blockquote>\n<p>The second redirect is then appended to the file, which at that\npoint already exists. And that pretty much sums up how an appending redirect\nfunctions: it appends output to the specified file if it exists, and creates a\nfile with the output if it does not exist. I find that this is most often the\nfunctionality that I want, but in some cases, you want to re-create the file\nfrom scratch with each redirect. That can be achieved with a truncating\nredirect.<\/p>\n<blockquote>\n<p><strong>Note:<\/strong> You may note that the output of <code>ls<\/code> is formatted differently when\noutput to the terminal, and when redirected to a file. <code>ls<\/code> checks whether\nthe stdout file descriptor points to a terminal, or something else, and\nformats the output accordingly. The details are somewhat out of scope.<\/p>\n<\/blockquote>\n<h3 id=\"truncating-output-redirection\">Truncating output redirection<\/h3>\n<p>Let's assume that we start over from the initial state of the directory, before\n<code>ls_output.txt<\/code> existed. We can then make a truncating redirect with <code>&gt;<\/code>.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">[<\/span>tmp<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>rm<span class=\"w\"> <\/span>ls_output.txt<span class=\"w\">    <\/span><span class=\"c1\"># restore initial directory state<\/span>\n<span class=\"o\">[<\/span>tmp<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>ls<span class=\"w\"> <\/span>&gt;<span class=\"w\"> <\/span>ls_output.txt<span class=\"w\">  <\/span><span class=\"c1\"># make a truncating redirect<\/span>\n<span class=\"o\">[<\/span>tmp<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>ls_output.txt<span class=\"w\">   <\/span><span class=\"c1\"># and inspect the results<\/span>\nfile1.txt\nfile2.txt\nimage1.png\nimage2.png\nls_output.txt\n<span class=\"o\">[<\/span>tmp<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>ls<span class=\"w\"> <\/span>&gt;<span class=\"w\"> <\/span>ls_output.txt<span class=\"w\">  <\/span><span class=\"c1\"># another truncating redirect<\/span>\n<span class=\"o\">[<\/span>tmp<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>cat<span class=\"w\"> <\/span>ls_output.txt\nfile1.txt\nfile2.txt\nimage1.png\nimage2.png\nls_output.txt\n<\/code><\/pre><\/div>\n\n<p>If you did not know what truncating meant before, you can probably figure it out\nnow. With a single <code>&gt;<\/code>, the specified file is created if it does not exist, just\nlike with <code>&gt;&gt;<\/code>, but it is entirely overwritten (truncated, clobbered) if it\nalready does exist. I rarely use a truncating redirect, as it is an easy thing\nto accidentally truncate a file you did not mean to touch. I recommend to always\nuse an appending redirect, unless you have a good reason to truncate the\ntargeted file.<\/p>\n<p>And that's it for this TOTW!<\/p>","category":[{"@attributes":{"term":"Tip of the Week"}},{"@attributes":{"term":"totw"}},{"@attributes":{"term":"bash"}}]},{"title":"Piping commands in bash","link":{"@attributes":{"href":"https:\/\/slar.se\/piping-commands-in-bash.html","rel":"alternate"}},"published":"2019-05-21T00:00:00+02:00","updated":"2019-05-21T00:00:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-05-21:\/piping-commands-in-bash.html","summary":"<p>Many, many bash commands are built around and meant to be used with a\nfundamental feature of the bash shell (actually, most shells), called <em>piping<\/em>.\nPut simply, piping takes the output of one command and provides it as input to\nthe next. Here's a simple example of running <code>ls<\/code> and \u2026<\/p>","content":"<p>Many, many bash commands are built around and meant to be used with a\nfundamental feature of the bash shell (actually, most shells), called <em>piping<\/em>.\nPut simply, piping takes the output of one command and provides it as input to\nthe next. Here's a simple example of running <code>ls<\/code> and filtering the result with\n<code>grep<\/code> to find all <code>.py<\/code> files in the current directory.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>ls<span class=\"w\"> <\/span><span class=\"c1\"># just run ls <\/span>\nfile1.md<span class=\"w\">  <\/span>file2.md<span class=\"w\">  <\/span>file3.md<span class=\"w\">  <\/span>script1.py<span class=\"w\">  <\/span>script2.py\n$<span class=\"w\"> <\/span>ls<span class=\"w\"> <\/span><span class=\"p\">|<\/span><span class=\"w\"> <\/span>grep<span class=\"w\"> <\/span><span class=\"s1\">&#39;\\.py$&#39;<\/span>\nscript1.py\nscript2.py\n<\/code><\/pre><\/div>\n\n<p>To be precise, the <code>|<\/code> (pipe) operator takes the output from the command on the\nleft, and provides it as input to the command on the right. Pipes can be chained\npractically as much as you'd like. For example, if we want to get amount of\n<code>.py<\/code> files in the current directory, we can pipe the output from <code>grep<\/code> to the\n<code>wc<\/code> (word count) command, with the <code>-l<\/code> option to count lines only.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>ls<span class=\"w\"> <\/span><span class=\"p\">|<\/span><span class=\"w\"> <\/span>grep<span class=\"w\"> <\/span><span class=\"s1\">&#39;\\.py$&#39;<\/span><span class=\"w\"> <\/span><span class=\"p\">|<\/span><span class=\"w\"> <\/span>wc<span class=\"w\"> <\/span>-l\n<span class=\"m\">2<\/span>\n<\/code><\/pre><\/div>\n\n<p><code>wc<\/code> counts two lines, which is precisely the amount of <code>.py<\/code> files that we\nfound. Let's move on to I\/O redirection. Piping allows you to easily compose\npowerful programs from simple commands, and is a very intuitive way to work.\nNext week, I'll cover I\/O redirection, which is another super useful feature of\nbash that's a bit more complicated.<\/p>","category":[{"@attributes":{"term":"Tip of the Week"}},{"@attributes":{"term":"totw"}},{"@attributes":{"term":"bash"}}]},{"title":"Using bash aliases","link":{"@attributes":{"href":"https:\/\/slar.se\/using-bash-aliases.html","rel":"alternate"}},"published":"2019-05-06T12:19:00+02:00","updated":"2019-05-06T12:19:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-05-06:\/using-bash-aliases.html","summary":"<p>For this <em>Tip of the Week<\/em>, I'd like to present something that took me a while\nto figure out why it was useful. That something is bash aliases, and I'll now\nwalk you through how to create aliases, and the two main ways in which I use\nthem (although I'm \u2026<\/p>","content":"<p>For this <em>Tip of the Week<\/em>, I'd like to present something that took me a while\nto figure out why it was useful. That something is bash aliases, and I'll now\nwalk you through how to create aliases, and the two main ways in which I use\nthem (although I'm sure there are more use cases).<\/p>\n<h1 id=\"using-aliases\">Using aliases<\/h1>\n<p>I think the <code>bash<\/code> manpage has a very good and concise description of what an\nalias is:<\/p>\n<blockquote>\n<p>Aliases allow a string to be substituted for a word when it is used as the\nfirst word of a simple command<\/p>\n<\/blockquote>\n<p>In other words, I can define a command that is substituted for some other\ncommand. Creating an alias is very simple. The syntax looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>alias &lt;NAME&gt;=&lt;COMMAND&gt;\n<\/code><\/pre><\/div>\n\n<p>So for example, if I want to have a command <code>hellofile<\/code> that creates a file with\nthe text \"Hello, world!\", I can achieve that with the following alias.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span><span class=\"nb\">alias<\/span><span class=\"w\"> <\/span><span class=\"nv\">hellofile<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;echo &quot;Hello, world!&quot; &gt; hellofile.txt&#39;<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note the single quotes around the command definition. Without them, <code>bash<\/code>\nwould interpret the alias as being only <code>echo<\/code>, and the rest of the line as\nanother command. Now, if I run the command <code>hellofile<\/code>, it fill be substituted\nwith <code>echo \"Hello, world!\" &gt; hellofile.txt<\/code>. You should think of aliases as pure\ntext substitution: precisely what you put in the alias definition will be put on\nthe command line when you invoke it. You can view all of your current aliases\nby running <code>alias<\/code> without any options. Now, let's have a look at some common\nuse cases!<\/p>\n<h2 id=\"specifying-default-options-for-commands\">Specifying \"default\" options for commands<\/h2>\n<p>This is probably the most common use case for aliases, and it's likely that you\nalready have some in play. A common one is to have <code>ls<\/code> aliased to <code>ls\n--color=auto<\/code>. That is to say, the following alias is defined:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span><span class=\"nb\">alias<\/span><span class=\"w\"> <\/span><span class=\"nv\">ls<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;ls --color=auto&#39;<\/span>\n<\/code><\/pre><\/div>\n\n<p>So if I now run e.g. <code>ls \/etc<\/code>, the resulting command is actually <code>ls\n--color=auto \/etc<\/code>. Note how the alias does not have to be the <em>only<\/em> word I\ntype for the command, it just has to be the first one. Another command that I\nuse an alias for is <code>xclip<\/code>, which is a small utility for copying stuff. I use\nit almost exclusively to copy file contents to the clipboard, but that's not the\ndefault functionality. In order to copy to the clipboard, I must write this\nrather cumbersome command.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>xclip<span class=\"w\"> <\/span>-selection<span class=\"w\"> <\/span>clipboard<span class=\"w\"> <\/span>&lt;FILEPATH&gt;\n<\/code><\/pre><\/div>\n\n<p>So I have an alias for it so I can just type <code>xclip &lt;FILEPATH&gt;<\/code> to copy to the\nclipboard.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span><span class=\"nb\">alias<\/span><span class=\"w\"> <\/span><span class=\"nv\">xclip<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;xclip -selection clipboard&#39;<\/span>\n<\/code><\/pre><\/div>\n\n<p>As a side note, it may not be the best style to clobber an existing command with\nan alias, but I still tend to do that for some of my most commonly used\ncommands. If you want to use the vanilla command, simply put it within single\nquotes, which will hinder the alias from expanding (e.g. type <code>'ls'<\/code> to run <code>ls<\/code>\nwithout <code>--color=auto<\/code>). Note that just defining an alias in a <code>bash<\/code> session\nwill not persist: it needs to be defined anew for each session. To have it\npermanently defined, put the definition in a startup script (e.g. <code>.bashrc<\/code> or\n<code>.bash_profile<\/code>).<\/p>\n<h2 id=\"creating-throwaway-commands\">Creating throwaway commands<\/h2>\n<p>Now, the aliases I described above are useful to have defined permanently, and\nshould be defined in a startup script. The second use case I have for aliases is\nwhen I have a repetitive command that I need to type over and over in the same\nsession, but isn't useful in general. An example would be when I need to run\nsome specific Java class in a project. Let's say I need to run the class\n<code>se.slar.awesome.project.Main<\/code> over and over. Instead of typing <code>java\nse.slar.awesome.project.Main<\/code> over and over, I define an alias for it.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span><span class=\"nb\">alias<\/span><span class=\"w\"> <\/span><span class=\"nv\">runmain<\/span><span class=\"o\">=<\/span><span class=\"s1\">&#39;java se.slar.awesome.project.Main&#39;<\/span>\n<\/code><\/pre><\/div>\n\n<p>And then, instead of writing all of that out, or having to do some\n<a href=\"https:\/\/slar.se\/reverse-search-in-bash.html\">reverse searching<\/a> or\n<a href=\"https:\/\/slar.se\/history-and-history-expansion-in-bash.html\">history lookups<\/a>, I can just type <code>runmain<\/code>.\nAs defining an alias is so effortless, I tend to do it even if I know I'm just\ngonna use the complex command a couple of times.<\/p>\n<p>And that's all I wanted to cover, hope you enjoyed it and stay tuned for the\nnext TOTW coming next week!<\/p>","category":[{"@attributes":{"term":"Tip of the Week"}},{"@attributes":{"term":"totw"}},{"@attributes":{"term":"bash"}}]},{"title":"Git local","link":{"@attributes":{"href":"https:\/\/slar.se\/git-local.html","rel":"alternate"}},"published":"2019-04-29T22:58:00+02:00","updated":"2019-04-29T22:58:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-04-29:\/git-local.html","summary":"<p>Nowadays, Git is almost ubiquitous in software development. Most developers also\nknow that Git is a <em>decentralized<\/em> version control system, meaning that every\ncopy of the repository carries the full revision history, and there is no\n\"central\" repository. A consequence of the decentralized aspect of Git is that\nyou can \u2026<\/p>","content":"<p>Nowadays, Git is almost ubiquitous in software development. Most developers also\nknow that Git is a <em>decentralized<\/em> version control system, meaning that every\ncopy of the repository carries the full revision history, and there is no\n\"central\" repository. A consequence of the decentralized aspect of Git is that\nyou can create repositories locally, and version control documents in them\nlocally, without ever setting up a remote repository on e.g. GitHub or GitLab.\nIn this TOTW, I'll show you how to use Git locally, and also how to change your\nmind and put it on e.g. GitHub at a later time.<\/p>\n<blockquote>\n<p><strong>Note:<\/strong> This also touches on an important and often misunderstood point: Git\nand GitHub are <em>not<\/em> the same thing. Git is a version control system, while\nGitHub is a service which allows hosting of remote repositories, issue\nmanagement etc. GitHub is also not the only service around,\n<a href=\"https:\/\/gitlab.com\">GitLab<\/a> and <a href=\"https:\/\/bitbucket.com\">BitBucket<\/a> are two\nother prominent services which host Git repositories.<\/p>\n<\/blockquote>\n<h3 id=\"using-git-locally\">Using Git locally<\/h3>\n<p>How do you use Git locally, then? It's simple. Just create a directory and run\n<code>git init<\/code> to initialize it as a Git repository. Here's an example command line\nsession of what it looks like.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">[<\/span>~<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>mkdir<span class=\"w\"> <\/span>repo\n<span class=\"o\">[<\/span>~<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span><span class=\"nb\">cd<\/span><span class=\"w\"> <\/span>repo\n<span class=\"o\">[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>ls<span class=\"w\"> <\/span>-a\n.<span class=\"w\"> <\/span>..<span class=\"w\">            <\/span><span class=\"c1\"># repo is empty<\/span>\n<span class=\"o\">[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>init\nInitialized<span class=\"w\"> <\/span>empty<span class=\"w\"> <\/span>Git<span class=\"w\"> <\/span>repository<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>\/home\/slarse\/repo\/.git\/\n<span class=\"o\">[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>ls<span class=\"w\"> <\/span>-a\n.<span class=\"w\">  <\/span>..<span class=\"w\">  <\/span>.git<span class=\"w\">     <\/span><span class=\"c1\"># the .git directory indicates that this is now a Git repo<\/span>\n<\/code><\/pre><\/div>\n\n<p>I often use Git to version control stuff that I have no intention of ever\nputting up in a remote repository. This is useful for when you accidentally\nremove stuff, or just need to try out a bunch of different ideas that you can\nswap back and forth between by simply switching branches.<\/p>\n<h3 id=\"changing-your-mind-also-called-adding-a-remote\">Changing your mind (also called adding a remote)<\/h3>\n<p>If you suddenly feel like that local repo should be put up on a hosting service\nafter all, maybe just to back it up, or maybe to collaborate with someone else,\nit's very simple to do so. First, create an empty repository (as in completely\nempty, don't initialize it with a README or license). Then copy the address to\nthe repository (I prefer to use SSH). Let's say I have a repo at\n<code>git@github.com:slarse\/superrepo.git<\/code>. I can then add it as a remote to my local\nrepo, and push my master branch to it.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>remote<span class=\"w\"> <\/span>add<span class=\"w\"> <\/span>origin<span class=\"w\"> <\/span>git@github.com:slarse\/superrepo.git\n<span class=\"o\">[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>branch\n*<span class=\"w\"> <\/span>master<span class=\"w\">  <\/span><span class=\"c1\"># I&#39;m on the master branch, which is what I want to push<\/span>\n<span class=\"o\">[<\/span>repo<span class=\"o\">]<\/span><span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>push<span class=\"w\"> <\/span>--set-upstream<span class=\"w\"> <\/span>origin<span class=\"w\"> <\/span>master\nEnumerating<span class=\"w\"> <\/span>objects:<span class=\"w\"> <\/span><span class=\"m\">3<\/span>,<span class=\"w\"> <\/span><span class=\"k\">done<\/span>.\nCounting<span class=\"w\"> <\/span>objects:<span class=\"w\"> <\/span><span class=\"m\">100<\/span>%<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">3<\/span>\/3<span class=\"o\">)<\/span>,<span class=\"w\"> <\/span><span class=\"k\">done<\/span>.\nWriting<span class=\"w\"> <\/span>objects:<span class=\"w\"> <\/span><span class=\"m\">100<\/span>%<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">3<\/span>\/3<span class=\"o\">)<\/span>,<span class=\"w\"> <\/span><span class=\"m\">213<\/span><span class=\"w\"> <\/span>bytes<span class=\"w\"> <\/span><span class=\"p\">|<\/span><span class=\"w\"> <\/span><span class=\"m\">213<\/span>.00<span class=\"w\"> <\/span>KiB\/s,<span class=\"w\"> <\/span><span class=\"k\">done<\/span>.\nTotal<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"w\"> <\/span><span class=\"o\">(<\/span>delta<span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"o\">)<\/span>,<span class=\"w\"> <\/span>reused<span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"w\"> <\/span><span class=\"o\">(<\/span>delta<span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"o\">)<\/span>\nTo<span class=\"w\"> <\/span>github.com:slarse\/superrepo.git\n<span class=\"w\"> <\/span>*<span class=\"w\"> <\/span><span class=\"o\">[<\/span>new<span class=\"w\"> <\/span>branch<span class=\"o\">]<\/span><span class=\"w\">      <\/span>master<span class=\"w\"> <\/span>-&gt;<span class=\"w\"> <\/span>master\nBranch<span class=\"w\"> <\/span><span class=\"s1\">&#39;master&#39;<\/span><span class=\"w\"> <\/span><span class=\"nb\">set<\/span><span class=\"w\"> <\/span>up<span class=\"w\"> <\/span>to<span class=\"w\"> <\/span>track<span class=\"w\"> <\/span>remote<span class=\"w\"> <\/span>branch<span class=\"w\"> <\/span><span class=\"s1\">&#39;master&#39;<\/span><span class=\"w\"> <\/span>from<span class=\"w\"> <\/span><span class=\"s1\">&#39;origin&#39;<\/span>.\n<\/code><\/pre><\/div>\n\n<p>Now my previously local-only repo is also in GitHub, and I can push and pull\nfrom it as usual. That's all for this tip of the week, it's just meant to spark\nan idea that took me quite a while to come up with myself!<\/p>","category":[{"@attributes":{"term":"Tip of the Week"}},{"@attributes":{"term":"totw"}},{"@attributes":{"term":"bash"}},{"@attributes":{"term":"git"}}]},{"title":"History and history expansion in bash","link":{"@attributes":{"href":"https:\/\/slar.se\/history-and-history-expansion-in-bash.html","rel":"alternate"}},"published":"2019-04-22T11:59:00+02:00","updated":"2019-04-22T11:59:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-04-22:\/history-and-history-expansion-in-bash.html","summary":"<p>Admittedly, this TOTW is one day late, so this week there will be 2xTOTW! In\nany case, the tip I want to bring up here is very much related to last week's\nTOTW on <a href=\"https:\/\/slar.se\/reverse-search-in-bash.html\">Reverse search in bash<\/a>. Sometimes,\nreverse searching just doesn't work out. You may not be quite \u2026<\/p>","content":"<p>Admittedly, this TOTW is one day late, so this week there will be 2xTOTW! In\nany case, the tip I want to bring up here is very much related to last week's\nTOTW on <a href=\"https:\/\/slar.se\/reverse-search-in-bash.html\">Reverse search in bash<\/a>. Sometimes,\nreverse searching just doesn't work out. You may not be quite sure what you\nare looking for, or there are just too many recent commands that look samey.\nIn such cases, using the <code>history<\/code> command is a good alternative. <\/p>\n<h3 id=\"history\"><code>history<\/code><\/h3>\n<p>The <code>history<\/code> command will display the last commands that you have entered, and\nlooks something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span><span class=\"nb\">history<\/span>\n<span class=\"w\"> <\/span><span class=\"m\">1009<\/span><span class=\"w\">  <\/span><span class=\"nb\">fg<\/span>\n<span class=\"w\"> <\/span><span class=\"m\">1010<\/span><span class=\"w\">  <\/span>git<span class=\"w\"> <\/span>status\n<span class=\"w\"> <\/span><span class=\"m\">1011<\/span><span class=\"w\">  <\/span>git<span class=\"w\"> <\/span>commit<span class=\"w\"> <\/span>-a<span class=\"w\"> <\/span>-m<span class=\"w\"> <\/span><span class=\"s1\">&#39;Add module docstring to github_api module&#39;<\/span>\n<span class=\"w\"> <\/span><span class=\"o\">[<\/span>***OUTPUT<span class=\"w\"> <\/span>TRUNCATED***<span class=\"o\">]<\/span>\n<span class=\"w\"> <\/span><span class=\"m\">2007<\/span><span class=\"w\">  <\/span><span class=\"nb\">history<\/span>\n<\/code><\/pre><\/div>\n\n<p>Each command is called an <em>event<\/em>, and the output is formatted as <code>&lt;event_nr&gt;\n&lt;event&gt;<\/code>. Precisely how many commands are returned by the <code>history<\/code> is\ndetermined by the <code>HISTSIZE<\/code> and <code>HISTFILESIZE<\/code> environment variables. Setting\nthese to something like <code>5000<\/code> and <code>10000<\/code>, respectively, should be manageable\neven for the weakest of computers. You can also limit the output of <code>history<\/code>\nby providing an integer argument, so e.g. <code>history 5<\/code> will display the last 5\ncommands. Now, the real power of <code>history<\/code> becomes apparent when using it\nwith <em>history expansion<\/em>.<\/p>\n<h3 id=\"history-expansion\">History expansion<\/h3>\n<p>History expansion can be used to expand an event number into the whole command\nit corresponds to. To expand an event, one simply types <code>!&lt;event_nr&gt;<\/code>. For\nexample, looking at the <code>history<\/code> output above I can see that event number 1010\ncorresponds to <code>git status<\/code>. I can execute the command again with history\nexpansion like so:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>!1010\ngit<span class=\"w\"> <\/span>status<span class=\"w\">         <\/span><span class=\"c1\"># Command is echoed<\/span>\nOn<span class=\"w\"> <\/span>branch<span class=\"w\"> <\/span>master<span class=\"w\">   <\/span><span class=\"c1\"># Output from executing the command<\/span>\n<span class=\"o\">[<\/span>***REST<span class=\"w\"> <\/span>OF<span class=\"w\"> <\/span>OUTPUT<span class=\"w\"> <\/span>OMITTED***<span class=\"o\">]<\/span>\n<\/code><\/pre><\/div>\n\n<p>The command is first echoed, and then executed. There are a few other ways to\nspecify the event number.<\/p>\n<ul>\n<li><code>!<\/code>: Execute the last event.<ul>\n<li>I.e. type <code>!!<\/code> in the terminal.<\/li>\n<li>Can be useful to re-execute a command that you realized you needed <code>sudo<\/code>\n  for with <code>sudo !!<\/code>.<\/li>\n<\/ul>\n<\/li>\n<li><code>-n<\/code>: Execute the nth previous event.<ul>\n<li>E.g. type <code>!-1<\/code> to execute the last event, <code>!-2<\/code> to execute the one\n  before that, and so on.<\/li>\n<li>I personally don't find this very useful.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>There is one more very useful feature that I often use, and that is the ability\nto only print the command. This can be achieved by appending <code>:p<\/code> to the\nhistory expansion command. Here is an example:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>!1011:p\ngit<span class=\"w\"> <\/span>commit<span class=\"w\"> <\/span>-a<span class=\"w\"> <\/span>-m<span class=\"w\"> <\/span><span class=\"s1\">&#39;Add module docstring to github_api module&#39;<\/span>\n<\/code><\/pre><\/div>\n\n<p>The command can then be accessed by pressing UP-arrow or <code>ctrl-p<\/code>, which is\nvery useful if you need to do minor modifications to it. There are tons of\nmore ways to use history expansion, and I strongly recommend reading the man-page\non it. Type <code>man bash<\/code> and then search for <code>HISTORY EXPANSION<\/code>, or do the same\nin <a href=\"https:\/\/linux.die.net\/man\/1\/bash\">this online bash man page<\/a>.<\/p>\n<h3 id=\"filtering-history\">Filtering history<\/h3>\n<p>A final tip on using history expansion is to filter the output with <code>grep<\/code>. For\nexample, if I only want to find commands that include the word <code>git<\/code>, I can\nfilter the output of <code>history<\/code> by <em>piping<\/em> to <code>grep<\/code> with the <code>|<\/code> character.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span><span class=\"nb\">history<\/span><span class=\"w\"> <\/span><span class=\"p\">|<\/span><span class=\"w\"> <\/span>grep<span class=\"w\"> <\/span>git\n<span class=\"w\"> <\/span><span class=\"m\">1010<\/span><span class=\"w\">  <\/span>git<span class=\"w\"> <\/span>status\n<span class=\"w\"> <\/span><span class=\"m\">1011<\/span><span class=\"w\">  <\/span>git<span class=\"w\"> <\/span>commit<span class=\"w\"> <\/span>-a<span class=\"w\"> <\/span>-m<span class=\"w\"> <\/span><span class=\"s1\">&#39;Add module docstring to github_api module&#39;<\/span>\n<\/code><\/pre><\/div>\n\n<p>I will most likely do another TOTW on piping, but the basic principle is that\n<code>|<\/code> takes the output from the command on the left and feeds it as input to the\ncommand on the right. That's it for this TOTW, stay tuned for the next one\ncoming on Sunday the 28th of April!<\/p>","category":[{"@attributes":{"term":"Tip of the Week"}},{"@attributes":{"term":"totw"}},{"@attributes":{"term":"bash"}}]},{"title":"Reverse search in bash","link":{"@attributes":{"href":"https:\/\/slar.se\/reverse-search-in-bash.html","rel":"alternate"}},"published":"2019-04-09T23:23:00+02:00","updated":"2019-04-09T23:23:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-04-09:\/reverse-search-in-bash.html","summary":"<p>Have you ever found yourself furiously tapping the UP-arrow (or <code>ctrl+p<\/code>) to\nfind a command that's probably waaaay up there? Would you be surprised if I\ntold you there's a better way? When you want to re-use a command you've written\npreviously, and you know it's not the previous \u2026<\/p>","content":"<p>Have you ever found yourself furiously tapping the UP-arrow (or <code>ctrl+p<\/code>) to\nfind a command that's probably waaaay up there? Would you be surprised if I\ntold you there's a better way? When you want to re-use a command you've written\npreviously, and you know it's not the previous command, or the one before that,\nyour first resort should be a <em>reverse search<\/em>. This can be accessed with\n<code>ctrl+r<\/code>. If you press that button combination, you should see something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">(<\/span>reverse-i-search<span class=\"o\">)<\/span><span class=\"sb\">`<\/span><span class=\"err\">&#39;<\/span>:<span class=\"w\"> <\/span>\n<\/code><\/pre><\/div>\n\n<p>Just start typing the beginning of the command you're looking for, and most\noften, it will pop up. For example, I sometimes need to re-run the\nprevious<code>git<\/code> command that I ran a while back. I then press <code>ctrl+r<\/code> and type\n<code>git<\/code> to get something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">(<\/span>reverse-i-search<span class=\"o\">)<\/span><span class=\"sb\">`<\/span>git<span class=\"err\">&#39;<\/span>:<span class=\"w\"> <\/span>git<span class=\"w\"> <\/span>push\n<\/code><\/pre><\/div>\n\n<p>Note how the initial <code>git<\/code> before the <code>:<\/code> is what I've actually written here,\nand the text after the <code>:<\/code> (in this case <code>git push<\/code>) is what's been found with\nthe reverse search. Pressing <code>tab<\/code> now will terminate the search and put the\nresult of the search on the command line for editing. Then, simply press\n<code>enter<\/code> to execute the command as usual. You can also skip over the editing\npart and press <code>enter<\/code> right away to execute the command as-is. Sometimes,\nhowever, the result you get first isn't what you want (obviously, just typing\n<code>git push<\/code> would have been faster in this case).  You can then press <code>ctrl+r<\/code>\nagain to cycle to the next hit.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>(reverse-i-search)`git&#39;: git commit -a -m &#39;Add module docstring to github_api module&#39;\n<\/code><\/pre><\/div>\n\n<p>Now there's a command that I might not want to have to type out again in its\nentirety, better showing why a reverse search may be useful. That's it for this\nweek's TotW, check back next week for more!<\/p>","category":[{"@attributes":{"term":"Tip of the Week"}},{"@attributes":{"term":"totw"}},{"@attributes":{"term":"bash"}}]},{"title":"Announcing Tip of the Week (TotW)","link":{"@attributes":{"href":"https:\/\/slar.se\/announcing-tip-of-the-week-totw.html","rel":"alternate"}},"published":"2019-04-09T23:15:00+02:00","updated":"2019-04-09T23:15:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-04-09:\/announcing-tip-of-the-week-totw.html","summary":"<p>In order to actually get around to writing some content, I've decided to start\na little series: Tip of the Week! Every week, I'll spend 30 minutes or so\nwriting a very small article about some tip related to programming, Linux or\ntechnology in general. And no, this one does \u2026<\/p>","content":"<p>In order to actually get around to writing some content, I've decided to start\na little series: Tip of the Week! Every week, I'll spend 30 minutes or so\nwriting a very small article about some tip related to programming, Linux or\ntechnology in general. And no, this one does not count, so I still have to\nwrite this week's TotW!<\/p>","category":[{"@attributes":{"term":"Tip of the Week"}},{"@attributes":{"term":"totw"}}]},{"title":"Migrating my blog","link":{"@attributes":{"href":"https:\/\/slar.se\/migrating-my-blog.html","rel":"alternate"}},"published":"2019-04-06T18:32:00+02:00","updated":"2019-04-10T23:20:00+02:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-04-06:\/migrating-my-blog.html","content":"<blockquote>\n<p><strong>Edit:<\/strong> The migration is complete! The Flask-based site has been retired\nand this Pelican-based site is fully fleshed out with the old content :)<\/p>\n<\/blockquote>\n<p>I'm currently in the midst of migrating my old blog over here. Until I'm done,\nboth sites will be a bit half-baked, sorry about that!<\/p>","category":[{"@attributes":{"term":"Blog"}},{"@attributes":{"term":"blog"}}]},{"title":"Testing tips: Tests that don't test","link":{"@attributes":{"href":"https:\/\/slar.se\/tests-that-dont-test.html","rel":"alternate"}},"published":"2019-03-05T22:07:56+00:00","updated":"2019-03-05T22:07:56+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2019-03-05:\/tests-that-dont-test.html","summary":"<p>Unit testing is a skill that takes some time to develop, and there are numerous\npitfalls for the beginner. As I've done my fair share of unit testing, and\ntaught a lot of students what I know, I've decided to share my top tips of\nthings to think about when \u2026<\/p>","content":"<p>Unit testing is a skill that takes some time to develop, and there are numerous\npitfalls for the beginner. As I've done my fair share of unit testing, and\ntaught a lot of students what I know, I've decided to share my top tips of\nthings to think about when testing. First up is one that may seem obvious, but\nbeginners and experienced testers alike fail with on occasion: make sure you\nare actually testing something.<\/p>\n<h2 id=\"tests-that-dont-test\">Tests that don't test<\/h2>\n<p>Quite often, I find tests written by students that don't actually test anything,\nand will pass regardless of what the student's code is doing. Sometimes, I find\ntests written by yours truly that are similarly ineffective. A test that passes\nwhen it should not is dangerous, because it makes you feel confident about code\nthat isn't properly tested. On the flip side, a test that fails when it should\nnot is annoying and may hamper productivity, but unlike a falsely positive test,\nit is highly noticeable. The devious part of tests that don't test is that they\neasily slip by unnoticed, you don't often investigate a test that passes! These\ntests generally come in four flavors:<\/p>\n<ol>\n<li>Not calling the function under test.<\/li>\n<li>Copy mistakes with references\/pointers.<\/li>\n<li>Mistakes during setup.<\/li>\n<li>Mistakes with assertions.<\/li>\n<\/ol>\n<p>Even though I have a few years worth of testing experience, and have written\nthousands upon thousands of tests, I still make these mistakes from time to\ntime. Let's first go over them one by one to get a feel for what can go wrong.\nAfter that, I'll share my techniques for catching these errors. For all of the\nexamples, we will look at a test case for sorting a randomly ordered list with\nan in-place sorting algorithm. The implementation under test is called <code>mysort<\/code>.\nAssume that, for all examples, a list called <code>random_list<\/code> with randomly ordered\nelements is setup in a fixture. The tests will be written in <code>pytest<\/code> syntax,\nbut most problems and solutions are easily transferable to many other languages\nand testing frameworks (e.g. JUnit in Java). Here is the test header and\ndocstring. Note the inclusion of the <code>random_list<\/code> fixture as a parameter. In the test,\nit can simply be used as a list.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">test_sort_randomly_ordered_list<\/span><span class=\"p\">(<\/span><span class=\"n\">random_list<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;Sort a randomly ordered list and ensure that the result for<\/span>\n<span class=\"sd\">    ``mysort`` is the same as the built-in ``list.sort``<\/span>\n<span class=\"sd\">    &quot;&quot;&quot;<\/span>\n<\/code><\/pre><\/div>\n\n<p>For brevity, the docstring will be excluded from now on.  Let's get to it the,\nshall we?<\/p>\n<h3 id=\"not-calling-the-function-under-test\">Not calling the function under test<\/h3>\n<p>This mistake definitely sits in the top two most common ones that I encounter. A\ntypical example of this is when using <em>redundant computation<\/em> to produce a test\noracle. That is, using some other implementation of the function under test to\ncompute the expected result. What I've seen happen many times is that the\nstudent by mistake uses the other implementation for both the expected value,\nand the actual value. Here's an example.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">test_sort_randomly_ordered_list<\/span><span class=\"p\">(<\/span><span class=\"n\">random_list<\/span><span class=\"p\">):<\/span>\n    <span class=\"c1\"># calculate test oracle<\/span>\n    <span class=\"n\">expected<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">list<\/span><span class=\"p\">(<\/span><span class=\"n\">random_list<\/span><span class=\"p\">)<\/span> <span class=\"c1\"># note the copy for later!<\/span>\n    <span class=\"n\">expected<\/span><span class=\"o\">.<\/span><span class=\"n\">sort<\/span><span class=\"p\">()<\/span>\n\n    <span class=\"c1\"># calculate actual value, use ``sort`` by mistake<\/span>\n    <span class=\"c1\"># should be ``mysort(random_list)``<\/span>\n    <span class=\"n\">random_list<\/span><span class=\"o\">.<\/span><span class=\"n\">sort<\/span><span class=\"p\">()<\/span>\n\n    <span class=\"k\">assert<\/span> <span class=\"n\">random_list<\/span> <span class=\"o\">==<\/span> <span class=\"n\">expected<\/span>\n<\/code><\/pre><\/div>\n\n<p>Obviously, this test will always pass as <code>list.sort<\/code> is used for both\ncomputations. This is a very common mistake, and if made once in a test suite, I\noften find it propagating elsewhere due to copy-paste errors. This kind of\nmistake is applicable in most any language, and is especially easy to make if\nthe redundant function and the function under test have similar names and usage\n(which was actually not the case here!).<\/p>\n<h3 id=\"copy-mistakes-with-referencespointers\">Copy mistakes with references\/pointers<\/h3>\n<p>Another very common issue that is often related to redundant computation is\nfailing to make a proper copy of a data structure. If you have a look at the\nprevious example, there is comment telling you to note the copy. Compare that\nwith this example:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">test_sort_randomly_ordered_list<\/span><span class=\"p\">(<\/span><span class=\"n\">random_list<\/span><span class=\"p\">):<\/span>\n    <span class=\"c1\"># calculate test oracle<\/span>\n    <span class=\"n\">expected<\/span> <span class=\"o\">=<\/span> <span class=\"n\">random_list<\/span> <span class=\"c1\"># this is not a copy!<\/span>\n    <span class=\"n\">expected<\/span><span class=\"o\">.<\/span><span class=\"n\">sort<\/span><span class=\"p\">()<\/span>\n\n    <span class=\"c1\"># calculate actual value<\/span>\n    <span class=\"n\">mysort<\/span><span class=\"p\">(<\/span><span class=\"n\">random_list<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"k\">assert<\/span> <span class=\"n\">random_list<\/span> <span class=\"o\">==<\/span> <span class=\"n\">expected<\/span>\n<\/code><\/pre><\/div>\n\n<p>Just assigning <code>expected = random_list<\/code> will not create a copy of <code>random_list<\/code>,\nbut copy the reference to the list. Therefore, both <code>expected<\/code> and <code>random_list<\/code>\nreference the <em>same list<\/em>. The assertion is then semantically equivalent to\n<code>assert random_list == random_list<\/code>, which is obviously true no matter what\n<code>mysort<\/code> did with the list. This is a problem in any language that uses\nreferences (not C++ references, but pointer-like references), such as Java and\nPython, or when dealing with pointers in pretty much any language that has them.<\/p>\n<h3 id=\"mistakes-during-setup\">Mistakes during setup<\/h3>\n<p>This is also fairly common, and can manifest in a variety of ways. The general\nidea is that the setup is performed such that the outcome of the test is very\nlikely to be the same even if the production code is anything but correct. One\nexample would be that the supposedly randomly ordered list is actually\ncomprised of duplicates of a single element. Let's have a look at an incorrect\nimplementation of the <code>random_list<\/code> fixture. Note that <code>_<\/code> is used as a\nvariable name when we don't care about the value of it.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nd\">@pytest<\/span><span class=\"o\">.<\/span><span class=\"n\">fixture<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">random_list<\/span><span class=\"p\">():<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;Generate a randomly ordered list with 100 elements.&quot;&quot;&quot;<\/span>\n    <span class=\"n\">lst<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[]<\/span>\n    <span class=\"k\">for<\/span> <span class=\"n\">_<\/span> <span class=\"ow\">in<\/span> <span class=\"nb\">range<\/span><span class=\"p\">(<\/span><span class=\"mi\">100<\/span><span class=\"p\">):<\/span>\n        <span class=\"n\">random<\/span><span class=\"o\">.<\/span><span class=\"n\">seed<\/span><span class=\"p\">(<\/span><span class=\"mi\">5234<\/span><span class=\"p\">)<\/span> <span class=\"c1\"># seed to make list generation deterministic<\/span>\n        <span class=\"n\">lst<\/span><span class=\"o\">.<\/span><span class=\"n\">append<\/span><span class=\"p\">(<\/span><span class=\"n\">random<\/span><span class=\"o\">.<\/span><span class=\"n\">randint<\/span><span class=\"p\">(<\/span><span class=\"o\">-<\/span><span class=\"mi\">100<\/span><span class=\"p\">,<\/span> <span class=\"mi\">100<\/span><span class=\"p\">))<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">lst<\/span>\n<\/code><\/pre><\/div>\n\n<p>It is good practice to <em>seed<\/em> the pseudo-random generator (PRG) when testing to\nmake tests reproducible. A PRG is actually a deterministic function that, given\nan initial state (a seed), will always produce the same sequence of numbers.\n<code>random.seed(5234)<\/code> sets this initial state to <code>5234<\/code>. This fixture is actually\nfairly well implemented, but has a critical error. Since the seed is set inside\nthe loop, before the call to <code>random.randint<\/code>, the latter will always produce\nthe same value. As the list is already sorted, <code>mysort<\/code> can do almost anything\nbut remove an element and still pass the test. This is a fairly sophisticated\nerror that an intermediate tester may accidentally make. There are infinite\nvariations on how setup may go wrong, and this is applicable to pretty much any\nprogramming language. As a side note, the correct way to do this would of\ncourse be to seed <em>before<\/em> the loop. Note that even with the correct\nconfiguration, there is a very small chance that the random elements are\ngenerated in ascending order.<\/p>\n<h3 id=\"mistakes-with-assertions\">Mistakes with assertions<\/h3>\n<p>The final issue is also common, and comes in many shapes and forms. One thing I\nsometimes see is that the assertions are tautologies, such as <code>assert\nrandom_list == random_list<\/code> (obviously true), and probably mostly result from\ntypos and unchecked auto-completion. Another common one is that assertions are\nsimply missing, and is most often found in tests that are large enough that a\nmissing line or two is not immediately apparent.<\/p>\n<h2 id=\"finding-tests-that-dont-test\">Finding tests that don't test<\/h2>\n<p>There are essentially two ways I know of to find tests that (pretty much) never\nfail.<\/p>\n<ol>\n<li>Write the tests first (Test-driven development)<\/li>\n<li>Inject errors into production code and expect tests to fail<\/li>\n<\/ol>\n<h3 id=\"test-driven-development-tdd\">Test-driven development (TDD)<\/h3>\n<p>TDD involves writing the test cases before you implement the functionality.\nYou first write the test cases, ensure that the test cases fail, and then\nimplement the production code such that the tests pas. I typically use TDD\nwhen:<\/p>\n<ul>\n<li>The functionality I need to implement is strictly defined.<ul>\n<li>Fox example when implementing well-defined algorithms and data structures.<\/li>\n<\/ul>\n<\/li>\n<li>I'm fixing a bug.<ul>\n<li>Reproduce the bug with a test-case, then fix it!<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>This approach will catch many incarnations of the errors I've brought up in\nthis article simply because the tests should definitely not pass before the\nproduction code is even written. There is one caveat, though. Some\npractitioners of TDD think that test cases should be written even before the\nfunction skeletons have been written, and argue that a compilation failure is\nalso a test failure. With that approach, you probably will not catch any of the\nerrors brought up here, except maybe\n<a href=\"#not-calling-the-function-under-test\">the first one<\/a>. My recommendation for\nTDD is to write function skeletons and make sure the function can actually be\ncalled (it's perfectly fine if it crashes after being called). <em>Then<\/em> write\nyour tests, and make sure they fail before you start implementing production\ncode. I don't think TDD is always practical to use, however, especially when\nI'm a bit unsure of what to do and need to experiment with different APIs.\nThat's when the second technique comes in real handy.<\/p>\n<h3 id=\"inject-errors-into-production-code-and-expect-tests-to-fail\">Inject errors into production code and expect tests to fail<\/h3>\n<p>This is a highly useful technique that can always be performed, and I do this\nalmost every time I implement tests after production code. The idea is simply to\nconsider what your test is testing, and inject errors into the production code\nsuch that the test should fail. <code>test_sort_randomly_ordered_list<\/code> is a fairly\nbroad test case, so we can inject fairly general errors. A simple example would\nsimply be to return early such that <code>mysort<\/code> does not sort at all. Narrower test\ncases may require more sophisticated errors to be injected.<\/p>\n<blockquote>\n<p><strong>Aside: Mutation testing<\/strong> There is actually a whole field of testing\ndedicated to this kind of error (or <em>fault<\/em>) injection called\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Mutation_testing\">mutation testing<\/a>. Faults are\nautomatically injected into production code, and the test suite is run to\ndetermine whether the fault is found (<em>killed<\/em>) or not. There are frameworks\nfor this, such as the <a href=\"http:\/\/pitest.org\/\">Pitest<\/a> for Java, and\n<a href=\"https:\/\/github.com\/sixty-north\/cosmic-ray\">Cosmic Ray<\/a> for Python. In\ngeneral, it takes a <em>long<\/em> time to run mutation testing on a test suite, as\noften the whole test suite needs to be run for a single fault. And there are\nmany, many possible faults.<\/p>\n<\/blockquote>\n<h2 id=\"summary\">Summary<\/h2>\n<p>While I framed this as a unit testing article, these concepts are applicable to\nmost kinds of testing. You should always attempt to make sure that your test is\ndoing what it claims to be doing. A single typo may be what stands between a\ntest that does not test, and a test that does. This article focused on finding\ntests that don't test, but there are also things you can do to <em>prevent<\/em> tests\nthat don't test from manifesting. Copy\/pasting test code and then making minor\nchanges is for example a common source of most of the discussed errors. But\nultimately, there is no surefire way of avoiding tests that don't test, so I\nstrongly recommend that you actively search for them no matter what precautions\nyou take!<\/p>","category":[{"@attributes":{"term":"Testing"}},{"@attributes":{"term":"unit testing"}},{"@attributes":{"term":"testing tips"}}]},{"title":"TornadoFX+Exposed pt. 3: Adding, editing and removing rows","link":{"@attributes":{"href":"https:\/\/slar.se\/tornadofxexposed-pt-3-adding-editing-and-removing-rows.html","rel":"alternate"}},"published":"2018-12-30T14:50:50+00:00","updated":"2018-12-30T15:13:57+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2018-12-30:\/tornadofxexposed-pt-3-adding-editing-and-removing-rows.html","summary":"<p>Welcome to the third and final part in this article series on using TornadoFX\ntogether with Exposed. In the previous two parts, we set up the database with a\nsingle table and created a simple TornadoFX view with which we could view its\ncontents. Now, we will focus on adding \u2026<\/p>","content":"<p>Welcome to the third and final part in this article series on using TornadoFX\ntogether with Exposed. In the previous two parts, we set up the database with a\nsingle table and created a simple TornadoFX view with which we could view its\ncontents. Now, we will focus on adding and deleting rows to the <code>Categories<\/code>\ntable, as well as adding new ones. This part is a bit longer than the two\nprevious ones, but it also contains a whole lot more content.<\/p>\n<blockquote>\n<p>The full source code is available\n<a href=\"https:\/\/github.com\/slarse\/tornadofx-exposed-example\/tree\/part_3\">on GitHub<\/a><\/p>\n<\/blockquote>\n<h1 id=\"article-index\">Article index<\/h1>\n<ol>\n<li><a href=\"https:\/\/slar.se\/tornadofxexposed-pt-1-project-and-database-setup.html\">Project and database setup<\/a><\/li>\n<li><a href=\"https:\/\/slar.se\/tornadofxexposed-pt-2-showing-a-database-table.html\">Showing a database table<\/a><\/li>\n<li>Adding, editing and removing rows -- This part!<\/li>\n<\/ol>\n<h1 id=\"making-the-app-interactive\">Making the app interactive<\/h1>\n<p>So far, all we can do with our app is view the contents of the database. That's\nneat and all, but it would be even nicer if we could interact with the database\nand edit its contents. What this article will address is how to:<\/p>\n<ol>\n<li>Delete rows.<\/li>\n<li>Add rows.<\/li>\n<li>Edit rows.<\/li>\n<\/ol>\n<p>Deleting rows is the simplest thing to accomplish, so let's start with that.<\/p>\n<h2 id=\"deleting-rows\">Deleting rows<\/h2>\n<p>Deleting a row is pretty easy. First, we'll add the desired functionality to\nthe controller.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">deleteCategory<\/span><span class=\"p\">(<\/span><span class=\"n\">model<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">CategoryModel<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">transaction<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">model<\/span><span class=\"p\">.<\/span><span class=\"na\">item<\/span><span class=\"p\">.<\/span><span class=\"na\">delete<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">categories<\/span><span class=\"p\">.<\/span><span class=\"na\">remove<\/span><span class=\"p\">(<\/span><span class=\"n\">model<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that <code>model.item<\/code> returns the backing <code>Category<\/code> object, on which we\nsimply call <code>delete()<\/code> to remove it from the database. Then, we also have to\nupdate our local list by removing the model from it. Note that I assume <code>model<\/code>\nto be in the <code>categories<\/code> list for the sake of simplicity, but this is a pretty\nbold assumption that you probably should not make in a real application. Now,\nlet's put this new functionality to work: we need to add a button to the view\nthat calls the delete function on the currently selected row. We will slightly\nalter the layout to make this happen. We change this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">override<\/span><span class=\"w\"> <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">root<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">borderpane<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">categories<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">dbController<\/span><span class=\"p\">.<\/span><span class=\"na\">categories<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">center<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">tableview<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">categoryTable<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">editModel<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">items<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">categories<\/span>\n\n<span class=\"w\">        <\/span><span class=\"n\">column<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Name&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">::<\/span><span class=\"n\">name<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">column<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Description&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">::<\/span><span class=\"n\">description<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>to this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">override<\/span><span class=\"w\"> <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">root<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">borderpane<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">categories<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">dbController<\/span><span class=\"p\">.<\/span><span class=\"na\">categories<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">center<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">vbox<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">buttonbar<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">button<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;DELETE SELECTED&quot;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">action<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">model<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">categoryTable<\/span><span class=\"p\">.<\/span><span class=\"na\">tableView<\/span><span class=\"p\">.<\/span><span class=\"na\">selectedItem<\/span>\n<span class=\"w\">                    <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">model<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                        <\/span><span class=\"kc\">null<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">return<\/span><span class=\"nd\">@action<\/span>\n<span class=\"w\">                        <\/span><span class=\"k\">else<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">dbController<\/span><span class=\"p\">.<\/span><span class=\"na\">deleteCategory<\/span><span class=\"p\">(<\/span><span class=\"n\">model<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">                    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">                <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">tableview<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">categoryTable<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">editModel<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">items<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">categories<\/span>\n\n<span class=\"w\">            <\/span><span class=\"n\">column<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Name&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">::<\/span><span class=\"n\">name<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">column<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Description&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">::<\/span><span class=\"n\">description<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>We use a <code>buttonbar<\/code> as we will be adding more buttons later on. The code should\nbe fairly easy to read: the button's action will do nothing if the currently\nselected model is <code>null<\/code> (i.e. nothing is selected), and call the\n<code>deleteCategory<\/code> method otherwise. You should now have a view looking something\nlike this:<\/p>\n<p><img alt=\"Table view with a delete button\" src=\"https:\/\/slar.se\/images\/tornado_exposed\/view_with_delete.jpg\"><\/p>\n<p>If you first click a row and then the delete button, the row should disappear.\nNow that we can delete rows, let's turn our attention to adding new rows.<\/p>\n<h2 id=\"adding-new-rows\">Adding new rows<\/h2>\n<p>For this, we're going to add a small form to the right of the table which will\nallow us to enter new rows. As before, we'll start with the controller, adding\nthe following method to it:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">addCategory<\/span><span class=\"p\">(<\/span><span class=\"n\">name<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">description<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">transaction<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">category<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Category<\/span><span class=\"p\">.<\/span><span class=\"na\">new<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">this<\/span><span class=\"p\">.<\/span><span class=\"na\">name<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">name<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">this<\/span><span class=\"p\">.<\/span><span class=\"na\">description<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">description<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">categories<\/span><span class=\"p\">.<\/span><span class=\"na\">add<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">CategoryModel<\/span><span class=\"p\">().<\/span><span class=\"na\">apply<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">item<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">category<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">})<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Here, we first create a new <code>Category<\/code>, and then add it to the <code>categories<\/code>\nlist (wrapped in a <code>CategoryModel<\/code>). Now, we need to add the form to the view\nso we can submit the values for <code>name<\/code> and <code>description<\/code>. First, we need to add\ntwo new properties to the <code>CategoryEditor<\/code> view:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">nameField<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">TextField<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">singleAssign<\/span><span class=\"p\">()<\/span>\n<span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">descriptionField<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">TextField<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">singleAssign<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>We need these to be able to access what we put in the form fields.  We also\nneed to import <code>TextField<\/code><\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">javafx.scene.control.TextField<\/span>\n<\/code><\/pre><\/div>\n\n<p>To add the actual form, we put the following <em>after<\/em> the <code>center<\/code> element:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">right<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">form<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">fieldset<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">field<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Name&quot;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">textfield<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">nameField<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">this<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">fieldset<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">field<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Description&quot;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">textfield<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">descriptionField<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">this<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">button<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;ADD CATEGORY&quot;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">action<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">dbController<\/span><span class=\"p\">.<\/span><span class=\"na\">addCategory<\/span><span class=\"p\">(<\/span><span class=\"n\">nameField<\/span><span class=\"p\">.<\/span><span class=\"na\">text<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">descriptionField<\/span><span class=\"p\">.<\/span><span class=\"na\">text<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">nameField<\/span><span class=\"p\">.<\/span><span class=\"na\">text<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;&quot;<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">descriptionField<\/span><span class=\"p\">.<\/span><span class=\"na\">text<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;&quot;<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This will result in a view looking something like this:<\/p>\n<p><img alt=\"View with add category form\" src=\"https:\/\/slar.se\/images\/tornado_exposed\/view_with_add_form.jpg\"><\/p>\n<p>Writing some stuff in the fields and clicking <code>ADD CATEGORY<\/code> should immediately\ncreate a new row in the table. Not the most beautiful thing in the world, I'll\nadmit, but it serves its purpose for this guide. Now we only have one more\nfeature to add, namely editing rows.<\/p>\n<h2 id=\"editing-rows\">Editing rows<\/h2>\n<p>Now we will finally see why we used a <code>TableViewEditModel<\/code> instead of a plain\n<code>TableView<\/code>: the former allows us to edit rows directly in the table. To allow\nfor inline editing, we need to add some stuff to the view itself. Our table\nview currently looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">tableview<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">categoryTable<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">editModel<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">items<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">categories<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">column<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Name&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">::<\/span><span class=\"n\">name<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">column<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Description&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">::<\/span><span class=\"n\">description<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>To enable editing, we simply add a call to <code>enableCellEditing()<\/code>, and call\n<code>makeEditable()<\/code> on the columns. We'll also add <code>enableDirtyTracking()<\/code> to\nallow us to see which cells have been edited, but not saved.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">tableview<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">categoryTable<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">editModel<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">items<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">categories<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">enableCellEditing<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">enableDirtyTracking<\/span><span class=\"p\">()<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">column<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Name&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">::<\/span><span class=\"n\">name<\/span><span class=\"p\">).<\/span><span class=\"na\">makeEditable<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">column<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Description&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">::<\/span><span class=\"n\">description<\/span><span class=\"p\">).<\/span><span class=\"na\">makeEditable<\/span><span class=\"p\">()<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now, we can edit cells by clicking them:<\/p>\n<p><img alt=\"Editing a cell\" src=\"https:\/\/slar.se\/images\/tornado_exposed\/editing_cell.jpg\"><\/p>\n<p>And after pressing enter, we can see that the cell has been edited by the blue\ntriangle. The cell is <em>dirty<\/em>:<\/p>\n<p><img alt=\"Dirty cell\" src=\"https:\/\/slar.se\/images\/tornado_exposed\/edited_cell.jpg\"><\/p>\n<p>However, the change won't \"stick\". If we restart the application, the text will\nbe back to what it was before we edited the cell. The reason is that the change\nwas never committed to the database, it was just stored in the model. Thus,\nwhat we need now is to commit any dirty rows to the database. As always, we\nstart with adding the functionality we need from the controller.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">commitDirty<\/span><span class=\"p\">(<\/span><span class=\"n\">modelDirtyMappings<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Sequence<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Map<\/span><span class=\"p\">.<\/span><span class=\"na\">Entry<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">CategoryModel<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">TableColumnDirtyState<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">&gt;&gt;&gt;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">transaction<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">modelDirtyMappings<\/span><span class=\"p\">.<\/span><span class=\"na\">filter<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"nb\">it<\/span><span class=\"p\">.<\/span><span class=\"na\">value<\/span><span class=\"p\">.<\/span><span class=\"na\">isDirty<\/span><span class=\"w\"> <\/span><span class=\"p\">}.<\/span><span class=\"na\">forEach<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"nb\">it<\/span><span class=\"p\">.<\/span><span class=\"na\">key<\/span><span class=\"p\">.<\/span><span class=\"na\">commit<\/span><span class=\"p\">()<\/span><span class=\"w\">     <\/span><span class=\"c1\">\/\/ commit value to database<\/span>\n<span class=\"w\">            <\/span><span class=\"nb\">it<\/span><span class=\"p\">.<\/span><span class=\"na\">value<\/span><span class=\"p\">.<\/span><span class=\"na\">commit<\/span><span class=\"p\">()<\/span><span class=\"w\">   <\/span><span class=\"c1\">\/\/ clear dirty state<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This function iterates over a sequence of map entries that map a model (key) to\na dirty state (value). We'll soon see that we can get such a map from the table\nview. Note that committing the key <em>must<\/em> be done in a transaction, as it will\nwrite to the database. The type is a bit of a mouthful, though, so let's define\na type alias for it.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">typealias<\/span><span class=\"w\"> <\/span><span class=\"n\">ModelToDirtyState<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Map<\/span><span class=\"p\">.<\/span><span class=\"na\">Entry<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">CategoryModel<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">TableColumnDirtyState<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">&gt;&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that the <code>typealias<\/code> must be a top level declaration (i.e. you can't put\nit in a class or function). And rewrite the header of <code>commitDirty<\/code> like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">commitDirty<\/span><span class=\"p\">(<\/span><span class=\"n\">modelDirtyMappings<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Sequence<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">ModelToDirtyState<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Slightly more readable, right? Now, let's put it to use. We'll add a new button\nin the button bar to execute the commit.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">button<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;COMMIT&quot;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">action<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">dbController<\/span><span class=\"p\">.<\/span><span class=\"na\">commitDirty<\/span><span class=\"p\">(<\/span><span class=\"n\">categoryTable<\/span><span class=\"p\">.<\/span><span class=\"na\">items<\/span><span class=\"p\">.<\/span><span class=\"na\">asSequence<\/span><span class=\"p\">())<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Clicking this button when there are dirty cells will allow us to commit these\nto the database. As a finishing touch, we'll add a button to reset (rollback)\ndirty cells to their previous state.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"n\">button<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;ROLLBACK&quot;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">action<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">categoryTable<\/span><span class=\"p\">.<\/span><span class=\"na\">rollback<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that this does not require a transaction, as all that happens is that the\nmodel state is reset (the DAO is unaffected). This will leave us with a final\nGUI looking like this:<\/p>\n<p><img alt=\"Final GUI\" src=\"https:\/\/slar.se\/images\/tornado_exposed\/final_gui.jpg\"><\/p>\n<h1 id=\"closing-words\">Closing words<\/h1>\n<p>That was all for this series of articles on TornadoFX and exposed. This is by\nno means a fully-fledged database UI, but it is a pretty good start.  There are\ntons of things here that need to be improved, though. Below are a few examples\noff the top of my head.<\/p>\n<ul>\n<li>There is just about no error handling, everything is just assumed to work\n  out.  For example, if a user enters a duplicate category, an unhandled\n  exception is raised.<\/li>\n<li>Much of the functionality is very specific to the <code>Category<\/code> type, and needs\n  to be generalized. As a lot of this is done with generics, such\n  generalization is actually not trivial (as generic types are invariant by\n  default).<\/li>\n<li>There is a lot of room for user error. For example, deleting a row is done\n  without prompting the user with something like \"Are you sure you wanna do\n  this?\". The commit\/rollback functionality of editing is much more user\n  friendly and a step in the right direction.<\/li>\n<li>The views are completely unstyled and look rather dull.<\/li>\n<\/ul>\n<p>And with that, I wish you good fortune in working with this! Of course, you are\nfree to use all of these examples as you see fit.<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"exposed"}},{"@attributes":{"term":"kotlin"}},{"@attributes":{"term":"kuizzy"}},{"@attributes":{"term":"tornadofx"}}]},{"title":"TornadoFX+Exposed pt. 2: Showing a database table","link":{"@attributes":{"href":"https:\/\/slar.se\/tornadofxexposed-pt-2-showing-a-database-table.html","rel":"alternate"}},"published":"2018-12-26T09:09:47+00:00","updated":"2018-12-30T15:14:09+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2018-12-26:\/tornadofxexposed-pt-2-showing-a-database-table.html","summary":"<p>Welcome to the second part of the TornadoFX+Exposed series of articles. In this\npart, we'll take a look at how to create a TornadoFX view for the <code>Categories<\/code>\ntable. In the next part, we'll expand upon the view and make it possible to\nadd, edit and delete rows.<\/p>\n<blockquote>\n<p>The \u2026<\/p><\/blockquote>","content":"<p>Welcome to the second part of the TornadoFX+Exposed series of articles. In this\npart, we'll take a look at how to create a TornadoFX view for the <code>Categories<\/code>\ntable. In the next part, we'll expand upon the view and make it possible to\nadd, edit and delete rows.<\/p>\n<blockquote>\n<p>The full source code is available\n<a href=\"https:\/\/github.com\/slarse\/tornadofx-exposed-example\/tree\/part_2\">on GitHub<\/a><\/p>\n<\/blockquote>\n<h1 id=\"article-index\">Article index<\/h1>\n<ol>\n<li><a href=\"https:\/\/slar.se\/tornadofxexposed-pt-1-project-and-database-setup.html\">Project and database setup<\/a><\/li>\n<li>Showing a database table -- This part!<\/li>\n<li><a href=\"https:\/\/slar.se\/tornadofxexposed-pt-3-adding-editing-and-removing-rows.html\">Adding, editing and removing rows<\/a><\/li>\n<\/ol>\n<h1 id=\"creating-a-table-view\">Creating a table view<\/h1>\n<p>To be able to view the <code>Categories<\/code> table, we're going to need three things:<\/p>\n<ol>\n<li>A view model to wrap <code>Category<\/code> instances. We can actually get away without\n   having a model, but having a model greatly simplifies some of the operations\n   we will implement in the next article.<\/li>\n<li>A controller for interacting with the database<\/li>\n<li>A view for displaying the data.<\/li>\n<\/ol>\n<p>We will do all of this in a new file called <code>categoryview.kt<\/code>. Let's start with\nthe view model, as it is by far the simplest component.<\/p>\n<h2 id=\"an-itemviewmodel-wrapper-for-category\">An ItemViewModel wrapper for Category<\/h2>\n<p>For this, we'll extend a utility class called <code>ItemViewModel<\/code> (you can read\nabout it in detail in the\n<a href=\"https:\/\/edvin.gitbooks.io\/tornadofx-guide\/part1\/11.%20Editing%20Models%20and%20Validation.html\">TornadoFX guide<\/a>.\nIt will simply look like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">tornadofx.*<\/span>\n\n<span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">CategoryModel<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ItemViewModel<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Category<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">name<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">bind<\/span><span class=\"p\">(<\/span><span class=\"n\">Category<\/span><span class=\"o\">::<\/span><span class=\"n\">name<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">description<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">bind<\/span><span class=\"p\">(<\/span><span class=\"n\">Category<\/span><span class=\"o\">::<\/span><span class=\"n\">description<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is essentially a proxy for the <code>Category<\/code> class, acting as a middle-man\nbetween the presentation layer and the database access layer. Any change we\nmake to a <code>CategoryModel<\/code> in the GUI will be stored in the model alone, and\nwill only propagate to the underlying <code>Category<\/code> object when we <em>commit<\/em> the\nchange(s).  This is very convenient, as it allows us to buffer changes and then\ncommit all of them in a single database transaction, instead of having one\ntransaction per change. Now, let's move on to the controller.<\/p>\n<h2 id=\"the-database-controller\">The database controller<\/h2>\n<p>The controller is also fairly simple. Initially, it will only be able to fetch\nitems from the database. In the next article, we will extend the controller\nwith add and delete-functionality. Here's the initial version of the\ncontroller:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">javafx.collections.ObservableList<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">java.sql.Connection<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">org.jetbrains.exposed.sql.Database<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">org.jetbrains.exposed.sql.transactions.transaction<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">org.jetbrains.exposed.sql.transactions.TransactionManager<\/span>\n\n<span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">DBController<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Controller<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">categories<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ObservableList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">lazy<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">transaction<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">Category<\/span><span class=\"p\">.<\/span><span class=\"na\">all<\/span><span class=\"p\">().<\/span><span class=\"na\">map<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"n\">CategoryModel<\/span><span class=\"p\">().<\/span><span class=\"na\">apply<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                    <\/span><span class=\"n\">item<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nb\">it<\/span>\n<span class=\"w\">                <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">}.<\/span><span class=\"na\">observable<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">init<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Database<\/span><span class=\"p\">.<\/span><span class=\"na\">connect<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;jdbc:sqlite:file:data.sqlite&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">driver<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;org.sqlite.JDBC&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">TransactionManager<\/span><span class=\"p\">.<\/span><span class=\"na\">manager<\/span><span class=\"p\">.<\/span><span class=\"na\">defaultIsolationLevel<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Connection<\/span><span class=\"p\">.<\/span><span class=\"na\">TRANSACTION_SERIALIZABLE<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The <code>categories<\/code> property is lazily initialized to a fetch from the database,\nin which all <code>Category<\/code> DAOs are wrapped in <code>CategoryModel<\/code>s. There's a bit of\na trade-off here: it's more efficient to fetch the whole table only once and\nthen maintain the state with any objects that are added or <code>init<\/code> contains\nprecisely the same database connection setup that we used in the first article.\nLet's move on to the actual view.<\/p>\n<h2 id=\"the-table-view\">The table view<\/h2>\n<p>For the table view, we're going to use a <code>TableViewEditModel<\/code> instead of a\nplain <code>TableView<\/code>. The reason is that the <code>TableViewEditModel<\/code> has some\nadditional functionality, most notably the ability to edit rows directly in the\ntable. Again, you can read up on the details in the\n<a href=\"https:\/\/edvin.gitbooks.io\/tornadofx-guide\/part1\/11.%20Editing%20Models%20and%20Validation.html\">TornadoFX guide<\/a>. Our initial attempt looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">CategoryEditor<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">View<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Categories&quot;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">dbController<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">DBController<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">inject<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">categoryTable<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">TableViewEditModel<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">singleAssign<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">categories<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ObservableList<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">singleAssign<\/span><span class=\"p\">()<\/span>\n\n<span class=\"w\">    <\/span><span class=\"kd\">override<\/span><span class=\"w\"> <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">root<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">borderpane<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">categories<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">dbController<\/span><span class=\"p\">.<\/span><span class=\"na\">categories<\/span>\n\n<span class=\"w\">        <\/span><span class=\"n\">center<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">tableview<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">categoryTable<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">editModel<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">items<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">categories<\/span>\n\n<span class=\"w\">            <\/span><span class=\"n\">column<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Name&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">::<\/span><span class=\"n\">name<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">column<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Description&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">CategoryModel<\/span><span class=\"o\">::<\/span><span class=\"n\">description<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>There's not too much going on here. The three properties store references to\nthe controller, the table view, and the list of categories. The view itself is\nnot very eventful either, we simply fetch the categories using the controller\nand initialize the table view. Note that <code>editModel<\/code> and <code>items<\/code> are properties\nof the <code>TableViewEditModel<\/code>, where the former is a reference to the table and\nthe latter the property containing the items of the table (which we set to the\n<code>categories<\/code> observable list). Later, when we wish to update the table, we\nsimply work with the <code>categories<\/code> list. Don't worry that there are some unused\nreferences here, we will put them to use in the next article.<\/p>\n<h2 id=\"creating-a-runnable-app\">Creating a runnable app<\/h2>\n<p>Now, we just need to make the app runnable. That's as simple as adding the\nfollowing:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Kuizzy<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">App<\/span><span class=\"p\">(<\/span><span class=\"n\">CategoryEditor<\/span><span class=\"o\">::<\/span><span class=\"n\">class<\/span><span class=\"p\">)<\/span>\n\n\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">args<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Array<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">String<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">launch<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Kuizzy<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">(<\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Running the main method will start the app, and you should then see a view that\nlooks something like this:<\/p>\n<p><img alt=\"Read only view\" src=\"https:\/\/slar.se\/images\/tornado_exposed\/read_only_view.jpg\"><\/p>\n<p>That's pretty much it for this part. In the next and final part, we'll look\ninto how to add, delete and edit rows of the <code>Categories<\/code> table. You can find\n<a href=\"https:\/\/slar.se\/tornadofxexposed-pt-3-adding-editing-and-removing-rows.html\">part 3 here.<\/a><\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"exposed"}},{"@attributes":{"term":"kotlin"}},{"@attributes":{"term":"kuizzy"}},{"@attributes":{"term":"tornadofx"}}]},{"title":"TornadoFX+Exposed pt. 1: Project and database setup","link":{"@attributes":{"href":"https:\/\/slar.se\/tornadofxexposed-pt-1-project-and-database-setup.html","rel":"alternate"}},"published":"2018-12-25T22:42:36+00:00","updated":"2018-12-30T14:53:11+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2018-12-25:\/tornadofxexposed-pt-1-project-and-database-setup.html","summary":"<p>I recently got it into my head that I'd like to make a quiz game with a GUI,\nwhich felt like a simple enough diversion during the holidays. Since I already\nhave this site to maintain in terms of web development, I figured that desktop\napp development in Kotlin using \u2026<\/p>","content":"<p>I recently got it into my head that I'd like to make a quiz game with a GUI,\nwhich felt like a simple enough diversion during the holidays. Since I already\nhave this site to maintain in terms of web development, I figured that desktop\napp development in Kotlin using the TornadoFX framework would be a nice change\nof pace. <em>Kuizzy<\/em>, which is what I call the project, will obviously need some\nkind of data storage for questions and the like, so I settled on usind\nJetBrains' framework Exposed with a sqlite database. Starting out, I had\ntrouble figuring out how to use TornadoFX and Exposed together, and therefore\ndecided to write this three-part series of articles on how I managed to make it\nwork. I won't dive deep into either, but rather show by example how to perform\nsome elementary tasks. In the end, we'll have a small piece of the database\nadmin part of Kuizzy up and running.<\/p>\n<blockquote>\n<p>The full source code is available\n<a href=\"https:\/\/github.com\/slarse\/tornadofx-exposed-example\/tree\/part_1\">on GitHub<\/a><\/p>\n<\/blockquote>\n<h1 id=\"article-index\">Article index<\/h1>\n<ol>\n<li>Project and database setup -- This part!<\/li>\n<li><a href=\"https:\/\/slar.se\/tornadofxexposed-pt-2-showing-a-database-table.html\">Showing a database table<\/a><\/li>\n<li><a href=\"https:\/\/slar.se\/tornadofxexposed-pt-3-adding-editing-and-removing-rows.html\">Adding, editing and removing<\/a><\/li>\n<\/ol>\n<h1 id=\"getting-started\">Getting started<\/h1>\n<p>In this first article, we will be concerned only with getting everything set up.\nThis includes getting the dependencies and setting up the database with a table.\nI will assume that you know how to use Kotlin, and how to handle dependencies\n(e.g. by using a build system like Gradle, or just doing it manually). These are\nthings that I will not explain, as there are plenty of resources for that\navailable elsewhere. It's also important to note that these articles are not\nmeant to be seen as <em>the<\/em> way to do this. In order to keep the articles\nreasonably focused and short, I take tons of shortcuts, completely eschew error\nhandling and create very specialized functionality. The point of this article\nseries is to show you how to get started with TornadoFX+Exposed, and you are\nmeant to develop it further on your own.<\/p>\n<h2 id=\"what-are-we-aiming-for\">What are we aiming for?<\/h2>\n<p>I think it helps tremendously when reading something to have the end goal in\nsight. What we're shooting for here is an interface that looks something like\nthis:<\/p>\n<p><img alt=\"Final app\" src=\"https:\/\/slar.se\/images\/tornado_exposed\/final_gui.jpg\"><\/p>\n<p>We will be able to create and delete rows, as well as edit rows directly in\nthe table. It's not\npretty and it's not very user friendly, but it conveys an idea and has all the\nbasic functionality required do administrate a single-table database.\nNow that you have a rough idea of what we're trying to accomplish, let's\nhave a look at what libraries and tools we need to make it happen.<\/p>\n<h2 id=\"preliminaries\">Preliminaries<\/h2>\n<p>Before we can get started, we need to make sure all dependencies are accounted\nfor. Here's a complete list of the libraries and frameworks I'll be using\nthroughout this series:<\/p>\n<ul>\n<li>Java 8 and openjfx 8<ul>\n<li>Note that if you install Oracle's JDK, JavaFX is included. You only need\n  openjfx if you use openjdk.<\/li>\n<\/ul>\n<\/li>\n<li>Kotlin 1.3.0<ul>\n<li>1.2+ should work fine<\/li>\n<\/ul>\n<\/li>\n<li><a href=\"https:\/\/mvnrepository.com\/artifact\/no.tornado\/tornadofx\/1.7.17\">TornadoFX 1.7.17<\/a><\/li>\n<li><a href=\"https:\/\/mvnrepository.com\/artifact\/org.jetbrains.exposed\/exposed\/0.11.2\">Exposed 0.11.2<\/a><\/li>\n<li><a href=\"https:\/\/mvnrepository.com\/artifact\/org.xerial\/sqlite-jdbc\/3.25.2\">xerial-sqlite-jdbc 3.25.2<\/a><ul>\n<li>I'll be using sqlite, but using any other SQL database supported by\n  Exposed only requires changing a line or two of code.<\/li>\n<\/ul>\n<\/li>\n<li>Gradle 5.0<ul>\n<li>Any reasonably up-to-date version should work. You can also just use\n  whatever way you see fit to handle the dependencies.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>Here's my <code>build.gradle<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"err\">plugi<\/span><span class=\"kc\">ns<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">id<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;org.je<\/span><span class=\"kc\">t<\/span><span class=\"err\">brai<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"err\">.jvm&#39;<\/span><span class=\"w\"> <\/span><span class=\"err\">versio<\/span><span class=\"kc\">n<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;<\/span><span class=\"mf\">1.3.0<\/span><span class=\"err\">&#39;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"err\">group<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;se.slarse&#39;<\/span>\n<span class=\"err\">versio<\/span><span class=\"kc\">n<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;<\/span><span class=\"mf\">0.0.1<\/span><span class=\"err\">&#39;<\/span>\n\n<span class=\"err\">reposi<\/span><span class=\"kc\">t<\/span><span class=\"err\">ories<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">mave<\/span><span class=\"kc\">n<\/span><span class=\"err\">Ce<\/span><span class=\"kc\">ntral<\/span><span class=\"err\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">jce<\/span><span class=\"kc\">nter<\/span><span class=\"err\">()<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"err\">depe<\/span><span class=\"kc\">n<\/span><span class=\"err\">de<\/span><span class=\"kc\">n<\/span><span class=\"err\">cies<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">compile<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;org.je<\/span><span class=\"kc\">t<\/span><span class=\"err\">brai<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"p\">:<\/span><span class=\"err\">ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"mi\">-<\/span><span class=\"err\">s<\/span><span class=\"kc\">t<\/span><span class=\"err\">dlib<\/span><span class=\"mi\">-<\/span><span class=\"err\">jdk<\/span><span class=\"mi\">8<\/span><span class=\"err\">&#39;<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">compile<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;<\/span><span class=\"kc\">n<\/span><span class=\"err\">o.<\/span><span class=\"kc\">t<\/span><span class=\"err\">or<\/span><span class=\"kc\">na<\/span><span class=\"err\">do<\/span><span class=\"p\">:<\/span><span class=\"kc\">t<\/span><span class=\"err\">or<\/span><span class=\"kc\">na<\/span><span class=\"err\">do<\/span><span class=\"kc\">f<\/span><span class=\"err\">x<\/span><span class=\"p\">:<\/span><span class=\"mf\">1.7.17<\/span><span class=\"err\">&#39;<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">compile<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;org.je<\/span><span class=\"kc\">t<\/span><span class=\"err\">brai<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.exposed<\/span><span class=\"p\">:<\/span><span class=\"err\">exposed<\/span><span class=\"p\">:<\/span><span class=\"mf\">0.11.2<\/span><span class=\"err\">&#39;<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">compile<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;org.xerial<\/span><span class=\"p\">:<\/span><span class=\"err\">sqli<\/span><span class=\"kc\">te<\/span><span class=\"mi\">-<\/span><span class=\"err\">jdbc<\/span><span class=\"p\">:<\/span><span class=\"mf\">3.25.2<\/span><span class=\"err\">&#39;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"err\">compileKo<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"err\">Op<\/span><span class=\"kc\">t<\/span><span class=\"err\">io<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.jvmTarge<\/span><span class=\"kc\">t<\/span><span class=\"w\"> <\/span><span class=\"err\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;1.8&quot;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"err\">compileTes<\/span><span class=\"kc\">t<\/span><span class=\"err\">Ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"err\">Op<\/span><span class=\"kc\">t<\/span><span class=\"err\">io<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.jvmTarge<\/span><span class=\"kc\">t<\/span><span class=\"w\"> <\/span><span class=\"err\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;1.8&quot;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<h2 id=\"setting-up-the-database\">Setting up the database<\/h2>\n<p>Any quiz game worth it's salt has categories, and that's the part of the\ndatabase that we'll develop. Exposed allows us to interact with a SQL database\nin two different ways: through the SQL Domain Specific Language (DSL), or\nthrough the Data Access Object (DAO) pattern. I'll use the DAO, as I thought it\nmeshed nicely with TornadoFX. You can read about both of them on the\n<a href=\"https:\/\/github.com\/JetBrains\/Exposed\">Exposed GitHub page<\/a>. We will put all of\nthe database code in a file called <code>database.kt<\/code>. Let's first define the table\nfor categories.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">org.jetbrains.exposed.dao.*<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">org.jetbrains.exposed.sql.*<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">org.jetbrains.exposed.sql.transactions.TransactionManager<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">org.jetbrains.exposed.sql.transactions.transaction<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">java.sql.Connection<\/span>\n\n<span class=\"kd\">object<\/span><span class=\"w\"> <\/span><span class=\"nc\">Categories<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">IntIdTable<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">name<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">varchar<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;name&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">64<\/span><span class=\"p\">).<\/span><span class=\"na\">uniqueIndex<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">description<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">varchar<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;description&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">128<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that we don't explicitly define the primary key, that's all handled in the\nbackground. Along with the table (which is a singleton object), we also need to\nrepresent rows.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Category<\/span><span class=\"p\">(<\/span><span class=\"n\">id<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">EntityID<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">Int<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">IntEntity<\/span><span class=\"p\">(<\/span><span class=\"n\">id<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">companion<\/span><span class=\"w\"> <\/span><span class=\"kd\">object<\/span><span class=\"w\"> <\/span><span class=\"err\">: <\/span><span class=\"nc\">IntEntityClass<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Category<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">(<\/span><span class=\"n\">Categories<\/span><span class=\"p\">)<\/span>\n\n<span class=\"w\">    <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">name<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">Categories<\/span><span class=\"p\">.<\/span><span class=\"na\">name<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">description<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">Categories<\/span><span class=\"p\">.<\/span><span class=\"na\">description<\/span>\n\n<span class=\"w\">    <\/span><span class=\"kd\">override<\/span><span class=\"w\"> <\/span><span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">toString<\/span><span class=\"p\">():<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">return<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Category(name=\\&quot;<\/span><span class=\"si\">$<\/span><span class=\"n\">name<\/span><span class=\"s\">\\&quot;, description=\\&quot;<\/span><span class=\"si\">$<\/span><span class=\"n\">description<\/span><span class=\"s\">\\&quot;)&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>The <code>Category<\/code> class is what we'll use to create DAOs, with which we can\ncreate, modify and delete rows in the <code>Categories<\/code> table. Finally, let's create\nthe table and add some rows to it. We won't actually touch the <code>Categories<\/code>\nobject directly at all.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">args<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Array<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">String<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ &quot;connect&quot; to database file called data.sqlite in the current working directory<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ (creates the file if it does not exist)<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Database<\/span><span class=\"p\">.<\/span><span class=\"na\">connect<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;jdbc:sqlite:file:data.sqlite&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">driver<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;org.sqlite.JDBC&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ this isolation level is required for sqlite, may not be applicable to other DBMS<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">TransactionManager<\/span><span class=\"p\">.<\/span><span class=\"na\">manager<\/span><span class=\"p\">.<\/span><span class=\"na\">defaultIsolationLevel<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Connection<\/span><span class=\"p\">.<\/span><span class=\"na\">TRANSACTION_SERIALIZABLE<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">transaction<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">addLogger<\/span><span class=\"p\">(<\/span><span class=\"n\">StdOutSqlLogger<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ create the table<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">SchemaUtils<\/span><span class=\"p\">.<\/span><span class=\"na\">create<\/span><span class=\"p\">(<\/span><span class=\"n\">Categories<\/span><span class=\"p\">)<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ add some entries<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Category<\/span><span class=\"p\">.<\/span><span class=\"na\">new<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">name<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;java&quot;<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">description<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;The Java programming language&quot;<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">        <\/span><span class=\"n\">Category<\/span><span class=\"p\">.<\/span><span class=\"na\">new<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">name<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;cpp&quot;<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">description<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;The C++ programming language&quot;<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ new transaction to check the results<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">transaction<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Category<\/span><span class=\"p\">.<\/span><span class=\"na\">all<\/span><span class=\"p\">().<\/span><span class=\"na\">forEach<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">println<\/span><span class=\"p\">(<\/span><span class=\"nb\">it<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note how all interactions with the database are conducted inside of a\n<code>transaction<\/code> (which is a function taking a lambda, that abstracts a database\ntransaction). You'll see this several times throughout these articles. That's\nit for database setup! If you run main function, you'll get output that looks\nsomething like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>SQL:<span class=\"w\"> <\/span>CREATE<span class=\"w\"> <\/span>TABLE<span class=\"w\"> <\/span>IF<span class=\"w\"> <\/span>NOT<span class=\"w\"> <\/span>EXISTS<span class=\"w\"> <\/span>Categories<span class=\"w\"> <\/span><span class=\"o\">(<\/span>id<span class=\"w\"> <\/span>INTEGER<span class=\"w\"> <\/span>PRIMARY<span class=\"w\"> <\/span>KEY,<span class=\"w\"> <\/span>name<span class=\"w\"> <\/span>VARCHAR<span class=\"o\">(<\/span><span class=\"m\">64<\/span><span class=\"o\">)<\/span><span class=\"w\"> <\/span>NOT<span class=\"w\"> <\/span>NULL,<span class=\"w\"> <\/span>description<span class=\"w\"> <\/span>VARCHAR<span class=\"o\">(<\/span><span class=\"m\">128<\/span><span class=\"o\">)<\/span><span class=\"w\"> <\/span>NOT<span class=\"w\"> <\/span>NULL<span class=\"o\">)<\/span>\nSQL:<span class=\"w\"> <\/span>CREATE<span class=\"w\"> <\/span>UNIQUE<span class=\"w\"> <\/span>INDEX<span class=\"w\"> <\/span>Categories_name<span class=\"w\"> <\/span>ON<span class=\"w\"> <\/span>Categories<span class=\"w\"> <\/span><span class=\"o\">(<\/span>name<span class=\"o\">)<\/span>\nSQL:<span class=\"w\"> <\/span>INSERT<span class=\"w\"> <\/span>INTO<span class=\"w\"> <\/span>Categories<span class=\"w\"> <\/span><span class=\"o\">(<\/span>description,<span class=\"w\"> <\/span>name<span class=\"o\">)<\/span><span class=\"w\"> <\/span>VALUES<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"s1\">&#39;The Java programming language&#39;<\/span>,<span class=\"w\"> <\/span><span class=\"s1\">&#39;java&#39;<\/span><span class=\"o\">)<\/span>\nSQL:<span class=\"w\"> <\/span>INSERT<span class=\"w\"> <\/span>INTO<span class=\"w\"> <\/span>Categories<span class=\"w\"> <\/span><span class=\"o\">(<\/span>description,<span class=\"w\"> <\/span>name<span class=\"o\">)<\/span><span class=\"w\"> <\/span>VALUES<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"s1\">&#39;The C++ programming language&#39;<\/span>,<span class=\"w\"> <\/span><span class=\"s1\">&#39;cpp&#39;<\/span><span class=\"o\">)<\/span>\nCategory<span class=\"o\">(<\/span><span class=\"nv\">name<\/span><span class=\"o\">=<\/span><span class=\"s2\">&quot;java&quot;<\/span>,<span class=\"w\"> <\/span><span class=\"nv\">description<\/span><span class=\"o\">=<\/span><span class=\"s2\">&quot;The Java programming language&quot;<\/span><span class=\"o\">)<\/span>\nCategory<span class=\"o\">(<\/span><span class=\"nv\">name<\/span><span class=\"o\">=<\/span><span class=\"s2\">&quot;cpp&quot;<\/span>,<span class=\"w\"> <\/span><span class=\"nv\">description<\/span><span class=\"o\">=<\/span><span class=\"s2\">&quot;The C++ programming language&quot;<\/span><span class=\"o\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you run the main function again, it will fail the unique constraint on the\n<code>name<\/code> attribute and crash. And that's it for part 1. In the next part, we'll\nlook at how to create a read-only view of the <code>Categories<\/code> table. You can\nfind\n<a href=\"https:\/\/slar.se\/tornadofxexposed-pt-2-showing-a-database-table.html\">part 2 here<\/a>.<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"kotlin"}},{"@attributes":{"term":"tornadofx"}},{"@attributes":{"term":"exposed"}},{"@attributes":{"term":"kuizzy"}}]},{"title":"Collapsing and expanding HTML elements using (mostly) CSS","link":{"@attributes":{"href":"https:\/\/slar.se\/collapsing-and-expanding-html-elements-using-mostly-css.html","rel":"alternate"}},"published":"2018-11-14T17:57:34+00:00","updated":"2018-11-14T17:57:34+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2018-11-14:\/collapsing-and-expanding-html-elements-using-mostly-css.html","summary":"<p>Sections that collapse and expand at the click of a button is fairly ubiquitous\nacross the web nowadays. It's especially handy for mobile, where the display is\nmuch smaller than your typical computer monitor. In this article, I'll walk you\nthrough how to create a basic collapsible content-area using almost \u2026<\/p>","content":"<p>Sections that collapse and expand at the click of a button is fairly ubiquitous\nacross the web nowadays. It's especially handy for mobile, where the display is\nmuch smaller than your typical computer monitor. In this article, I'll walk you\nthrough how to create a basic collapsible content-area using almost only CSS,\nalong with a few lines of close-to-trivial JavaScript. The focus is on CSS, not\nJavaScript, so you should be able to follow this even with the most rudimentary\nprogramming experience.<\/p>\n<h1 id=\"the-fictional-sidebar\">The fictional sidebar<\/h1>\n<p>For this toy example, we will be creating a collapsible <code>div<\/code> (it could really\nbe just about any element) that can be collapsed and expanded by clicking a\n\"trigger\". Just for the purpose of showing the effects more clearly, we'll do\nit inside of another <code>div<\/code> element, which we'll imagine is a sidebar of a\nwebsite (like the sidebar with recent posts and tags on this site). Here's the\nmarkup for the sidebar:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">&lt;<\/span><span class=\"nt\">div<\/span> <span class=\"na\">class<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;sidebar&quot;<\/span><span class=\"p\">&gt;<\/span>\n    <span class=\"cp\">&lt;!- our content goes in here! --&gt;<\/span>\n<span class=\"p\">&lt;\/<\/span><span class=\"nt\">div<\/span><span class=\"p\">&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>And the CSS:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>.sidebar {\n  width: 30%;\n  border: black solid 2px;\n}\n<\/code><\/pre><\/div>\n\n<p>This is really <em>not<\/em> important for this demo, I just mention it so that you\ndon't wonder about some unknown HTML and CSS in the final demo. Now, let's fill\nthat sidebar up with some content.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">&lt;<\/span><span class=\"nt\">div<\/span> <span class=\"na\">class<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;sidebar&quot;<\/span><span class=\"p\">&gt;<\/span>\n  <span class=\"p\">&lt;<\/span><span class=\"nt\">div<\/span> <span class=\"na\">id<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;trigger&quot;<\/span><span class=\"p\">&gt;<\/span>Cool content heading<span class=\"p\">&lt;\/<\/span><span class=\"nt\">div<\/span><span class=\"p\">&gt;<\/span>\n  <span class=\"p\">&lt;<\/span><span class=\"nt\">div<\/span> <span class=\"na\">id<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;content&quot;<\/span><span class=\"p\">&gt;<\/span>\n    <span class=\"p\">&lt;<\/span><span class=\"nt\">p<\/span><span class=\"p\">&gt;<\/span>\n      This content would be neat to hide and show at the click of a button!\n    <span class=\"p\">&lt;\/<\/span><span class=\"nt\">p<\/span><span class=\"p\">&gt;<\/span>\n  <span class=\"p\">&lt;\/<\/span><span class=\"nt\">div<\/span><span class=\"p\">&gt;<\/span>\n<span class=\"p\">&lt;\/<\/span><span class=\"nt\">div<\/span><span class=\"p\">&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>We have 3 <code>div<\/code> tags in total: one is the container (sidebar) which really has\nlittle to do with this article. The second is a heading for the content, which\nwill act as the trigger for showing and hiding the content. The third is the\none containing the content that we want to hide\/show (a single paragraph).\nLet's get to it! Note the <code>id<\/code> attributes on the two inner <code>div<\/code> tags. When I\nlater refer to the <code>#trigger<\/code>, I mean the div with <code>id=\"trigger\"<\/code>, and likewise\nfor the <code>#content<\/code>. The <code>id<\/code> attributes serve no other purpose here, you can\nremove them if you wish and everything will still work as expected.<\/p>\n<h2 id=\"collapsing-and-expanding-the-div\">Collapsing and expanding the <code>div<\/code><\/h2>\n<p>To collapse and expand <code>#content<\/code>, we will use two classes: <code>collapse-trigger<\/code>\nand <code>collapse<\/code>. The basic idea is this:<\/p>\n<ol>\n<li>An element with the <code>collapse<\/code> is hidden by default.<\/li>\n<li>If a <code>collapse<\/code> element follows an element with the <code>collapse-trigger<\/code> AND\n   the <code>active<\/code> classes, the <code>collapse<\/code> is visible.<\/li>\n<\/ol>\n<p>You can probably guess where to put the classes in the markup already:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">&lt;<\/span><span class=\"nt\">div<\/span> <span class=\"na\">class<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;sidebar&quot;<\/span><span class=\"p\">&gt;<\/span>\n  <span class=\"p\">&lt;<\/span><span class=\"nt\">div<\/span> <span class=\"na\">id<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;trigger&quot;<\/span> <span class=\"na\">class<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;collapse-trigger&quot;<\/span><span class=\"p\">&gt;<\/span>Cool content heading<span class=\"p\">&lt;\/<\/span><span class=\"nt\">div<\/span><span class=\"p\">&gt;<\/span>\n  <span class=\"p\">&lt;<\/span><span class=\"nt\">div<\/span> <span class=\"na\">id<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;content&quot;<\/span> <span class=\"na\">class<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;collapsible&quot;<\/span><span class=\"p\">&gt;<\/span>\n    <span class=\"p\">&lt;<\/span><span class=\"nt\">p<\/span><span class=\"p\">&gt;<\/span>\n      This content would be neat to hide and show at the click of a button!\n    <span class=\"p\">&lt;\/<\/span><span class=\"nt\">p<\/span><span class=\"p\">&gt;<\/span>\n  <span class=\"p\">&lt;\/<\/span><span class=\"nt\">div<\/span><span class=\"p\">&gt;<\/span>\n<span class=\"p\">&lt;\/<\/span><span class=\"nt\">div<\/span><span class=\"p\">&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>For the CSS, fulfilling point 1 above (<code>collapsible<\/code> hidden by default) is\nsimple:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">.<\/span><span class=\"nc\">collapsible<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">display<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kc\">none<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This will simply not display the element.  But how do we fulfill the second\nrequirement? We can use the\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/Adjacent_sibling_selectors\">adjacent sibling combinator<\/a>\n(<code>+<\/code>). It's a selector combinator that allows us to match some element, only if\nit is immediately preceded by some other element. For example, the selector <code>h1\n+ p<\/code> will match any <code>p<\/code> tag that is immediately preceded by an <code>h1<\/code> tag:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nt\">&lt;h1&gt;<\/span>This<span class=\"w\"> <\/span>is<span class=\"w\"> <\/span>a<span class=\"w\"> <\/span>heading<span class=\"nt\">&lt;\/h1&gt;<\/span>\n<span class=\"nt\">&lt;p&gt;<\/span>This<span class=\"w\"> <\/span>paragraph<span class=\"w\"> <\/span>will<span class=\"w\"> <\/span>be<span class=\"w\"> <\/span>matched<span class=\"w\"> <\/span>by<span class=\"w\"> <\/span>&quot;h1<span class=\"w\"> <\/span>+<span class=\"w\"> <\/span>p&quot;<span class=\"nt\">&lt;\/p&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<p>So, to show our <code>collapsible<\/code> when it is directly preceded by a\n<code>collapse-trigger<\/code> AND <code>active<\/code> element, we do this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">.<\/span><span class=\"nc\">collapse-trigger<\/span><span class=\"p\">.<\/span><span class=\"nc\">active<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"p\">.<\/span><span class=\"nc\">collapsible<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">display<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kc\">block<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>We display it as a <code>block<\/code> here, but one could use other display modes as well,\ndepending on what visual effect is sought.  Note that we are chaining two\nclasses in the left hand side of the <code>+<\/code> combinator, which means that an\nelement matches only if it's <code>class<\/code> attribute contains both of those classes\n(and possibly more of them). The order of the classes is however not important,\ni.e. <code>.active.collapse-trigger<\/code> would be equivalent.<\/p>\n<p>That's actually all there is to it, as far as the CSS goes. Now, we can\ncollapse and expand the <code>#content<\/code> by opening the developer tools (<code>F12<\/code> in\nFirefox and Chrome) and manually assigning the <code>active<\/code> class to <code>#trigger<\/code>.\nBut that's not very convenient in every day use. This is where we need the\ntiniest bit of JavaScript to be able to toggle <code>active<\/code>.<\/p>\n<h2 id=\"toggling-the-active-class-with-the-click-of-a-button\">Toggling the <code>active<\/code> class with the click of a button<\/h2>\n<p>What we want to do is to remove and add the <code>active<\/code> class from any\n<code>collapse-trigger<\/code> element by clicking it. Here, we need JavaScript, because\nthere is no way to change the class of an element with only CSS. For every\n<code>collapse-trigger<\/code> in the page, we need to attach an event listener that\ntoggles the <code>active<\/code> class every time the element is clicked. It can be done\nlike this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">function<\/span><span class=\"w\"> <\/span><span class=\"nx\">attachCollapseTriggers<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">colTriggers<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nb\">document<\/span><span class=\"p\">.<\/span><span class=\"nx\">getElementsByClassName<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;collapse-trigger&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">colTrig<\/span><span class=\"w\"> <\/span><span class=\"k\">of<\/span><span class=\"w\"> <\/span><span class=\"nx\">colTriggers<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">colTrig<\/span><span class=\"p\">.<\/span><span class=\"nx\">addEventListener<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;click&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\">  <\/span><span class=\"kd\">function<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">this<\/span><span class=\"p\">.<\/span><span class=\"nx\">classList<\/span><span class=\"p\">.<\/span><span class=\"nx\">toggle<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;active&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">});<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Essentially, we use the <code>getElementsByClassName<\/code> DOM method to find all\nelements with the <code>collapse-trigger<\/code> class. Then, we iterate over those\nelements, and add an event listener to it. The first argument to\n<code>addEventListener<\/code> is an event (in this case a button click). The second\nargument is a callback function, for which we provide an anonymous function. If\nyou have a hard time wrapping your head around anonymous functions, this will\naccomplish the same thing:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">function<\/span><span class=\"w\"> <\/span><span class=\"nx\">collapseTrigger<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">this<\/span><span class=\"p\">.<\/span><span class=\"nx\">classList<\/span><span class=\"p\">.<\/span><span class=\"nx\">toggle<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;active&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">function<\/span><span class=\"w\"> <\/span><span class=\"nx\">attachCollapseTriggers<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">colTriggers<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nb\">document<\/span><span class=\"p\">.<\/span><span class=\"nx\">getElementsByClassName<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;collapse-trigger&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">colTrig<\/span><span class=\"w\"> <\/span><span class=\"k\">of<\/span><span class=\"w\"> <\/span><span class=\"nx\">colTriggers<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">colTrig<\/span><span class=\"p\">.<\/span><span class=\"nx\">addEventListener<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;click&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"nx\">collapseTrigger<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>When the element is clicked, the <code>collapseTrigger<\/code> function is called.  Of\ncourse, we need to call <code>attachCollapseTriggers<\/code> sometime after the page has\nloaded for this to take effect. And that's it for the JavaScript, clicking the\n<code>#trigger<\/code> will now cause <code>#content<\/code> to collapse and expand!  However, it's not\nvery clear to the user that the <code>#trigger<\/code> even can be clicked. Let's make that\njust a little bit more clear by adding some visual cues.<\/p>\n<h2 id=\"finishing-touches-using-the-after-pseudo-class\">Finishing touches using the <code>::after<\/code> pseudo class<\/h2>\n<p>A typical visual cue that a drop down can be expanded is a down-triangle (\u25bc).\nAn up-triangle (\u25b2) is as recognizable a cue that a menu can be collapsed. The\ndown-triangle should be appended to any <code>collapse-trigger<\/code> that is not active,\nwhile the up-triangle should be appended to any <code>collapse-trigger<\/code> that also\nhas the <code>active<\/code> class. We can do that simply use the <code>::after<\/code> pseudo class.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"p\">.<\/span><span class=\"nc\">collapse-trigger<\/span><span class=\"p\">::<\/span><span class=\"nd\">after<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">content<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;\u25bc&quot;<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">float<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kc\">right<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"c\">\/* float to the right-hand side of the content box *\/<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"p\">.<\/span><span class=\"nc\">collapse-trigger<\/span><span class=\"p\">.<\/span><span class=\"nc\">active<\/span><span class=\"p\">::<\/span><span class=\"nd\">after<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">content<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;\u25b2&quot;<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>So, what happens here, exactly? When a <code>collapse-trigger<\/code> is not <code>active<\/code>, it\ndoesn't match the <code>.collapse-trigger.active<\/code> selector, so the content will\nsimply be the down-triangle. When a <code>collapse-trigger<\/code> <em>is<\/em> active, it will\nmatch both selectors. However, <code>.collapse-trigger.active<\/code> is more specific than\n<code>.collapse-trigger<\/code>, so it wins out, and the content will be an up-triangle.\nAnd that's it, all done!<\/p>\n<h1 id=\"code-listing-and-jsfiddle-link\">Code listing and JSFiddle link<\/h1>\n<p>The full code is available in the following subsections, and you can find a\n<a href=\"https:\/\/jsfiddle.net\/p3qtev5w\/\">JSFiddle here<\/a>.<\/p>\n<h3 id=\"markup\">Markup<\/h3>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"cp\">&lt;!- the outer div with the class &quot;sidebar&quot; isn&#39;t important, it&#39;s just any container --&gt;<\/span>\n<span class=\"p\">&lt;<\/span><span class=\"nt\">div<\/span> <span class=\"na\">class<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;sidebar&quot;<\/span><span class=\"p\">&gt;<\/span>\n  <span class=\"p\">&lt;<\/span><span class=\"nt\">div<\/span> <span class=\"na\">class<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;collapse-trigger&quot;<\/span><span class=\"p\">&gt;<\/span>Cool content heading<span class=\"p\">&lt;\/<\/span><span class=\"nt\">div<\/span><span class=\"p\">&gt;<\/span>\n  <span class=\"p\">&lt;<\/span><span class=\"nt\">div<\/span> <span class=\"na\">class<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;collapsible&quot;<\/span><span class=\"p\">&gt;<\/span>\n    <span class=\"p\">&lt;<\/span><span class=\"nt\">p<\/span><span class=\"p\">&gt;<\/span>\n      This content would be neat to hide and show at the click of a button!\n    <span class=\"p\">&lt;\/<\/span><span class=\"nt\">p<\/span><span class=\"p\">&gt;<\/span>\n  <span class=\"p\">&lt;\/<\/span><span class=\"nt\">div<\/span><span class=\"p\">&gt;<\/span>\n<span class=\"p\">&lt;\/<\/span><span class=\"nt\">div<\/span><span class=\"p\">&gt;<\/span>\n<\/code><\/pre><\/div>\n\n<h3 id=\"css\">CSS<\/h3>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c\">\/* the sidebar class is just an arbitrary container for this example *\/<\/span>\n<span class=\"p\">.<\/span><span class=\"nc\">sidebar<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">width<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">30<\/span><span class=\"kt\">%<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">padding<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"kt\">em<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">  <\/span><span class=\"k\">border<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kc\">black<\/span><span class=\"w\"> <\/span><span class=\"kc\">solid<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"kt\">px<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"p\">.<\/span><span class=\"nc\">collapse-trigger<\/span><span class=\"p\">::<\/span><span class=\"nd\">after<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">content<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;\u25bc&quot;<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">float<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kc\">right<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"p\">.<\/span><span class=\"nc\">collapse-trigger<\/span><span class=\"p\">.<\/span><span class=\"nc\">active<\/span><span class=\"p\">::<\/span><span class=\"nd\">after<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">content<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;\u25b2&quot;<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"p\">.<\/span><span class=\"nc\">collapsible<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">display<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kc\">none<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"p\">.<\/span><span class=\"nc\">collapse-trigger<\/span><span class=\"p\">.<\/span><span class=\"nc\">active<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"p\">.<\/span><span class=\"nc\">collapsible<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">display<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kc\">block<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<h3 id=\"javascript\">JavaScript<\/h3>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">function<\/span><span class=\"w\"> <\/span><span class=\"nx\">attachCollapseTriggers<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">colTriggers<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nb\">document<\/span><span class=\"p\">.<\/span><span class=\"nx\">getElementsByClassName<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;collapse-trigger&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nx\">colTrig<\/span><span class=\"w\"> <\/span><span class=\"k\">of<\/span><span class=\"w\"> <\/span><span class=\"nx\">colTriggers<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"nx\">colTrig<\/span><span class=\"p\">.<\/span><span class=\"nx\">addEventListener<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;click&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\">  <\/span><span class=\"kd\">function<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"k\">this<\/span><span class=\"p\">.<\/span><span class=\"nx\">classList<\/span><span class=\"p\">.<\/span><span class=\"nx\">toggle<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;active&quot;<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">});<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"nx\">attachCollapseTriggers<\/span><span class=\"p\">();<\/span>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"html"}},{"@attributes":{"term":"css"}},{"@attributes":{"term":"javascript"}}]},{"title":"A binary search tree in Kotlin pt. 2: Generic node","link":{"@attributes":{"href":"https:\/\/slar.se\/a-binary-search-tree-in-kotlin-pt-2-generic-node.html","rel":"alternate"}},"published":"2018-10-30T08:26:05+00:00","updated":"2018-10-30T08:26:05+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2018-10-30:\/a-binary-search-tree-in-kotlin-pt-2-generic-node.html","summary":"<p>Welcome to part 2 of my series on the idiomatic Kotlin binary tree! In this\npart, we're gonna have a look at how to make the node representation from part 1\ncapable of carrying any kind of data (i.e. <em>generic<\/em>).<\/p>\n<h2 id=\"series-index\">Series index<\/h2>\n<ol>\n<li><a href=\"https:\/\/slar.se\/a-binary-search-tree-in-kotlin-pt-1-representing-a-node.html\">Representing a node<\/a><\/li>\n<li>Generic node (this part \u2026<\/li><\/ol>","content":"<p>Welcome to part 2 of my series on the idiomatic Kotlin binary tree! In this\npart, we're gonna have a look at how to make the node representation from part 1\ncapable of carrying any kind of data (i.e. <em>generic<\/em>).<\/p>\n<h2 id=\"series-index\">Series index<\/h2>\n<ol>\n<li><a href=\"https:\/\/slar.se\/a-binary-search-tree-in-kotlin-pt-1-representing-a-node.html\">Representing a node<\/a><\/li>\n<li>Generic node (this part!)<\/li>\n<li>Generic BST with insert, contains and traversal (coming soon!)<\/li>\n<\/ol>\n<h2 id=\"attribution-and-reading-recommendations\">Attribution and reading recommendations<\/h2>\n<p>In this part, we'll start working a little bit with binary tree algorithms. More\nspecifically, we'll complete the <code>contains<\/code> function from part 1. All of the\nalgorithms I implement in this series are based on\n<a href=\"https:\/\/yourbasic.org\/algorithms\/binary-search-tree\/\">this article by Stefan Nilsson<\/a>.\nIf you are unfamiliar with the concepts of binary trees, I highly recommend that\nyou sift through that article before continuing with this one.<\/p>\n<h2 id=\"improving-contains\">Improving <code>contains<\/code><\/h2>\n<p>Recall the <code>contains<\/code> function that we started working on in part 1. Before we\nstart working on generics, I want us to complete this function. It will make\nsome of the decisions about generics much more apparent. Anyway, here's\n<code>contains<\/code> as we wrote it in part 1.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ check if data is contained in node<\/span>\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"kt\">Boolean<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ note implicit cast<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>It's not a particularly useful function, as it only checks the current node.\nWhat we'd rather have it do is check the entire subtree, in which <code>node<\/code> is the\nroot. This can quite easily be performed with recursion. The <code>Empty<\/code> case still\nstands, if we hit an empty node, the data is not contained in the tree. If\n<code>node<\/code> is a <code>Node<\/code>, on the other hand, there are three possibilities:<\/p>\n<ol>\n<li><code>data &lt; node.data<\/code>, in which case we keep searching in the left subtree.<\/li>\n<li><code>data &gt; node.data<\/code>, in which case we keep searching in the right subtree.<\/li>\n<li><code>data<\/code> is neither smaller or larger than <code>node.data<\/code>, so they are comparably\nequal. If this actually means that they are equal or not is implementation\nspecific, but it is <em>highly<\/em> recommended that ordering is consistent with\n<code>equals<\/code>. We will assume that this is the case.<\/li>\n<\/ol>\n<p>As we have three distinct cases, we can again use a <code>when<\/code> expression.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ check if data is contained in the tree rooted in node<\/span>\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"kt\">Boolean<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ no-argument when so we can do arbitrary comparisons<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">left<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">right<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">else<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kc\">true<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that the nested <code>when<\/code> expression has no argument in parentheses, allowing\nus to perform more complex operations in the matchings. And that's it for the\n<code>contains<\/code> operation. It's really quite elegant. We can quickly ammend the\n<code>main<\/code> function to try it out:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">args<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Array<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">String<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ create the tree<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/          6<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/         \/ \\<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/        3   9<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/         \\<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/          4<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">root<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">6<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">left<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">3<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">                    <\/span><span class=\"n\">right<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">4<\/span><span class=\"p\">)),<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">right<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">9<\/span><span class=\"p\">))<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">println<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Search for elements in the tree&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">listOf<\/span><span class=\"p\">(<\/span><span class=\"m\">6<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">4<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">9<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">println<\/span><span class=\"p\">(<\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">root<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">println<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Search for elements not in the tree&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">listOf<\/span><span class=\"p\">(<\/span><span class=\"m\">10<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"o\">-<\/span><span class=\"m\">12<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">println<\/span><span class=\"p\">(<\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">root<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>With that out of the way, let's dive into making the whole thing generic!<\/p>\n<h2 id=\"getting-generic\">Getting generic<\/h2>\n<p>Now, how do we make the node classes generic? A first attempt might be to just\nchange the <code>Node<\/code> class, and do something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">data<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Node<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">(<\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">left<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">right<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">()<\/span>\n\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Comparable<\/span><span class=\"err\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"err\">&gt; <\/span><span class=\"nf\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"kt\">Boolean<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">left<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">right<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">else<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kc\">true<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is a reasonable attempt. Before we dive into the problems, let's analyze\nwhat we just did. After <code>fun<\/code> we write <code>&lt;T : Comparable&lt;T&gt;&gt;<\/code>, which makes this\nfunction generic. The addition states that the type parameter <code>T<\/code> can be\nsubstituted by any type that implements <code>Comparable&lt;T&gt;<\/code> (which we need to be\nable to use <code>&lt;<\/code> and <code>&gt;<\/code>). <code>Node&lt;T&gt;<\/code> simply defines a type parameter <code>T<\/code> that\ncan be substituted with <em>any<\/em> type. It is a bit inconvenient that we could put\nnon-comparable types in a <code>Node<\/code> object, but we'll see that it sorts itself out\nwhen we create the <code>Tree<\/code> class in part 3. For now, just ignore that detail.<\/p>\n<p>Now, the above code won't compile, for multiple reasons. The first problem is\nthat we can't ask at runtime if <code>node is Node&lt;T&gt;<\/code> (the compiler will say <em>Cannot\ncheck for erased type: Node<T><\/em>), becuase information about generics is erased\nat runtime. We could succesfully match against a wildcard type parameter\n(meaning <em>any<\/em> type) with <code>is Node&lt;*&gt;<\/code>, but then we run into the real\nshowstopper: we don't know whether <code>data<\/code> and <code>node.data<\/code> are actually\ncomparable, as they might not have the same type. With the current class\nhierarchy, there is <em>no<\/em> reasonable way around this. An <code>ANode<\/code> is not\nparameterized, and therefore the dynamic type of an <code>ANode<\/code> can be any <code>Node<\/code>\ntype (e.g. <code>Node&lt;Int&gt;<\/code>, <code>Node&lt;String&gt;<\/code> etc) or <code>Empty<\/code>. We have to put the type\nparameter <code>T<\/code> higher up in the inheritance chain. <\/p>\n<h3 id=\"inheriting-from-a-generic-class\">Inheriting from a generic class<\/h3>\n<p>Since <code>ANode<\/code> is the only class higher up in the inheritance chain (apart from\n<code>Any<\/code>), this is where we need to put our type parameter. For <code>ANode<\/code> and <code>Node<\/code>,\nit is straightforward.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">sealed<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span>\n\n<span class=\"kd\">data<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Node<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">(<\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">left<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">right<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span>\n<span class=\"w\">        <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that <code>Node&lt;T&gt;<\/code> is inheriting from <code>ANode&lt;T&gt;<\/code>. We cannot (and wouldn't want\nto, anyway) leave it as <code>ANode<\/code>, because unlike Java, Kotlin does not support\nraw types. Now, since we cannot inherit from <code>ANode<\/code>, but must specify the type\nparameter with a concrete type, what do we put there for <code>Empty<\/code>? In the case of\n<code>Node&lt;T&gt;<\/code>, we simply inherit from <code>ANode&lt;T&gt;<\/code>, because <code>T<\/code> is declared as a\nparameter to <code>Node&lt;T&gt;<\/code> and is therefore concrete for for <code>ANode<\/code>. We can't\nhowever just do something like<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">object<\/span><span class=\"w\"> <\/span><span class=\"nc\">Empty<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>because <code>T<\/code> is not declared in that scope. We also can't give <code>Empty<\/code> a type\nparameter, because <code>Empty<\/code> is a singleton object, and type parameters simply\ndon't work with singletons (it wouldn't make much sense, if you stop to think\nabout it for a while). What we actually want to put as the type parameter, is\nnothing. Literally. We wan't <code>Nothing<\/code>, a concrete type in Kotlin which is a\nsubtype of every non-nullable type. <\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">object<\/span><span class=\"w\"> <\/span><span class=\"nc\">Empty<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Nothing<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that we don't want to put <code>Any<\/code> (which is the supertype of every\nnon-nullable type), because the we wouldn't be able to assign <code>Empty<\/code> to any\nconcrete type of <code>ANode&lt;T&gt;<\/code>. Now you may be angrily shouting that you\n<em>still<\/em> can't assign <code>Empty<\/code> to <em>any<\/em> type of <code>ANode&lt;T&gt;<\/code>. Unfortunately,\n<code>ANode&lt;T&gt;<\/code> (for any substition of <code>T<\/code>) is <em>invariant<\/em>. Let's fix that.<\/p>\n<h2 id=\"generics-are-invariant-by-default-but-kotlin-can-stretch-the-rules\">Generics are invariant by default, but Kotlin can stretch the rules<\/h2>\n<p>Any generc class is invariant by default. What does this mean? In short, it\nmeans that a generic type (e.g. <code>ANode&lt;Int&gt;<\/code>) is not a supertype, nor subtype,\nof any other type. Formally, it means that if we have two types <code>A<\/code> and <code>B<\/code>\nsuch that <code>B<\/code> is a subtype of <code>A<\/code>, <code>ANode&lt;B&gt;<\/code> is <em>not<\/em> a subtype of <code>ANode&lt;A&gt;<\/code>.\nTake for example <code>Empty<\/code>, which subtypes <code>ANode&lt;Nothing&gt;<\/code>. It is not a subtype\nof <code>ANode&lt;Int&gt;<\/code>, even though <code>Nothing<\/code> is a subtype of <code>Int<\/code>. Inconvenient, we\nwant <code>Empty<\/code> to be a subtype of <em>any<\/em> concrete <code>ANode<\/code>. We can achieve this by\nusing the <code>out<\/code> modifier, and declaring <code>Anode&lt;out T&gt;<\/code>. Formally, we make\n<code>ANode<\/code> <em>covariant<\/em> on the type parameter <code>T<\/code>. We can only do this if every use\nof <code>T<\/code> is in an <em>out<\/em> position (i.e.  return values). Note that this\nrestriction applies only to the body of <code>ANode<\/code>, the <code>T<\/code> in <code>Node&lt;T&gt;<\/code> is <em>not<\/em>\nthe same type parameter as in <code>ANode&lt;out T&gt;<\/code>.  If you found all of that\nconfusing (I sure did the first time I read about it), you can read more about\nvariance in the\n<a href=\"https:\/\/kotlinlang.org\/docs\/reference\/generics.html\">Kotlin docs on generics<\/a>.\nHere is what the working class hierarchy looks like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">sealed<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span>\n\n<span class=\"kd\">object<\/span><span class=\"w\"> <\/span><span class=\"nc\">Empty<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Nothing<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">()<\/span>\n\n<span class=\"kd\">data<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Node<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">left<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">            <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">right<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p><code>contains<\/code> now looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ check if data is contained in node<\/span>\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Comparable<\/span><span class=\"err\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"err\">&gt; <\/span><span class=\"nf\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"kt\">Boolean<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">left<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">right<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">else<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kc\">true<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now, you may be asking yourself why in the world we can do the <code>is Node&lt;T&gt;<\/code>\ncheck <em>now<\/em>, while we could not before? Well, we're not actually checking at\nruntime whether <code>node<\/code> is <code>Node&lt;T&gt;<\/code>, because the compiler knows any variable\nwith the static type <code>ANode&lt;T&gt;<\/code> is either <code>Empty<\/code>, or <code>Node&lt;T&gt;<\/code>. So, for\nexample, <code>ANode&lt;Int&gt;<\/code> must have dynamic type <code>Empty<\/code> or <code>Node&lt;Int&gt;<\/code>, there are\nno other possibilities. As the compiler knows this, we can in fact skip the\n<code>&lt;T&gt;<\/code> and just write <code>is Node<\/code>. That's all we need of our node classes, so we\ncan move on to implement the <code>Tree<\/code> class in part 3!<\/p>\n<h2 id=\"final-code-listing\">Final code listing<\/h2>\n<p>This is the final state of the code that we'll be using for part 3.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">sealed<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"k\">out<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span>\n\n<span class=\"kd\">object<\/span><span class=\"w\"> <\/span><span class=\"nc\">Empty<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Nothing<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">()<\/span>\n\n<span class=\"kd\">data<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Node<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">left<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">right<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">()<\/span>\n\n<span class=\"c1\">\/\/ check if data is contained in node<\/span>\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Comparable<\/span><span class=\"err\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"err\">&gt; <\/span><span class=\"nf\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">T<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"kt\">Boolean<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">T<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">&lt;<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">left<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">right<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">else<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kc\">true<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">args<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Array<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">String<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ create the tree<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/          6<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/         \/ \\<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/        3   9<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/         \\<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/          4<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">root<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">6<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">left<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">3<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">                    <\/span><span class=\"n\">right<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">4<\/span><span class=\"p\">)),<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">right<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">9<\/span><span class=\"p\">))<\/span>\n\n<span class=\"w\">    <\/span><span class=\"n\">println<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Search for elements in the tree&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">listOf<\/span><span class=\"p\">(<\/span><span class=\"m\">6<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">4<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">9<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">println<\/span><span class=\"p\">(<\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">root<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">println<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Search for elements not in the tree&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">listOf<\/span><span class=\"p\">(<\/span><span class=\"m\">10<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"o\">-<\/span><span class=\"m\">12<\/span><span class=\"p\">))<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">println<\/span><span class=\"p\">(<\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">root<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"bst"}},{"@attributes":{"term":"kotlin"}},{"@attributes":{"term":"data structures"}}]},{"title":"A binary search tree in Kotlin pt. 1: Representing a node","link":{"@attributes":{"href":"https:\/\/slar.se\/a-binary-search-tree-in-kotlin-pt-1-representing-a-node.html","rel":"alternate"}},"published":"2018-10-28T15:13:08+00:00","updated":"2018-10-30T08:27:09+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2018-10-28:\/a-binary-search-tree-in-kotlin-pt-1-representing-a-node.html","summary":"<p>In my journey to become a somewhat competent Kotlin developer, I've decided to\nimplement a few of the basic data structures that I've picked up during my\nthree years of computer science studies. First up, we have a generic binary\ntree. This is an interesting case, because it lets us \u2026<\/p>","content":"<p>In my journey to become a somewhat competent Kotlin developer, I've decided to\nimplement a few of the basic data structures that I've picked up during my\nthree years of computer science studies. First up, we have a generic binary\ntree. This is an interesting case, because it lets us both delve into generics\nin Kotlin, and some aspects of inheritance that differ from inheritance in\nJava (in a good way!). As I want to cover some topics in depth, this will be\na three-part series with the following content:<\/p>\n<ol>\n<li>In the first part, we'll develop a basic class hierarchy for representing\n   nodes. It covers <strong>object<\/strong> types, <strong>data classes<\/strong> and <strong>sealed classes<\/strong>,\n   as well as some other related topics. The node is however restricted to only\n   carry <code>Int<\/code> data.<\/li>\n<li>In the second part, we'll expand upon the class hierarchy from part 1 to\n   create a generic node class that can hold any type of data.<\/li>\n<li>Finally, we'll use the results of part 2 to develop a rudimentary binary tree\n   in (what is in my opinion) idiomatic Kotlin.<\/li>\n<\/ol>\n<p>If you already know about object types, data classes and sealed classes, I\nrecommend that you skip directly to part 2. If you are already comfortable with\ngenerics, including generic inheritance, you may skip directly to part 3.<\/p>\n<h2 id=\"series-index\">Series index<\/h2>\n<ol>\n<li>Representing a node (this part!)<\/li>\n<li><a href=\"https:\/\/slar.se\/a-binary-search-tree-in-kotlin-pt-2-generic-node.html\">Generic node<\/a><\/li>\n<li>Generic BST with insert, contains and traversal (coming soon!)<\/li>\n<\/ol>\n<h2 id=\"goals-and-intended-audience\">Goals and intended audience<\/h2>\n<p>I write articles mostly for myself, and as such, this article series is intended\nfor developers with some experience with Java looking to get into Kotlin. Let's\nget at it then, shall we?<\/p>\n<h2 id=\"representing-a-node-a-java-like-attempt\">Representing a node: A Java-like attempt<\/h2>\n<p>As I see it, a tree node can be one of two things: existent, or non-existent.\nIn other words, it can be a node or an empty node. As Kotlin is, thankfully,\nquite adverse to using <code>null<\/code>, I will refrain from doing so as well. So what we\nwant is an abstract node class <code>ANode<\/code> and sub-classes <code>Node<\/code> and <code>Empty<\/code>. Let's\ngive it a first try in a pretty Java-like manner, and then improve upon it with\nsome neat Kotlin language constructs.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">abstract<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ANode<\/span>\n\n<span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Empty<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">()<\/span>\n\n<span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Node<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">left<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">right<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span>\n\n<span class=\"w\">    <\/span><span class=\"k\">constructor<\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"k\">super<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">this<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">right<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">left<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you've had any experience with any remotely Java-looking language, you can\nprobably guess what's going on here. There's the abstract <code>ANode<\/code> class, the\n<code>Empty<\/code> class representing the absence of a node and the <code>Node<\/code> class\nrepresenting an actual node. Note also that we have not delved into generics\nyet, this is a node that can only hold <code>Int<\/code> data. That's fine for now, we'll\nexpand upon this implementation with generics in part 2. When we later implement\nthe binary tree, we will often want to distinguish between a <code>Node<\/code> and <code>Empty<\/code>.\nOne such case is when we search the tree for a given value, to see if it is\ncontained in the tree. This operation can be succinctly expressed using\nrecursion, but let us leave that for part 2. For now, let's just check the first\nnode (the <em>root<\/em>), without exploring its children.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ check if data is contained in node<\/span>\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"kt\">Boolean<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ note implicit cast<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">else<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">throw<\/span><span class=\"w\"> <\/span><span class=\"n\">IllegalArgumentException<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;node argument was neither Empty nor Node!&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is of course a pretty stupid function at this point, but we'll make it much\nmore worthwhile in part 2. Note the \n<a href=\"https:\/\/kotlinlang.org\/docs\/reference\/basic-syntax.html\">expression body<\/a>\nused here, in combination with a\n<a href=\"https:\/\/kotlinlang.org\/docs\/reference\/control-flow.html\"><code>when<\/code> expression<\/a>.\nIf you are unfamiliar with those concepts, follow the links and read up on them,\nthey will be crucial when implementing the tree algorithms in parts 2 and 3.\nAlso note the\n<a href=\"https:\/\/kotlinlang.org\/docs\/reference\/typecasts.html\">implicit cast<\/a> occurring\non the second line of the function. Since we used <code>is Node<\/code> to match <code>node<\/code>, the\ncompiler can infer that <code>node<\/code> is in fact a <code>Node<\/code> object, and we can safely\ndereference it with <code>node.data<\/code>! Finally, note that the <code>else<\/code> case is needed as\nthe compiler does not know that there are only two subclasses of <code>ANode<\/code> (even\nthough we currently do, in this very small project). We'll see how to resolve\nthat shortly. Let's try this function out:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">Empty<\/span><span class=\"p\">(),<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"p\">)<\/span>\n<span class=\"kc\">false<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">2<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"p\">)<\/span>\n<span class=\"kc\">true<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">2<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"p\">)<\/span>\n<span class=\"kc\">false<\/span>\n<\/code><\/pre><\/div>\n\n<p>It seems to work just fine. We <em>could<\/em> leave the class hierarchy like this and\njump straight into generics. There are, however, three notable problems with the\nnode classes.<\/p>\n<ol>\n<li>For each empty node we need, a new instance of <code>Empty<\/code> is created. This is\n   wasteful.<\/li>\n<li>The body of <code>Node<\/code> is a whole lot of code for very little functionality.<\/li>\n<li>The compiler can't tell that <code>Node<\/code> and <code>Empty<\/code> are the only subtypes of\n   <code>ANode<\/code>, forcing us to use an <code>else<\/code> in the <code>when<\/code> expression.<\/li>\n<\/ol>\n<p>As it turns out, all of these problems are easy to solve in Kotlin!<\/p>\n<h3 id=\"problem-1-solution-singleton-objects\">Problem 1 solution: Singleton objects<\/h3>\n<p>Problem number 1 can be solved very easily, as Kotlin has language support for\nthe singleton pattern. We simply swap this declaration<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Empty<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>for this declaration<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">object<\/span><span class=\"w\"> <\/span><span class=\"nc\">Empty<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p><code>Empty<\/code> is now a singleton object, so we can assign it without instantiating\n<code>Empty<\/code>s all over the place. The constructor for <code>Node<\/code> now looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">constructor<\/span><span class=\"p\">(<\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"k\">super<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">this<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">;<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">right<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\">       <\/span><span class=\"c1\">\/\/ note the lack of parentheses!<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">left<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>One problem solved, two to go!<\/p>\n<h3 id=\"problem-2-solution-primary-constructors-and-data-classes\">Problem 2 solution: Primary constructors and data classes<\/h3>\n<p>We can solve problem number 2 with Kotlin's syntax for\n<a href=\"https:\/\/kotlinlang.org\/docs\/reference\/classes.html\">primary constructors<\/a>.\nInstead of defining <code>Node<\/code> the Java way, we do it the Kotlin way:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Node<\/span><span class=\"p\">(<\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">right<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">left<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is <em>almost<\/em> equivalent to the previous declaration, with the exception that\n<code>right<\/code> and <code>left<\/code> are assigned default values in the header such that they can\nbe replaced by explicit arguments when calling the constructor. Note that\n<code>ANode<\/code> must be instantiated right there in the header as well. However, since\nwe know that <code>Node<\/code> will always be a simple container, we can do one better here\nby prepending <code>data<\/code> to the declaration.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">data<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Node<\/span><span class=\"p\">(<\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">right<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">left<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div>\n\n<p>This makes <code>Node<\/code> a\n<a href=\"https:\/\/kotlinlang.org\/docs\/reference\/data-classes.html\">data class<\/a>, which\namong other things come with implementations of <code>equals<\/code> and <code>toString<\/code>. A\nfortunate accident here is that the <code>toString<\/code> of <code>Node<\/code> will actually let us\nview the whole tree with very little effort, as <code>toString<\/code> will be called on\nboth <code>left<\/code> and <code>right<\/code>, recursively (this will be demonstrated in part 3). Do\nbe careful not to create a cycle, though, as this will cause a stack overflow,\nendlessly calling <code>toString<\/code> (a tree, by definition, has no cycles, so we are\ngood in this case).<\/p>\n<h3 id=\"problem-3-solution-sealed-classes\">Problem 3 solution: Sealed classes<\/h3>\n<p>To reiterate, the problem was that the compiler can't tell that <code>Node<\/code> and\n<code>Empty<\/code> are the only subtypes of <code>ANode<\/code>. Therefore, we needed the <code>else<\/code> in the\n<code>when<\/code> expression to cover up the non-existent case of the argument to\n<code>contains<\/code> being anything else.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ check if data is contained in node<\/span>\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"kt\">Boolean<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">else<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">throw<\/span><span class=\"w\"> <\/span><span class=\"n\">IllegalArgumentException<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;node argument was neither Empty nor Node!&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>We can, however, <em>tell<\/em> the compiler that <code>Node<\/code> and <code>Empty<\/code> <em>are<\/em> the only\nsubtypes by making <code>ANode<\/code> a\n<a href=\"https:\/\/kotlinlang.org\/docs\/reference\/sealed-classes.html_\"><code>sealed<\/code> class<\/a>.\nAny subclass of a sealed class must be declared inside the same file, which lets\nthe compiler know precisely which subtypes can exist. To accomplish this, we\nsimply replace the <code>abstract<\/code> modifier with <code>sealed<\/code> (because <code>sealed<\/code> implies\n<code>abstract<\/code>, we don't need the latter).<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">sealed<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ANode<\/span>\n<\/code><\/pre><\/div>\n\n<p>We can now drop the <code>else<\/code> from <code>contains<\/code>, because the compiler knows that a\nvariable with static type <code>ANode<\/code> is either <code>Empty<\/code>, or a <code>Node<\/code>, there are no\nother possibilities.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ check if data is contained in node<\/span>\n<span class=\"n\">fun<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Int<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"n\">Boolean<\/span><span class=\"w\"> <\/span><span class=\"p\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">false<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"n\">data<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Let's give it a try<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">2<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"p\">)<\/span>\n<span class=\"kc\">true<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">Empty<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"p\">)<\/span>\n<span class=\"kc\">false<\/span>\n<\/code><\/pre><\/div>\n\n<p>Neat, now we have a good base for venturing into the fraught land of generics in\n<a href=\"https:\/\/slar.se\/a-binary-search-tree-in-kotlin-pt-2-generic-node.html\">part 2<\/a>.<\/p>\n<h2 id=\"final-code-listing\">Final code listing<\/h2>\n<p>The final version of the code, that we'll use in part 2, can be found below.\nI've also included a main function such that you can run the code in your\npreferred way, right off the bat!<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">sealed<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">ANode<\/span>\n\n<span class=\"kd\">object<\/span><span class=\"w\"> <\/span><span class=\"nc\">Empty<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">()<\/span>\n\n<span class=\"kd\">data<\/span><span class=\"w\"> <\/span><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Node<\/span><span class=\"p\">(<\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">left<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"kd\">var<\/span><span class=\"w\"> <\/span><span class=\"nv\">right<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">()<\/span>\n\n<span class=\"c1\">\/\/ check if data is contained in node<\/span>\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">ANode<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span><span class=\"p\">):<\/span><span class=\"w\"> <\/span><span class=\"kt\">Boolean<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">when<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">node<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Empty<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"kc\">false<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">is<\/span><span class=\"w\"> <\/span><span class=\"n\">Node<\/span><span class=\"w\"> <\/span><span class=\"o\">-&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span><span class=\"w\"> <\/span><span class=\"o\">==<\/span><span class=\"w\"> <\/span><span class=\"n\">node<\/span><span class=\"p\">.<\/span><span class=\"na\">data<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ note implicit cast<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">args<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Array<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">String<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">println<\/span><span class=\"p\">(<\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">Empty<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">println<\/span><span class=\"p\">(<\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">2<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"m\">2<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">println<\/span><span class=\"p\">(<\/span><span class=\"n\">contains<\/span><span class=\"p\">(<\/span><span class=\"n\">Node<\/span><span class=\"p\">(<\/span><span class=\"m\">2<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"p\">))<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"bst"}},{"@attributes":{"term":"kotlin"}},{"@attributes":{"term":"data structures"}}]},{"title":"Creating a standalone (runnable) Kotlin .jar file with IntelliJ and Gradle","link":{"@attributes":{"href":"https:\/\/slar.se\/creating-a-standalone-runnable-kotlin-jar-file-with-intellij-and-gradle.html","rel":"alternate"}},"published":"2018-10-17T20:15:46+00:00","updated":"2018-10-29T21:02:18+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2018-10-17:\/creating-a-standalone-runnable-kotlin-jar-file-with-intellij-and-gradle.html","summary":"<p>I've recently started dabbling in some Kotlin, and have found it a very pleasant\nexperience. One of the first things I wanted to do was to create a standalone\n<code>.jar<\/code> file, including the Kotlin runtime and any other dependencies. This,\nas it turns out, was a bit tricky. In this \u2026<\/p>","content":"<p>I've recently started dabbling in some Kotlin, and have found it a very pleasant\nexperience. One of the first things I wanted to do was to create a standalone\n<code>.jar<\/code> file, including the Kotlin runtime and any other dependencies. This,\nas it turns out, was a bit tricky. In this short article, I will walk you\nthrough creating a small command line application using the\nawesome <a href=\"https:\/\/ajalt.github.io\/clikt\/\"><code>clikt<\/code> library<\/a>, and then packaging\nit into a standalone <code>.jar<\/code>.<\/p>\n<h2 id=\"setting-up\">Setting up<\/h2>\n<p>Start out with creating a new project by going to <code>File -&gt; New -&gt; Project<\/code>, select\nGradle in the leftmost menu bar (i.e. <em>not<\/em> Kotlin), and then tick the Kotlin\nbox in the <code>Additional Libraries and Frameworks<\/code> menu. Then just fill in any\nGroupId, ArtifactId and Version (I will use <code>slarse<\/code>, <code>app<\/code> and <code>0.1<\/code> for these\nfields, respectively). Then just click <code>Next<\/code> with the defaults until the\nproject is created.<\/p>\n<h3 id=\"initial-gradle-configuration\">Initial Gradle configuration<\/h3>\n<p>In the project root, you should now have a file called <code>build.gradle<\/code>, which\nlooks something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"err\">plugi<\/span><span class=\"kc\">ns<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">id<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;org.je<\/span><span class=\"kc\">t<\/span><span class=\"err\">brai<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"err\">.jvm&#39;<\/span><span class=\"w\"> <\/span><span class=\"err\">versio<\/span><span class=\"kc\">n<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;<\/span><span class=\"mf\">1.2.51<\/span><span class=\"err\">&#39;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"err\">group<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;slarse&#39;<\/span>\n<span class=\"err\">versio<\/span><span class=\"kc\">n<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;<\/span><span class=\"mf\">0.1<\/span><span class=\"err\">&#39;<\/span>\n\n<span class=\"err\">reposi<\/span><span class=\"kc\">t<\/span><span class=\"err\">ories<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">mave<\/span><span class=\"kc\">n<\/span><span class=\"err\">Ce<\/span><span class=\"kc\">ntral<\/span><span class=\"err\">()<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"err\">depe<\/span><span class=\"kc\">n<\/span><span class=\"err\">de<\/span><span class=\"kc\">n<\/span><span class=\"err\">cies<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">compile<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;org.jetbrains.kotlin:kotlin-stdlib-jdk8&quot;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"err\">compileKo<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"err\">Op<\/span><span class=\"kc\">t<\/span><span class=\"err\">io<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.jvmTarge<\/span><span class=\"kc\">t<\/span><span class=\"w\"> <\/span><span class=\"err\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;1.8&quot;<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"err\">compileTes<\/span><span class=\"kc\">t<\/span><span class=\"err\">Ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"err\">Op<\/span><span class=\"kc\">t<\/span><span class=\"err\">io<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.jvmTarge<\/span><span class=\"kc\">t<\/span><span class=\"w\"> <\/span><span class=\"err\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;1.8&quot;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Before we can compile a project with <code>clikt<\/code>, we need to add it as a dependency.\nWe can do that by adding <code>compile \"com.github.ajalt:clikt:1.5.0\"<\/code> in the\ndependencies section. It should now look like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"err\">depe<\/span><span class=\"kc\">n<\/span><span class=\"err\">de<\/span><span class=\"kc\">n<\/span><span class=\"err\">cies<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">compile<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;org.jetbrains.kotlin:kotlin-stdlib-jdk8&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">compile<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;com.github.ajalt:clikt:1.5.0&quot;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Then hit the little refresh symbol in the bottom left corner\n(should say <code>Refresh Gradle Project<\/code> when you hover your mouse over it) to\ndownload the new dependency. And that's it for now!\nWe'll get back to the <code>gradle.build<\/code> file once we\nwant to configure our <code>jar<\/code> task, but let's create the app first!<\/p>\n<h2 id=\"creating-the-application\">Creating the application<\/h2>\n<p>Let's make this easy: we'll just use the sample application available from the\n<a href=\"https:\/\/ajalt.github.io\/clikt\/\"><code>clikt<\/code> documentation<\/a>. It looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Hello<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">CliktCommand<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">count<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">option<\/span><span class=\"p\">(<\/span><span class=\"n\">help<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;Number of greetings&quot;<\/span><span class=\"p\">).<\/span><span class=\"na\">int<\/span><span class=\"p\">().<\/span><span class=\"na\">default<\/span><span class=\"p\">(<\/span><span class=\"m\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">name<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">option<\/span><span class=\"p\">(<\/span><span class=\"n\">help<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;The person to greet&quot;<\/span><span class=\"p\">).<\/span><span class=\"na\">prompt<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Your name&quot;<\/span><span class=\"p\">)<\/span>\n\n<span class=\"w\">    <\/span><span class=\"kd\">override<\/span><span class=\"w\"> <\/span><span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">run<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">i<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">1.<\/span><span class=\"p\">.<\/span><span class=\"na\">count<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">echo<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Hello <\/span><span class=\"si\">$<\/span><span class=\"n\">name<\/span><span class=\"s\">!&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">args<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Array<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">String<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Hello<\/span><span class=\"p\">().<\/span><span class=\"na\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<p>Create a Kotlin file called <code>main.kt<\/code> at <code>src\/main\/kotlin\/main.kt<\/code> and paste\nthe above code into it. Note that we are using the default package here\n(i.e. not defining a package) for the sake of simplicity.<\/p>\n<p>For this to compile, we will need to add the following imports at the top:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">com.github.ajalt.clikt.core.CliktCommand<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">com.github.ajalt.clikt.parameters.options.default<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">com.github.ajalt.clikt.parameters.options.option<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">com.github.ajalt.clikt.parameters.options.prompt<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">com.github.ajalt.clikt.parameters.types.int<\/span>\n<\/code><\/pre><\/div>\n\n<p>And that's it for the application, you should now be able to run it as usual.\nWhen running it, there should appear a prompt in the terminal saying <code>Your name:<\/code>.\nWith that out of the way, the only thing left to do is to package our\nfantastic application into a standalone <code>.jar<\/code> file.<\/p>\n<h2 id=\"packaging-the-application-into-a-standalone-jar-file\">Packaging the application into a standalone <code>.jar<\/code> file<\/h2>\n<p>This is actually not very difficult, but you need to know what to do. We need\nto create a so-called \"fat\" jar, which includes both the Kotlin runtime and the\n<code>clikt<\/code> library. We also need to specify the name of our main class.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"err\">jar<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">ma<\/span><span class=\"kc\">n<\/span><span class=\"err\">i<\/span><span class=\"kc\">fest<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"err\">a<\/span><span class=\"kc\">ttr<\/span><span class=\"err\">ibu<\/span><span class=\"kc\">tes<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;Mai<\/span><span class=\"kc\">n<\/span><span class=\"mi\">-<\/span><span class=\"err\">Class&#39;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;Mai<\/span><span class=\"kc\">n<\/span><span class=\"err\">K<\/span><span class=\"kc\">t<\/span><span class=\"err\">&#39;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"kc\">fr<\/span><span class=\"err\">om<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"err\">co<\/span><span class=\"kc\">nf<\/span><span class=\"err\">igura<\/span><span class=\"kc\">t<\/span><span class=\"err\">io<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.compile.collec<\/span><span class=\"kc\">t<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"err\">i<\/span><span class=\"kc\">t<\/span><span class=\"err\">.isDirec<\/span><span class=\"kc\">t<\/span><span class=\"err\">ory()<\/span><span class=\"w\"> <\/span><span class=\"err\">?<\/span><span class=\"w\"> <\/span><span class=\"err\">i<\/span><span class=\"kc\">t<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"err\">zipTree(i<\/span><span class=\"kc\">t<\/span><span class=\"err\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Note that the class file generated by Kotlin for a file called <code>something.kt<\/code>\nwill be <code>SomethingKt.class<\/code>, which is why our main class is called <code>MainKt<\/code>.\nWith that in mind, the <code>manifest<\/code> section is self-explanatory: we specify\nthe main class. The <code>from<\/code> section collects all compile dependencies\n(that we specified in the <code>dependencies<\/code> section) and package them with the\n<code>.jar<\/code> file. The little piece of logic in the lambda is to properly add\ndirectories and <code>.jar<\/code> files, respectively (directories are just added,\n<code>.jar<\/code> files are unzipped and added).<\/p>\n<blockquote>\n<p><strong>Important:<\/strong> The main class file must be specified with its fully qualified\nname. For example, if I were to define <code>main.kt<\/code> in the package <code>se.slarse<\/code>,\nthen I would need to put <code>se.slarse.MainKt<\/code> instead of just <code>MainKt<\/code> in the\nmanifest.<\/p>\n<\/blockquote>\n<p>Anyway, that's really all we need to do.\nIt should now be possible to run the <code>jar<\/code> Gradle task to produce a <code>.jar<\/code> file\nin <code>build\/libs\/&lt;ArtifactId&gt;-&lt;Version&gt;<\/code> (so in my case it is at\n<code>build\/libs\/app-0.1.jar<\/code>). And that's it, hope it helped someone!<\/p>\n<h1 id=\"full-source-code-and-buildgradle\">Full source code and <code>build.gradle<\/code><\/h1>\n<p>Here are both of the files we wrote in this tutorial, in their entirety.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ main.kt<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">com.github.ajalt.clikt.core.CliktCommand<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">com.github.ajalt.clikt.parameters.options.default<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">com.github.ajalt.clikt.parameters.options.option<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">com.github.ajalt.clikt.parameters.options.prompt<\/span>\n<span class=\"k\">import<\/span><span class=\"w\"> <\/span><span class=\"nn\">com.github.ajalt.clikt.parameters.types.int<\/span>\n\n<span class=\"kd\">class<\/span><span class=\"w\"> <\/span><span class=\"nc\">Hello<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">CliktCommand<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">count<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">Int<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">option<\/span><span class=\"p\">(<\/span><span class=\"n\">help<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;Number of greetings&quot;<\/span><span class=\"p\">).<\/span><span class=\"na\">int<\/span><span class=\"p\">().<\/span><span class=\"na\">default<\/span><span class=\"p\">(<\/span><span class=\"m\">1<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">val<\/span><span class=\"w\"> <\/span><span class=\"nv\">name<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kt\">String<\/span><span class=\"w\"> <\/span><span class=\"k\">by<\/span><span class=\"w\"> <\/span><span class=\"n\">option<\/span><span class=\"p\">(<\/span><span class=\"n\">help<\/span><span class=\"o\">=<\/span><span class=\"s\">&quot;The person to greet&quot;<\/span><span class=\"p\">).<\/span><span class=\"na\">prompt<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Your name&quot;<\/span><span class=\"p\">)<\/span>\n\n<span class=\"w\">    <\/span><span class=\"kd\">override<\/span><span class=\"w\"> <\/span><span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">run<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">i<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"m\">1.<\/span><span class=\"p\">.<\/span><span class=\"na\">count<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">echo<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;Hello <\/span><span class=\"si\">$<\/span><span class=\"n\">name<\/span><span class=\"s\">!&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"kd\">fun<\/span><span class=\"w\"> <\/span><span class=\"nf\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">args<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"n\">Array<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">String<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Hello<\/span><span class=\"p\">().<\/span><span class=\"na\">main<\/span><span class=\"p\">(<\/span><span class=\"n\">args<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div>\n\n<hr>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ build.gradle<\/span>\n<span class=\"err\">plugi<\/span><span class=\"kc\">ns<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">id<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;org.je<\/span><span class=\"kc\">t<\/span><span class=\"err\">brai<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"err\">.jvm&#39;<\/span><span class=\"w\"> <\/span><span class=\"err\">versio<\/span><span class=\"kc\">n<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;<\/span><span class=\"mf\">1.2.51<\/span><span class=\"err\">&#39;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"err\">group<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;se.slarse&#39;<\/span>\n<span class=\"err\">versio<\/span><span class=\"kc\">n<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;<\/span><span class=\"mf\">0.1<\/span><span class=\"err\">&#39;<\/span>\n\n<span class=\"err\">reposi<\/span><span class=\"kc\">t<\/span><span class=\"err\">ories<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">mave<\/span><span class=\"kc\">n<\/span><span class=\"err\">Ce<\/span><span class=\"kc\">ntral<\/span><span class=\"err\">()<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"err\">depe<\/span><span class=\"kc\">n<\/span><span class=\"err\">de<\/span><span class=\"kc\">n<\/span><span class=\"err\">cies<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">compile<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;org.jetbrains.kotlin:kotlin-stdlib-jdk8&quot;<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">compile<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;com.github.ajalt:clikt:1.5.0&quot;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"err\">compileKo<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"err\">Op<\/span><span class=\"kc\">t<\/span><span class=\"err\">io<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.jvmTarge<\/span><span class=\"kc\">t<\/span><span class=\"w\"> <\/span><span class=\"err\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;1.8&quot;<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"err\">compileTes<\/span><span class=\"kc\">t<\/span><span class=\"err\">Ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">ko<\/span><span class=\"kc\">tl<\/span><span class=\"err\">i<\/span><span class=\"kc\">n<\/span><span class=\"err\">Op<\/span><span class=\"kc\">t<\/span><span class=\"err\">io<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.jvmTarge<\/span><span class=\"kc\">t<\/span><span class=\"w\"> <\/span><span class=\"err\">=<\/span><span class=\"w\"> <\/span><span class=\"s2\">&quot;1.8&quot;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"err\">jar<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"err\">ma<\/span><span class=\"kc\">n<\/span><span class=\"err\">i<\/span><span class=\"kc\">fest<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"err\">a<\/span><span class=\"kc\">ttr<\/span><span class=\"err\">ibu<\/span><span class=\"kc\">tes<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;Mai<\/span><span class=\"kc\">n<\/span><span class=\"mi\">-<\/span><span class=\"err\">Class&#39;<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"err\">&#39;Mai<\/span><span class=\"kc\">n<\/span><span class=\"err\">K<\/span><span class=\"kc\">t<\/span><span class=\"err\">&#39;<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"kc\">fr<\/span><span class=\"err\">om<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"err\">co<\/span><span class=\"kc\">nf<\/span><span class=\"err\">igura<\/span><span class=\"kc\">t<\/span><span class=\"err\">io<\/span><span class=\"kc\">ns<\/span><span class=\"err\">.compile.collec<\/span><span class=\"kc\">t<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"err\">i<\/span><span class=\"kc\">t<\/span><span class=\"err\">.isDirec<\/span><span class=\"kc\">t<\/span><span class=\"err\">ory()<\/span><span class=\"w\"> <\/span><span class=\"err\">?<\/span><span class=\"w\"> <\/span><span class=\"err\">i<\/span><span class=\"kc\">t<\/span><span class=\"w\"> <\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"err\">zipTree(i<\/span><span class=\"kc\">t<\/span><span class=\"err\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"kotlin"}},{"@attributes":{"term":"gradle"}},{"@attributes":{"term":"intellij"}}]},{"title":"Awesome Python Podcasts","link":{"@attributes":{"href":"https:\/\/slar.se\/awesome-python-podcasts.html","rel":"alternate"}},"published":"2018-07-03T07:34:33+00:00","updated":"2018-10-29T21:03:07+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2018-07-03:\/awesome-python-podcasts.html","summary":"<p>Whenever I find myself occupied with some monotonous task, I\nvery much enjoy listening to podcasts. As programming is my\nnumber one passion, and Python is my favorite language, I tend\nto listen to podcasts that relate to them. In this post, I'll\ngive a brief overview of my three \u2026<\/p>","content":"<p>Whenever I find myself occupied with some monotonous task, I\nvery much enjoy listening to podcasts. As programming is my\nnumber one passion, and Python is my favorite language, I tend\nto listen to podcasts that relate to them. In this post, I'll\ngive a brief overview of my three favorite podcasts, and just\nwhy I enjoy them as much as I do!<\/p>\n<h3 id=\"python-bytes\">Python Bytes<\/h3>\n<p><a href=\"https:\/\/pythonbytes.fm\/\"><em>Python Bytes<\/em><\/a> was the first podcast I ever\nlistened to. It's a really neat show that comes out on a weekly basis,\nand focuses on delivering news and headlines in the Python community.\nThe best part about the show is that they highlight awesome Python\npackages and tools that I would not have heard about otherwise. The\nepisodes are fairly short, usually around the 20 minute mark, so they\nfit in even on a short commute. The episodes have, as far as I can recall,\nbeen published every week without fail for almost two years now, which\nis really nice. The hosts (Brian Okken and Micheal Kennedy) have great\nchemistry, and the show is recorded with decent enough equipment and\nwell edited. All in all, I really enjoy the show and highly recommend it!<\/p>\n<h3 id=\"talk-python-to-me\">Talk Python To Me<\/h3>\n<p><a href=\"https:\/\/talkpython.fm\/\"><em>Talk Python To Me<\/em><\/a> is Micheal Kennedy's (from\nPython Bytes) own show. In each episode, Micheal invites someone (sometimes\nmultiple people at once) from\nthe Python community to come talk about what they do. The episodes\nare fairly lengthy and often reach for the 1 hour mark, but they are\nalso mostly entertaining throughout. As with Python Bytes, the episodes\nare well edited, meaning that awkward pauses and the like shine with their\nabsence. Talk Python To Me is probably my favorite podcast right now and\nI can't recommend it enough.<\/p>\n<h3 id=\"podcast__init__\">Podcast.__init__<\/h3>\n<p><a href=\"https:\/\/www.podcastinit.com\/\">_Podcast.__init___<\/a> is very similar to\nTalk Python To Me, seeing as both shows revolve around inviting prominent\npersonalities to talk about their work. I haven't listened to all that many\nof the episodes, but I really enjoyed the first 7-8 episodes. Initially,\nthe show had two hosts, but in the later episodes one of the original hosts\nis conspicuously abscent, which to me was to the detriment of the show. It's\nstill a good show, mind you, but I enjoyed the early episodes more than the\nfew late ones that I've listened to. The length of the episodes seem hover\naround the 1 hour mark, +\/- some 20 minutes. I will probably revisit this\npost once I've listened to a few more of the episodes, but as it stands I\nrecommend listening to the show from the beginning.<\/p>\n<h3 id=\"did-i-miss-something\">Did I miss something?<\/h3>\n<p>Those were my 3 top picks for Python podcasts. If you feel like I've missed\nsome great podcast(s), feel free to drop a comment!<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"python"}},{"@attributes":{"term":"podcast"}}]},{"title":"What the self? Python's self demystified!","link":{"@attributes":{"href":"https:\/\/slar.se\/what-the-self-pythons-self-demystified.html","rel":"alternate"}},"published":"2018-05-01T16:04:01+00:00","updated":"2018-05-01T16:04:01+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2018-05-01:\/what-the-self-pythons-self-demystified.html","summary":"<p>Any Python programmer will sooner or later want to (or have to) write a class.\nWith classes come <code>self<\/code>, the <em>seemingly<\/em> (do note the emphasis there)\nmagical keyword that you just have to write out as the first parameter to every\nmethod. To really understand classes, you need to understand \u2026<\/p>","content":"<p>Any Python programmer will sooner or later want to (or have to) write a class.\nWith classes come <code>self<\/code>, the <em>seemingly<\/em> (do note the emphasis there)\nmagical keyword that you just have to write out as the first parameter to every\nmethod. To really understand classes, you need to understand what <code>self<\/code>\nactually is: neither magical, nor a keyword. Let's demystify this integral part\nof Python classes!<\/p>\n<h2 id=\"self-is-not-a-keyword\"><code>self<\/code> is not a keyword<\/h2>\n<p>This is pretty easy to prove. Just open a Python interpreter and import the\n<code>keyword<\/code> module.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">keyword<\/span><span class=\"o\">.<\/span><span class=\"n\">iskeyword<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;for&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"kc\">True<\/span>                            <span class=\"c1\"># aha, makes sense<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">keyword<\/span><span class=\"o\">.<\/span><span class=\"n\">iskeyword<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;else&quot;<\/span><span class=\"p\">)<\/span> \n<span class=\"kc\">True<\/span>                            <span class=\"c1\"># seems to be working<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">keyword<\/span><span class=\"o\">.<\/span><span class=\"n\">iskeyword<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;self&quot;<\/span><span class=\"p\">)<\/span>\n<span class=\"kc\">False<\/span>                           <span class=\"c1\"># proof!<\/span>\n<\/code><\/pre><\/div>\n\n<p>Alternatively, one can always consult the\n<a href=\"https:\/\/docs.python.org\/3\/reference\/lexical_analysis.html#keywords\">list of keywords in the Python docs<\/a>.\nSince <code>self<\/code> is not a keyword, it has no special significance in the language\nitself. We can also verify that it's not some funky builtin by simply typing\nit out in the interpreter.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"bp\">self<\/span>\n<span class=\"n\">Traceback<\/span> <span class=\"p\">(<\/span><span class=\"n\">most<\/span> <span class=\"n\">recent<\/span> <span class=\"n\">call<\/span> <span class=\"n\">last<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">module<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"ne\">NameError<\/span><span class=\"p\">:<\/span> <span class=\"n\">name<\/span> <span class=\"s1\">&#39;self&#39;<\/span> <span class=\"ow\">is<\/span> <span class=\"ow\">not<\/span> <span class=\"n\">defined<\/span>\n<span class=\"n\">name<\/span> <span class=\"s1\">&#39;self&#39;<\/span> <span class=\"ow\">is<\/span> <span class=\"ow\">not<\/span> <span class=\"n\">defined<\/span>\n<\/code><\/pre><\/div>\n\n<p>This can <a href=\"https:\/\/docs.python.org\/3.6\/library\/constants.html\">verified here<\/a>).\nSo, what in the world is <code>self<\/code>? Actually, it's just a variable name.<\/p>\n<blockquote>\n<p><strong>Trivia:<\/strong> If you try <code>keyword.iskeyword(\"True\")<\/code> and\n<code>keyword.iskeyword(\"False\")<\/code> in both Python2 and Python3, you will find that\nboth are keywords in Python3, but not in Python2 (in 2, <code>True<\/code> and <code>False<\/code>\nare just builtin constants). In fact, <code>True<\/code> and <code>False<\/code> are not even\nwrite-protected in Python2, leading to shenanigans such as <code>True, False =\nFalse, True<\/code> being possible. In Python3, the keyword status of <code>True<\/code> and\n<code>False<\/code> make such an assignment a syntax error.<\/p>\n<\/blockquote>\n<h2 id=\"self-is-just-a-variable-name\"><code>self<\/code> is just a variable name<\/h2>\n<p>Consider the following code snippet of a (pretty useless) class that just\nstores two values (that are just assumed to be addable with each other),\nand defines a method that returns the sum of the values.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">class<\/span> <span class=\"nc\">Tuple<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;A class for storing two values.&quot;&quot;&quot;<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"fm\">__init__<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span> <span class=\"n\">first<\/span><span class=\"p\">,<\/span> <span class=\"n\">second<\/span><span class=\"p\">):<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">first<\/span> <span class=\"o\">=<\/span> <span class=\"n\">first<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">second<\/span> <span class=\"o\">=<\/span> <span class=\"n\">second<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">sum<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Return the sum of &#39;first` and &#39;second&#39;.&quot;&quot;&quot;<\/span>\n        <span class=\"k\">return<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">first<\/span> <span class=\"o\">+<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">second<\/span>\n<\/code><\/pre><\/div>\n\n<p>Okay, so the class is terrible, but that really doesn't matter for the\npurposes of this article. Now we see <code>self<\/code> in action for the first time.\nFrom the code, it's purpose is quite clear: it refers to the object instance\non which the method is called. Usage looks something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Tuple<\/span><span class=\"p\">(<\/span><span class=\"mi\">4<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">first<\/span>\n<span class=\"mi\">4<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">second<\/span>\n<span class=\"mi\">3<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">sum<\/span><span class=\"p\">()<\/span>  <span class=\"c1\"># `self` in `sum` refers to `t`<\/span>\n<span class=\"mi\">7<\/span>\n<\/code><\/pre><\/div>\n\n<p>So, <code>self<\/code> is just a reference to the object on which the method is called (in\nthis case, <code>t<\/code>). This will probably become more apparent when reading\n<a href=\"#two-ways-to-call-methods\">Two ways to call methods<\/a> further down, but just\nsuspend your disbelief for moment and assume it is so.\nBut, considering the <code>self<\/code> is just a variable to which <code>t<\/code> is assigned, what\nhappens if we replace <code>self<\/code> with, say, <code>donkey<\/code>?<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">class<\/span> <span class=\"nc\">Tuple<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;A class for storing two values.&quot;&quot;&quot;<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"fm\">__init__<\/span><span class=\"p\">(<\/span><span class=\"n\">donkey<\/span><span class=\"p\">,<\/span> <span class=\"n\">first<\/span><span class=\"p\">,<\/span> <span class=\"n\">second<\/span><span class=\"p\">):<\/span>\n        <span class=\"n\">donkey<\/span><span class=\"o\">.<\/span><span class=\"n\">first<\/span> <span class=\"o\">=<\/span> <span class=\"n\">first<\/span>\n        <span class=\"n\">donkey<\/span><span class=\"o\">.<\/span><span class=\"n\">second<\/span> <span class=\"o\">=<\/span> <span class=\"n\">second<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">sum<\/span><span class=\"p\">(<\/span><span class=\"n\">donkey<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Return the sum of &#39;first&#39; and &#39;second&#39;.&quot;&quot;&quot;<\/span>\n        <span class=\"k\">return<\/span> <span class=\"n\">donkey<\/span><span class=\"o\">.<\/span><span class=\"n\">first<\/span> <span class=\"o\">+<\/span> <span class=\"n\">donkey<\/span><span class=\"o\">.<\/span><span class=\"n\">second<\/span>\n<\/code><\/pre><\/div>\n\n<p>In fact, this will work exactly the same as when the first parameter was called\n<code>self<\/code>, and usage is unchanged:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Tuple<\/span><span class=\"p\">(<\/span><span class=\"mi\">4<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">first<\/span>\n<span class=\"mi\">4<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">second<\/span>\n<span class=\"mi\">3<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">sum<\/span><span class=\"p\">()<\/span>\n<span class=\"mi\">7<\/span>\n<\/code><\/pre><\/div>\n\n<p>To summarize, the first parameter in a method is simply a variable that refers to\nthe instance on which the method was called. Naming it <code>self<\/code> is\n<a href=\"https:\/\/docs.python.org\/3.6\/howto\/descriptor.html#functions-and-methods\">just a convention<\/a>\n, and we could name it anything. Note also that there is no technical\nneed for consistency across methods, we could name the first parameter to the\n<code>__init__<\/code> method <code>donkey<\/code>, and the first (only) parameter to the <code>sum<\/code> method\n<code>shrek<\/code>, and it'd still work.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">class<\/span> <span class=\"nc\">Tuple<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;A class for storing two values.&quot;&quot;&quot;<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"fm\">__init__<\/span><span class=\"p\">(<\/span><span class=\"n\">donkey<\/span><span class=\"p\">,<\/span> <span class=\"n\">first<\/span><span class=\"p\">,<\/span> <span class=\"n\">second<\/span><span class=\"p\">):<\/span>\n        <span class=\"n\">donkey<\/span><span class=\"o\">.<\/span><span class=\"n\">first<\/span> <span class=\"o\">=<\/span> <span class=\"n\">first<\/span>\n        <span class=\"n\">donkey<\/span><span class=\"o\">.<\/span><span class=\"n\">second<\/span> <span class=\"o\">=<\/span> <span class=\"n\">second<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">sum<\/span><span class=\"p\">(<\/span><span class=\"n\">shrek<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Return the sum of &#39;first&#39; and &#39;second&#39;.&quot;&quot;&quot;<\/span>\n        <span class=\"k\">return<\/span> <span class=\"n\">shrek<\/span><span class=\"o\">.<\/span><span class=\"n\">first<\/span> <span class=\"o\">+<\/span> <span class=\"n\">shrek<\/span><span class=\"o\">.<\/span><span class=\"n\">second<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p><strong>IMPORTANT:<\/strong> <em>Always<\/em> name the first parameter to a method <code>self<\/code>. The\nconvention exists for a reason: it makes your code more readable.<\/p>\n<\/blockquote>\n<p>We could leave it at this, and hopefully walk away with a slightly better\nunderstanding of why we put <code>self<\/code> everywhere in methods. But I think diving\njust a little bit deeper into where the first argument to methods actually\ncomes from will prove fruitful.<\/p>\n<h2 id=\"two-ways-of-calling-methods\">Two ways of calling methods<\/h2>\n<p>Methods are defined on the class itself, and not on the instance. There is\nactually a way to call a method directly on the class, that is equivalent to\nthe way we usually call methods on the instance.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Tuple<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span> <span class=\"mi\">6<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">sum<\/span><span class=\"p\">()<\/span>         <span class=\"c1\"># regular method call<\/span>\n<span class=\"mi\">11<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">Tuple<\/span><span class=\"o\">.<\/span><span class=\"n\">sum<\/span><span class=\"p\">(<\/span><span class=\"n\">t<\/span><span class=\"p\">)<\/span>    <span class=\"c1\"># calling the method on the class itself, and passing<\/span>\n<span class=\"mi\">11<\/span>                  <span class=\"c1\"># `t` as the `self` argument<\/span>\n<\/code><\/pre><\/div>\n\n<p>The second way of calling <code>sum<\/code> is explicit about where <code>self<\/code> comes from: it's\npassed in as the first argument. If we think of the first, \"regular\" way of\ncalling methods as shorthand for the second, it's suddenly entirely clear what\nthe first argument actually is (the instance itself). Calling a method that has\nmore parameters than just <code>self<\/code> works as expected: simply pass in the\nadditional arguments. To be super clear, with the following method added to\n<code>Tuple<\/code><\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">sum_mod<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span> <span class=\"n\">mod<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;Return the sum of the members modulo &#39;mod&#39;.&quot;&quot;&quot;<\/span>\n    <span class=\"k\">return<\/span> <span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">first<\/span> <span class=\"o\">+<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">second<\/span><span class=\"p\">)<\/span> <span class=\"o\">%<\/span> <span class=\"n\">mod<\/span>\n<\/code><\/pre><\/div>\n\n<p>the following two method calls are equivalent<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Tuple<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">,<\/span> <span class=\"mi\">7<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">sum_mod<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">2<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">Tuple<\/span><span class=\"o\">.<\/span><span class=\"n\">sum_mod<\/span><span class=\"p\">(<\/span><span class=\"n\">t<\/span><span class=\"p\">,<\/span> <span class=\"mi\">5<\/span><span class=\"p\">)<\/span>\n<span class=\"mi\">2<\/span>\n<\/code><\/pre><\/div>\n\n<p>And that pretty much concludes what I wanted to cover in this article!<\/p>\n<h2 id=\"summary\">Summary<\/h2>\n<p>In the beginning, someone (probably Guido) said <em>let there be <code>self<\/code><\/em>. And there was.\nThe first parameter to a method is since then, <em>by convention<\/em>, called <code>self<\/code>, and\nrefers to the object on which the method was called.\nCalling a method on some object <code>t<\/code> (e.g. <code>t.sum()<\/code>) can be viewed as shortand for\ncalling the method on its class, and passing in a reference to <code>t<\/code> as the first\nargument (e.g. <code>Tuple.sum(t)<\/code>). If you are interested in learning about the dark magic\ngoing on behind the scenes, you can read up on the official documentation for the\n<a href=\"https:\/\/docs.python.org\/3.6\/howto\/descriptor.html\">descriptor protocol<\/a>, and\nmore specifically the\n<a href=\"https:\/\/docs.python.org\/3.6\/howto\/descriptor.html#functions-and-methods\">Functions and Methods<\/a>\npart of it. It is however somewhat advanced, and I don't find it essential to\nunderstanding the semantics of method calls in Python. I hope you have found\nthis article enlightening, stay tuned for more Python in the coming week!<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"python"}}]},{"title":"Properties as Pythonic setters","link":{"@attributes":{"href":"https:\/\/slar.se\/properties-as-pythonic-setters.html","rel":"alternate"}},"published":"2018-04-05T18:26:10+00:00","updated":"2018-04-05T18:26:10+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2018-04-05:\/properties-as-pythonic-setters.html","summary":"<p>This is the second part in a two part series on Python properties. In\n<a href=\"https:\/\/slar.se\/properties-as-pythonic-getters.html\">Part 1<\/a> (which readers will be assumed to\nhave at least skimmed through), we saw how a property can be used to create a\nread-only attribute that can be accessed like any data attribute (i.e \u2026<\/p>","content":"<p>This is the second part in a two part series on Python properties. In\n<a href=\"https:\/\/slar.se\/properties-as-pythonic-getters.html\">Part 1<\/a> (which readers will be assumed to\nhave at least skimmed through), we saw how a property can be used to create a\nread-only attribute that can be accessed like any data attribute (i.e with\n<code>obj.attr<\/code>), but raises an <code>AttributeError<\/code> when written to. Now, we will look\nat how to expand the property to also allow us to write to <code>count<\/code> like it's a\nnormal data attribute (i.e. with <code>t.count = 42<\/code>), while also doing input\nvalidation.<\/p>\n<h3 id=\"a-property-as-a-pythonic-setter\">A property as a Pythonic setter<\/h3>\n<p>Using the <code>Ticker<\/code> class version from the final listing in \n<a href=\"https:\/\/slar.se\/properties-as-pythonic-getters.html\">Part 1<\/a>, we are unable to set the <code>count<\/code>\nattribute to <em>any<\/em> value.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>&gt;&gt;&gt;<span class=\"w\"> <\/span><span class=\"nv\">t<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span>Ticker<span class=\"o\">(<\/span><span class=\"m\">24<\/span><span class=\"o\">)<\/span><span class=\"w\">  <\/span><span class=\"c1\"># valid range for count is thus [0, 23]<\/span>\n&gt;&gt;&gt;<span class=\"w\"> <\/span>t.count<span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"m\">11<\/span><span class=\"w\">    <\/span><span class=\"c1\"># this is well within that range<\/span>\nTraceback<span class=\"w\"> <\/span><span class=\"o\">(<\/span>most<span class=\"w\"> <\/span>recent<span class=\"w\"> <\/span>call<span class=\"w\"> <\/span>last<span class=\"o\">)<\/span>:\n<span class=\"w\">  <\/span>File<span class=\"w\"> <\/span><span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span>,<span class=\"w\"> <\/span>line<span class=\"w\"> <\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>&lt;module&gt;\nAttributeError:<span class=\"w\"> <\/span>can<span class=\"s1\">&#39;t set attribute<\/span>\n<span class=\"s1\">can&#39;<\/span>t<span class=\"w\"> <\/span><span class=\"nb\">set<\/span><span class=\"w\"> <\/span>attribute\n\n&gt;&gt;&gt;<span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span>_<span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span>range<span class=\"o\">(<\/span><span class=\"m\">11<\/span><span class=\"o\">)<\/span>:<span class=\"w\"> <\/span><span class=\"c1\"># doing it the hard way ...<\/span>\n...<span class=\"w\">     <\/span>t.tick<span class=\"o\">()<\/span>\n&gt;&gt;&gt;<span class=\"w\"> <\/span>t.count\n<span class=\"m\">11<\/span>\n<\/code><\/pre><\/div>\n\n<p>This presents something of a usability issue, as the only way to set the\n<code>Ticker<\/code>'s internal count to a specific value (using the public API) is by\ncalling <code>tick()<\/code> an appropriate amount of times. If we were to use the Ticker\nas, say, a clock, we'd definitely want to be able to set <code>count<\/code> to a value\nwithin the range <code>[0, _end)<\/code> by simple assignment. Fortunately, there is a\nsimple way to expand a property with a setter method using the <code>@&lt;name&gt;.setter<\/code>\ndecorator, where <code>&lt;name&gt;<\/code> is replaced with the name of the property. For the\n<code>count<\/code> property of the <code>Ticker<\/code> class, it looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nd\">@count<\/span><span class=\"o\">.<\/span><span class=\"n\">setter<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">count<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span> <span class=\"n\">val<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;Set the internal count to val.&quot;&quot;&quot;<\/span>\n    <span class=\"k\">if<\/span> <span class=\"n\">val<\/span> <span class=\"o\">&lt;<\/span> <span class=\"mi\">0<\/span> <span class=\"ow\">or<\/span> <span class=\"n\">val<\/span> <span class=\"o\">&gt;=<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_end<\/span><span class=\"p\">:<\/span>\n        <span class=\"k\">raise<\/span> <span class=\"ne\">ValueError<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s2\">&quot;<\/span><span class=\"si\">{<\/span><span class=\"n\">val<\/span><span class=\"si\">}<\/span><span class=\"s2\"> is out of range for attribute count.&quot;<\/span><span class=\"p\">)<\/span>\n    <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_count<\/span> <span class=\"o\">=<\/span> <span class=\"n\">val<\/span>\n<\/code><\/pre><\/div>\n\n<blockquote>\n<p><strong>Note:<\/strong> A string literal preceeded with an <code>f<\/code> is an <em>f-string<\/em>. This is a\nPython 3.6 feature. For backwards compatability, you could change to using\n<code>string.format<\/code> like this: \n  <code>\"{} is out of range for attribute count.\".format(val)<\/code><\/p>\n<\/blockquote>\n<p>The code should be fairly self-explanatory. The setter takes a value <code>val<\/code> as\nan argument. If <code>val<\/code> is outside of the allowed range <code>[0, _end)<\/code>, a\n<code>ValueError<\/code> is raised.  Otherwise, <code>_count<\/code> is set to <code>val<\/code>. The error message\ncould be more informative, but I did not want to obscure the important parts\nwith a lot of text. We have thus defeated the aforementioned usability issue,\nand usage now looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Ticker<\/span><span class=\"p\">(<\/span><span class=\"mi\">24<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span>\n<span class=\"mi\">0<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">tick<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span>\n<span class=\"mi\">1<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">11<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span>\n<span class=\"mi\">11<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">tick<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span>\n<span class=\"mi\">12<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">24<\/span>\n<span class=\"n\">Traceback<\/span> <span class=\"p\">(<\/span><span class=\"n\">most<\/span> <span class=\"n\">recent<\/span> <span class=\"n\">call<\/span> <span class=\"n\">last<\/span><span class=\"p\">):<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">module<\/span><span class=\"o\">&gt;<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">23<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">count<\/span>\n<span class=\"ne\">ValueError<\/span><span class=\"p\">:<\/span> <span class=\"mi\">24<\/span> <span class=\"ow\">is<\/span> <span class=\"n\">out<\/span> <span class=\"n\">of<\/span> <span class=\"nb\">range<\/span> <span class=\"k\">for<\/span> <span class=\"n\">attribute<\/span> <span class=\"n\">count<\/span><span class=\"o\">.<\/span>\n<span class=\"mi\">24<\/span> <span class=\"ow\">is<\/span> <span class=\"n\">out<\/span> <span class=\"n\">of<\/span> <span class=\"nb\">range<\/span> <span class=\"k\">for<\/span> <span class=\"n\">attribute<\/span> <span class=\"n\">count<\/span><span class=\"o\">.<\/span>\n<\/code><\/pre><\/div>\n\n<p>Seems to work just the way we want it to!<\/p>\n<h3 id=\"ticker-full-listing-with-gettersetter-property\">Ticker full listing (with getter\/setter property)<\/h3>\n<p>Here is the full listing of the <code>Ticker<\/code> class.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">class<\/span> <span class=\"nc\">Ticker<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;A Ticker ticks from 0 to an upper limit, and then starts over.&quot;&quot;&quot;<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"fm\">__init__<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span> <span class=\"n\">end<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Create a Ticker that starts over at end&quot;&quot;&quot;<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">end<\/span> <span class=\"o\">&lt;=<\/span> <span class=\"mi\">0<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">raise<\/span> <span class=\"ne\">ValueError<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;end must be greater than 0!&quot;<\/span><span class=\"p\">)<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_end<\/span> <span class=\"o\">=<\/span> <span class=\"n\">end<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_count<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">0<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">tick<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Increment the internal count by 1.&quot;&quot;&quot;<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_count<\/span> <span class=\"o\">=<\/span> <span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_count<\/span> <span class=\"o\">+<\/span> <span class=\"mi\">1<\/span><span class=\"p\">)<\/span> <span class=\"o\">%<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_end<\/span>\n\n    <span class=\"nd\">@property<\/span>\n    <span class=\"k\">def<\/span> <span class=\"nf\">count<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Return the current count.&quot;&quot;&quot;<\/span>\n        <span class=\"k\">return<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_count<\/span>\n\n    <span class=\"nd\">@count<\/span><span class=\"o\">.<\/span><span class=\"n\">setter<\/span>\n    <span class=\"k\">def<\/span> <span class=\"nf\">count<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span> <span class=\"n\">val<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Set the internal count to val.&quot;&quot;&quot;<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">val<\/span> <span class=\"o\">&lt;<\/span> <span class=\"mi\">0<\/span> <span class=\"ow\">or<\/span> <span class=\"n\">val<\/span> <span class=\"o\">&gt;=<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_end<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">raise<\/span> <span class=\"ne\">ValueError<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s2\">&quot;<\/span><span class=\"si\">{<\/span><span class=\"n\">val<\/span><span class=\"si\">}<\/span><span class=\"s2\"> is out of range for attribute count.&quot;<\/span><span class=\"p\">)<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_count<\/span> <span class=\"o\">=<\/span> <span class=\"n\">val<\/span>\n<\/code><\/pre><\/div>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"python"}}]},{"title":"Properties as Pythonic getters","link":{"@attributes":{"href":"https:\/\/slar.se\/properties-as-pythonic-getters.html","rel":"alternate"}},"published":"2018-04-05T18:25:55+00:00","updated":"2018-04-05T18:25:55+00:00","author":{"name":"Simon Lars\u00e9n"},"id":"tag:slar.se,2018-04-05:\/properties-as-pythonic-getters.html","summary":"<p>If you come from either Java or C++, you've probably written your fair\nshare of getter and setter (also called accessor and mutator) methods.\nIt is common for programmers that transition from such a language to Python\nto carry over this practice. In many cases in Python, we simply forego \u2026<\/p>","content":"<p>If you come from either Java or C++, you've probably written your fair\nshare of getter and setter (also called accessor and mutator) methods.\nIt is common for programmers that transition from such a language to Python\nto carry over this practice. In many cases in Python, we simply forego the\nabstraction and access the attributes directly. Sometimes, however, getters\nand setters are useful for providing write-protection and input validation.\nIn this two-part series, we are going to explore how to make Pythonic setters\nand getters using one of my favorite Python features: <strong>properties<\/strong>. <\/p>\n<h3 id=\"part-1-this-part-properties-as-pythonic-getters\">Part 1 (this part): Properties as Pythonic getters<\/h3>\n<p>In this first part, we take a look at how to use a property\nto implement a read-only data attribute that can be accessed just like any other\ndata attribute (e.g. like <code>obj.attr<\/code>). Writing to it will, however, result in an\n<code>AttributeError<\/code>. This is useful for preventing users\nfrom accidentally changing the internal state of an object in an unintended\nway, while still providing a uniform API. For example, we might want a \nway to access the root element of a binary tree, but without risking to alter \nits container.<\/p>\n<h3 id=\"part-2-properties-as-pythonic-setters\"><a href=\"https:\/\/slar.se\/properties-as-pythonic-setters.html\">Part 2: Properties as Pythonic setters<\/a><\/h3>\n<p>In the second part, we'll have a look at how we can use properties to also\nimplement a setter method, with input validation, that can be utulized just \nlike any plain ol' data attribute (e.g. like <code>obj.attr = 42<\/code>). This is useful\nwhen the attribute has some legal set of values.<\/p>\n<h2 id=\"the-ticker-class\">The Ticker class<\/h2>\n<p>For the purpose of learning properties, we will develop a fairly useless class\ncalled <code>Ticker<\/code>. All it does is tick from <code>0<\/code> to some boundary, and then restart\nfrom <code>0<\/code>. Two <code>Ticker<\/code> instances could, for example, represent a rudimentary\nclock with hour and minute counts. The first version of <code>Ticker<\/code> is outlined\nbelow.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">class<\/span> <span class=\"nc\">Ticker<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;A Ticker ticks from 0 to an upper limit, and then starts over.&quot;&quot;&quot;<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"fm\">__init__<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span> <span class=\"n\">end<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span><span class=\"p\">):<\/span> <span class=\"c1\"># &#39;: int&#39; is an optional type hint<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Create a Ticker that starts over at end&quot;&quot;&quot;<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">end<\/span> <span class=\"o\">&lt;=<\/span> <span class=\"mi\">0<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">raise<\/span> <span class=\"ne\">ValueError<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;end must be greater than 0!&quot;<\/span><span class=\"p\">)<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_end<\/span> <span class=\"o\">=<\/span> <span class=\"n\">end<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">0<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">tick<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Increment the internal count by 1.&quot;&quot;&quot;<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span> <span class=\"o\">=<\/span> <span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span> <span class=\"o\">+<\/span> <span class=\"mi\">1<\/span><span class=\"p\">)<\/span> <span class=\"o\">%<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_end<\/span>    \n<\/code><\/pre><\/div>\n\n<p>We can use this class something like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Ticker<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span>\n<span class=\"mi\">0<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">tick<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">tick<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span>\n<span class=\"mi\">2<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"k\">for<\/span> <span class=\"n\">_<\/span> <span class=\"ow\">in<\/span> <span class=\"nb\">range<\/span><span class=\"p\">(<\/span><span class=\"mi\">3<\/span><span class=\"p\">):<\/span>\n<span class=\"o\">...<\/span>     <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">tick<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span>\n<span class=\"mi\">0<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">42<\/span>    <span class=\"c1\"># uh oh...<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span>\n<span class=\"mi\">42<\/span>                  <span class=\"c1\"># this is an illegal state<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">tick<\/span><span class=\"p\">()<\/span>        <span class=\"c1\"># back to a legal state in the next tick<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span>\n<span class=\"mi\">3<\/span>\n<\/code><\/pre><\/div>\n\n<p>As long as the <code>count<\/code> variable is only read from, there are no issues with this\ndesign. Unfortunately, directly assigning to <code>count<\/code> may put the <code>Ticker<\/code> in an\nillegal state, i.e. such that <code>count<\/code> is outside of its expected range of\n<code>[0, _end)<\/code>. This isn't so much an issue for the <code>Ticker<\/code> itself, as it is\nreturned to a legal state on the next tick. Other functionality\ndepending on the <code>Ticker<\/code> to keep within the <code>[0, _end)<\/code> range could however be\nin for a nasty surprise, meaning that there is a serious usability issue here.<\/p>\n<p>Thus to the crux:<\/p>\n<blockquote>\n<p>How do we protect the <code>count<\/code> variable from being put in an illegal state,\nwhile still allowing access to it?<\/p>\n<\/blockquote>\n<h2 id=\"solving-the-problem\">Solving the problem<\/h2>\n<p>First of all, we should make the <code>count<\/code> variable private (which in Python\nequates to prepending an underscore). The issue that remains to be resolved is\nhow to expose <code>_count<\/code> in the public API of the class.<\/p>\n<h3 id=\"solution-1-a-java-style-getter\">Solution 1: A Java-style getter<\/h3>\n<p>A Java or C++ programmer might instinctevly think of a traditional getter method.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">def<\/span> <span class=\"nf\">get_count<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;Return the current count.&quot;&quot;&quot;<\/span>\n    <span class=\"k\">return<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_count<\/span>\n<\/code><\/pre><\/div>\n\n<p>This solution has two issues: it breaks the api, and it makes us think about\n<code>count<\/code> as something more complicated than the mere data attribute that it\nis. It would be much preferable if we could access <code>_count<\/code> just like we\naccessed it before it was made private (i.e. with <code>t.count<\/code>), but at the same \ntime provide write protection (such that <code>t.count = 42<\/code> raises an error).\nEnter the <em>property<\/em>.<\/p>\n<h3 id=\"solution-2-using-a-property-as-a-read-only-data-attribute\">Solution 2: Using a property as a read-only data attribute<\/h3>\n<p>Implementing the same functionality as <code>get_count()<\/code> with a property is dead \nsimple.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"nd\">@property<\/span>\n<span class=\"k\">def<\/span> <span class=\"nf\">count<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;Return the current count.&quot;&quot;&quot;<\/span>\n    <span class=\"k\">return<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_count<\/span>\n<\/code><\/pre><\/div>\n\n<p>We use the <code>@property<\/code> decorator to say that the <code>count<\/code> method is a property.\nThis will let us invoke the <code>count<\/code> method without providing the parens, so\nit will look like we are just accessing a data attribute named <code>count<\/code>.\nUsage now looks like below:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span> <span class=\"o\">=<\/span> <span class=\"n\">Ticker<\/span><span class=\"p\">(<\/span><span class=\"mi\">5<\/span><span class=\"p\">)<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span>\n<span class=\"mi\">0<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">tick<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">tick<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span>\n<span class=\"mi\">2<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"k\">for<\/span> <span class=\"n\">_<\/span> <span class=\"ow\">in<\/span> <span class=\"nb\">range<\/span><span class=\"p\">(<\/span><span class=\"mi\">3<\/span><span class=\"p\">):<\/span>\n<span class=\"o\">...<\/span>     <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">tick<\/span><span class=\"p\">()<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span>\n<span class=\"mi\">0<\/span>\n<span class=\"o\">&gt;&gt;&gt;<\/span> <span class=\"n\">t<\/span><span class=\"o\">.<\/span><span class=\"n\">count<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">42<\/span>\n<span class=\"n\">Traceback<\/span> <span class=\"p\">(<\/span><span class=\"n\">most<\/span> <span class=\"n\">recent<\/span> <span class=\"n\">call<\/span> <span class=\"n\">last<\/span><span class=\"p\">):<\/span>\n  <span class=\"n\">File<\/span> <span class=\"s2\">&quot;&lt;stdin&gt;&quot;<\/span><span class=\"p\">,<\/span> <span class=\"n\">line<\/span> <span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"ow\">in<\/span> <span class=\"o\">&lt;<\/span><span class=\"n\">module<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"ne\">AttributeError<\/span><span class=\"p\">:<\/span> <span class=\"n\">can<\/span><span class=\"s1\">&#39;t set attribute<\/span>\n<span class=\"n\">can<\/span><span class=\"s1\">&#39;t set attribute<\/span>\n<\/code><\/pre><\/div>\n\n<p>Excellent! We have the exact same API as when <code>count<\/code> was a public attribute,\nbut without the risk of accidental overwriting. This is precisely what we wanted,\nand a Pythonic way of dealing with the issue of providing read access to fragile\nstate variables.<\/p>\n<h3 id=\"ticker-full-listing\">Ticker full listing<\/h3>\n<p>It always annoys me when I get to the conclusion of some tutorial, and the end\nresult is just assumed to be obvious. Therefore, here is the full listing of\n<code>Ticker<\/code> with a property as a getter.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">class<\/span> <span class=\"nc\">Ticker<\/span><span class=\"p\">:<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">&quot;&quot;&quot;A Ticker ticks from 0 to an upper limit, and then starts over.&quot;&quot;&quot;<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"fm\">__init__<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span> <span class=\"n\">end<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Create a Ticker that starts over at end&quot;&quot;&quot;<\/span>\n        <span class=\"k\">if<\/span> <span class=\"n\">end<\/span> <span class=\"o\">&lt;=<\/span> <span class=\"mi\">0<\/span><span class=\"p\">:<\/span>\n            <span class=\"k\">raise<\/span> <span class=\"ne\">ValueError<\/span><span class=\"p\">(<\/span><span class=\"s2\">&quot;end must be greater than 0!&quot;<\/span><span class=\"p\">)<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_end<\/span> <span class=\"o\">=<\/span> <span class=\"n\">end<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_count<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">0<\/span>\n\n    <span class=\"k\">def<\/span> <span class=\"nf\">tick<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Increment the internal count by 1.&quot;&quot;&quot;<\/span>\n        <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_count<\/span> <span class=\"o\">=<\/span> <span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_count<\/span> <span class=\"o\">+<\/span> <span class=\"mi\">1<\/span><span class=\"p\">)<\/span> <span class=\"o\">%<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_end<\/span>    \n\n    <span class=\"nd\">@property<\/span>\n    <span class=\"k\">def<\/span> <span class=\"nf\">count<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">):<\/span>\n<span class=\"w\">        <\/span><span class=\"sd\">&quot;&quot;&quot;Return the current count.&quot;&quot;&quot;<\/span>\n        <span class=\"k\">return<\/span> <span class=\"bp\">self<\/span><span class=\"o\">.<\/span><span class=\"n\">_count<\/span>\n<\/code><\/pre><\/div>\n\n<p>Now is about the time to move on to\n<a href=\"https:\/\/slar.se\/properties-as-pythonic-setters.html\">Part 2<\/a>, in which we expand on the <code>count<\/code>\nproperty to allow us to set the internal count, but only within the range <code>[0,\n_end)<\/code>!<\/p>","category":[{"@attributes":{"term":"Programming"}},{"@attributes":{"term":"python"}}]}]}