A Single Line Of Code
December 3, 2019
I have been using the following one-liner for years; it’s stored in my home directory, in an executable file named contacts:
grep -i "$*" <<EOF John Smith, 1234 Main Street, Anytown, USA, 99999 Mary Jones, 5678 Elm Street, Anytown, USA, 99999 EOF $ ./contacts Smith John Smith, 1234 Main Street, Anytown, USA, 99999
The real version of the program includes phone numbers, email addresses, and birthdates. Recently I’ve been using this program to maintain the passwords on my social media accounts:
$ cat keys ( base64 -d | ccdecrypt -f | grep -i "$*" ) <<EOF Ag6BI+0Z7iPGZgGL30+NNUExUXm1IYi8C4P4oxjiA3MdW2yng9bk7a45yHw2Qpi9z8T2y9kJNwfp mW4gKScu13GZ1KmMFDMeNcIhQf/Wzryk4PHJRbhToYTMk7nwOyUtRddv9Vv8pyymEB5sDmgYWzRY ... lots of lines elided ... XKSWfV8SDNO50h4+vWfzFFHLwFoLaTBOk5ZXzIWnyFMxRUb/zlOvzo9RVZWTnt1b/6e+oZ6pVpPU SU53kHrEYXgAZuYh9blCVPvFFrpT3EWq27T7sNvh1vkrXtgtWxJ/teMOWy0d7KEN2kL+3OQBSB15 bFyf EOF $ ./keys amazon Enter decryption key: Amazon|amazon.com|johnsmith@gmail.com|abcdefg
The encrypted here-doc is created by ( ccencrypt -f | base 64 ). To maintain the file, extract all of the keys with keys "^", edit the file, encrypt it, and re-assemble the executable file.
The concept of “useful” is hard to quantify. Certainly the keys program qualifies; you wouldn’t want to type all that every time you want to look up a password. The contacts program is more interesting; my claim is that it has been in my home directory for years, so at least I find it useful.
I use a lot of perl 1-liners in work (sometimes they do get very long…) – you said I couldn’t abuse 1 line… but thought I would include one – very long one-liner in Perl – which is an array to table HTML renderer I wrote probably 15+ years ago.. {I still use the same basic code regularly at work}
sub produce_table{ my( $C,$T ) = (0,{}); return map { qq(<table cellpadding="2" cellspacing="0" align="@{[ exists $_[2]{align} ? $_[2]{align} : 'center' ]}" width="@{[ exists $_[2]{width} ? $_[2]{width} : '100%' ]}">@{[ map( { $T->{$_->{key}||$C}=0 if exists $_->{total}; $C++; () }@{$_[0]} ), ($_[2]{'header'}||'' eq 'no' ? () : qq(<tr valign="middle">@{[ map{ $T->{$_->{key}||$C}=0 if exists $_->{total}; $C++; qq(<th>$_->{title}</th>) }@{$_[0]} ]}</tr>)) ]}@{[ map{ my $a=$_; $C=0; qq(<tr valign="@{[ exists $_[2]{valign} ? $_[2]{valign} : 'top' ]}" @{[ exists $_[2]{rows} ? qq( class="@{[ [ push( @{$_[2]{rows}},shift @{$_[2]{rows}}) , $_[2]{rows}[-1] ]->[1] ]}") : '' ]}>@{[ map{ my $b = ref($a) eq 'ARRAY' ? $a->[$C] : ref($a) eq 'HASH' ? $a->{$_->{key}} : $a->${\$_->{key}}; exists $_->{total} and $T->{$_->{key}||$C}+=$b; $C++; qq(<td@{[ $_->{align} ? qq( align="$_->{align}") : '' ]}@{[ $_->{width} ? qq( width="$_->{width}") : '' ]}>@{[ $b eq'' ? ' ' : $_->{format} ? $_->{format}->($b,$a) : $b ]}</td>) }@{$_[0]} ]}</tr>) }@{$_[1]} ]}@{[ ($C=-1)&&%$T ? qq(<tr valign="@{[ exists $_[2]{valign} ? $_[2]{valign} : 'top' ]}">@{[ map { $C++; qq(<td @{[ $_->{align} ? qq( align="$_->{align}") : '' ]}>@{[ !exists $_->{total} ? ' ' : ref $_->{total} eq 'CODE' ? $_->{total}->($T->{$_->{key}||$C},$T) : $_->{total} || $T->{$_->{key}||$C} ]}</td>) } @{$_[0]} ]}</tr>) : '' ]}</table>) } 1; }An example invocation would be:
print produce_table( [ { 'key'=>'c', 'title'=>'Amount', 'align' => 'center', 'format' => sub { sprintf '<b>£%0.2f</b>', $_[0]}, 'total' => '<b>Total</b>', 'width'=>'50%' }, { 'key'=>'a', 'title'=>'x', 'align' => 'right' , TOTAL_BOLD , 'width'=>'20%' }, { 'key'=>'b', 'title'=>'x^2', 'align' => 'right' , TOTAL_BOLDITALIC , FORMAT_ITALIC, 'width'=>'10%' }, { 'key'=>'d', 'title'=>'x^3', 'align' => 'right' , TOTAL_BOLD, 'width' => '10%' }, { 'key'=>'z', 'title'=>'x^4', 'align' => 'right' , TOTAL_BOLD, 'width' => '10%' }, ], [ map {{'z'=>$_*$_*$_*$_,'a'=>$_,'b'=>$_*$_,'c'=>"$_",'d'=>$_*$_*$_}} 0..$MAX_VALUE ], );Have similar code in PHP using lambdas to drive an advanced templating system
Mumps version
Using Pari/GP,
genit(mx)={forprime(p=2,mx,q=p+1;ok=0;while(q>2,q=precprime(q-1);if(isprime(round(pqPi)),ok=1;break));if(!ok,print1(p,”,”)));}
The output will be 7,113, 265381,…
These will be denominators for increasingly accurate approximations to Pi.
So they correspond to 22/7, 355/113, 833719/265381, …
The code using continued fractions is about the same length.
FindClosestDataPoint(x0::Float64, x::Array{<:Real, 1}) = argmin(abs.(x .- x0))
A simple function to find the index of the point of array x that’s closest to x. Not much on its own, but a useful auxiliary function overall.
These are more than one line, but there’s only one line of executable code.
~$ cat bin/sumcol
#!/bin/sh
exec awk "{ sum += \$${1-1}} END { print sum }"
~$ cat bin/lensort
#!/usr/bin/env python3
import fileinput
import sys
sys.stdout.write(''.join(sorted(fileinput.input(), key=len)))
~$
sumcol sums the numbers in a column of a text file — defaults to column 1 to work with
uniq -c,wc, etc.lensort sorts its input by line length.
Haskell seems the natural place to look for interesting one liners.
For example, Pascal’s triangle by iteration:
Or a nice impredicative definition of the Catalan numbers:
More impredicativity, we can list all integer pairs that generate primitive Pythagorean triples, as (a^2-b^2,2ab,a^2+b^2):
Or in a similar way, enumerate the rationals (as in the “Calkin-Wilf Tree”):
which can also be done with “Stern’s Diatomic Sequence”:
or by a direct iteration:
Here’s a one-liner in Python that prints the lines in a file as a list of strings (e.g., for copying and pasting elsewhere).
with open('/path/to/file') as f: print(repr(f.read().splitlines()))