Skip to content

Instantly share code, notes, and snippets.

View nomeyer's full-sized avatar

Nick Omeyer nomeyer

View GitHub Profile
@nomeyer
nomeyer / flatten_list.py
Last active February 10, 2016 20:55
Flatten a list of lists in Python
from itertools import chain
l = [[0, 1], [2, 3]]
l = list(chain.from_iterable(l))
@nomeyer
nomeyer / bar_plot.py
Last active February 10, 2016 20:54
Bar plot using matplotlib.pyplot.bar (where bars are already given)
import matplotlib.pyplot as plt
bars = [3, 6, 2, 4]
plt.figure(figsize=(10, 5))
plt.bar(range(len(bars)), bars, align='center')
plt.show()
@nomeyer
nomeyer / hist_plot.py
Last active February 12, 2016 13:39
Normalised histogram using matplotlib.pyplot.hist and numpy weights
import numpy as np
import matplotlib.pyplot as plt
counts = [10, 8, 6, 14]
weights = np.ones_like(counts) / float(len(counts))
plt.figure(figsize=(10, 5))
plt.hist(counts, bins=range(1, max(counts)+2), align='left', weights=weights)
plt.xticks(range(1, max(counts)+1))
plt.show()
@nomeyer
nomeyer / text_query.py
Last active February 10, 2016 20:52
SQL query using sqlalchemy core
from sqlalchemy import create_engine
from sqlalchemy.engine.url import URL
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.expression import text as Text
def db_connect(db):
return create_engine(URL(**db)) # db should be a dict with connection params
@nomeyer
nomeyer / sort_dict.py
Last active February 10, 2016 20:54
Sort a dictionary by value (descending) – see http://stackoverflow.com/a/613218
from operator import itemgetter
sorted_d = sorted(d.items(), key=itemgetter(1), reverse=True)
# sorted_dict is a list of tuples (key, value)
@nomeyer
nomeyer / get_all_positions.py
Last active February 10, 2016 20:54 — forked from matthieualouis/get_all_positions.py
Get all positions of a value in a list
L = [1, 2, 3, 1]
[i for i, x in enumerate(L) if x == value]
@nomeyer
nomeyer / flask_query_args.py
Last active February 10, 2016 20:53
Get a query argument by name from a request in Flask
from flask import request
# here we want to get the value of user (i.e. ?user=value)
user = request.args.get('user')
@nomeyer
nomeyer / sqlalchemy_query_profiling.py
Last active February 9, 2016 19:28
Context manager to profile sqlalchemy query performance
import cProfile
import StringIO
import pstats
import contextlib
@contextlib.contextmanager
def profiled():
pr = cProfile.Profile()
pr.enable()
@nomeyer
nomeyer / curl_with_cookies.sh
Created January 20, 2016 19:31
Send cookies with curl
curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/
@nomeyer
nomeyer / validation_decorator.py
Last active February 10, 2016 20:51
Decorator to validate post requests in Flask
from functools import wraps
from flask import request, abort
def validate_post(validator, status_code):
"""Validate the POST request with the given validator function.
Abort with the given status_code upon validation failure.
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):