publish backlog of things

master
osmarks 12 months ago
parent 78602eabd6
commit 95e84ceb80

@ -0,0 +1,50 @@
from PIL import Image
import numpy.fft as fft
import numpy as np
import random
import math
w, h = 512, 512
out = np.zeros((w, h, 3))
random.seed(4)
def operate_on_channel(n):
mask = np.full((w, h), 1)
midx, midy = w // 2, h // 2
J = 1
for x in range(midx - J, midx + J + 1):
for y in range(midy - J, midy + J + 1):
mask[x, y] = 0.5
"""
for x in range(w):
for y in range(h):
dist = (x - midx) ** 2 + abs(y - midy) ** 2
#if 1024 > dist > 4:
# mask[x, y] = 1
#mask[x, y] = math.sqrt(dist) / 500
if dist < 256: mask[x, y] = 1
"""
"""
for x in range(w):
for y in range(h):
mask[x, y] = random.uniform(0.7, 1)
"""
channel = fft.ifftshift(mask)
rfft = fft.ifft2(channel)
channel = np.abs(np.real(rfft))
#red2 = np.abs(np.imag(rfft))
#red = np.log(np.abs(np.real(red)))
#red = np.abs(mask)
channel = channel * (255 / np.max(channel))
#red2 = red2 * (255 / np.max(red2))
out[..., n] = channel
for i in range(3):
operate_on_channel(i)
out = Image.fromarray(out, "RGB")
out.save("/tmp/out.png")

@ -0,0 +1,27 @@
from PIL import Image
import numpy.fft as fft
import numpy as np
import random
import math
w, h = 512, 512
out = np.zeros((w, h, 3), dtype=np.uint8)
def bitstring(x): return f"{x:06b}"
def concat(l):
out = []
for m in l:
for n in m:
out.append(n)
return "".join(out)
for r in range(2**6):
for g in range(2**6):
for b in range(2**6):
a = concat(zip(*(bitstring(r), bitstring(g), bitstring(b))))
a = int(a, 2)
x, y = a & 0b111111111, a >> 9
out[x, y] = (r << 2, g << 2, b << 2)
out = Image.fromarray(out, "RGB")
out.save("/tmp/out.png")

@ -0,0 +1,69 @@
<!DOCTYPE html>
<input type="text" id="text">
<button id="send">do thing</button>
<button id="recv">do thing 2</button>
<canvas id="vis" style="width: 100%; height: 20em; "></canvas>
<script>
const ctx = new AudioContext()
const encoder = new TextEncoder()
const visCanvas = document.querySelector("#vis")
const transmit = bytes => {
const tones = Array.from(bytes).flatMap(x => [x >> 6, x >> 4 & 3, x >> 2 & 3, x & 3])
console.log(tones)
let pos = 0
const oscillator = ctx.createOscillator()
oscillator.connect(ctx.destination)
oscillator.start()
const interval = setInterval(() => {
const tone = tones[pos]
oscillator.frequency.value = [200, 400, 600, 800][tone]
pos++
if (pos == tones.length) {
oscillator.stop()
oscillator.disconnect()
clearInterval(interval)
}
}, 500)
}
const analyzer = ctx.createAnalyser()
//analyzer.smoothingTimeConstant = 0
const CWIDTH = 512
const CWIDTH_MINUS_ONE = 511
const cctx = visCanvas.getContext("2d")
let q = 0;
const visualizerLoop = () => {
const w = analyzer.frequencyBinCount
const frequencyData = new Uint8Array(w)
analyzer.getByteFrequencyData(frequencyData)
const im = cctx.getImageData(1, 0, CWIDTH, w)
let max = -1;
let maxIndex = -1;
for (let i = 0; i < w; i++) {
im.data[(i * CWIDTH + CWIDTH_MINUS_ONE) * 4 + 3] = 255
im.data[(i * CWIDTH + CWIDTH_MINUS_ONE) * 4 + 1] = frequencyData[i]
if (frequencyData[i] > max) {
max = frequencyData[i]
maxIndex = i
}
}
console.log((maxIndex + 1) / w * 24000)
cctx.putImageData(im, 0, 0)
q++
requestAnimationFrame(visualizerLoop)
}
document.querySelector("#send").addEventListener("click", () => {
transmit(encoder.encode(document.querySelector("#text").value))
})
document.querySelector("#recv").addEventListener("click", () => {
navigator.mediaDevices.getUserMedia({video: false, audio: true}).then(stream => {
console.log(stream)
const node = ctx.createMediaStreamSource(stream)
node.connect(analyzer)
visCanvas.height = analyzer.frequencyBinCount
visCanvas.width = CWIDTH
cctx.fillStyle = "black"
cctx.fillRect(0, 0, CWIDTH, analyzer.frequencyBinCount)
requestAnimationFrame(visualizerLoop)
})
})
</script>

@ -0,0 +1,78 @@
from fractions import Fraction
from functools import reduce
import sys
from math import floor
import random
def interpolate(points):
def mul_polys(p1, p2):
out = [0] * (len(p1) + len(p2) - 1)
for i1, c1 in enumerate(p1):
for i2, c2 in enumerate(p2):
out[i1 + i2] += c1 * c2
return out
def sum_polys(ps):
out = [0] * max(map(len, ps))
for p in ps:
for i, c in enumerate(p):
out[i] += c
return out
def basis(j):
px = points[j][0]
out = []
for x, y in points:
if x != px:
div = px - x
out.append([-Fraction(x, div), Fraction(1, div)])
return reduce(mul_polys, out)
out = []
for i, (x, y) in enumerate(points):
out.append([c * y for c in basis(i)])
return sum_polys(out)
def evaluate(poly, x):
y = 0
for c in reversed(poly):
y *= x
y += c
return y
indents = {"\t": 8, " ": 1, "": Fraction(2, 3), " ": 2, "": 4, "": Fraction(4, 3), "": 0}
def get_indent(line):
i = 0
e = 0
for j, c in enumerate(line):
if c in indents:
i += indents[c]
e = j + 1
else: break
return i, e
with open(sys.argv[1]) as tplfile:
counts = [ (lnum, get_indent(line)[0]) for lnum, line in enumerate(tplfile.readlines()) ]
counts = random.sample(counts, k=4)
poly = interpolate(counts)
lindents = [ (Fraction(size), char) for char, size in indents.items() if size != 0 ]
lindents.sort()
def gen_indent(n):
n = Fraction(abs(n))
out = ""
for (csize, cchar), (nsize, _) in zip(lindents, lindents[1:] + [(100000000000000, " ")]):
nmult = 0
while True:
nxt = nmult + nsize
if nxt <= n:
nmult = nxt
else: break
dif = floor((n - nmult) / csize)
n -= dif * csize
out += cchar * dif
return out
with open(sys.argv[2]) as infile:
for lnum, line in enumerate(infile.readlines()):
line = line[get_indent(line)[1]:]
print(gen_indent(evaluate(poly, lnum)) + line, end="")

@ -10,8 +10,8 @@ import struct
# disk instead of buffering it all in memory list this. But most sounds will fit in
# memory.
audio = []
sample_rate = 44100.0
sample_rate = 48000.0
phase = 0
def append_silence(duration_milliseconds=500):
num_samples = duration_milliseconds * (sample_rate / 1000.0)
@ -24,10 +24,12 @@ def append_sinewave(
freq=440.0,
duration_milliseconds=500,
volume=1.0):
global audio # using global variables isn't cool.
global phase
num_samples = duration_milliseconds * (sample_rate / 1000.0)
pc = math.tau * freq / sample_rate
for x in range(int(num_samples)):
audio.append(volume * math.sin(2 * math.pi * freq * ( x / sample_rate )))
phase += pc
audio.append(volume * math.sin(phase))
def append_squarewave(
freq=440.0,
@ -54,11 +56,10 @@ def save_wav(file_name):
wav_file.close()
return
#for _ in range(8):
# append_sinewave(volume=1.0, freq=1000.0)
# append_silence()
append_sinewave(freq=500, duration_milliseconds=500)
append_sinewave(freq=1000, duration_milliseconds=500)
append_sinewave(freq=2000, duration_milliseconds=500)
append_sinewave(freq=500, duration_milliseconds=500)
save_wav("output.wav")
import random
freq = 6
for i in range(160):
append_sinewave(volume=1.0, freq=math.exp(freq), duration_milliseconds=50)
freq += random.uniform(-0.2, 0.2)
freq = max(4.5, min(freq, 9))
save_wav("output.wav")

@ -0,0 +1,35 @@
import sqlite3, pyperclip, os.path, subprocess, sys
conn = sqlite3.connect(os.path.expanduser("~/.local/share/clipstack.sqlite3"))
conn.executescript("""CREATE TABLE IF NOT EXISTS stack (pos INTEGER PRIMARY KEY, data BLOB NOT NULL)""")
def push(data):
c = conn.cursor()
c.execute("SELECT max(pos) FROM stack")
res = c.fetchone()[0]
if res == None: nxt = 0
else: nxt = res + 1
c.execute("INSERT INTO stack VALUES (?, ?)", (nxt, data))
conn.commit()
def pop():
c = conn.cursor()
c.execute("SELECT * FROM stack ORDER BY pos DESC LIMIT 1")
res = c.fetchone()
if not res: return
pos, data = res
c.execute("DELETE FROM stack WHERE pos = ?", (pos,))
return data
conn.commit()
mode = sys.argv[1]
if mode == "push":
proc = subprocess.run(["xclip", "-selection", "clipboard", "-o"], stdout=subprocess.PIPE)
if proc.returncode == 0:
push(proc.stdout)
print("push")
elif mode == "pop":
data = pop()
if data:
proc = subprocess.run(["xclip", "-selection", "clipboard"], input=data)
print("pop")

@ -0,0 +1,254 @@
<style>
* { box-sizing: border-box;; }
#disp .cell {
width: 32px;
height: 32px;
display: inline-block;
font-family: monospace;
position: relative;
}
.cell img {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
image-rendering: crisp-edges;
image-rendering: pixelated;
}
.cell.selected {
background: yellow;
}
</style>
<div id="disp"></div>
<div id="controls">
<select id="interactmode">
<option selected>select</option>
<option>rotate</option>
<option>place drill</option>
<option>place belt</option>
<option>place inserter</option>
</select>
<button id="step">run step</button>
</div>
<script>
const noiseSeed = Math.random() * (2**32-1)
const hash = (str, seed = 0) => {
let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i)
h1 = Math.imul(h1 ^ ch, 2654435761)
h2 = Math.imul(h2 ^ ch, 1597334677)
}
h1 = Math.imul(h1 ^ (h1>>>16), 2246822507) ^ Math.imul(h2 ^ (h2>>>13), 3266489909)
h2 = Math.imul(h2 ^ (h2>>>16), 2246822507) ^ Math.imul(h1 ^ (h1>>>13), 3266489909)
return 4294967296 * (2097151 & h2) + (h1>>>0)
}
const normalize = ([x, y]) => [x / Math.hypot(x, y), y / Math.hypot(x, y)]
const dot = ([a, b], [c, d]) => a*c+b*d
const cartesianProduct = (xs, ys) => xs.flatMap(x => ys.map(y => [x, y]))
const gradients = cartesianProduct([-1, -0.5, 0.5, 1], [-1, -0.5, 0.5, 1]).map(normalize)
const gradientFor = (x, y) => gradients[hash(x+"."+y, noiseSeed) % gradients.length]
const interpolate = (a0, a1, w) => (a1 - a0) * (3.0 - w * 2.0) * w * w + a0
const perlin = (x, y) => {
const i = Math.floor(x), j = Math.floor(y)
const u = x - i, v = y - j
const n00 = dot(gradientFor(i, j), [u, v])
const n01 = dot(gradientFor(i + 1, j), [u - 1, v])
const n10 = dot(gradientFor(i, j + 1), [u, v - 1])
const n11 = dot(gradientFor(i + 1, j + 1), [u - 1, v - 1])
return interpolate(interpolate(n00, n01, u), interpolate(n10, n11, u), v)
}
const disp = document.querySelector("#disp")
let interactMode = document.querySelector("#interactmode").value
document.querySelector("#interactmode").addEventListener("input", ev => {
interactMode = ev.target.value
console.log(interactMode)
})
const directions = {
0: [0, 1],
1: [-1, 0],
2: [0, -1],
3: [1, 0]
}
const arrows = "→↓←↑"
const grid = {}
const SIZE = 24
for (let x = 0; x < SIZE; x++) {
for (let y = 0; y < SIZE; y++) {
let thing = { type: "empty", direction: 0, x, y }
thing.mapNoise = perlin(x * 3 / SIZE, y * 3 / SIZE)
grid[x+"."+y] = thing
}
}
const noises = Object.values(grid).map(x => x.mapNoise)
noises.sort((a, b) => a - b)
const thresh1 = noises[Math.floor(noises.length * (6/7))]
const thresh2 = noises[Math.ceil(noises.length * (1/12))]
for (const cell of Object.values(grid)) {
if (cell.mapNoise > thresh1) {
cell.type = "ore1"
} else if (cell.mapNoise < thresh2) {
cell.type = "ore2"
}
}
const adjacentAt = (x, y, d) => {
const dir = directions[d]
const nx = x + dir[0], ny = y + dir[1]
return grid[nx+"."+ny]
}
let updateOrder
const itemHandlers = ["drill", "belt"]
const recomputeBelts = () => {
for (const cell of Object.values(grid)) {
delete cell.inext
delete cell.iprev
if (itemHandlers.includes(cell.structure)) {
cell.inext = adjacentAt(cell.x, cell.y, cell.direction)
if (cell.inext) cell.inext.iprev = cell
}
}
for (const cell of Object.values(grid)) {
if (cell.inext) {
if (!cell.iprev) { // root of tree thing
let order = 0
let visited = new Set()
let current = cell
while (current && !visited.has(current) && itemHandlers.includes(current.structure)) {
if (current.order === undefined || current.order < order) {
current.order = order
}
order++
visited.add(current)
current = current.inext
}
}
}
}
const iorder = []
for (const cell of Object.values(grid)) {
if (cell.order !== undefined) {
iorder[cell.order] ||= []
iorder[cell.order].push(cell)
}
}
updateOrder = [].concat(...iorder).reverse()
}
const update = () => {
recomputeBelts()
for (const cell of Object.values(grid)) {
if (cell.type === "inserter") {
}
}
for (const cell of updateOrder) {
if (cell.structure === "drill") {
cell.item = cell.type
}
if (cell.inext && !cell.inext.item) {
if (cell.item) {
cell.inext.item = cell.item
cell.item = null
}
}
}
render()
}
document.querySelector("#step").addEventListener("click", () => {
update()
})
const rotate = (d, e) => (d + e) % 4
const render = () => {
while (disp.firstChild) disp.removeChild(disp.firstChild)
for (let y = 0; y < SIZE; y++) {
for (let x = 0; x < SIZE; x++) {
const cell = document.createElement("span")
cell.id = x+"."+y
cell.classList.add("cell")
const thing = grid[x+"."+y]
const type = thing.type
const layers = []
layers.push("blank")
if (type === "empty") {
} else if (type.startsWith("ore")) {
layers.push({ sprite: type, rotation: hash(cell.id) % 4 })
if (thing.structure === "drill") {
layers.push("drill")
}
}
if (thing.structure === "belt") {
const isInboundBelt = side => {
const newCell = adjacentAt(x, y, rotate(thing.direction, side))
return newCell && newCell.structure === "belt" && newCell.direction == rotate(thing.direction, rotate(side, 2))
}
const left = isInboundBelt(1), back = isInboundBelt(2), right = isInboundBelt(3)
if (left && !back) {
layers.push({ sprite: "belt-corner", reflect: true, rotation: 3 })
if (right) { layers.push("belt-conn") }
}
else if (right && !back) { layers.push({ sprite: "belt-corner", rotation: 1 }) }
else {
layers.push("belt")
if (right) { layers.push("belt-conn") }
if (left) { layers.push({ sprite: "belt-conn", reflect: true }) }
console.log(x, y, right, left)
}
if (thing.item) {
layers.push({ sprite: thing.item, scale: 0.5 })
}
}
if (thing.structure === "inserter") {
console.log("inserter")
layers.push("inserter-base")
layers.push("inserter-arm")
}
if (thing.selected) {
cell.classList.add("selected")
}
for (const layer of layers) {
const im = document.createElement("img")
im.src = `/sprites/${typeof layer === "string" ? layer : layer.sprite}.png`
const transforms = []
if (layer.rotation) { transforms.push(`rotate(${layer.rotation * 90}deg)`) }
if (layer.reflect) { transforms.push(`scaleX(-1)`) }
if (layer.scale) { transforms.push(`scale(${layer.scale})`) }
const transformString = transforms.join(" ")
if (transformString) { im.style.transform = transformString }
cell.appendChild(im)
}
cell.style.transform = `rotate(${thing.direction * 90}deg)`
disp.appendChild(cell)
}
disp.appendChild(document.createElement("br"))
}
}
disp.addEventListener("click", ev => {
const cell = ev.target.parentElement.id
console.log(grid[cell], cell)
if (interactMode === "select") {
grid[cell].selected ^= 1
} else if (interactMode === "place drill") {
if (grid[cell].type.startsWith("ore")) {
grid[cell].structure = "drill"
}
} else if (interactMode === "place belt") {
grid[cell].structure = "belt"
} else if (interactMode === "place inserter") {
grid[cell].structure = "inserter"
} else if (interactMode === "rotate") {
grid[cell].direction++
grid[cell].direction %= 4
}
ev.preventDefault()
render()
})
render()
</script>

@ -0,0 +1,48 @@
import os, csv, re, itertools, numpy, collections, json
rawbuffer = bytearray()
with open("/tmp/input.csv") as f:
r = csv.reader(f)
for row in r:
channel, timestamp, message, _ = row
message = re.sub("<@!?[0-9]+>", "", message)
message = re.sub("<:([A-Za-z0-9_-]+):[0-9]+>", lambda match: match.group(1), message)
rawbuffer += (message.strip() + " ").encode("utf-8")
#print(rawbuffer.count(b"\x0f"))
#raise SystemExit()
print(len(rawbuffer))
buffer = numpy.array(rawbuffer, dtype=numpy.uint16)
dc = {}
for newindex in range(256, 1024):
freqs = collections.Counter(zip(buffer, buffer[1:]))
(fst, snd), count = freqs.most_common(1)[0]
print(newindex, count, repr(chr(fst)), repr(chr(snd)))
dc[newindex] = int(fst), int(snd)
pending = False
newbuffer = numpy.zeros_like(buffer)
z = 0
for code in buffer:
if pending:
if code == snd:
newbuffer[z] = newindex
z += 1
pending = False
continue
else:
newbuffer[z] = fst
z += 1
pending = False
if code == fst:
pending = True
else:
newbuffer[z] = code
z += 1
buffer = newbuffer[:z]
with open("compr.json", "w") as f:
json.dump({
"dicts": dc,
"frequencies": dict(collections.Counter(map(int, buffer)))
}, f, separators=",:")

@ -0,0 +1,158 @@
# Programs are to validate JSON according to the JSON spec (https://www.json.org/), with the exception that you may assume that the string will consist entirely of the classic printable ASCII characters (codepoints 32-127, horizontal tabs, and newlines).
# You may additionally assume that the input will not be nested more than 16 levels.
def entry(string):
if string == "":
return True
elif string[0] == '{':
return entry_object(string)
elif string[0] == '[':
return entry_array(string)
elif string[0] == '"':
return entry_string(string)
elif string[0] in '-0123456789':
return entry_number(string)
elif string[0] == 't':
return entry_true(string)
elif string[0] == 'f':
return entry_false(string)
elif string[0] == 'n':
return entry_null(string)
else:
return False
def entry_object(string):
if string[0] != '{':
return False
string = string[1:]
if string[0] == '}':
return True
while True:
if not entry_string(string):
return False
if not entry_colon(string):
return False
if not entry(string):
return False
if string[0] == '}':
return True
if not entry_comma(string):
return False
def entry_array(string):
if string[0] != '[':
return False
string = string[1:]
if string[0] == ']':
return True
while True:
if not entry(string):
return False
if string[0] == ']':
return True
if not entry_comma(string):
return False
def entry_string(string):
if string[0] != '"':
return False
string = string[1:]
while True:
if string[0] == '"':
return True
if string[0] == '\\':
string = string[1:]
if string[0] == 'u':
string = string[1:]
if not string[0] in '0123456789abcdef':
return False
string = string[1:]
if not string[0] in '0123456789abcdef':
return False
string = string[1:]
if not string[0] in '0123456789abcdef':
return False
string = string[1:]
if not string[0] in '0123456789abcdef':
return False
string = string[1:]
elif string[0] == '"':
pass
elif string[0] == '\\':
pass
elif string[0] == '/':
pass
elif string[0] == 'b':
pass
elif string[0] == 'f':
pass
elif string[0] == 'n':
pass
elif string[0] == 'r':
pass
elif string[0] == 't':
pass
else:
return False
else:
string = string[1:]
def entry_number(string):
if string[0] not in '-0123456789':
return False
string = string[1:]
if string[0] == '.':
string = string[1:]
if string[0] not in '0123456789':
return False
string = string[1:]
if string[0] in 'eE':
string = string[1:]
if string[0] in '+-':
string = string[1:]
if string[0] not in '0123456789':
return False
string = string[1:]
if string[0] not in '0123456789':
return False
string = string[1:]
return True
def entry_colon(string):
if string[0] != ':':
return False
string = string[1:]
return True
def entry_comma(string):
if string[0] != ',':
return False
string = string[1:]
return True
def entry_true(string):
if string[0:4] != 'true':
return False
string = string[4:]
return True
def entry_false(string):
if string[0:5] != 'false':
return False
string = string[5:]
return True
def entry_null(string):
if string[0:4] != 'null':
return False
string = string[4:]
return True
def main():
string = input()
if entry(string):
print("Valid JSON")
else:
print("Invalid JSON")
if __name__ == "__main__":
main()

@ -0,0 +1,117 @@
# Programs are to validate JSON according to the JSON spec (https://www.json.org/), with the exception that you may assume that the string will consist entirely of the classic printable ASCII characters (codepoints 32-127, horizontal tabs, and newlines).
# You may additionally assume that the input will not be nested more than 16 levels.
def entry(string):
string = string.strip()
if len(string) == 0:
return True
if string[0] == '{':
return object(string)
elif string[0] == '[':
return array(string)
elif string[0] in '-0123456789':
return number(string)
elif string[0] == '"':
return string(string)
else:
return False
def object(string):
if string[0] != '{':
return False
string = string[1:]
if string[0] == '}':
return True
string = string.strip()
if string[0] != '"':
return False
string = string[1:]
if string[0] != ':':
return False
string = string[1:]
string = string.strip()
if not entry(string):
return False
string = string.strip()
if string[0] == '}':
return True
if string[0] != ',':
return False
string = string[1:]
string = string.strip()
if not object(string):
return False
string = string.strip()
if string[0] != '}':
return False
return True
def array(string):
if string[0] != '[':
return False
string = string[1:]
if string[0] == ']':
return True
string = string.strip()
if not entry(string):
return False
string = string.strip()
if string[0] == ']':
return True
if string[0] != ',':
return False
string = string[1:]
string = string.strip()
if not array(string):
return False
string = string.strip()
if string[0] != ']':
return False
return True
def number(string):
if string[0] not in '-0123456789':
return False
string = string[1:]
if string[0] == '.':
string = string[1:]
if string[0] not in '0123456789':
return False
string = string[1:]
while string[0] in '0123456789':
string = string[1:]
if string[0] not in '0123456789':
return False
string = string[1:]
if string[0] not in 'eE':
return False
string = string[1:]
if string[0] not in '+-':
return False
string = string[1:]
if string[0] not in '0123456789':
return False
string = string[1:]
while string[0] in '0123456789':
string = string[1:]
return True
def string(string):
if string[0] != '"':
return False
string = string[1:]
while string[0] != '"':
if string[0] == '\\':
string = string[1:]
if string[0] not in '"\\/bfnrt':
return False
string = string[1:]
else:
string = string[1:]
return True
def main():
string = input()
print(entry(string))
if __name__ == "__main__":
main()

File diff suppressed because one or more lines are too long

@ -0,0 +1,95 @@
import json, numpy, math, functools, base64
real_bped = numpy.frombuffer(base64.b64decode('ZQAgAHQAIABzACAAdABoAGkAbgBkACAAZQByAGEAbgB5ACAAbwAgAG8AbgAgACAAbwB1AG8AcgBnACAAZQBuAGEAbAAEAQ4BYQAgAHIAZQBhAHIAaQACASAAAwF0AAkBcwB0AGkAAQFpAHQAbwBtAGEAdAAgAHcAe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IPAWcAdwAAAU8BbAClAXQAaQFwAGEAdQBtAGUBdAARARMBBQFoAEABawEJAW8AWAF8AHwAjgGOAeIAjgCJA5UACwIVAmIAaQBFAWYCYgBsAHAAPAEWAUsBaQEtAv4CUQG3AcoBaAAVAXMCiwA9AccCbQAQAWkAGAEvAUcDRQEAAWsAJwEHAQgB8QIpAasBqwFiAOECEQEuATUBYwBiAHkAdgAgAGcACQEHA7UCXQAgACgBbwETAS8ByQE2AbkBdQJvADgBEwEAAUoCMgEYAWQAngEHASoBFAEJAoEBFwEuAR0BcgDaAXMAawF1Ar4CIQFsABsCBAIgAHMAGgIqAccBbgAaAosBZAC8AhIBaAASARABqwI2ADgALAEsAXUAAgHiALUAwwOXAIkB4QEyADAAZQAiAWsBgAFVAbICYgBzAI8BAAEPATUBbwBRAQ8B8wEGARwBbQAqAnQBAgFjAGQAYQAEAR0BAAE7ACAA3AEpAWQAmAEHAXQAzgEyAYkBIAFoAQUBdwCfAo0DcwF5ADICrQFUAWIAbAEtACAAQgFPASUBLgEUAQgBZgBpAfIBNgErAW4AYQBBARYBDAJiACkBdgARARoBEQFkACkBdQFwALsBAgFvADIB/AI8ATQBYwBEARQBQQJBAngCeAKEApECKwECAb8DCAF0AGkBcwBsAGMCCAF3AGEA1QEAAUcBUQHdATIB'), dtype=numpy.uint32)
bped_inv = {}
for i in range(256, 1024):
x = real_bped[i - 256]
a, b = x & 0xFFFF, x >> 16
bped_inv[a, b] = i
N_bits = 14
X_bits = 2 ** N_bits
mask = X_bits - 1
qfreqs = numpy.frombuffer(base64.b64decode('AQEBAQEBAQEBAUwBAQEBAQEBAQEBAQEBAQEBAQEBAQGyDTEUDwoKMko0ECE3RFY6N0tFNjctJTA4LxwXGSMeFAQsGB8WIRERDycNFxchEhweBR0jHwsKDQkHBioKIw0vLWd8pH6MbW9qciJPU2JjSYkJYaGdVDxJM0giEwwTDAECBQQEBgEBAgICAwUJAgEBAQIBAgQCAQMEAgEBAQEBBAIBBAECAgQBBgEBAg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FBgYBBQQFAQUFBQYFBQYGBgUGBQUEBQUGBQQFBQYFBgUFBQUGBQUFBQUFBQYGBgYFBQYEBQQFBQIDBQYFBQUFBQUEBQ=='), dtype=numpy.uint8)
cdf = numpy.insert(numpy.cumsum(qfreqs, dtype=numpy.uint16), 0, 0)
@functools.cache
def icdf(y):
for i, x in enumerate(cdf):
if y < x: return i - 1
def decompress_bpe(s):
s = numpy.array(s, dtype=numpy.uint16)
while True:
r = numpy.zeros(len(s) * 2, dtype=numpy.uint16)
z = 0
for c in s:
if c > 255:
x = real_bped[c - 256]
a, b = x & 0xFFFF, x >> 16
r[z] = a
z += 1
r[z] = b
z += 1
else:
r[z] = c
z += 1
if z == len(s): break
s = r[:z]
return bytes(s.astype(numpy.uint8))
def compress_bpe(s):
s = numpy.array(bytearray(s), dtype=numpy.uint16)
while True:
r = numpy.zeros_like(s)
z = 0
used = False
for pair in zip(s, s[1:]):
if used:
used = False
else:
mp = bped_inv.get(pair)
if mp:
r[z] = mp
z += 1
used = True
else:
r[z] = pair[0]
z += 1
used = False
if not used:
r[z] = s[-1]
z += 1
if z == len(s): break
s = r[:z]
return s
def compress_ans(bpes):
def C(x, s):
s_count = int(qfreqs[s])
return (x // s_count) * X_bits + int(cdf[s]) + (x % s_count)
x = 1
for symbol in bpes:
x = C(x, symbol)
return len(bpes), x
def decompress_ans(ilen, num):
def D(x):
slot = x & mask
sym = icdf(slot)
prev_state = (x // X_bits) * int(qfreqs[sym]) + slot - int(cdf[sym])
return sym, prev_state
x = num
syms = []
for _ in range(ilen):
sym, x = D(x)
syms.append(sym)
syms.reverse()
return syms
def compress(s):
l, x = compress_ans(compress_bpe(s))
return l.to_bytes(4, "little") + x.to_bytes(math.ceil(x.bit_length() / 8), "little")
def decompress(s):
l, x = s[:4], s[4:]
return decompress_bpe(decompress_ans(int.from_bytes(l, "little"), int.from_bytes(x, "little")))

@ -0,0 +1,366 @@
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <complex.h>
#include <string.h>
#include <stdlib.h>
#define nfibs 93
#define what int64_t
#define the fibs
#define fuck [
#define did nfibs
#define you ]
#define just =
#define fucking {
#define say 0
#define about ,
#define me 1
#define YOU ,
#define little 0
#define bitch }
#define i ;
#define ll void
#define have initf
#define YoU (
#define know )
#define I {
#define graduated for
#define top (
#define of int
#define my k
#define class =
#define in 2
#define tHe ;
#define navy k
#define seals <
#define and nfibs
#define ve k
#define been ++
#define involved )
#define In {
#define numerous fibs
#define secret [
#define raids k
#define on ]
#define al_quaeda =
#define anD fibs
#define i_ [
#define haVE k
#define over -
#define three 1
#define hundred ]
#define confirmed +
#define kills fibs
#define am k
#define trained -
#define gorilla ]
#define warfare ;
#define aNd }
#define I_ }
#define m bool
#define thE iusol
#define TOp [
#define sniper nfibs
#define IN ]
#define THE =
#define entire {
#define us 0
#define armed }
#define forces ;
#define yoU int
#define are bsectf
#define nothing (
#define to int64_t
#define Me n
#define but ,
#define JUsT int
#define another aa
#define target ,
#define i__ int
#define will b
#define wipe )
#define YOu {
#define The while
#define FuCK (
#define out aa
#define with <
#define precision b
#define THe )
#define likes {
#define which mid
#define has =
#define never (
#define BEEN aa
#define seen +
#define before b
#define ON )
#define this >>
#define earth 1
#define mark ;
#define My if
#define fuCkINg (
#define words fibs
#define yOu [
#define think mid
#define can <
#define get n
#define away )
#define With {
#define saying aa
#define that =
#define shit mid
#define TO +
#define ovEr ;
#define ThE }
#define internet else
#define Think {
#define again b
#define fucker =
#define as mid
#define we ;
#define speak }
#define aM return
#define contacting aa
#define MY ;
#define SecrEt }
#define network int
#define oF sumf
#define spies (
#define across int64_t
#define tHE trg
#define usa )
#define aND {
#define your int
#define ip pt
#define is =
#define being bsectf
#define traced (
#define right trg
#define now ,
#define so 0
#define yOU ,
#define better nfibs
#define prepare )
#define FOr ;
#define the_ if
#define storm (
#define maggot fibs
#define ThE_ [
#define STorm pt
#define THAT ]
#define wipes ==
#define ouT trg
#define pathetic {
#define LitTLe iusol
#define thing [
#define You pt
#define call ]
#define yOur =
#define life true
#define you_ ;
#define re return
#define FuCKINg 1
#define dead ;
#define kid }
#define I__ for
#define CAN (
#define be int
#define anywhere k
#define anytime =
#define And pt
#define i___ -
#define cAN 1
#define kill ;
#define You_ k
#define iN >
#define OvER 1
#define seven ;
#define hUndred k
#define ways --
#define AND )
#define tHat {
#define s if
#define jusT (
#define WitH iusol
#define mY [
#define bare k
#define hands ]
#define not )
#define only continue
#define AM ;
#define I___ iusol
#define extensively [
#define trAInEd k
#define unarmed =
#define combat true
#define bUT ;
#define i____ if
#define Have (
#define access sumf
#define tO (
#define eNtIRe -
#define arsenal fibs
#define Of [
#define THE_ k
#define united ]
#define states )
#define marine )
#define corps return
#define ANd 1
#define WILl iusol
#define use [
#define it k
#define To ]
#define its =
#define full false
#define extent ;
#define to_ }
#define WiPe return
#define YoUR 0
#define miserable ;
#define ass }
#define off long
#define tHE_ *
#define face f
#define OF (
#define tHe_ int64_t
#define continent trg
#define LIttle int
#define ShIT *
#define iF length
#define OnLY )
#define could if
#define hAvE (
#define known fibs
#define whAt [
#define unholy 2
#define retribution ]
#define YouR ==
#define clever )
#define comment initf
#define was (
#define aBout )
#define To_ ;
#define bring memset
#define down (
#define upon iusol
#define maybe 0
#define would nfibs
#define hAVE )
#define held ;
#define YOUR sumf
#define FUCkIng (
#define tongue trg
#define buT )
#define couldn *
#define t length
#define YoU_ =
#define didn 0
#define T ;
#define AnD for
#define NOw (
#define RE k
#define paying =
#define The_ 0
#define price ;
#define YOU_ k
#define goddamn <
#define idiot nfibs
#define wiLl k
#define shIT ++
#define fury )
#define all {
#define OVEr if
#define and_ iusol
#define wilL k
#define drown ]
#define in_ )
#define iT {
#define Re *
#define FuCkING length
#define DEad )
#define kiddo ++
#define WhAT ;
#define f___ }
#define DID int
#define yOU_ j
#define f___ing 0
#define type ;
#define AbOuT long
#define ME *
#define yOu_ out
#define lITTLe =
#define bitcH calloc
#define I____ (
#define Ll *
#define HAVe length
#define Know sizeof
#define gRADUaTED uint64_t
#define ToP )
#define of_ )
#define CLaSs for
#define at (
#define mit int
#define aNd_ k
#define i_____ =
#define Ve 0
#define bEEN ;
#define INVoLVED k
#define IN_ <
#define NUmeRouS nfibs
#define secreT ;
#define wITH ++
#define anonymous )
#define HAve (
#define oVer iusol
#define threE [
#define hUNdReD k
#define coNfIRMEd ]
#define ddoses )
#define Am out
#define trAined [
#define In_ j
#define online ]
#define trolling =
#define anD_ k
#define M j
#define thE_ ++
#define tOp ;
#define hacker }
#define iN_ }
#define THe_ return
#define ENTirE out
#define world ;
#define YOu_ }
#define aRe int
#define NOthinG main
#define mE )
#define BUt {
#define juSt initf
#define AnotHER (
#define virus )
#define host ;
#define WilL (
#define wIpE int
#define yoU_ k
#define F___ 0
#define oUt ;
#define wITh k
#define PReCiSiON <
#define the__ 100
#define LIKeS ;
#define oF_ k
#define WHICH ++
#define Has )
#define nevEr {
#define BeEN sumf
#define sEen (
#define befoRE 1
#define InTeRNET sumf
#define mArK (
#define my_ 2
#define f___Ing )
#define wORds ;
#define ThinK }
what the fuck did you just fucking say about me YOU little bitch i ll have YoU know I graduated top of my class in tHe navy seals and i ve been involved In numerous secret raids on al_quaeda anD i_ haVE over three hundred confirmed kills i_ am trained in gorilla warfare aNd I_ m thE TOp sniper IN THE entire us armed forces yoU are nothing to Me but JUsT another target i__ will wipe YOu The FuCK out with precision THe likes of which has never BEEN seen before ON this earth mark My fuCkINg words yOu think you can get away With saying that shit TO me ovEr ThE internet Think again fucker as we speak I_ aM contacting MY SecrEt network oF spies across tHE usa aND your ip is being traced right now so yOU better prepare FOr the_ storm maggot ThE_ STorm THAT wipes ouT THe pathetic LitTLe thing You call yOur life you_ re FuCKINg dead kid I__ CAN be anywhere anytime And i___ cAN kill You_ iN OvER seven hUndred ways AND tHat s jusT WitH mY bare hands not only AM I___ extensively trAInEd IN unarmed combat bUT i____ Have access tO tHE eNtIRe arsenal Of THE_ united states marine corps ANd i WILl use it To its full extent to_ WiPe YoUR miserable ass off tHE_ face OF tHe_ continent yOU LIttle ShIT iF OnLY YOu could hAvE known whAt unholy retribution YouR little clever comment was aBout To_ bring down upon yOU maybe YOU would hAVE held YOUR FUCkIng tongue buT you_ couldn t YoU_ didn T AnD NOw yoU RE paying The_ price YOU_ goddamn idiot i wiLl shIT fury all OVEr YoU and_ yOu wilL drown in_ iT YoU Re FuCkING DEad kiddo WhAT ThE f___ DID yOU_ just f___ing type AbOuT ME yOu_ lITTLe bitcH I____ Ll HAVe yOU Know I____ gRADUaTED ToP of_ MY CLaSs at mit aNd_ i_____ Ve bEEN INVoLVED IN_ NUmeRouS secreT raids wITH anonymous aND i____ HAve oVer threE hUNdReD coNfIRMEd ddoses I Am trAined In_ online trolling anD_ i M thE_ tOp hacker iN_ THe_ ENTirE world YOu_ aRe NOthinG tO mE BUt juSt AnotHER virus host I__ WilL wIpE yoU_ THE F___ oUt wITh PReCiSiON the__ LIKeS oF_ WHICH Has nevEr BeEN sEen befoRE ON tHe InTeRNET mArK my_ f___Ing wORds YOu_ ThinK

@ -0,0 +1,73 @@
import subprocess
import ctypes
import tempfile
import bisect
fibs = [0, 1]
def make_fibs(n):
while fibs[-1] < n:
fibs.append(fibs[-1] + fibs[-2])
def dfs(target, inuse=set()):
make_fibs(target)
end_index = bisect.bisect_left(fibs, target)
if fibs[end_index] == target and target not in inuse:
return inuse | {end_index}
for i, possibility in enumerate(fibs[end_index:1:-1]):
reali = end_index - i
if reali in inuse: continue
new = inuse | {reali}
if result := dfs(target - possibility, new): return result
make_fibs(2**63)
print(len(fibs))
"""
raise SystemExit()
for i in range(2, 10000):
print("doing", i)
res = dfs(i)
print(res)
assert sum(map(lambda x: fibs[x], res)) == i, "numbers do not sum to thing"
assert tuple(sorted(set(res))) == tuple(sorted(res)), "things are not unique"
"""
def c_wrapper(file):
print("Compiling", file)
temp = tempfile.mktemp(prefix="lib-compile-")
print(temp)
if subprocess.run(["gcc", file, "-o", temp, "-shared", "-fPIC"]).returncode != 0:
raise ValueError("compilation failed")
library = ctypes.CDLL(temp)
entry = library.f
entry.restype = ctypes.POINTER(ctypes.c_int64)
def wrapper(n):
vlen_ptr = ctypes.c_int(0)
out = entry(n, ctypes.byref(vlen_ptr))
l_out = []
for i in range(vlen_ptr.value):
#print(out[i])
l_out.append(out[i])
return l_out
return wrapper
def gollariosolver(n):
#print(n, "is n")
x = bisect.bisect_left(fibs, n)
out = set()
z = 0
for i in range(x, 0, -1):
#print("gollario", i, z, fibs[i])
if (y := fibs[i] + z) <= n:
z = y
out.add(i)
if z == n:
return out
print(fibs[12]+ fibs[23] + fibs[34])
c_code = c_wrapper("fib.c")
for i in range(2, 2**16):
res = c_code(i)
#res = gollariosolver(i)
assert sum(map(lambda x: fibs[x], res)) == i, "numbers do not sum to thing"
assert tuple(sorted(set(res))) == tuple(sorted(res)), "things are not unique"

@ -0,0 +1,71 @@
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <complex.h>
#include <string.h>
#include <stdlib.h>
#define nfibs 93
int64_t fibs[nfibs] = {0, 1, 0};
void initf() {
for (int k = 2; k < nfibs; k++) {
fibs[k] = fibs[k-1] + fibs[k-2];
}
}
bool iusol[nfibs] = {0};
int bsectf(int64_t n, int aa, int b) {
while (aa < b) {
int mid = (aa + b) >> 1;
if (fibs[mid] < n) { aa = mid + 1; }
else { b = mid; }
}
return aa;
}
int sumf(int64_t trg) {
int pt = bsectf(trg, 0, nfibs);
if (fibs[pt] == trg) {
iusol[pt] = true;
return 1;
}
for (int k = pt - 1; k > 1; k--) {
if (iusol[k]) continue;
iusol[k] = true;
if (sumf(trg - fibs[k])) return 1;
iusol[k] = false;
}
return 0;
}
long*f(int64_t trg, int*length) {
if (fibs[2] == 0) initf();
memset(iusol, 0, nfibs);
sumf(trg);
*length = 0;
for (int k = 0; k < nfibs; k++) {
if (iusol[k]) {
(*length)++;
}
}
int j = 0;
long*out = calloc(*length, sizeof(uint64_t));
for (int k = 0; k < nfibs; k++) {
if (iusol[k]) {
out[j] = k;
j++;
}
}
return out;
}
int main() {
initf();
for (int k = 0; k < 100; k++) {
sumf(1);
sumf(2);
}
}

@ -0,0 +1,70 @@
#include <stdint.h>