Skip to content

Instantly share code, notes, and snippets.

@allemangD
allemangD / property_field.py
Last active January 8, 2023 18:03
Enable correctly annotated properties in Python dataclasses.
"""
Enable correctly annotated properties with @dataclass
>>> @dataclasses.dataclass
... class Person:
... first: str
... last: str
...
... @property_field
... def name(self) -> str:
import sys
import inspect
def get_outer_frame():
current = inspect.currentframe()
outers = inspect.getouterframes(current, 0)
return outers[2].frame
import json
import slicer
from slicer.ScriptedLoadableModule import ScriptedLoadableModuleLogic
_NODE = "__parameter_node__"
def parameterProperty(name):
"""Create a property backed by a parameter in a parameter node.
import inspect
def curry(func):
sig = inspect.signature(func)
num = len(sig.parameters)
def make(frozen_args):
def wrap(e):
args = frozen_args + (e,)
@allemangD
allemangD / timedec.py
Created February 22, 2019 00:36
Utility function for timeit module - call a function with optional args and print statistics about timeit results
def timedec(*args, func=None, repeat=5, number=1000000):
import timeit
from functools import partial
import statistics
def dec(f):
p = partial(f, *args)
pname = f"{f.__name__}({', '.join(map(str, args))})"
result = timeit.Timer(p).repeat(repeat, number)
@allemangD
allemangD / gen_context.py
Created November 1, 2018 02:12
Show how context managers do not support suspended execution
class CM:
mode = 0
def __init__(self, m):
self.m = m
def __enter__(self):
self.old = CM.mode
CM.mode = self.m
@allemangD
allemangD / async_context.py
Last active November 1, 2018 15:40
Show how Context Managers do not correctly support suspended execution
import asyncio
class CM:
mode = 0
def __init__(self, m):
self.m = m
def __enter__(self):
self.old = CM.mode
units = {
1: 'I',
5: 'V',
10: 'X',
50: 'L',
100: 'C',
500: 'D',
1000: 'M'
}
@allemangD
allemangD / navpaneutil.py
Created July 23, 2017 02:07
Adds folders to Navigation Pane in windows explorer
import uuid
import os
import re
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('title', help='Name for the folder in the nav bar')
parser.add_argument('folder', help='Path to the target folder')
parser.add_argument('-i', '--icon', help='Path to the icon to use. Defaults to empty folder icon', default='')
parser.add_argument('-s', '--sort', help='Sorting index of folder. Controls position in navbar', type=int, default=0x42)
# Example values convert '8DA5' from hexidecimal to decimal.
# Get valid digits in our base.
# input '0123456789ABCDEF'
digits = raw_input('Enter valid digits for this number system.\nRepeats are allowed, but will cause unexpected results.\n> ')
# Get the number we want to convert and reverse it (so the 1's place is on the left)
# input '8DA5' (becomes '5AD8')
number = raw_input('Enter a number in base %s\n> '%len(digits))[::-1]