Skip to content

Instantly share code, notes, and snippets.

from random import choice
t = ""
s = " ▁▂▃▄▅▆▇█"
z = 0
for i in range(5000):
z += choice([-1, 1])
if z < 0:
z = z + 2
elif z >= len(s):
z = z - 2
@chaddotson
chaddotson / navigation_with_reduce.py
Created September 3, 2020 03:19
Using reduce to navigate dictionaries and lists
# Demonstrate reduce to navigate a nested dictionary or list.
from functools import reduce
from operator import getitem
data_dict = {
'a': 12,
'b': [
{
@chaddotson
chaddotson / py3_bin.py
Created January 14, 2019 00:35
Working with binary in Python 3
from ctypes import c_int, Structure
from inspect import getsource
from struct import pack_into, unpack_from
# Create 2 buffers, one smaller than the other for
# demonstration purposes.
buff1 = bytearray(64)
buff2 = bytearray(32)
from ctypes import *
class Point(Structure):
_fields_ = [
("x", c_float),
@chaddotson
chaddotson / ttl_cache_example.py
Created May 25, 2016 03:35
Example of TTLCache from cachetools
from cachetools import TTLCache
from sched import scheduler
cache = TTLCache(maxsize=128, ttl=5)
runner = scheduler()
cache["abc"] = 42
def display_cached_value(cache_key):
@chaddotson
chaddotson / load_jquery.js
Last active September 7, 2015 01:55
Copy and paste in the console of a page without jquery to load jquery. Leaves no artifacts of itself once it executes.
// loading jQuery on a site that doesn't have jquery for fun and ... hmmm profit?.
(function (jQueryURL) {
function loadSuccess() {
eval(this.responseText);
console.log("jQuery loaded.");
}
function loadFailed(event) {
@chaddotson
chaddotson / simple_gpio_with_javascript.js
Last active August 30, 2017 21:42
This snippet is intended to be the hello world equivalent for working with the raspberry pi gpio with node.js. This simply flashes an LED connected to pin 7 based on the duration.
/*
Requires:
- pi-gpio
- gpio-admin
This snippet is intended to be the hello world equivalent for working
with the raspberry pi gpio with node.js. This simply flashes an LED
connected to pin 7 based on the duration.
*/
@chaddotson
chaddotson / exec_code.py
Created October 20, 2013 21:02
A code snippet that allows arbitrary code to be executed given a set of inputs. The expected outputs will be returned.
def exec_code(code, inputs, outputs):
"""Execute the provided code given the inputs, return a dictonary of the outputs.
Keyword arguments:
code -- the python code to run.
inputs -- a dictionary of variable/initial values.
outputs -- the list of output variables to preserve from the run.
"""
for variable, value in inputs.items():