Snippets

HTML

Details & Summary

<details>
        <summary>People are a problem.</summary>
        <p>Anyone who is capable of getting themselves made President should on no account be allowed to do the job.</p>
</details>

Progressive Web App (PWA)

<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<link rel='icon' href='./icon.png'>
<!-- add to home screen for Safari on iOS. -->
<meta name='apple-mobile-web-app-capable' content='yes'>
<meta name='apple-mobile-web-app-status-bar-style' content='white'>
<meta name='apple-mobile-web-app-title' content='Drink?'>
<link rel='apple-touch-icon' href='./icon.png'>

JavaScript

Array

Array.prototype.last = function() {
        return this[ this.length - 1 ];
}
Array.prototype.sum = function() {
        return this.reduce( ( acc, i ) => acc + i, 0 );
}

LocalStorage

Storage.prototype.putValue = function( k, v ) {
        this.setItem( k, JSON.stringify( v ) );
}
Storage.prototype.getValue = function( k ) {
        return JSON.parse( this.getItem( k ) || 'null' );
};

String

String.prototype.toTitleCase = function() {
        return this.split( ' ' )
                   .map( word => `${word.charAt( 0 ).toUpperCase()}${word.slice( 1 )}` )
                   .join( ' ' );
}

CSS

Built-In Night Mode

:root {
        color-scheme: light dark;
}

Night Mode

:root {
        --background-color: white;
        --foreground-color: black;
}
@media (prefers-color-scheme: dark) {
    :root {
        --background-color: #1f1f1f;
        --foreground-color: #ddd;
    }
}
body {
        background: var(--background-color);
        color:      var(--foreground-color);
}

Grids

body {
        display:   grid;
        grid-gap:  10px;
        height:    100vh;
        margin:    0;

        grid-template-areas:
            "header  main  ."
            "nav     main  .";
        grid-template-columns:
            1fr 4fr 1fr;
        grid-template-rows:
            auto 1fr;
}
header {
        grid-area:   header;
        text-align:  center;
}
main {
        grid-area:   main;
        overflow-y:  scroll;
}
nav {
        grid-area:   nav;
        overflow-y:  scroll;
}

Web-Safe Fonts

/* serif */
font-family: Georgia, serif;
font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif;
font-family: "Times New Roman", Times, serif;

/* sans-serif */
font-family: Arial, Helvetica, sans-serif;
font-family: "Arial Black", Gadget, sans-serif;
font-family: "Comic Sans MS", cursive, sans-serif;
font-family: Impact, Charcoal, sans-serif;
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
font-family: Tahoma, Geneva, sans-serif;
font-family: "Trebuchet MS", Helvetica, sans-serif;
font-family: Verdana, Geneva, sans-serif;

/* monospace */
font-family: "Courier New", Courier, monospace;
font-family: "Lucida Console", Monaco, monospace;

Python

Argument Parsing

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--db', type=argparse.FileType('r'),
                required=True, help='path to db.yaml')
parser.add_argument('--output', type=argparse.FileType('w'),
                required=True, help='path to output HTML')
parser.add_argument('--enum', type=str, choices=('on', 'off'),
                required=True, help='generate on things or off things')
args = parser.parse_args()

Jinja2

environment = jinja2.Environment()
environment.filters['strip'] = lambda s: s.strip()
print(environment.from_string(TEMPLATE).render(
    snippets=snippets), file=args.output)

Go

net.Listen

var conn net.Listener
var err error
if *port != 0 {
        conn, err = net.Listen("tcp", fmt.Sprintf(":%v", *port))
} else if *socket != "" {
        _ = os.Remove(*socket)
        conn, err = net.Listen("unix", *socket)
        _ = os.Chmod(*socket, 0660)
}
if err != nil {
        log.Fatalf("failed to listen: %v", err)
}
defer conn.Close()

gorilla/websocket

pongTimout := 15*time.Second
pingPeriod := (pongTimeout / 9) * 10

conn, _, err := websocket.DefaultDialer.DialContext(ctx, uri, nil)
if err != nil {
        ...
}

conn.SetPongHandler(func(text string) error {
        return conn.SetReadDeadline(time.Now().Add(pongTimeout))
})

connectionClosed := make(chan struct{})
readChan := make(chan interface{})
go func() {
        defer close(connectionClosed)
        for {
                data := &ResponseObject{}
                if err := conn.ReadJSON(data); err != nil {
                        // pass the error down a channel, or log it, or something.
                        return  // closes connectionClosed, so the write loop also stops.
                }
                readChan <- data
        }
}()

writeChan := make(chan interface{})
go func() {
        ping := ticker.NewTicker(pingPeriod)
        defer ping.Stop()
        for {
                select {
                case data := <-writeChan:
                        if err := conn.WriteJSON(data); err != nil {
                                // handle error, etc etc.
                                return  // ends the pings, eventually ending the connection.
                        }
                case <-ping.C:
                        if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
                                // likewise handle the error somehow.
                                return  // ends the pings, eventually ending the connection.
                        }
                case <-connectionClosed:
                        conn.Close()
                        return
                }
        }
}()

text/template

{{ range $index, $item := $items }}
        {{ ( index $item 3 ).Timestamp | formatTimestamp }}
{{ end }}

C

Platform Macros

#if defined(__APPLE__)

#include <TargetConditionals.h>
#ifdef TARGET_OS_IPHONE
#endif

#elif defined(__linux__)

#else

#endif

SQL

variables that are tables

DECLARE @Cthulhu TABLE (name VARCHAR(8));

INSERT INTO @Cthulhu VALUES ('Cthulhu'), ('Cthulu'), ('Ktulu');

SELECT *
FROM Members
WHERE name NOT IN (SELECT * FROM @Cthulhu);