Skip to content

Instantly share code, notes, and snippets.

View julik's full-sized avatar
💭
🎺

Julik Tarkhanov julik

💭
🎺
View GitHub Profile
class StreamingController < ApplicationController
class Writer
def initialize(&blk)
@blk = blk
end
def write(stuff)
@blk.call(stuff)
stuff.bytesize
end
@julik
julik / pecobox.rb
Created February 9, 2024 14:59
A circuit breaker using Pecorino leaky buckets
# frozen_string_literal: true
# Pecobox is a Circuitbox-like class which uses Pecorino for
# measurement error rates. It is less resilient than Circuitbox
# because your error stats are stored in the database, but guess what:
# if your database is down your product is already down, so there is
# nothing to circuit-protect. And having a shared data store for
# the circuits allows us to track across machines and processes, so
# we do not have to have every worker hammer at an already failing
# resource right after start
@julik
julik / localities.sql
Created June 4, 2023 10:23
Versioned table with grouping by updated_at
CREATE TABLE localities (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
source_updated_at TIMESTAMP,
name TEXT
);
INSERT INTO localities (name, source_updated_at) VALUES
('London', '2023-04-01'),
('London', '2023-03-15'),
('Paris', '2023-02-11'),
('Canberra', '2022-10-05');
@julik
julik / transactional.rb
Created November 1, 2011 18:27
Transactional database in Minitest in 7 lines of code
module TransactionalTests
# See minitest doco - use_transactional_fixtures_but_in_ruby
# to use include this into your test case
def run(runner)
test_result = nil
ActiveRecord::Base.transaction { test_result = super; raise ActiveRecord::Rollback }
test_result
end
end
# This offers just the leaky bucket implementation with fill control, but without the timed lock.
# It does not raise any exceptions, it just tracks the state of a leaky bucket in Postgres.
#
# Leak rate is specified directly in tokens per second, instead of specifying the block period.
# The bucket level is stored and returned as a Float which allows for finer-grained measurement,
# but more importantly - makes testing from the outside easier.
#
# Note that this implementation has a peculiar property: the bucket is only "full" once it overflows.
# Due to a leak rate just a few microseconds after that moment the bucket is no longer going to be full
# anymore as it will have leaked some tokens by then. This means that the information about whether a
@julik
julik / composition-normalization-and-morons.markdown
Created February 17, 2012 09:43
Композиция, нормализация и уроды

В своих разговорах о Юникоде я не затронул несколько интересных моментов, о которых полезно знать. Кофейный столик "Юлик о Юникоде" продолжает прием посетителей.

Байт, кодпойнт, глиф

Юникод - многобайтовый способ кодирования текста. Текст состоит из codepoints (кодовых позиций), все позиции присутствуют в каталоге символов Unicode. Кодпойнты включают базовые компоненты графем и графемы в целом. При этом:

Каждый кодпойнт можно выразить в байтовом виде как минимум 5 разными способами

Один из них - UTF-8, в котором все латинские буквы заменены на однобайтовые ASCII-эквиваленты. Другие варианты - UTF-16 и UTF-32. UTF-16 - стандартный способ хранения Unicode-строк в операционных системах. InDesign импортирует тексты именно в UTF-16 например.

mft_gap_mm = 96
offset_outer_mm = 70 # (mft_gap_mm / 2)
# Long side needs an odd number of gaps so that the center span of the
# workbench ends up between two rows of holes and never overlaps the holes
1.step(22,2) do |n_gaps_x|
1.upto(10) do |n_gaps_y|
width_mm = (offset_outer_mm * 2) + (mft_gap_mm * n_gaps_x)
height_mm = (offset_outer_mm * 2) + (mft_gap_mm * n_gaps_y)
puts "#{width_mm}x#{height_mm}mm with #{n_gaps_x + 1} holes along and #{n_gaps_y + 1} holes across"
end
@julik
julik / slip.py
Created July 30, 2012 15:07
Offset and slip ALL OF EM KEYFRAMES on nodes
import nuke, re
def start_anim_at(node, frame):
"""
Will move all the animations of the passed node so that they start at the passed frame instead of the
current ont
"""
slip_by = frame - first_keyframe_location(node)
slip_animations_of_node(node, slip_by)
# Rig up livereload for frontend stuff
guard 'livereload', apply_js_live: false, apply_css_live: true do
# Do full reloads for everything except CSS
watch(%r{.+\.(js|coffee|erb)$})
# Do full reloads when we modify the bom.json file with
# our Javascripts listed in loading order
watch(%r{.+\/bom\.json$})
# Using live compilation has it's downsides.
@julik
julik / INSTALL.command
Created May 20, 2021 16:01
Python 3 compatible Logik-Matchbook install script
#!/usr/bin/env python
import contextlib as __stickytape_contextlib
@__stickytape_contextlib.contextmanager
def __stickytape_temporary_dir():
import tempfile
import shutil
dir_path = tempfile.mkdtemp()
try:
yield dir_path