Skip to content

Instantly share code, notes, and snippets.

View brettvitaz's full-sized avatar

Brett Vitaz brettvitaz

View GitHub Profile
@brettvitaz
brettvitaz / gather_with_concurrency.py
Created February 18, 2023 00:09
Limit concurrent coroutines using async gather
async def gather_with_concurrency(n, *coros):
semaphore = asyncio.Semaphore(n)
async def sem_coro(coro):
async with semaphore:
return await coro
return await asyncio.gather(*(sem_coro(c) for c in coros))
@brettvitaz
brettvitaz / print_progress_bar.py
Created February 17, 2023 22:06
Simple console progress bar with no dependencies
def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', print_end=""):
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filled_length = int(length * iteration // total)
bar = fill * filled_length + '-' * (length - filled_length)
print(f'\r{prefix} |{bar}| {percent}% {suffix}', end=print_end)
# Print New Line on Complete
if iteration == total:
print()
@brettvitaz
brettvitaz / prune_dict_for_dataclass.py
Created February 9, 2023 23:01
Prune dict for dataclass
def prune_dict_for_dataclass(d: dict, cls):
ret = {}
for field in fields(cls):
if field.name in d:
if is_dataclass(field.type):
ret[field.name] = prune_dict_for_dataclass(d[field.name], field.type)
elif typing.get_origin(field.type) is list and type(d[field.name]) is list:
list_cls = typing.get_args(field.type)[0]
if is_dataclass(list_cls):
ret[field.name] = [prune_dict_for_dataclass(i, list_cls) for i in d[field.name]]
@brettvitaz
brettvitaz / AppSettings.py
Created January 14, 2023 23:15
An "interesting" approach to dicts with dot notation
from typing import Union
import json
class AppSettings(dict):
def __init__(self, settings_filename):
self._settings_filename = settings_filename
with open(settings_filename, "r") as settings_file:
super().__init__(json.load(settings_file))
@brettvitaz
brettvitaz / Data.py
Last active January 9, 2023 18:06
dataclasses-json Counter deserialization example
from collections import Counter
from dataclasses import dataclass, field
from dataclasses_json import dataclass_json
from utils import counter_config
@dataclass_json
@dataclass
@brettvitaz
brettvitaz / JsonSerializable.py
Created December 29, 2022 23:29
JsonSerializable
from abc import ABC
class JsonSerializable(ABC):
IGNORE = []
@staticmethod
def serialize(obj):
if isinstance(obj, JsonSerializable):
return obj.to_json()
@brettvitaz
brettvitaz / hashing.py
Created October 2, 2022 00:54
Python Hashing for List and Dict types
def hash_list(list_: list) -> int:
__hash = 0
for i, e in enumerate(list_):
__hash = hash((__hash, i, hash_item(e)))
return __hash
def hash_dict(dict_: dict) -> int:
__hash = 0
for k, v in dict_.items():
@brettvitaz
brettvitaz / no_motion_light_off.yaml
Last active January 11, 2023 21:10
Home Assistant Blueprint: Turn off a light when no motion is detected.
blueprint:
name: No Motion - Light Off
description: Turn off a light when no motion is detected.
domain: automation
source_url: https://gist.github.com/brettvitaz/223151868704e40ddac8023df06be7f0
input:
motion_entity:
name: Motion Sensor
selector:
entity:
// Includes functions for exporting active sheet or all sheets as JSON object (also Python object syntax compatible).
// Tweak the makePrettyJSON_ function to customize what kind of JSON to export.
var FORMAT_ONELINE = 'One-line';
var FORMAT_MULTILINE = 'Multi-line';
var FORMAT_PRETTY = 'Pretty';
var LANGUAGE_JS = 'JavaScript';
var LANGUAGE_PYTHON = 'Python';
@brettvitaz
brettvitaz / csd-wrapper.sh
Last active February 10, 2018 08:32 — forked from l0ki000/csd-wrapper.sh
Cisco Anyconnect CSD wrapper for OpenConnect (exhanced to autodownload and autoupdate hostscan)
#!/usr/bin/env bash
# Cisco Anyconnect CSD wrapper for OpenConnect
# Requirements:
# - wget (brew install wget)
# - md5sum (brew install md5sha1sum)
# Enter your vpn host here
#CSD_HOSTNAME=
if [[ -z ${CSD_HOSTNAME} ]]
then