Skip to content

Instantly share code, notes, and snippets.

View edelooff's full-sized avatar

Elmer de Looff edelooff

View GitHub Profile
@edelooff
edelooff / expression.py
Created June 12, 2020 22:50
Evaluating SQLAlchemy expressions in Python (for ORM objects and such)
from __future__ import annotations
import operator
from collections import deque
from enum import Enum, auto
from typing import Any, Dict, Iterator, NamedTuple, Optional, Tuple
from sqlalchemy import Column
from sqlalchemy.sql import operators
from sqlalchemy.sql.elements import (
@edelooff
edelooff / integrity_example.py
Created June 5, 2015 18:44
Catching and handling IntegrityError in SQLAlchemy
import sys
import sqlalchemy as sa
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
base = declarative_base()
print 'SQLAlchemy version {}'.format(sa.__version__)
@edelooff
edelooff / freeform-tags.py
Created July 22, 2022 22:35
AO3 freeform tag analysis given a search tag
"""Retrieve AO3 freeform tag popularity for works of a given tag.
$ python freeform-tags.py "Clark Kent"
Requirements:
* cssselect
* lxml
* requests
"""
@edelooff
edelooff / sqla_secondary.py
Created April 24, 2020 09:14
SQLAlchemy secondary join
from sqlalchemy import (
Column,
ForeignKey,
Integer,
Text,
create_engine)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
relationship,
sessionmaker)
@edelooff
edelooff / feistel.py
Last active November 10, 2021 00:24
Simple Python Feistel encoder/decoder
"""A simple 8-round Feistel network to encode/decode 8-bit integers.
See https://en.wikipedia.org/wiki/Feistel_cipher for construction details.
"""
from random import randint
ROUNDS = 8
KEYS = [(randint(11, 19), randint(1, 200)) for _ in range(ROUNDS)]
@edelooff
edelooff / tree-typing.py
Last active July 1, 2021 12:24
Playing with structural typing
from __future__ import annotations
from dataclasses import dataclass
from typing import Generic, Optional, Protocol, TypeVar
CT = TypeVar("CT", bound="Comparable")
class Comparable(Protocol):
def __lt__(self: CT, other: CT) -> bool:
@edelooff
edelooff / functional_trees.py
Created November 24, 2020 22:52
Functional recursive tree creation from pre-order sequence.
# Haskell functional trees: https://gist.github.com/jerbaroo/bd48ff01a9988650ec698cbce4b0f2da
from collections import namedtuple
from typing import Any, List, Optional, Tuple
Node = namedtuple("Node", ["value", "left", "right"], defaults=[None, None])
def dfs_pre(node: Node) -> Any:
"""Depth-first search, pre-order sequence."""
@edelooff
edelooff / tree_reconstruction.py
Created October 20, 2020 22:25
Recreation of a binary tree from pre and post-order sequentialisations.
"""Recreation of a binary tree from pre and post-order sequentialisations.
There are no constraints or expectations of explicit ordering. The algorithm
runs in linear time and storage space, with a small stack that is dependent
on the height of the tree.
"""
def recreate_tree(pre_order, in_order):
print(f"\nStack recreating tree from PO {pre_order} and IO {in_order}")
pre_order_iter = iter(pre_order)
@edelooff
edelooff / eager_defaults.py
Created October 13, 2020 22:21
SQLAlchemy actively applied column defaults
from datetime import datetime
from sqlalchemy import Column, DateTime, Integer, Text, func, inspect
from sqlalchemy.ext.declarative import as_declarative, declared_attr
from sqlalchemy.sql.functions import Function
def defaults_included_constructor(instance, **kwds):
mapper = inspect(instance).mapper
for column in mapper.columns:
@edelooff
edelooff / design.lark
Created July 11, 2020 10:53
Parsing a simple DSL with Lark
?start: design
design: UCASE SIZE flower* INT+
flower: INT+ LCASE
SIZE: ("S"|"L")
%import common.LCASE_LETTER -> LCASE
%import common.UCASE_LETTER -> UCASE
%import common.INT
%ignore "\n"