Skip to content

Instantly share code, notes, and snippets.

View victory-sokolov's full-sized avatar
🎯
Focusing

Viktor Sokolov victory-sokolov

🎯
Focusing
View GitHub Profile
@victory-sokolov
victory-sokolov / async_wrap.py
Created April 21, 2025 08:37
Run synch code in the executor
def async_wrap(
loop: Optional[asyncio.BaseEventLoop] = None, executor: Optional[Executor] = None
) -> Callable:
def _async_wrap(func: Callable) -> Callable:
@wraps(func)
async def run(*args, loop=loop, executor=executor, **kwargs):
if loop is None:
loop = asyncio.get_event_loop()
pfunc = partial(func, *args, **kwargs)
return await loop.run_in_executor(executor, pfunc)
@victory-sokolov
victory-sokolov / server.js
Created May 11, 2024 17:25
Express server with Http2 support
const express = require('express');
const spdy = require('spdy');
const PORT = 8000;
const app = express();
app.get('/', (_, res) => {
res.send('hello world');
});
@victory-sokolov
victory-sokolov / ratelimit.ts
Created February 4, 2024 15:33
Ratelimit using upstash with nextjs
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';
import type { NextRequest, NextFetchEvent } from 'next/server';
import { NextResponse } from 'next/server';
type MiddlewareFactory = (middleware: NextMiddleware) => NextMiddleware;
export const withRateLimit: MiddlewareFactory =
next => async (request: NextRequest, _next: NextFetchEvent) => {
const url = process.env.UPSTASH_REDIS_REST_URL!;
@victory-sokolov
victory-sokolov / rn-functions.sh
Created February 3, 2024 08:52
ReactNative Bash functions
bapk() # build android apk (Must run inside react-native project)
{
apk_path="./android/app/build/outputs/apk/debug"
if [ ! -f package.json ]; then
echo "package.json was not found. Run command inside root dir of your project."
return 1
fi
if ! grep --quiet '"react-native":' package.json; then
import asyncio
import logging
import logging.handlers
try:
# Python 3.7 and newer, fast reentrant implementation
# without task tracking (not needed for that when logging)
from queue import SimpleQueue as Queue
except ImportError:
from queue import Queue
from typing import List
@victory-sokolov
victory-sokolov / flake8.js
Created January 15, 2024 19:51
JavaScript execute Flake8 formatter
const { exec } = require('child_process');
const pythonCode = `def hello_world():
print("Hello, World!")`;
exec(`echo "${pythonCode}" | python -m flake8 -`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
@victory-sokolov
victory-sokolov / test_nplusone.py
Created January 15, 2024 19:40
Python nplusone inside tests
from functools import wraps
from django.test import TestCase
def raise_nplusone_decorator(cls):
original_setup_class = getattr(cls, 'setUpClass')
original_teardown_class = getattr(cls, 'tearDownClass')
@classmethod
def new_setup_class(cls):
# Perform setup steps before the test class
@victory-sokolov
victory-sokolov / dict_to_enum.py
Created January 15, 2024 14:07
Python Enum from Dict
from enum import Enum
# Define a dictionary
my_dict = {
"foo": 1,
"bar": 2,
"baz": 3,
}
# Create an Enum class by passing the dictionary to the Enum constructor
@victory-sokolov
victory-sokolov / exception_nodes_ast.py
Created January 15, 2024 14:06
Python Get exception nodes with AST
import ast
# define a sample function
def foo():
try:
x = 1 / 0
except ZeroDivisionError:
pass
# parse the function into an AST tree
@victory-sokolov
victory-sokolov / string_to_code.py
Created January 15, 2024 14:05
Python String to Code with AST
import ast
import compile
# define the source code
src = '''
def foo(x):
return x + 1
print(foo(1))
'''