Skip to content

Instantly share code, notes, and snippets.

View clayadavis's full-sized avatar

Clayton A Davis clayadavis

View GitHub Profile
import sys
import io
def _text_encoding(encoding, stacklevel=2, /): # pragma: no cover
return encoding
try:
text_encoding = io.text_encoding
@clayadavis
clayadavis / dice.js
Last active August 10, 2021 18:12
Random die face
const d6 = () => String.fromCodePoint(0x2680 + Math.floor(Math.random() * 6))
function d6() {
const faceIdx = Math.floor(Math.random() * 6);
const codePoint = 0x2680 + faceIdx;
return String.fromCodePoint(codePoint)
}
@clayadavis
clayadavis / graphpaper.css
Created August 11, 2020 13:52
CSS graph paper
body {
background-size: 40px 40px;
background-image:
linear-gradient(to right, lightblue 1px, transparent 1px),
linear-gradient(to bottom, lightblue 1px, transparent 1px);
}
@clayadavis
clayadavis / entropy.py
Last active June 16, 2020 19:02
Compute entropy of a probability vector
import math
def entropy(vec):
norm = sum(vec)
p = (x / norm for x in vec)
return -sum(p_k * math.log(p_k) for p_k in p if p_k)
import numpy as np
def entropy(p):
function stringTruncator (numChars, buffer) {
buffer = buffer || 3
return function (str) {
return function (str) {
let cutoff = str.slice(0, numChars).lastIndexOf(' ')
if (cutoff === -1) cutoff = numChars
str = str.slice(0, cutoff) + '…'
}
return str
}
@clayadavis
clayadavis / botometer_flatten.py
Last active March 19, 2018 18:04
Flatten a botometer response
from collections import namedtuple
DataRow = namedtuple('DataRow', ['header', 'data'])
def flatten_botometer_result(result):
'''
Flattens a botometer response object.
Parameters:
result: A botometer result object
@clayadavis
clayadavis / backup_crontab.sh
Created March 15, 2018 18:21
Back up your crontab
#!/bin/bash
set -uo pipefail
IFS=$'\n\t'
if [[ $# -eq 0 ]]; then
echo "usage: $0 <target_directory>"
exit 1
fi
TARGET_DIR=$1
@clayadavis
clayadavis / list_iter.py
Last active August 13, 2021 17:26
Redis list iterator
def lrange_iter(r, key, N_max=None, step=10**5):
if N_max is None:
starts = itertools.count(step=step)
else:
starts = range(0, N_max, step)
for start in starts:
end = start + step - 1
if N_max is not None:
end = min(end, N_max - 1)
import math
from collections import namedtuple
def haversine_distance(origin, destination):
""" Haversine formula to calculate the distance between two lat/long points on a sphere """
radius = 6371 # FAA approved globe radius in km
dlat = math.radians(destination.lat-origin.lat)
dlon = math.radians(destination.lng-origin.lng)
@clayadavis
clayadavis / wiki_crawler.py
Created November 29, 2016 20:09
Wiki crawler
'''
(c)2016 Clayton A Davis
'''
import itertools
import random
import time
from html.parser import HTMLParser
from urllib.parse import urlparse, urljoin, unquote