Skip to content

Instantly share code, notes, and snippets.

@axil
axil / bench-factorize.py
Created January 13, 2023 11:45
bench-factorize
from contextlib import contextmanager
from time import perf_counter as clock
from itertools import count
import numpy as np
import pandas as pd
def f1(a):
return s.factorize()[0]
def f2(s):
@axil
axil / groupby-sort.py
Created January 4, 2023 17:18
groupby-sort
>>> s = pd.Series([1, 3, 20, 2, 10])
>>> for k, v in s.groupby(s//10, sort=False):
print(k, v.tolist())
0 [1, 3, 2]
2 [20]
1 [10]
@axil
axil / roundtrip.py
Last active August 26, 2022 18:01
roundtrip
import bokeh.models as bm
from bokeh.layouts import row
from bokeh.plotting import show
data = bm.TextInput(width=100)
go = bm.Button(label='Go', width=50)
result = bm.TextInput(width=100)
callback = bm.CustomJS(args={'data': data, 'result': result}, code="""
var g = window.pyodide.globals;
g.set('data', data.value);
@axil
axil / load_numpy.js
Last active August 27, 2022 16:16
load_numpy
%%javascript
async function prepare() {
await window.pyodide.loadPackage("numpy");
alert(window.pyodide.runPython(`
import numpy as np
np.array([3, 4]).sum()
`));
}
prepare();
@axil
axil / load_pyodide.js
Created August 26, 2022 11:33
load_pyodide
%%javascript
require([
'//cdn.jsdelivr.net/pyodide/v0.20.0/full/pyodide.js',
], function() {
async function main() {
let pyodide = await loadPyodide();
window.pyodide = pyodide;
alert('pyodide ready');
}
main();
@axil
axil / interpolate.py
Created August 19, 2022 16:52
interpolate
x = [0, 1, 2, 3, 4, 5]
y = [8.1, 10.2, 15.4, 24.6, 29.8, 31.9]
from scipy.interpolate import CubicSpline
f = CubicSpline(x, y)
f(1.25) # 11.05833333
@axil
axil / subclass_tuple.py
Last active April 16, 2022 19:24
subclass_tuple
class Point(tuple):
def __new__(cls, x, y):
return super().__new__(cls, (x, y))
@property
def x(self):
return self[0]
@property
def y(self):
@axil
axil / subclass_list.py
Created April 16, 2022 19:19
subclass_list
class Point(list):
def __init__(self, x, y):
super().__init__((x, y))
>>> points = [Point(1,2), Point(2,3), Point(1,2)]
>>> Counter(points)
TypeError: unhashable type: 'Point'
@axil
axil / namedtuple.py
Last active April 16, 2022 19:14
namedtuple
>>> Point = namedtuple('Point', ('x', 'y'))
>>> points = [Point(1,2), Point(2,3), Point(1,2)]
>>> Counter(points)
Counter({Point(x=1, y=2): 2, Point(x=2, y=3): 1})
@axil
axil / immutable.py
Last active April 16, 2022 19:34
immutable
class Point:
def __init__(self, x, y):
super().__setattr__('x', x) # workaround for the
super().__setattr__('y', y) # rule below
def __repr__(self):
return f'Point({self.x}, {self.y})'
def __eq__(self, other):
return self.x == other.x and self.y == other.y