<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>accidental.cc</title><description>Jon Raphaelson&apos;s blog and stuff</description><link>https://accidental.cc/</link><item><title>bit-struct, a bit-struct macro for racket</title><link>https://accidental.cc/notes/bit-struct/</link><guid isPermaLink="true">https://accidental.cc/notes/bit-struct/</guid><pubDate>Fri, 08 Nov 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I&apos;ve been playing with &lt;code&gt;mdns&lt;/code&gt;, as a way to do local-only automatic syncing
as part of a notebook application I&apos;m working on in Racket, and I needed a
way to represent DNS reconds, which are packed c-style structs.&lt;/p&gt;
&lt;p&gt;I could have used the FFI package to define these, but I like playing around,
and ended up with these two modules, which define &lt;code&gt;bit-spec&lt;/code&gt;, a struct which
describes a field in a bit-struct, and &lt;code&gt;define-bit-struct&lt;/code&gt;, a macro which builds
up a packed bit-struct.&lt;/p&gt;
&lt;p&gt;Right now they handle endianness, signed numbers and padding; I may end up with
more features eventually.&lt;/p&gt;
&lt;p&gt;As an example,&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-racket&quot;&gt;(require &quot;./bit-struct.rkt&quot;)

(define-bit-struct dns-header
  [(some-header 16 #:signed? #t)
   (some-field  32)  ; 32 bit number
   (some-bool    1)  ; 1 bit boolean
   (_            7)  ; 7 bits of padding
   (some-bytes   0)]) ; rest as a bytestring
  
(define obj (build-dns-header #:some-bytes #&quot;hello world&quot; #:some-field 12345 #:some-bool #t))
;=&gt; (dns-header 0 12345 #t #&quot;hello world&quot;)

(define out (dns-header-&gt;bytes obj))
;=&gt; #&quot;\0\0\0\00009\200hello world&quot;

(bytes-&gt;dns-header #&quot;\0\0\0\00009\200hello world&quot;)
;=&gt; (dns-header 0 12345 #t #&quot;hello world&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The macro defines:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;dns-header&lt;/code&gt; struct, with contract (&lt;code&gt;dns-header/c&lt;/code&gt;) and getters&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dns-header-allspecs&lt;/code&gt;, a list of all bitspecs in order, (including padding)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dns-header-bitspecs&lt;/code&gt;, a hash table of field names to bitspecs&lt;/li&gt;
&lt;li&gt;&lt;code&gt;build-dns-header&lt;/code&gt;, which takes an arbitrary set of keyword args&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dns-header-data&lt;/code&gt;, which returns a all the struct&apos;s data in a list&lt;/li&gt;
&lt;li&gt;&lt;code&gt;bytes-&gt;dns-header&lt;/code&gt; and &lt;code&gt;dns-header-&gt;bytes&lt;/code&gt; which de/serialize respectively&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code class=&quot;language-racket&quot;&gt;#lang racket/base

; a bitspec determines the layout of a given field
; ie; (build-bitspec bitlen #:big-endian? #:signed?)
;
; you can get a default value, and a generated contract for the field
; you can convert a value+bitspec into a bit string
;                   bit string+bitspec into a value

(require bitsyntax

         racket/contract
         racket/match
         racket/math)

(provide bitspec
         bitspec/c

         build-bitspec

         bitspec-bitlen
         bitspec-big-endian?
         bitspec-signed?

         bitspec-rest?
         bitspec-default-value
         bitspec-contract

         bit-string+bitspec-&gt;value
         value+bitspec-&gt;bit-string)

; prefab so we can splice in as syntax
(struct bitspec [bitlen big-endian? signed?] #:prefab)

; contract because we can&apos;t use a guard with prefab
(define bitspec/c  (struct/c bitspec natural? boolean? boolean?))
(define bitvalue/c (or/c bytes? boolean? exact-integer?))

(define (bit-length/c n)
  (and/c exact-integer?
         (make-flat-contract
          #:name        &quot;bit-length/c&quot;
          #:first-order (lambda (v) (and (exact-integer? v) (&amp;#x3C;= (integer-length v) n))))))

;;;;

(define/contract (build-bitspec bitlen #:big-endian? (big-endian? #t) #:signed? (signed? #f))
  (-&gt;* (natural?) (#:big-endian? boolean? #:signed? boolean?) bitspec/c)
  (bitspec bitlen big-endian? signed?))

(define/contract (bitspec-rest? spec)
  (-&gt; bitspec/c boolean?)
  (zero? (bitspec-bitlen spec)))

(define/contract (bitspec-contract spec)
  (-&gt; bitspec/c contract?)

  (match (bitspec-bitlen spec)
    [0 bytes?]
    [1 boolean?]
    [x (if (bitspec-signed? spec)
           (and/c exact-integer? (bit-length/c (- x 1)))
           (and/c natural?       (bit-length/c x)))]))

(define/contract (bitspec-default-value spec)
  (-&gt;i ([spec bitspec/c]) [_ (spec) (and/c bitvalue/c (bitspec-contract spec))])
  (match (bitspec-bitlen spec)
    [0 #&quot;&quot;]
    [1  #f]
    [_   0]))

(define/contract (bit-string+bitspec-&gt;value chunk spec)
  (-&gt;i ([str bit-string?] [spec bitspec/c]) [_ (spec) (and/c bitvalue/c (bitspec-contract spec))])
  (match (bitspec-bitlen spec)
    [0 (bit-string-&gt;bytes chunk)]
    [1 (= 1 (bit-string-ref chunk 0))]
    [_ (bit-string-&gt;integer chunk (bitspec-big-endian? spec) (bitspec-signed? spec))]))

(define/contract (value+bitspec-&gt;bit-string value config)
  (-&gt;i ([str (spec) (and/c bitvalue/c (bitspec-contract spec))] [spec bitspec/c]) [_ bit-string?])
  (match (bitspec-bitlen config)
    [0 value] ; zero means rest
    [1 (integer-&gt;bit-string (if value 1 0) 1 #t)]
    [_ (integer-&gt;bit-string value (bitspec-bitlen config) (bitspec-big-endian? config))]))

(module+ test
  (require rackunit)
  
  (check-exn exn:fail:contract? (lambda () (build-bitspec &apos;hi)))
  (check-exn exn:fail:contract? (lambda () (build-bitspec 0 #:big-endian? 6)))
  (check-exn exn:fail:contract? (lambda () (build-bitspec 0 #:signed? 15)))
  
  ; check signed output
  (let [(s-bitspec (build-bitspec 8 #:signed? #t))
        (u-bitspec (build-bitspec 8))]
    (check-equal? (bit-string+bitspec-&gt;value #&quot;\201&quot; u-bitspec) 129)
    (check-equal? (bit-string+bitspec-&gt;value #&quot;\201&quot; s-bitspec) -127)
    (check-equal? (value+bitspec-&gt;bit-string 129 u-bitspec) #&quot;\201&quot;)
    (check-equal? (value+bitspec-&gt;bit-string -127 s-bitspec) #&quot;\201&quot;))
  
  ; check endian output
  (let [(b-bitspec (build-bitspec 32))
        (l-bitspec (build-bitspec 32 #:big-endian? #f))]
    (check-equal? (bit-string+bitspec-&gt;value #&quot;\0\0\0\1&quot; b-bitspec) 1)
    (check-equal? (bit-string+bitspec-&gt;value #&quot;\0\0\0\1&quot; l-bitspec) #x1000000)
    (check-equal? (value+bitspec-&gt;bit-string 1         b-bitspec) #&quot;\0\0\0\1&quot;)
    (check-equal? (value+bitspec-&gt;bit-string #x1000000 l-bitspec) #&quot;\0\0\0\1&quot;))
  
  ; contract violation with out of range values
  (let [(spec (build-bitspec 8 #:signed? #t))]
    (check-exn exn:fail:contract? (lambda () (value+bitspec-&gt;bit-string #f     spec)))
    (check-exn exn:fail:contract? (lambda () (value+bitspec-&gt;bit-string 129    spec)))
    (check-exn exn:fail:contract? (lambda () (value+bitspec-&gt;bit-string -129   spec)))
    (check-exn exn:fail:contract? (lambda () (value+bitspec-&gt;bit-string #&quot;wat&quot; spec)))))
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-racket&quot;&gt;#lang racket/base

(require bitsyntax
         &quot;./bit-spec.rkt&quot;
         racket/struct
         racket/contract)

(require
  (for-syntax arguments
              &quot;./bit-spec.rkt&quot;
              racket/base
              racket/contract
              racket/list
              racket/syntax))

(provide define-bit-struct)

(define-syntax (define-bit-struct stx)
  (syntax-case stx ()
    [(_ struct-name ([name* bitspecs* ...] ...))
     (begin
       (define symbol-&gt;keyword (compose string-&gt;keyword symbol-&gt;string))
       
       ; get symbols and cons from the syntax, so we can precompute some stuff
       (define parsed-names    (syntax-&gt;datum #&apos;(name* ...)))
       (define parsed-bitspecs (syntax-&gt;datum #&apos;((bitspecs* ...) ...)))
       
       ; get structs from the parsed cons lists
       (define built-bitspecs
         (for/list ([bitspec (in-list parsed-bitspecs)])
           (define bitspec-args   (make-arguments (list (car bitspec)) (apply hash (cdr bitspec))))
           (define bitspec-struct (apply/arguments build-bitspec bitspec-args))
           bitspec-struct))
       
       ; get a hash of field name to bitspecs, excluding anonymous padding
       (define named-bitspecs
         (for/hash ([name (in-list parsed-names)]
                    [spec (in-list built-bitspecs)]
                    #:unless (eq? name &apos;_))
           (values name spec)))
       
       ; (list name...) for named named
       (define struct-named-fields
         (for/list ([name (in-list parsed-names)]
                    #:unless (eq? name &apos;_))
           name))
       
       ; (list contract ...) for named fields
       (define struct-contract-fields
         (for/list ([name (in-list parsed-names)]
                    #:unless (eq? name &apos;_))
           (bitspec-contract (hash-ref named-bitspecs name))))
       
       ; (list (#:keyword (keyword default)) ...)
       (define builder-kw-default-arguments
         (for/list ([(name spec) (in-hash named-bitspecs)])
           (list (symbol-&gt;keyword name) (list name (bitspec-default-value spec)))))
       
       ; (list (#:keyword contract) ...)
       (define builder-kw-contract-arguments
         (for/list ([(name spec) (in-hash named-bitspecs)])
           (list (symbol-&gt;keyword name) (bitspec-contract spec))))
       
       (with-syntax ([contract-name (format-id stx &quot;~a/c&quot;        #&apos;struct-name)]
                     [allspecs-name (format-id stx &quot;~a-allspecs&quot; #&apos;struct-name)]
                     [bitspecs-name (format-id stx &quot;~a-bitspecs&quot; #&apos;struct-name)]
                     [builder-name  (format-id stx &quot;build-~a&quot;    #&apos;struct-name)]
                     [data-name     (format-id stx &quot;~a-data&quot;     #&apos;struct-name)]
                     [bytes-&gt;-name  (format-id stx &quot;bytes-&gt;~a&quot;   #&apos;struct-name)]
                     [-&gt;bytes-name  (format-id stx &quot;~a-&gt;bytes&quot;   #&apos;struct-name)])
         
         #`(begin
             (struct struct-name #,struct-named-fields #:transparent)
             
             (define contract-name
               (struct/c struct-name #,@struct-contract-fields))
             
             (define allspecs-name
               &apos;#,(datum-&gt;syntax stx built-bitspecs))
             
             (define bitspecs-name
               (for/hash [(name (in-list &apos;#,parsed-names))
                          (spec (in-list allspecs-name))
                          #:unless (eq? name &apos;_)]
                 (values name spec)))
             
             ; drops the first value, which is the
             (define/contract (data-name obj)
               (-&gt; contract-name list?)
               (struct-&gt;list obj))
             
             ; builder with keywords + default values
             (define/contract (builder-name #,@(append* builder-kw-default-arguments))
               (-&gt;* () #,(append* builder-kw-contract-arguments) contract-name)
               (struct-name #,@struct-named-fields))
             
             (define/contract (bytes-&gt;-name input)
               (-&gt; bytes? contract-name)
               (define (append-maybe-padding name arg arguments)
                 (if (eq? name &apos;_) arguments (cons arg arguments)))
               
               (for/fold ([offset    0]
                          [arguments null]
                          #:result (apply struct-name (reverse arguments)))
                         ([name (in-list &apos;#,parsed-names)]
                          [spec (in-list allspecs-name)])
                 (if (bitspec-rest? spec)
                     ; read the rest of the string
                     (let* ([offset^ (bytes-length input)]
                            [chunk   (bit-string-drop input offset)]
                            [arg     (bit-string+bitspec-&gt;value chunk spec)])
                       (values offset^ (append-maybe-padding name arg arguments)))
                     ; or read bitlen bits
                     (let* ([offset^ (+ offset (bitspec-bitlen spec))]
                            [chunk   (sub-bit-string input offset offset^)]
                            [arg     (bit-string+bitspec-&gt;value chunk spec)])
                       (values offset^ (append-maybe-padding name arg arguments))))))
             
             (define/contract (-&gt;bytes-name self #:align-right? (align-right? #t))
               (-&gt;* (contract-name) (#:align-right? boolean?) bytes?)
               (for/fold ([acc #&quot;&quot;]
                          [data (data-name self)]
                          #:result (bit-string-&gt;bytes/align acc align-right?))
                         ([name (in-list &apos;#,parsed-names)]
                          [spec (in-list allspecs-name)])
                 (if (eq? name &apos;_)
                     ; padding gets default values
                     (values (bit-string-append acc (value+bitspec-&gt;bit-string (bitspec-default-value spec) spec)) data)
                     ; not padding puts values from the struct
                     (values (bit-string-append acc (value+bitspec-&gt;bit-string (car data) spec)) (cdr data))))))))]))

(module+ test
  (require rackunit)
  
  (define-bit-struct example-le-struct
    ([fielda  32 #:big-endian? #f]
     [fieldb  16 #:signed? #t]))
  
  (let* ([empty-val   (build-example-le-struct)]
         [empty-bytes (example-le-struct-&gt;bytes empty-val)])
    (check-equal? empty-bytes #&quot;\0\0\0\0\0\0&quot;))
  
  (let* ([something-val   (build-example-le-struct #:fielda 512 #:fieldb 512)]
         [something-bytes (example-le-struct-&gt;bytes something-val)])
    (check-equal? something-bytes #&quot;\0\2\0\0\2\0&quot;))
  
  (define-bit-struct example-be-struct
    ([fielda  32 #:big-endian? #t]
     [fieldb  16 #:signed? #t]))
  
  (let* ([something-val   (build-example-be-struct #:fielda 512 #:fieldb 512)]
         [something-bytes (example-be-struct-&gt;bytes something-val)])
    (check-equal? something-bytes #&quot;\0\0\2\0\2\0&quot;))
  
  (define-bit-struct example-data-struct
    ([fielda  1]
     [_      39]
     [fieldb  0]))
  
  (let* ([data-val    (build-example-data-struct #:fielda #t #:fieldb #&quot;hello!&quot;)]
         [data-bytes  (example-data-struct-&gt;bytes data-val)]
         [rebuilt-val (bytes-&gt;example-data-struct data-bytes)])
    (check-equal? data-bytes #&quot;\200\0\0\0\0hello!&quot;)
    (check-equal? rebuilt-val data-val)))
 
&lt;/code&gt;&lt;/pre&gt;</content:encoded></item><item><title>Notes on &quot;The Art of the Metaobject Protocol&quot;</title><link>https://accidental.cc/notes/art-of-mop-review/</link><guid isPermaLink="true">https://accidental.cc/notes/art-of-mop-review/</guid><pubDate>Tue, 19 Dec 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Quick thoughts, I&apos;ll update this over time:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;this is a new-to-me data point in the design of the Ruby object system: ruby meta-programming and the interesting things you can do with ancestors lists &lt;code&gt;#prepend&lt;/code&gt; match up to interesting points in the design space of object systems that the authors write about&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;the MOP feels less like an &quot;object system&quot; than a &quot;multiple disptach&quot; system with enough typing to linearize the dependency graph; that makes me wonder if there&apos;s a further separation to make, where we take the multi-disptach but leave the subtyping?&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;</content:encoded></item><item><title>Sabattical, &apos;23</title><link>https://accidental.cc/notes/sabbatical/</link><guid isPermaLink="true">https://accidental.cc/notes/sabbatical/</guid><pubDate>Sat, 01 Apr 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;It&apos;s been 10 years of startup grind, and I need a break.&lt;/p&gt;
&lt;p&gt;My kids are five and eight, Sarah&apos;s kicking ass at work, and it&apos;s almost summer.&lt;/p&gt;
&lt;p&gt;I have kids to take on a hike, a library card, side projects and good weather.&lt;/p&gt;
&lt;p&gt;I&apos;ll see y&apos;all on the other side!&lt;/p&gt;</content:encoded></item><item><title>protohackers in CL (part 1 &apos;call/cc&apos;)</title><link>https://accidental.cc/notes/protohackers-cl-ii/</link><guid isPermaLink="true">https://accidental.cc/notes/protohackers-cl-ii/</guid><pubDate>Fri, 17 Mar 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;See also &lt;a href=&quot;../protohackers-cl&quot;&gt;../protohackers-cl&lt;/a&gt; for more info.&lt;/p&gt;
&lt;p&gt;So, after the simple thread-per-request version I put together last time, I
wanted to see if I could handle multiple clients in an event-based way, on a
single thread.&lt;/p&gt;
&lt;h3&gt;insights from reading code&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;usocket:wait-for-input&lt;/code&gt; function is basically our &lt;code&gt;select(2)&lt;/code&gt;;
it takes a list of sockets and blocks until some subset are ready for reading.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;I&apos;ve played around some with &lt;code&gt;cl-cont&lt;/code&gt; and &lt;code&gt;cl-coroutine&lt;/code&gt; (both on quicklisp);&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;cl-cont&lt;/code&gt; provides a bunch of sweet macros to transform some code into
cps, and then manage
running that code such that we can use &lt;code&gt;call/cc&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;cl-coroutine&lt;/code&gt; is a really simple macro on top, which I&apos;m not going to use,
but which was instrumental in helping me get my head around how we can provide
a DSL of sorts with &lt;code&gt;macrolet&lt;/code&gt;
getting a body form in a macro.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;With &quot;select amongst ready sockets&quot; and &quot;coroutines&quot; in my head from reading code
this last couple of weeks, I&apos;ve figured out a plan:&lt;/p&gt;
&lt;h3&gt;sketch of the plan&lt;/h3&gt;
&lt;p&gt;In pseudocode, we&apos;re doing something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;socket-registry = make-hash-table
server-socket   = socket-listen *host* *port*

loop:
  usocket:wait-for-input (hash-keys socket-registry)
  for each ready-socket:
    continuation      = socket-registry[ready-socket]
    command, nextcont = funcall continuation ready-socket
    case command:
      wait: 
        socket-registry[socket] = nextcont
      fork:
        socket-registry[socket] = client-handler socket
        socket-registry[server] = nextcont
      close:
        delete socket-registry[socket]
        close socket
&lt;/code&gt;&lt;/pre&gt;
&lt;ol&gt;
&lt;li&gt;the &lt;code&gt;socket-registry&lt;/code&gt; stores continuations from previous work against the socket&lt;/li&gt;
&lt;li&gt;assume the &lt;code&gt;server-socket&lt;/code&gt; got into the hash table at some point, so &lt;code&gt;socket-accept&lt;/code&gt;
is part of the server&apos;s coroutine loop&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;accept loop&lt;/h3&gt;
&lt;p&gt;I like to write code where I just use the name of a function or macro that I haven&apos;t written
yet, to see what it feels like, so let&apos;s start with this definition of the accept-loop coroutine.
This is the one that&apos;s performing the accept loop, accepting connections and forking them off into
the registery for processing.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-lisp&quot;&gt;(cl-cont:defun/cc server-accept (socket handlerfn)    ; 1.
  (loop do
    (wait-for-input socket)                           ; 2.
    (let ((client (usocket:socket-accept socket)))
      (fork-socket socket client handlerfn))))        ; 3.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Immediately confusing is &lt;code&gt;cl-cont:defun/cc&lt;/code&gt;; this is just a macro from the &lt;code&gt;cl-cont&lt;/code&gt; system which
builds a function definition in such a way that it&apos;s usable with the cps transforms stuff that &lt;code&gt;cl-cont&lt;/code&gt;
uses. &lt;code&gt;macroexpand&lt;/code&gt; can be a very healthy excercise[^defuncc-expand].&lt;/p&gt;
&lt;p&gt;[^defuncc-expand]:
Despite being nearly impossible to actually read, thanks to copious &lt;code&gt;gensym&lt;/code&gt;, it&apos;s
obvious that the code has been transformed from something that runs linearly, to some
stack of &lt;code&gt;funcall&lt;/code&gt; and &lt;code&gt;lambda&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;```lisp
(cl-cont:defun/cc example-defun (name)
  (format t &quot;name ~a~%&quot; name))

;; macroexpands to:
;; (with a bunch of declare ignorable and storing to the symbol properties removed)

(cl-cont::make-funcallable
(lambda (#:g365 name)
  (funcall
    (lambda (&amp;#x26;optional #:g366 &amp;#x26;rest #:g367)
      (let ((#:g368 #:g365))
        (funcall
        (lambda (&amp;#x26;optional #:g369 &amp;#x26;rest #:g370)
          (funcall
            (lambda (&amp;#x26;optional #:g371 &amp;#x26;rest #:g372)
              (funcall
              (lambda (&amp;#x26;optional #:g373 &amp;#x26;rest #:g374)
                (funcall
                  (lambda (&amp;#x26;optional #:g375 &amp;#x26;rest #:g376)
                    (funcall (cl-cont::fdesignator-to-function/cc #:g369) #:g368 #:g371 #:g373 #:g375))
                  name))
              &quot;name: ~a~%&quot;))
            t))
        #&apos;format)))
    nil)))
```

Seeing this, I&apos;m not sure if it&apos;s a great idea memory wise, but it&apos;s cool, so we&apos;ll 
keep going for now.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Anyway, assuming we come back and implement &lt;code&gt;wait-for-input&lt;/code&gt; and &lt;code&gt;fork-socket&lt;/code&gt; as &lt;code&gt;cl-cont&lt;/code&gt; based non-local returns,
this will do exactly what we want (sans error handling) -- loop on the server socket, trying to accept connections.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;fork-socket&lt;/code&gt; is a little different than &lt;code&gt;wait-for-input&lt;/code&gt;, in that it will actually run the other code
immediately (this function&apos;s continuation &lt;em&gt;and&lt;/em&gt; &lt;code&gt;handlerfn&lt;/code&gt;), collecting their results for updating the
registry.&lt;/p&gt;
&lt;p&gt;Essentially it gives us a fork at the point of call -- in one continuation, we&apos;re the server, and continue
running after the fork, landing on &lt;code&gt;wait-for-input&lt;/code&gt; after finishing the &lt;code&gt;loop&lt;/code&gt;. In the &lt;em&gt;other&lt;/em&gt; continuation,
we&apos;re running whatever code was handed to us as &lt;code&gt;handlerfn&lt;/code&gt;, with &lt;code&gt;server-accept&lt;/code&gt; up the callstack,&lt;/p&gt;
&lt;h3&gt;client handler&lt;/h3&gt;
&lt;p&gt;Similarly, we&apos;ll just define the client handler assuming the code that we&apos;ll need;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-lisp&quot;&gt;(defun client-handler (socket)
  (loop do
    (wait-for-input socket)                           ; 1.
    (let* ((stream (usocket:socket-stream socket))
           (input  (read-line stream)))
      (if (equal input &quot;quit&quot;)
          (close-and-finish socket)                   ; 2.
          (progn 
            (format stream &quot;echo: ~a~%&quot; input)
            (finish-output stream))))))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Same thing here; assuming that &lt;code&gt;wait-for-input&lt;/code&gt; and &lt;code&gt;close-and-finish&lt;/code&gt; are non-local returns via whatever
continuation based runtime we&apos;ve got, this shouldn&apos;t ever block, and we should be able to handle mulitple
clients.&lt;/p&gt;
&lt;h2&gt;the actual runtime&lt;/h2&gt;
&lt;p&gt;Here it is, I&apos;ll break it down after:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-lisp&quot;&gt;(defmacro wait-for-input (s)
  (alexandria:with-gensyms (cc)
    `(cl-cont:let/cc ,cc
       (list :wait ,s ,cc))))

(defmacro close-and-finish (s)
  `(cl-cont:let/cc _
     (declare (ignorable _))
     (list :close ,s)))

(defmacro fork-socket (server client handler)
  (alexandria:with-gensyms (cc)
    `(cl-cont:let/cc ,cc
         (list :fork ,server ,cc ,client ,handler))))

(defun socket-handler-case (registry result)
  (alexandria:destructuring-case result
    ((:wait socket continue)
     (format t &quot;waiting on ~A from ~A ~%&quot; socket continue)
     (setf (gethash socket registry) continue))

    ((:close socket)
     (format t &quot;finished on ~A ~%&quot; socket)
     (remhash socket registry)
     (usocket:socket-close socket))

    ((:fork server-socket server-cont client-socket client-handler)
     (format t &quot;forking from ~A to ~A ~A ~%&quot; server-socket client-socket client-handler)
     (socket-handler-case registry (funcall server-cont server-socket))
     (format t &quot;...running client... ~%&quot;)
     (socket-handler-case registry (funcall client-handler client-socket)))))

(defun make-server ()
  (cl-cont:with-call/cc
    (let* ((registry      (make-hash-table))
           (server-socket (usocket:socket-listen &quot;0.0.0.0&quot; 6000 :reuseaddress t))
           (server-result (server-listen server-socket #&apos;client-handler)))

      ;; let the server get started, and register the server socket
      (socket-handler-case registry server-result)

      ;; now, we basically just loop over ready sockets, handling forks
      (loop do
        (format t &quot;waiting for a ready socket ~%&quot;)
        (let* ((sockets (alexandria:hash-table-keys registry))
               (ready   (usocket:wait-for-input sockets :ready-only t)))
          (format t &quot;ready sockets! ~%&quot;)
          (dolist (socket ready)
            (let* ((continue (gethash socket registry))
                   (command  (funcall continue socket)))
              (format t &quot;handled socket ~A ~%&quot; socket)
              (socket-handler-case registry command))))))))
&lt;/code&gt;&lt;/pre&gt;</content:encoded></item><item><title>protohackers in CL (part 0)</title><link>https://accidental.cc/notes/protohackers-cl/</link><guid isPermaLink="true">https://accidental.cc/notes/protohackers-cl/</guid><pubDate>Sat, 04 Mar 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;A couple of weeks ago, &lt;a href=&quot;https://lobste.rs/s/wshlf0/protohackers_server_programming&quot;&gt;synack on lobste.rs&lt;/a&gt;
shared &lt;a href=&quot;https://protohackers.com&quot;&gt;https://protohackers.com&lt;/a&gt;, a &quot;server programming challenge&quot;
which asks you to implement servers responding to some protocol, and
can run automated tests against your solutions.&lt;/p&gt;
&lt;p&gt;I got nerd-sniped pretty hard, and with my current copious free-time,
I decided to use it as an excuse to practice writing actual &quot;software&quot;
in &lt;a href=&quot;https://lisp-lang.org&quot;&gt;common lisp&lt;/a&gt;, exploring the package
ecosystem some, and at least seeing the parts I&apos;d need to make
something more significant than the messing around with the language
I&apos;ve done in the past.&lt;/p&gt;</content:encoded></item><item><title>Redesigning accidental.systems</title><link>https://accidental.cc/notes/redesign/</link><guid isPermaLink="true">https://accidental.cc/notes/redesign/</guid><pubDate>Tue, 29 Nov 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Slowly but surely, I&apos;m rebuilding this site.&lt;/p&gt;
&lt;p&gt;As twitter&apos;s been collapsing, a lot of my #indieweb inclinations have been stirred
up, and with #mastodon and #activitypub starting to blow up, I&apos;d really like to
figure out how the federation et al. works.&lt;/p&gt;
&lt;p&gt;:::books{.books}
Have Read:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;ActivityStreams spec&lt;/li&gt;
&lt;li&gt;ActivityPub spec&lt;/li&gt;
&lt;li&gt;LinkedData spec&lt;/li&gt;
&lt;li&gt;damn there&apos;s a lot of specs
:::&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;graph LR
  A --&gt; B
  B --&gt; C
  B --&gt; D
  C --&gt; A
  D --&gt; A
&lt;/code&gt;&lt;/pre&gt;</content:encoded></item><item><title>Stack.pop_until, a handy ocaml function</title><link>https://accidental.cc/notes/ocaml-stack-extensions/</link><guid isPermaLink="true">https://accidental.cc/notes/ocaml-stack-extensions/</guid><pubDate>Fri, 14 Oct 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;is this wrong, somehow?&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ocaml&quot;&gt;open Core

module Stack = struct
  include Stack

  let rec pop_until pred stack =
    pop_until&apos; pred stack 0

  and pop_until&apos; pred stack n =
    let a = Stack.pop stack in
    if pred a then
      (a, n)
    else
      pop_until&apos; pred stack (n + 1)

  let rec pop_until_exn pred stack =
    pop_until_exn&apos; pred stack 0

  and pop_until_exn&apos; pred stack n =
    let a = Stack.pop_exn stack in
    if pred a then
      (a, n)
    else
      pop_until_exn&apos; pred stack (n + 1)

end

let%expect_test _ =
  let stack = Stack.create () in
    Stack.push stack 10;
    Stack.push stack 20;
    Stack.push stack 30;

    printf &quot;initial top: %d\n&quot; (Stack.top_exn stack);
    let v, m = Stack.pop_until_exn (fun i -&gt; i &amp;#x3C;= 19) stack in
      printf &quot;popped count: %d\n&quot; m;
      printf &quot;popped value: %d\n&quot; v;
      printf &quot;empty?: %b\n&quot; (Stack.is_empty stack);

      [%expect {|
        initial top: 30
        popped count: 2
        popped value: 10
        empty?: true
      |}]

let%expect_test _ =
  try
    let stack = Stack.create () in
    ignore (Stack.pop_until_exn (fun i -&gt; i &amp;#x3C; 0) stack);
  with
    e -&gt; printf &quot;error: %s\n&quot; (Exn.to_string e)
  ;

  [%expect {|error: &quot;Stack.pop of empty stack&quot;|}]
&lt;/code&gt;&lt;/pre&gt;</content:encoded></item><item><title>psf format font loader for zig</title><link>https://accidental.cc/notes/psf-zig/</link><guid isPermaLink="true">https://accidental.cc/notes/psf-zig/</guid><pubDate>Thu, 15 Sep 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;PSF font-file loading, into an easy to render format&lt;/p&gt;
&lt;p&gt;&lt;code&gt;buildFont&lt;/code&gt; takes a path to a font file, and returns a struct wrapping that
font with the ability to easily get an iterator of pixels over charactors.&lt;/p&gt;
&lt;p&gt;see https://www.win.tue.nl/~aeb/linux/kbd/font-formats-1.html&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;I&apos;ve been playing with a kernel, and wanted to be able to embed a font at &lt;code&gt;comptime&lt;/code&gt;;
so far, it&apos;s &lt;em&gt;kinda&lt;/em&gt; working, but this little library has been helpful.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-zig&quot;&gt;const std = @import(&quot;std&quot;);

/// PSF font-file loading, into an easy to render format
///
/// {buildFont} takes a path to a font file, and returns a struct wrapping that
/// font with the ability to easily get an iterator of pixels over charactors
///
/// @see https://www.win.tue.nl/~aeb/linux/kbd/font-formats-1.html

const PSF1_MAGIC: [2]u8 = .{ 0x36, 0x04 };
const PSF2_MAGIC: [4]u8 = .{ 0x72, 0xb5, 0x4a, 0x86 };

const PSF1_MODE_HAS512  = 0x01;
const PSF1_MODE_HASTAB  = 0x02;
const PSF1_MODE_HASSEQ  = 0x04;

/// build an iterator that can walk over the pixel data in a given PSFFont
/// iterates over single bits, aligning forward a bite when hitting the glyph
/// width.
///
/// user assumes responsibility for coordinating iteration in x/y coordinates,
/// at the row pitch level, no signal for &quot;end of row&quot; is provided.
fn PSFPixelIterator(comptime T: type) type {
    return struct {
        const Self = @This();

        font: *const T,
        glyph: u32,

        index: usize  = 0,          // the current index into the glyph byte array
        bitcount: u8  = 0,          // the number of bits we&apos;ve read out of the working glyph
        workglyph: u8 = undefined,  // the byte we&apos;re currently destructing to get bits

        /// Resets the iterator to the initial state.
        pub fn reset(self: *Self) void {
            self.resetIndex(0);
        }

        /// aligns to the next byte
        pub fn alignForward(self: *Self) void {
            if (self.bitcount &gt; 0) {
                self.resetIndex(self.index + 1);
            }
        }

        /// Returns whether the next pixel is set or not,
        /// or null if we&apos;ve read all pixels for the glyph
        pub fn next(self: *Self) ?bool {
            if (self.index &gt;= self.font.glyph_size)
                return null;

            defer {
                self.bitcount += 1;
                // todo: memorize the min? this happens on every iteration
                if (self.bitcount &gt;= std.math.min(8, self.font.glyph_width)) {
                    self.resetIndex(self.index + 1);
                }
            }

            return @shlWithOverflow(u8, self.workglyph, 1, &amp;#x26;self.workglyph);
        }

        // reset to the given index
        // used for full resets and byte-to-byte transitions
        fn resetIndex(self: *Self, index: usize) void {
            self.index    = index;
            self.bitcount = 0;

            // if we&apos;re about to roll out of the glyph, don&apos;t
            // otherwise, the last iteration (which would return null) panics for out-of-bounds
            if (index &amp;#x3C; self.font.glyph_size) {
                self.workglyph = self.font.glyphs[self.glyph][index];
            }
        }

    };
}

/// build a font struct from the given file
/// will cause a compile error if the file is not parsable as a PSF v1 or v2
pub fn buildFont(comptime path: []const u8) type {
    const file = @embedFile(path);

    if (std.mem.eql(u8, file[0..2], PSF1_MAGIC[0..2])) {
        return buildPSF1Font(file);
    }

    if (std.mem.eql(u8, file[0..4], PSF2_MAGIC[0..4])) {
        return buildPSF2Font(file);
    }

    @compileError(&quot;file isn&apos;t PSF (no matching magic)&quot;);
}

// options for the common PSF struct generator
const PSFHeaderMetrics = struct {
    file: []const u8,
    header_size:  u32,
    glyph_count:  u32,
    glyph_size:   u32,
    glyph_width:  u32,
    glyph_height: u32,
};

// given font metrics, generate a struct type which can read font glyphs at compile time
fn buildPSFCommon(comptime options: PSFHeaderMetrics) type {
    return struct {
        const Self          = @This();
        const PixelIterator = PSFPixelIterator(Self);

        // explicitly sized per the header file
        pub const Glyph     = [options.glyph_size]u8;
        pub const GlyphSet  = [options.glyph_count]Glyph;

        glyphs:       GlyphSet,
        // todo: unicode table

        glyph_count:  u32,
        glyph_width:  u32,
        glyph_height: u32,
        glyph_size:   u32,

        pub fn init() Self {
            // get a stream over the embedded file and skip the header
            var glyphStream = std.io.fixedBufferStream(options.file);
            glyphStream.seekTo(options.header_size) catch unreachable;

            comptime var index = 0;
            var data: GlyphSet = undefined;

            // then read every glyph out of the file into the struct
            // without the eval branch quota, compiler freaks out in read for backtracking
            @setEvalBranchQuota(100000);
            inline while(index &amp;#x3C; options.glyph_count) : (index += 1) {
                _ = glyphStream.read(data[index][0..]) catch unreachable;
            }

            return Self{
                .glyphs       = data,
                .glyph_count  = options.glyph_count,
                .glyph_width  = options.glyph_width,
                .glyph_height = options.glyph_height,
                .glyph_size   = options.glyph_size,
            };
        }

        pub fn pixelIterator(self: *const Self, glyph: u32) PixelIterator {
            var iter = PixelIterator{ .font = self, .glyph = glyph };
            iter.reset();

            return iter;
        }
    };
}

/// return a PSF2 font struct,
fn buildPSF2Font(comptime file: []const u8) type {
    var stream   = std.io.fixedBufferStream(file);
    var reader   = stream.reader();

    _                  = try reader.readIntLittle(u32); // magic (already validated)
    _                  = try reader.readIntLittle(u32); // version
    const header_size  = try reader.readIntLittle(u32);

    _                  = try reader.readIntLittle(u32); // flags (1 if unicode table)
    const glyph_count  = try reader.readIntLittle(u32);
    const glyph_size   = try reader.readIntLittle(u32);
    const glyph_height = try reader.readIntLittle(u32);
    const glyph_width  = try reader.readIntLittle(u32);

    return buildPSFCommon(.{
        .file         = file,
        .header_size  = header_size, // 8 u32 fields, = 32 bytes
        .glyph_count  = glyph_count,
        .glyph_size   = glyph_size,
        .glyph_width  = glyph_width,
        .glyph_height = glyph_height,
    });
}

fn buildPSF1Font(comptime file: []const u8) type {
    var stream   = std.io.fixedBufferStream(file);
    var reader   = stream.reader();

    _                  = try reader.readIntLittle(u16); // magic (already validated)
    const font_mode    = try reader.readIntLittle(u8);  // version
    const glyph_height = try reader.readIntLittle(u8);
    const glyph_count  = if (font_mode &amp;#x26; PSF1_MODE_HAS512 == 1) 512 else 256;

    return buildPSFCommon(.{
        .file         = file,
        .header_size  = 4,            // bytes
        .glyph_count  = glyph_count,  // always 256, unless 512 mode
        .glyph_size  = glyph_height, // because each row is always 1 byte, so it takes height bytes for a glyph
        .glyph_width  = 8,
        .glyph_height = glyph_height,
    });
}
&lt;/code&gt;&lt;/pre&gt;</content:encoded></item><item><title>nifty &quot;microgem&quot; pattern</title><link>https://accidental.cc/notes/nifty-microgem-pattern/</link><guid isPermaLink="true">https://accidental.cc/notes/nifty-microgem-pattern/</guid><pubDate>Thu, 09 Jun 2022 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;By having a &lt;code&gt;gemspec&lt;/code&gt; which &lt;em&gt;parses the yaml frontmatter of it&apos;s own &lt;code&gt;readme&lt;/code&gt;&lt;/em&gt;,
you can drive a &lt;code&gt;gemspec&lt;/code&gt; from a &lt;em&gt;really&lt;/em&gt; simple template, and get a nice small
footprint gem, hostable as a gist.&lt;/p&gt;
&lt;p&gt;Basically, I found out that since YAML frontmatter in a markdown file uses the
same separators as YAML itself for document separation (which I&apos;m certain was
on purpose), using &lt;code&gt;YAML.load_file&lt;/code&gt; on a markdown file will return the frontmatter!&lt;/p&gt;
&lt;p&gt;SO, define important parts of the gem in front matter, and take &lt;code&gt;README&lt;/code&gt; driven
development to the next level!&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;require &quot;yaml&quot;

header = YAML.safe_load_file(&quot;readme.md&quot;)
Gem::Specification.new do |spec|
  spec.name          = header[&quot;name&quot;]
  spec.version       = header[&quot;version&quot;]
  spec.authors       = [&quot;Jon Raphaelson&quot;]
  spec.email         = [&quot;jon@accidental.cc&quot;]

  spec.summary       = header[&quot;summary&quot;]
  spec.license       = &quot;MIT&quot;

  spec.files         = Dir.glob(&quot;**/*.rb&quot;, base: __dir__)
  spec.require_paths = [&quot;.&quot;]
end
&lt;/code&gt;&lt;/pre&gt;</content:encoded></item><item><title>Principles to build by</title><link>https://accidental.cc/notes/principles-to-build-by/</link><guid isPermaLink="true">https://accidental.cc/notes/principles-to-build-by/</guid><pubDate>Mon, 08 Jan 2018 18:07:00 GMT</pubDate><content:encoded>&lt;ul&gt;
&lt;li&gt;Over communicate.&lt;/li&gt;
&lt;li&gt;Err on the side of professionalism.&lt;/li&gt;
&lt;li&gt;Embrace scrutiny with confidence.&lt;/li&gt;
&lt;li&gt;Don&apos;t do anything by yourself.&lt;/li&gt;
&lt;li&gt;It doesn&apos;t exist if it&apos;s not written down, so get a receipt.&lt;/li&gt;
&lt;/ul&gt;</content:encoded></item><item><title>sitemaps_parser, a gem for parsing XML sitemaps</title><link>https://accidental.cc/notes/sitemaps-rb/</link><guid isPermaLink="true">https://accidental.cc/notes/sitemaps-rb/</guid><pubDate>Fri, 25 Mar 2016 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;a href=&quot;https://github.com/lygaret/sitemaps&quot;&gt;&lt;code&gt;sitemaps_parser&lt;/code&gt;&lt;/a&gt; is a simple gem for discovering, fetching and
parsing XML sitemaps according to the spec at &lt;a href=&quot;http://sitemaps.org&quot;&gt;sitemaps.org&lt;/a&gt;. There are a
ton of gems out there that can generate a sitemap file, but I couldn&apos;t find any that
supported parsing.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://img.shields.io/gem/v/sitemaps_parser.svg?maxAge=2592000&quot; alt=&quot;Current Version&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;require &apos;sitemaps&apos;

# parse a sitemap from a string
Sitemaps.parse(&quot;&amp;#x3C;xml ns=\&quot;...&quot;)

# fetch and parse a sitemap from a known url
sitemap = Sitemaps.fetch(&quot;http://termscout.com/sitemap.xml&quot;)

# fetch and parse sitemaps, excluding paths matching a filter, and limiting to the top 200
sitemap = Sitemaps.fetch(&quot;https://www.digitalocean.com/sitemaps.xml.gz&quot;, max_entries: 200) do |entry|
  entry.loc.path !~ /blog/i
end

# attempt to discover sitemaps for a site without a known sitemap location. Checks robots.txt and some common locations.
sitemap = Sitemaps.discover(&quot;https://www.digitalocean.com&quot;, max_entries: 200) do |entry|
  entry.loc.path !~ /blog/i
end

# sitemap usage
sitemap.entries.first
#&gt; Sitemaps::Entry(loc: &apos;http://example.com/page&apos;, lastmod: DateTime.utc, changefreq: :monthly, priority: 0.5)

urls = sitemap.entries.map(&amp;#x26;:loc)
#&gt; [&apos;http://example.com/page&apos;, &apos;http://example.com/page2, ...]
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Why?&lt;/h2&gt;
&lt;p&gt;I&apos;ve been working on a project at work lately that involves a lot of web
crawling. Given a domain, we crawl the site looking for information we can index:
sort of like a search engine, except we crawl on demand, rather than storing a huge
index perpetually. Our particular use-case involves finding a handful of &quot;important&quot;
pages to extract a specific kind of data - imagine a maps crawler trying to find the
locations page of a pizza chain, or a calendar for extracting events.&lt;/p&gt;
&lt;p&gt;There&apos;s an inherit trade-off in those requirements: finding &quot;important&quot; pages when
you don&apos;t know the structure of the site is ~~hard~~slow. I actually think it might
be impossible in general, given it&apos;s similarity to the Halting Problem, but even in
the relatively normal case, you have to crawl a good bit of the site before you can
say with confidence that you either found the most important pages or they&apos;re not
present. And since the only way that confidence goes up is to crawl more, the slower
the process gets. But when it&apos;s slow, it&apos;s less useful for the on-demand use-case.[^1]&lt;/p&gt;
&lt;p&gt;[^1]: Either it doesn&apos;t get used, or gets complained about endlessly ;)&lt;/p&gt;
&lt;h2&gt;Yay Sitemaps&lt;/h2&gt;
&lt;p&gt;Luckily for us, many sites implement XML sitemaps based on
&lt;a href=&quot;http://sitemaps.org&quot;&gt;the spec at sitemaps.org&lt;/a&gt;, which can be submitted to search engines to
help them better crawl your site for indexing. A sitemap presents a set of urls, with
metadata about frequency of updates, and indexing priority. That means that we can
make an initial pass over &lt;em&gt;all&lt;/em&gt; the urls a website advertises, trying to preselect
pages we might be interested before in we even start. If we don&apos;t find any urls that
look like they might be event pages, for example, we can even ignore the domain
altogether, or kick it to a background job.&lt;/p&gt;
&lt;p&gt;Unfortunately, there&apos;s no standard well-known location for a &lt;code&gt;sitemaps.xml&lt;/code&gt; to live
on a host. Sitemaps are usually submitted directly to a search engine, and while
there&apos;s some non-standard support for a &lt;code&gt;Sitemap:&lt;/code&gt; directive in
&lt;a href=&quot;https://en.wikipedia.org/wiki/Robots_exclusion_standard#Sitemap&quot;&gt;a &lt;code&gt;robots.txt&lt;/code&gt; file&lt;/a&gt;, in practice it&apos;s not used very often. That being said
there&apos;s some commonality: if not present in the &lt;code&gt;robots.txt&lt;/code&gt;, look in
&lt;code&gt;/sitemaps.xml&lt;/code&gt;, for example.[^hueristic]&lt;/p&gt;
&lt;p&gt;[^hueristic]: It&apos;s hard to tell if this is a good hueristic, since I have no idea what
percentage of sites actually have a sitemap that I can&apos;t find, but it&apos;s been
helpful so far.&lt;/p&gt;
&lt;h2&gt;The Gem&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;sitemaps_parser&lt;/code&gt; exists because I couldn&apos;t find anything else to do this. I&apos;m
attempting to keep dependencies small, with &lt;code&gt;activesupport&lt;/code&gt; as it&apos;s only required
dependency, though it supports &lt;code&gt;nokogiri&lt;/code&gt; as well, which significantly speeds up
parsing over &lt;code&gt;rexml&lt;/code&gt;. &lt;a href=&quot;http://www.rubyinside.com/ruby-xml-performance-benchmarks-1641.html&quot;&gt;REXML is a &lt;em&gt;dog&lt;/em&gt; in benchmarks&lt;/a&gt;[^3], but it&apos;s in
the standard library.&lt;/p&gt;
&lt;p&gt;So yeah, give it a try!&lt;/p&gt;
&lt;p&gt;[^3]: Yes, I understand that this benchmark is 8 years old, but it&apos;s what I could
find and anecdotally it&apos;s still that slow.&lt;/p&gt;</content:encoded></item><item><title>org-mode relative deadlines?</title><link>https://accidental.cc/notes/org-mode-relative-deadlines/</link><guid isPermaLink="true">https://accidental.cc/notes/org-mode-relative-deadlines/</guid><pubDate>Sat, 14 Nov 2015 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I have an org-mode tree that looks like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;* Schedule
** First Session &amp;#x3C;2016-01-15 Tue&gt;
*** TODO send introduction email
*** TODO write survey
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I would like to be able to add relative deadlines to the TODO items. Basically, something like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;*** TODO write survey
DEADLINE: -3w
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and then have that TODO show up in my agenda as if the deadline were &amp;#x3C;2016-01-05 Tue&gt; - 3 weeks. The goal is that when the date in the parent headline changes, the deadlines would move along with it.&lt;/p&gt;
&lt;p&gt;Is this possible? I know that the date picker for deadline supports default dates, but it&apos;s only used in the case of a date range.&lt;/p&gt;</content:encoded></item><item><title>Stars over Joshua Tree</title><link>https://accidental.cc/notes/stars-over-joshua-tree/</link><guid isPermaLink="true">https://accidental.cc/notes/stars-over-joshua-tree/</guid><pubDate>Thu, 15 Oct 2015 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/uToPIc5.jpg&quot; alt=&quot;Screenshot&quot;&gt;&lt;/p&gt;</content:encoded></item><item><title>link to github in org-mode</title><link>https://accidental.cc/notes/org-mode-github-links/</link><guid isPermaLink="true">https://accidental.cc/notes/org-mode-github-links/</guid><pubDate>Mon, 07 Sep 2015 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;a href=&quot;https://github.com/lygaret/emacs.d/blob/4c9ee66dc8407c0bfea789e59629f6260a431400/site-lisp/org-github-links.el&quot;&gt;org-github-links.el&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This is pretty much my first non-trivial elisp stuff; it lets you create links in org-mode to github repos, commits and issues, pretty much the same as Github Flavored Markdown allows:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;github:user/repo
github:user/repo@sha
github:user/repo#issue
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Being not that great with elisp (mostly just knowledge of what functions are available, etc), I&apos;d love critique and comment on this. Thanks!&lt;/p&gt;</content:encoded></item><item><title>digging my prompt</title><link>https://accidental.cc/notes/new-prompt/</link><guid isPermaLink="true">https://accidental.cc/notes/new-prompt/</guid><pubDate>Thu, 19 Feb 2015 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/HYUlzM2.png?1&quot; alt=&quot;my current zsh prompt&quot;&gt;&lt;/p&gt;</content:encoded></item><item><title>Marks + Scratchpad = Awesome!</title><link>https://accidental.cc/notes/i3-marks-scratchpad-awesome/</link><guid isPermaLink="true">https://accidental.cc/notes/i3-marks-scratchpad-awesome/</guid><pubDate>Sun, 28 Sep 2014 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;By creating bindings that set a mark on a window, you can manage individual windows in the scratchpad, and have bindings that hide/show a particular window.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;bindsym $mod+Shift+Mod4+0 mark &quot;alpha&quot;, move scratchpad
bindsym $mod+Mod4+0 [con_mark=&quot;alpha&quot;] scratchpad show
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With those two bindings, I can move a window into the scratchpad, but do so with the ability to explicitly call it back. I have the full number row set up that way, and also a bunch of assignments to do this to certain apps.&lt;/p&gt;
&lt;p&gt;With that, I can have what I&apos;m considering &quot;non-contextual&quot; windows: profanity (a chat client), spotify, etc.; and pull them up on whatever workspace I&apos;m working on, without the weird cycling that scratchpad does normally. For example, this is the full set of bindings for my spotify (which is launched by i3):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-i3&quot;&gt;bindsym $mod+Mod4+m [con_mark=&quot;music&quot;] scratchpad show
for_window [class=&quot;Spotify&quot;] mark &quot;music&quot;, move scratchpad
exec spotify
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I just figured this out, and thought I&apos;d share. Pretty sure it&apos;s not novel at all, but it&apos;s been really useful for me.&lt;/p&gt;</content:encoded></item><item><title>JSX Quali-Literal</title><link>https://accidental.cc/notes/jsx-quasiliteral/</link><guid isPermaLink="true">https://accidental.cc/notes/jsx-quasiliteral/</guid><pubDate>Wed, 09 Jul 2014 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;I&apos;ve been struggling to get the JSX transpiler playing nicely with the &lt;a href=&quot;https://github.com/google/traceur-compiler&quot;&gt;traceur compiler&lt;/a&gt;, specifically the flags hidden behind &lt;code&gt;--experimental&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The problem is that the since both the JSX transpiler and the traceur compiler are actually parsing the full javascript AST, they would have to mutually agree on the syntax extensions you use: traceur can&apos;t parse the faux-xml syntax JSX adds, and JSX can&apos;t parse the &lt;code&gt;async&lt;/code&gt; or &lt;code&gt;await&lt;/code&gt; keywords, for example, or generator functions.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://gist.github.com/lygaret/a68220defa69174bdec5#file-index-js&quot;&gt;This proof-of-concept is a potential solution&lt;/a&gt;: instead of using an external JSX transpiler, we&apos;ll parse the faux-xml ourselves, using an ES6 feature called &lt;a href=&quot;http://wiki.ecmascript.org/doku.php?id=harmony:quasis&quot;&gt;quasi-literals&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://gist.github.com/lygaret/a68220defa69174bdec5#file-index-js&quot;&gt;JSX Quasi-literal Gist&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Example&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;define(function(require) {

    var React   = require(&apos;react&apos;);
    var jsx     = require(&apos;lib/jsxquasi&apos;);

    var EchoComponent = React.createClass({
        getInitialState: function() {
            return { value: &apos;&apos; };
        },

        handleChange: function() {
            this.setState({ value: this.refs.input.getDOMNode().value });
        },

        render: function() {
            return jsx`
                &amp;#x3C;div&gt;
                    &amp;#x3C;input
                        ref=&apos;input&apos;
                        onChange=&apos;${this.handleChange}&apos;
                        defaultValue=&apos;${this.state.value}&apos; /&gt;
                    ${this.state.value}
                &amp;#x3C;/div&gt;
            `;
        }
    })

    return function() {
        var comp = jsx`&amp;#x3C;${EchoComponent} /&gt;`;
        React.renderComponent(comp, document.body);
    };
});

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A couple of things to notice:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;This is valid javascript! Or harmony or es6 or whatever, but importantly, it&apos;s not happening outside the js environment. This also allows us to use our standard tooling: the traceur compiler knows how to turn &lt;code&gt;jsx`&amp;#x3C;div&gt;Hello&amp;#x3C;/div&gt;`;&lt;/code&gt; into the equivalent browser compatible es3, and hence we can use anything the traceur compile accepts!&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;This is not exactly the same as JSX according to the spec: it includes quotes around the attributes, etc. This is because this parser is based on &lt;code&gt;DOMParser&lt;/code&gt;, and hence needs to be valid XML. It would be straighforward though to change it so it matched exactly, or to remove the browser dependency (so it could run on the server, eg.)&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;</content:encoded></item></channel></rss>