An Algorithmic Lucidity

a blog

December 2015

2015 Year In Reverse

(Previously, previously.)

Dear reader (that's reader in the singular because I doubt that there are two actual humans who read my blog; it's not because there are many and I'm addressing you individually), it's that time of the year again—the time of the year when it stops being the year. A time to think thoughtfully and ask, "What happened since the last time we did this?"

In the year 2015, this blog has seen (at press time) 43 posts and 30 comments. Among these—

We shared a recipe for a more-wholesome-than-some-of-the-likely-alternatives breakfast (although honestly, I worry about coffee having unknown-to-me degenerative effects on the brain—just because lots of people in your Society indulge in a drug doesn't mean it's safe; it just means that any long-term damage has to be subtle enough that people still feel safe using it—and is that really so high of a bar?). We heard some error message free verse. I wished for a crypto subplot in the yet-unnamed 2017 Star Trek series. A train was late. We heard a poem about sin and a pæan to one's employer. A tablet app for sports recordkeeping enthusiasts was proposed. I got mail. We considered the quiet holocaust of things left unsaid perpetrated by the forces of laziness and evil that lurk in people's hearts. I got a patch into OpenStack Swift (ninth draft landed as 06bede894 on 7 October, first draft proposed for review on 19 July). You heard about some of my favorite things in September. We went back to basics on the justification of a classic property of arithmetic. I commented on a certain matter of misperceived incentives, and another matter of determination in the absence of what others could discern as incentives. I went to the first Rust conference. My bold investigative reporting showed that the seemingly-straightforward $ directive treacherously means different things to different regular-expression engines. I confessed to favoring a nonstandard pronunciation of a file extension. I mentioned that I was trying to write a compiler, although honestly, I don't think it went so well (the lexer, parser, and obligatory Emacs mode weren't that bad, but I kind of intuited the context-handling and code-generation parts, and should really get farther in the textbook and give it another try later). I explained how erasure codes work. We heard some more error-message poetry. Some readers of this blog (!!) relieved me of some of my confusion about why the Rust borrow-checker rejects bad code that you might think is good if you grew up the cartoon fantasy world that calls itself Python. I explained why "Pi Day" is an unholy festival of sin that is corrupting our children. You heard from me during February, and we saw a macro that is just too cute.

Beyond these, there are many more things that remain to be said.

But they will have to wait until next year.

Naughty List

(examining a Christmas card and enclosed document, frowning) "I think my Uncle Benny is mad at me."

"Why?"

"Well, every Christmas since me and my brother were kids, instead of getting us toys or cash as gifts, Uncle Benny would give us some kind of financial instrument, like a savings bond or a share of stock in some company. You know, to teach us the value of productive investment over mere consumption."

"And this year?"

"Commodity options."

"That doesn't s—"

"In coal."

Attentional Shunt

#!/usr/bin/env python3

# Copyright © 2015 Zack M. Davis

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

"""
Configure the machine to shunt traffic to distracting sites to localhost,
preserving attention.
"""

import os
import argparse
import subprocess
import sys
from datetime import datetime, timedelta

ETC_HOSTS = os.path.join(os.sep, 'etc', 'hosts')
HEADER = "# below managed by attentional shunt"
INVERSE_COMMANDS = {'enable': "disable", 'disable': "enable"}

DISTRACTING_HOSTS = (  # modify as needed
    'news.ycombinator.com',
    'math.stackexchange.com',
    'scifi.stackexchange.com',
    'worldbuilding.stackexchange.com',
    'workplace.stackexchange.com',
    'academia.stackexchange.com',
    'codereview.stackexchange.com',
    'puzzling.stackexchange.com',
    'slatestarcodex.com',
    'twitter.com',
    'www.facebook.com',
    'slatestarscratchpad.tumblr.com',
)
SHUNTING_LINES = "\n{}\n{}\n".format(
    HEADER,
    '\n'.join("127.0.0.1 {}".format(domain)
              for domain in DISTRACTING_HOSTS)
)


def conditionally_reexec_with_sudo():
    if os.geteuid() != 0:
        os.execvp("sudo", ["sudo"] + sys.argv)


def enable_shunt():
    if is_enabled():
        return  # nothing to do
    with open(ETC_HOSTS, 'a') as etc_hosts:
        etc_hosts.write(SHUNTING_LINES)


def disable_shunt():
    with open(ETC_HOSTS) as etc_hosts:
        content = etc_hosts.read()
    if SHUNTING_LINES not in content:
        return  # nothing to do
    with open(ETC_HOSTS, 'w') as etc_hosts:
        etc_hosts.write(content.replace(SHUNTING_LINES, ''))


def is_enabled():
    with open(ETC_HOSTS) as etc_hosts:
        content = etc_hosts.read()
    return HEADER in content


def status():
    state = "enabled" if is_enabled() else "disabled"
    print("attentional shunt is {}".format(state))


def schedule(command, when):  # requires `at` job-scheduling utility
    timestamp = when.strftime("%H:%M %Y-%m-%d")
    at_command = ['at', timestamp]
    at = subprocess.Popen(
        at_command,
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    at.communicate(command.encode())


if __name__ == "__main__":
    arg_parser = argparse.ArgumentParser(description=__doc__)
    arg_parser.add_argument('command',
                            choices=("enable", "disable", "status"))
    arg_parser.add_argument('duration', nargs='?', type=int,
                            help=("revert state change after this many "
                                  "minutes"))
    args = arg_parser.parse_args()
    if args.command == "status":
        status()
    else:
        conditionally_reexec_with_sudo()
        if args.command == "enable":
            enable_shunt()
        elif args.command == "disable":
            disable_shunt()

        if args.duration:
            now = datetime.now()
            inverse_command = INVERSE_COMMANDS[args.command]
            schedule(
                "{} {}".format(os.path.realpath(__file__), inverse_command),
                now + timedelta(minutes=args.duration)
            )

I Want to Be the One

This life is not to last and it awaits apotheosis
And the passerby all sipping on their Monday coffee know this
Their stumbling through their week
Contrasts the path by which I seek
A practical ambition
For a special type of girl
I want to be the one who writes the code
That writes the code
That writes the code
That ends the world

Californian Raktajino

Ingredients:

californian_raktajino1

Instructions:

  1. Pour coffee powder in bottom of glass.
  2. Add enough water to dissolve the coffee powder; stir.
    californian_raktajino2
  3. Pour Soylent. Soylent will mostly sink below the coffee; stir with a somewhat vertical motion until color is uniform.
    californian_raktajino3 californian_raktajino4 californian_raktajino5
  4. Today is a good day to live! Drink; enjoy; move fast; break things!