Skip to content

Instantly share code, notes, and snippets.

View meredian's full-sized avatar
🦆
Because ducks can!

Anton Sidelnikov meredian

🦆
Because ducks can!
View GitHub Profile
@meredian
meredian / 0_README.MD
Last active December 17, 2024 14:32
Drizzle transaction extractor for PG Dialect. Use in cases where you want get transaction object and commit and rollback it explicitly after passing around the code - allows you not to nest all your code inside transaction, but rather be more flexible with that

Extracting Drizzle transaction object

What code does is that it wraps Drizzle transaction function into number of helpers to allow you safely extract transaction, while keeping proper error handling.

It uses PostgreSQL types for simplicity, but it can be done with any data source since transaction is part of basic interface.

What is missing

@meredian
meredian / main.rs
Last active December 1, 2021 08:49
How to properly pass Warp errors
// As stated by author, you shouldn't use rejection as "return value" for
// error, since rejection mostly means "This filter is not capable of handling
// this request". So other filters should be tried.
// https://github.com/seanmonstar/warp/issues/388#issuecomment-576453485
//
// So whatever you return (Ok or Error), it should be a response value. Implementing
// that was not obvious, however Warp `3.2` added an approach to solve that.
// Operation `map` was added to cast whatever's on the chain into response, and we
// can use it to convert our custom error into Reply, not Rejection, to make warp
// work properly
@meredian
meredian / warp.rs
Created November 3, 2021 16:42
One more example how to override warp's problem with having lowest priority for rejection::not_found (so it starts looking into other branches and often results in e.g. 405 METHOD NOT ALLOWED)
// Define custom error enum,
pub enum Error {
NotFound()
// ... and any more errors here
}
// Make it castable to Rejection
impl warp::reject::Reject for Error {}
pub async fn handler() -> std::result::Result<impl Reply, Rejection> {
@meredian
meredian / lead_measures.md
Last active December 8, 2021 06:45
Compiled list of example lead measures for IT (in 4DX framework) which I found in numerous articles
@meredian
meredian / proxyWrapper.spec.js
Created May 14, 2020 17:48
ProxyWrapper to catch data changes - almost full spec, good for TDD approach :) Missing details is "Minimal subtree in diffs" on update requirement, but it's already complex enough.
const assert = require('assert');
const ProxyWrapper = require('./proxyWrapper');
describe('ProxyWrapper', function() {
describe('#wrap', function() {
beforeEach(function() {
this.data = { a: 1, b: { c: { d: 2 } }, e: { f: [3, 4] } };
this.wrappedData = ProxyWrapper.wrap(this.data);
});
@meredian
meredian / data-shoveler.js
Created May 28, 2019 10:16
Simple CLI tool with no dependencies. It reads given file by lines, group them in batches, and send batches to list of given HTTP services.
#!/usr/bin/env node
const fs = require('fs');
const url = require('url');
const path = require('path');
const http = require('http');
const readline = require('readline');
const EventEmitter = require('events');
const p = console.log;
@meredian
meredian / browser.js
Last active March 20, 2020 05:45
First approach to sniffing detector
'use strict';
// Prerequisites: node 8+
// Install: npm install puppeteer
const puppeteer = require('puppeteer');
// const Membrane = require('es7-membrane');
function sniffDetector() {
@meredian
meredian / fizz_buzz.md
Last active June 17, 2022 10:51
FizzBuzz in python

Задачка FizzBuzz

Напишите программу, которая выводит на экран числа от 1 до 100. При этом вместо чисел, кратных трем, программа должна выводить слово «Fizz», а вместо чисел, кратных пяти — слово «Buzz». Если число кратно и 3, и 5, то программа должна выводить слово «FizzBuzz»

Цитата: "Нормальный программист должен написать такую программу на бумажке за пару минут. Но вот что интересно: многие люди с профильным образованием вообще не могут справится с этой задачей. Были даже случаи, когда кандидаты, подававшие резюме на вакансию «Senior developer» тратили на эту программу больше 15 минут."

Подробнее про историю задачи и ее значимость можете прочитать по ссылке: https://habrahabr.ru/post/298134/

class AsyncMapState:
def __init__(self, func, items, **kwargs):
self.pool = Pool(kwargs.pop('procs', 6))
self.async_result = self.pool.map_async(func, items, 1, self.stop)
self.pool.close()
self.start_time = time.time()
self.size = len(items)
def item_status(self):
time_spent = time.time() - self.start_time
@meredian
meredian / powers-02.py
Last active October 27, 2016 18:01
Решение второй задачи по информатике отборочного тура http://nti-contest.ru/wp-content/uploads/7-%D0%91%D0%94.pdf
# Константа, очень большое значение,
# будет намекать нам, что мы пока не знаем,
# как на самом деле представить какое-то число
# в виде оптимальной суммы
NONE = 1000000000
def solve(n, x):
# Создаём пустой массив чисел из X + 1 ячеек,
# так что storage[i] - сумма степеней для i
storage = [NONE] * (x + 1)