Skip to content

Instantly share code, notes, and snippets.

View howardhamilton's full-sized avatar
💭
Tap tap tap...is this mic on?

Howard Hamilton howardhamilton

💭
Tap tap tap...is this mic on?
  • Atlanta, GA, USA
View GitHub Profile
@howardhamilton
howardhamilton / multipro.py
Created October 3, 2018 20:29
Multiprocessing pattern
import multiprocessing
class Consumer(multiprocessing.Process):
"""Consumer processes. Subclassed from Process in multiprocessing."""
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
@howardhamilton
howardhamilton / hinton.py
Created July 25, 2018 21:51
Hinton diagram on a football pitch
import numpy as n
import pylab as p
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
from pitch import create_normalized_pitch
def _add_centered_square(xy, area):
size = n.sqrt(area)
@howardhamilton
howardhamilton / pitch.py
Last active January 4, 2021 13:06
Normalized football pitch written with matplotlib package
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as pch
import matplotlib.image as img
def create_normalized_pitch(size=(12.5, 8.0), pcolor='none', ecolor='black'):
"""
Create figure that has football pitch lines drawn on it. Figure coordinates are normalized to a 100x100 grid.
If aspect ratio of figure is not equal to 1.5625 (12.5 in / 8.0 in), the figure width is
@howardhamilton
howardhamilton / unique_dicts.py
Last active November 3, 2016 15:50
Unique list of dictionaries
# unique list of dictionaries
# ---------------------------
# This problem comes up when I bulk insert records into databases
# because I can't check for existence of records (they don't exist yet, too slow, etc)
#
# I typically use a set to make list elements unique, but dicts and lists themselves
# can't be inserted in sets because they're mutable and thus unhashable.
#
# Solution is to make a tuple of the dict's items and insert it in set,
# then create dicts from each member of the set.
@howardhamilton
howardhamilton / logging.json
Created October 19, 2016 16:33
Setup logging configuration
{
"version": 1,
"disable_existing_loggers": false,
"formatters": {
"default": {
"format": "%(asctime)s - %(name)s - %(levelname)s: %(message)s"
},
"console": {
"format": "%(name)-12s: %(message)s"
}
@howardhamilton
howardhamilton / xml_wrap.py
Created October 19, 2016 16:28
Pattern to wrap XML content in outer tag, in order to get attributes in original root tag
from lxml import etree
from lxml.builder import E
if __name__ == "__main__":
with open('sample.xml') as f:
xml = f.read()
new_xml = E.Wrapper(etree.XML(xml))
print(etree.tostring(new_xml, pretty_print=True))
@howardhamilton
howardhamilton / exec_cmd.py
Last active November 3, 2016 21:14
Execute command using a subprocess and write streaming output to the screen
import logging
import subprocess
from io import BytesIO
def execute_command(cmd, ns=__name__, shell_flag=False):
"""
Execute command using a subprocess, and write streaming output to the screen.
:param cmd: Command-line statement
@howardhamilton
howardhamilton / replacer.py
Created May 23, 2016 12:38
Apply regex patterns and substitutions to text with a map
class RegexpReplacer(object):
"""
Take in list or dictionary of regex patterns and substitutes, and apply them to text with a map.
"""
def __init__(self, patterns):
if type(patterns) is dict:
self.patterns = [(re.compile(r"{}".format(regex)), patterns['replace'])
for regex in patterns['pattern']]
else:
@howardhamilton
howardhamilton / pushd.py
Last active May 2, 2023 02:56
A pushd/popd context for Python scripts
"""A Python context to move in and out of directories.
Copyright 2016-2020, Howard Hamilton.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction, in-
cluding without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
@howardhamilton
howardhamilton / player_similarity.py
Last active November 9, 2017 17:42
Identify N nearest neighbors to player's season statistics
"""
An outline for identifying N players with similar summary statistics to a player of interest.
A list of candidate players is compiled by filtering on position and end-of-season age.
Summary statistics are scaled to z-scores, which are the inputs to the machine learning model.
This algorithm uses K-Nearest Neighbor, but other algorithms (eg K-Means Clustering) can be substituted.
(c) 2015 Soccermetrics Research LLC
This code is licensed under the terms of the MIT License (http://choosealicense.com/licenses/mit/)
"""
from sklearn.neighbors import NearestNeighbors