example_name
stringlengths
10
28
python_file
stringlengths
9
32
python_code
stringlengths
490
18.2k
rust_code
stringlengths
0
434
has_rust
bool
2 classes
category
stringlengths
2
20
python_lines
int32
13
586
rust_lines
int32
0
6
blocking_features
listlengths
0
7
suspiciousness
float32
0
0.95
error
stringlengths
33
500
example_num_matrix
num_matrix_cli.py
"""Matrix Operations CLI. Demonstrates matrix operations: add, mul, transpose, inverse. """ import math import sys from dataclasses import dataclass @dataclass class Matrix: """2D matrix of floats.""" data: list[list[float]] rows: int cols: int @classmethod def from_list(cls, data: list[list[float]]) -> "Matrix": """Create matrix from nested list.""" rows = len(data) cols = len(data[0]) if data else 0 return cls(data, rows, cols) @classmethod def zeros(cls, rows: int, cols: int) -> "Matrix": """Create zero matrix.""" data = [[0.0] * cols for _ in range(rows)] return cls(data, rows, cols) @classmethod def ones(cls, rows: int, cols: int) -> "Matrix": """Create matrix of ones.""" data = [[1.0] * cols for _ in range(rows)] return cls(data, rows, cols) @classmethod def identity(cls, n: int) -> "Matrix": """Create identity matrix.""" data = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)] return cls(data, n, n) @classmethod def diagonal(cls, values: list[float]) -> "Matrix": """Create diagonal matrix.""" n = len(values) data = [[values[i] if i == j else 0.0 for j in range(n)] for i in range(n)] return cls(data, n, n) def __getitem__(self, idx: tuple[int, int]) -> float: return self.data[idx[0]][idx[1]] def __setitem__(self, idx: tuple[int, int], value: float) -> None: self.data[idx[0]][idx[1]] = value def __eq__(self, other: object) -> bool: if not isinstance(other, Matrix): return False if self.rows != other.rows or self.cols != other.cols: return False for i in range(self.rows): for j in range(self.cols): if abs(self.data[i][j] - other.data[i][j]) > 1e-10: return False return True def add(self, other: "Matrix") -> "Matrix": """Matrix addition.""" if self.rows != other.rows or self.cols != other.cols: raise ValueError("Matrix dimensions must match") result = Matrix.zeros(self.rows, self.cols) for i in range(self.rows): for j in range(self.cols): result.data[i][j] = self.data[i][j] + other.data[i][j] return result def sub(self, other: "Matrix") -> "Matrix": """Matrix subtraction.""" if self.rows != other.rows or self.cols != other.cols: raise ValueError("Matrix dimensions must match") result = Matrix.zeros(self.rows, self.cols) for i in range(self.rows): for j in range(self.cols): result.data[i][j] = self.data[i][j] - other.data[i][j] return result def mul(self, other: "Matrix") -> "Matrix": """Matrix multiplication.""" if self.cols != other.rows: raise ValueError( f"Cannot multiply {self.rows}x{self.cols} by {other.rows}x{other.cols}" ) result = Matrix.zeros(self.rows, other.cols) for i in range(self.rows): for j in range(other.cols): total = 0.0 for k in range(self.cols): total += self.data[i][k] * other.data[k][j] result.data[i][j] = total return result def scale(self, scalar: float) -> "Matrix": """Scalar multiplication.""" result = Matrix.zeros(self.rows, self.cols) for i in range(self.rows): for j in range(self.cols): result.data[i][j] = self.data[i][j] * scalar return result def transpose(self) -> "Matrix": """Matrix transpose.""" result = Matrix.zeros(self.cols, self.rows) for i in range(self.rows): for j in range(self.cols): result.data[j][i] = self.data[i][j] return result def trace(self) -> float: """Sum of diagonal elements.""" if self.rows != self.cols: raise ValueError("Trace requires square matrix") return sum(self.data[i][i] for i in range(self.rows)) def det(self) -> float: """Calculate determinant using LU decomposition.""" if self.rows != self.cols: raise ValueError("Determinant requires square matrix") n = self.rows lu = [row[:] for row in self.data] sign = 1 for i in range(n): # Find pivot max_row = i for k in range(i + 1, n): if abs(lu[k][i]) > abs(lu[max_row][i]): max_row = k if max_row != i: lu[i], lu[max_row] = lu[max_row], lu[i] sign *= -1 if abs(lu[i][i]) < 1e-10: return 0.0 for k in range(i + 1, n): factor = lu[k][i] / lu[i][i] for j in range(i, n): lu[k][j] -= factor * lu[i][j] det_val = float(sign) for i in range(n): det_val *= lu[i][i] return det_val def inverse(self) -> "Matrix": """Calculate matrix inverse using Gauss-Jordan.""" if self.rows != self.cols: raise ValueError("Inverse requires square matrix") n = self.rows # Augment with identity aug = [self.data[i][:] + [1.0 if i == j else 0.0 for j in range(n)] for i in range(n)] # Forward elimination for i in range(n): max_row = i for k in range(i + 1, n): if abs(aug[k][i]) > abs(aug[max_row][i]): max_row = k aug[i], aug[max_row] = aug[max_row], aug[i] if abs(aug[i][i]) < 1e-10: raise ValueError("Matrix is singular") pivot = aug[i][i] for j in range(2 * n): aug[i][j] /= pivot for k in range(n): if k != i: factor = aug[k][i] for j in range(2 * n): aug[k][j] -= factor * aug[i][j] result = Matrix.zeros(n, n) for i in range(n): for j in range(n): result.data[i][j] = aug[i][n + j] return result def frobenius_norm(self) -> float: """Frobenius norm.""" total = 0.0 for i in range(self.rows): for j in range(self.cols): total += self.data[i][j] ** 2 return math.sqrt(total) def row(self, i: int) -> list[float]: """Get row.""" return self.data[i][:] def col(self, j: int) -> list[float]: """Get column.""" return [self.data[i][j] for i in range(self.rows)] def to_list(self) -> list[list[float]]: """Convert to nested list.""" return [row[:] for row in self.data] def dot(v1: list[float], v2: list[float]) -> float: """Dot product of vectors.""" return sum(a * b for a, b in zip(v1, v2, strict=False)) def simulate_matrix(operations: list[str]) -> list[str]: """Simulate matrix operations.""" results: list[str] = [] for op in operations: parts = op.split(":", 1) cmd = parts[0] if cmd == "add": m1 = Matrix.from_list([[1, 2], [3, 4]]) m2 = Matrix.from_list([[5, 6], [7, 8]]) result = m1.add(m2) results.append(str(result.to_list())) elif cmd == "mul": m1 = Matrix.from_list([[1, 2], [3, 4]]) m2 = Matrix.from_list([[5, 6], [7, 8]]) result = m1.mul(m2) results.append(str(result.to_list())) elif cmd == "transpose": m = Matrix.from_list([[1, 2, 3], [4, 5, 6]]) result = m.transpose() results.append(str(result.to_list())) elif cmd == "det": m = Matrix.from_list([[1, 2], [3, 4]]) result = m.det() results.append(f"{result:.1f}") elif cmd == "inverse": m = Matrix.from_list([[4, 7], [2, 6]]) result = m.inverse() results.append(str([[round(x, 2) for x in row] for row in result.to_list()])) elif cmd == "identity": n = int(parts[1]) result = Matrix.identity(n) results.append(str(result.to_list())) return results def main() -> int: """CLI entry point.""" if len(sys.argv) < 2: print("Usage: num_matrix_cli.py <command>") return 1 cmd = sys.argv[1] if cmd == "demo": A = Matrix.from_list([[1, 2], [3, 4]]) B = Matrix.from_list([[5, 6], [7, 8]]) print(f"A = {A.to_list()}") print(f"B = {B.to_list()}") print(f"A + B = {A.add(B).to_list()}") print(f"A * B = {A.mul(B).to_list()}") print(f"A^T = {A.transpose().to_list()}") print(f"det(A) = {A.det()}") try: print(f"A^-1 = {A.inverse().to_list()}") except ValueError as e: print(f"Cannot invert: {e}") else: print("Unknown command") return 1 return 0 if __name__ == "__main__": sys.exit(main())
false
num_matrix
287
0
[ "context_manager", "class_definition", "exception_handling", "decorator" ]
0.652
Error: Unsupported type annotation: Constant(ExprConstant { range: 335..343, value: Str("Matrix"), kind: None })
example_num_matrix
test_num_matrix_cli.py
"""Tests for num_matrix_cli.py""" import math import pytest from num_matrix_cli import Matrix, dot, simulate_matrix class TestMatrixCreation: def test_from_list(self): m = Matrix.from_list([[1, 2], [3, 4]]) assert m.rows == 2 assert m.cols == 2 def test_zeros(self): m = Matrix.zeros(2, 3) assert m.rows == 2 assert m.cols == 3 assert m.data == [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] def test_ones(self): m = Matrix.ones(2, 2) assert m.data == [[1.0, 1.0], [1.0, 1.0]] def test_identity(self): m = Matrix.identity(3) assert m.data == [[1, 0, 0], [0, 1, 0], [0, 0, 1]] def test_diagonal(self): m = Matrix.diagonal([1, 2, 3]) assert m.data == [[1, 0, 0], [0, 2, 0], [0, 0, 3]] class TestMatrixAccess: def test_getitem(self): m = Matrix.from_list([[1, 2], [3, 4]]) assert m[0, 0] == 1 assert m[1, 1] == 4 def test_setitem(self): m = Matrix.zeros(2, 2) m[0, 1] = 5.0 assert m[0, 1] == 5.0 def test_row(self): m = Matrix.from_list([[1, 2, 3], [4, 5, 6]]) assert m.row(0) == [1, 2, 3] def test_col(self): m = Matrix.from_list([[1, 2], [3, 4], [5, 6]]) assert m.col(1) == [2, 4, 6] class TestMatrixAdd: def test_basic(self): m1 = Matrix.from_list([[1, 2], [3, 4]]) m2 = Matrix.from_list([[5, 6], [7, 8]]) result = m1.add(m2) assert result.data == [[6, 8], [10, 12]] def test_dimension_mismatch(self): m1 = Matrix.from_list([[1, 2], [3, 4]]) m2 = Matrix.from_list([[1, 2, 3]]) with pytest.raises(ValueError): m1.add(m2) class TestMatrixSub: def test_basic(self): m1 = Matrix.from_list([[5, 6], [7, 8]]) m2 = Matrix.from_list([[1, 2], [3, 4]]) result = m1.sub(m2) assert result.data == [[4, 4], [4, 4]] class TestMatrixMul: def test_square(self): m1 = Matrix.from_list([[1, 2], [3, 4]]) m2 = Matrix.from_list([[5, 6], [7, 8]]) result = m1.mul(m2) assert result.data == [[19, 22], [43, 50]] def test_non_square(self): m1 = Matrix.from_list([[1, 2, 3], [4, 5, 6]]) # 2x3 m2 = Matrix.from_list([[7, 8], [9, 10], [11, 12]]) # 3x2 result = m1.mul(m2) # Should be 2x2 assert result.rows == 2 assert result.cols == 2 def test_dimension_mismatch(self): m1 = Matrix.from_list([[1, 2], [3, 4]]) m2 = Matrix.from_list([[1, 2, 3]]) with pytest.raises(ValueError): m1.mul(m2) def test_identity_mul(self): m = Matrix.from_list([[1, 2], [3, 4]]) i = Matrix.identity(2) result = m.mul(i) assert result == m class TestMatrixScale: def test_basic(self): m = Matrix.from_list([[1, 2], [3, 4]]) result = m.scale(2) assert result.data == [[2, 4], [6, 8]] def test_zero(self): m = Matrix.from_list([[1, 2], [3, 4]]) result = m.scale(0) assert result == Matrix.zeros(2, 2) class TestMatrixTranspose: def test_square(self): m = Matrix.from_list([[1, 2], [3, 4]]) result = m.transpose() assert result.data == [[1, 3], [2, 4]] def test_non_square(self): m = Matrix.from_list([[1, 2, 3], [4, 5, 6]]) result = m.transpose() assert result.rows == 3 assert result.cols == 2 assert result.data == [[1, 4], [2, 5], [3, 6]] def test_double_transpose(self): m = Matrix.from_list([[1, 2], [3, 4]]) result = m.transpose().transpose() assert result == m class TestMatrixTrace: def test_basic(self): m = Matrix.from_list([[1, 2], [3, 4]]) assert m.trace() == 5 def test_identity(self): m = Matrix.identity(5) assert m.trace() == 5 def test_non_square(self): m = Matrix.from_list([[1, 2, 3], [4, 5, 6]]) with pytest.raises(ValueError): m.trace() class TestMatrixDet: def test_2x2(self): m = Matrix.from_list([[1, 2], [3, 4]]) assert abs(m.det() - (-2)) < 1e-10 def test_3x3(self): m = Matrix.from_list([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) assert abs(m.det() - (-3)) < 1e-10 def test_identity(self): m = Matrix.identity(4) assert abs(m.det() - 1) < 1e-10 def test_singular(self): m = Matrix.from_list([[1, 2], [2, 4]]) assert abs(m.det()) < 1e-10 class TestMatrixInverse: def test_2x2(self): m = Matrix.from_list([[4, 7], [2, 6]]) inv = m.inverse() result = m.mul(inv) identity = Matrix.identity(2) # Check it's close to identity for i in range(2): for j in range(2): assert abs(result[i, j] - identity[i, j]) < 1e-10 def test_singular(self): m = Matrix.from_list([[1, 2], [2, 4]]) with pytest.raises(ValueError): m.inverse() class TestFrobeniusNorm: def test_basic(self): m = Matrix.from_list([[1, 2], [3, 4]]) norm = m.frobenius_norm() expected = math.sqrt(1 + 4 + 9 + 16) assert abs(norm - expected) < 1e-10 class TestDot: def test_basic(self): assert dot([1, 2, 3], [4, 5, 6]) == 32 class TestSimulateMatrix: def test_add(self): result = simulate_matrix(["add:"]) assert "[[6, 8], [10, 12]]" in result[0] def test_mul(self): result = simulate_matrix(["mul:"]) assert "19" in result[0] and "22" in result[0] and "43" in result[0] and "50" in result[0] def test_transpose(self): result = simulate_matrix(["transpose:"]) assert "[[1, 4], [2, 5], [3, 6]]" in result[0] def test_det(self): result = simulate_matrix(["det:"]) assert result == ["-2.0"] def test_identity(self): result = simulate_matrix(["identity:2"]) assert "[[1.0, 0.0], [0.0, 1.0]]" in result[0]
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_num_matrix/test_num_matrix_cli.py (6020 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_num_matrix/test_num_matrix_cli.rs (10080 bytes) ⏱️ Parse time: 53ms 📊 Throughput: 110.7 KB/s ⏱️ Total time: 53ms
true
num_matrix
216
5
[ "context_manager", "class_definition" ]
0.652
null
example_num_roots
num_roots_cli.py
"""Root Finding CLI. Demonstrates root finding methods: Newton, bisection, secant. """ import math import sys from collections.abc import Callable from dataclasses import dataclass @dataclass class RootResult: """Result of root finding.""" root: float iterations: int converged: bool error: float def bisection( f: Callable[[float], float], a: float, b: float, tol: float = 1e-10, max_iter: int = 100 ) -> RootResult: """Find root using bisection method.""" if f(a) * f(b) > 0: raise ValueError("f(a) and f(b) must have opposite signs") for i in range(max_iter): c = (a + b) / 2 fc = f(c) if abs(fc) < tol or (b - a) / 2 < tol: return RootResult(c, i + 1, True, abs(fc)) if fc * f(a) < 0: b = c else: a = c return RootResult((a + b) / 2, max_iter, False, abs(f((a + b) / 2))) def newton( f: Callable[[float], float], df: Callable[[float], float], x0: float, tol: float = 1e-10, max_iter: int = 100, ) -> RootResult: """Find root using Newton-Raphson method.""" x = x0 for i in range(max_iter): fx = f(x) dfx = df(x) if abs(dfx) < 1e-14: return RootResult(x, i + 1, False, abs(fx)) x_new = x - fx / dfx if abs(x_new - x) < tol: return RootResult(x_new, i + 1, True, abs(f(x_new))) x = x_new return RootResult(x, max_iter, False, abs(f(x))) def secant( f: Callable[[float], float], x0: float, x1: float, tol: float = 1e-10, max_iter: int = 100 ) -> RootResult: """Find root using secant method.""" for i in range(max_iter): f0, f1 = f(x0), f(x1) if abs(f1 - f0) < 1e-14: return RootResult(x1, i + 1, False, abs(f1)) x_new = x1 - f1 * (x1 - x0) / (f1 - f0) if abs(x_new - x1) < tol: return RootResult(x_new, i + 1, True, abs(f(x_new))) x0, x1 = x1, x_new return RootResult(x1, max_iter, False, abs(f(x1))) def regula_falsi( f: Callable[[float], float], a: float, b: float, tol: float = 1e-10, max_iter: int = 100 ) -> RootResult: """Find root using regula falsi (false position) method.""" if f(a) * f(b) > 0: raise ValueError("f(a) and f(b) must have opposite signs") for i in range(max_iter): fa, fb = f(a), f(b) c = (a * fb - b * fa) / (fb - fa) fc = f(c) if abs(fc) < tol: return RootResult(c, i + 1, True, abs(fc)) if fc * fa < 0: b = c else: a = c c = (a * f(b) - b * f(a)) / (f(b) - f(a)) return RootResult(c, max_iter, False, abs(f(c))) def brent( f: Callable[[float], float], a: float, b: float, tol: float = 1e-10, max_iter: int = 100 ) -> RootResult: """Find root using Brent's method.""" if f(a) * f(b) > 0: raise ValueError("f(a) and f(b) must have opposite signs") if abs(f(a)) < abs(f(b)): a, b = b, a c = a d = a # Initialize d for Brent's method mflag = True for i in range(max_iter): fa, fb, fc = f(a), f(b), f(c) if abs(fb) < tol: return RootResult(b, i + 1, True, abs(fb)) # Try inverse quadratic interpolation if fa != fc and fb != fc: s = ( a * fb * fc / ((fa - fb) * (fa - fc)) + b * fa * fc / ((fb - fa) * (fb - fc)) + c * fa * fb / ((fc - fa) * (fc - fb)) ) else: s = b - fb * (b - a) / (fb - fa) # Check if s is acceptable cond1 = (s < (3 * a + b) / 4 or s > b) if a < b else (s > (3 * a + b) / 4 or s < b) cond2 = mflag and abs(s - b) >= abs(b - c) / 2 cond3 = not mflag and abs(s - b) >= abs(c - d) / 2 if i > 0 else False cond4 = mflag and abs(b - c) < tol cond5 = not mflag and abs(c - d) < tol if i > 0 else False if cond1 or cond2 or cond3 or cond4 or cond5: s = (a + b) / 2 mflag = True else: mflag = False d = c c = b if f(a) * f(s) < 0: b = s else: a = s if abs(f(a)) < abs(f(b)): a, b = b, a return RootResult(b, max_iter, False, abs(f(b))) def fixed_point( g: Callable[[float], float], x0: float, tol: float = 1e-10, max_iter: int = 100 ) -> RootResult: """Find fixed point x = g(x).""" x = x0 for i in range(max_iter): x_new = g(x) if abs(x_new - x) < tol: return RootResult(x_new, i + 1, True, abs(x_new - g(x_new))) x = x_new return RootResult(x, max_iter, False, abs(x - g(x))) def find_all_roots( f: Callable[[float], float], a: float, b: float, n_intervals: int = 100, tol: float = 1e-10 ) -> list[float]: """Find all roots in interval by searching subintervals.""" roots = [] dx = (b - a) / n_intervals for i in range(n_intervals): x0 = a + i * dx x1 = a + (i + 1) * dx if f(x0) * f(x1) <= 0: try: result = bisection(f, x0, x1, tol) if result.converged: # Check if we already found this root if not any(abs(r - result.root) < tol * 10 for r in roots): roots.append(result.root) except ValueError: pass return sorted(roots) def simulate_roots(operations: list[str]) -> list[str]: """Simulate root finding operations.""" results: list[str] = [] # Test function: x^2 - 2 (root at sqrt(2)) def f(x): return x**2 - 2 def df(x): return 2 * x for op in operations: parts = op.split(":", 1) cmd = parts[0] if cmd == "bisection": result = bisection(f, 1, 2) results.append(f"root={result.root:.6f} iter={result.iterations}") elif cmd == "newton": result = newton(f, df, 1.5) results.append(f"root={result.root:.6f} iter={result.iterations}") elif cmd == "secant": result = secant(f, 1, 2) results.append(f"root={result.root:.6f} iter={result.iterations}") elif cmd == "sin_roots": roots = find_all_roots(math.sin, 0, 10) results.append(f"roots={[round(r, 4) for r in roots]}") return results def main() -> int: """CLI entry point.""" if len(sys.argv) < 2: print("Usage: num_roots_cli.py <command>") return 1 cmd = sys.argv[1] if cmd == "demo": def f(x): return x**3 - x - 2 def df(x): return 3 * x**2 - 1 print("Finding root of x^3 - x - 2:") result = bisection(f, 1, 2) print(f"Bisection: root={result.root:.10f}, iterations={result.iterations}") result = newton(f, df, 1.5) print(f"Newton: root={result.root:.10f}, iterations={result.iterations}") result = secant(f, 1, 2) print(f"Secant: root={result.root:.10f}, iterations={result.iterations}") print("\nRoots of sin(x) in [0, 10]:") roots = find_all_roots(math.sin, 0, 10) print(f"Roots: {[f'{r:.4f}' for r in roots]}") else: print("Unknown command") return 1 return 0 if __name__ == "__main__": sys.exit(main())
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_num_roots/num_roots_cli.py (7371 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_num_roots/num_roots_cli.rs (14607 bytes) ⏱️ Parse time: 53ms 📊 Throughput: 133.4 KB/s ⏱️ Total time: 54ms
true
num_roots
275
5
[ "class_definition", "exception_handling", "decorator" ]
0.612
null
example_num_roots
test_num_roots_cli.py
"""Tests for num_roots_cli.py""" import math import pytest from num_roots_cli import ( RootResult, bisection, brent, find_all_roots, fixed_point, newton, regula_falsi, secant, simulate_roots, ) class TestBisection: def test_sqrt2(self): def f(x): return x**2 - 2 result = bisection(f, 1, 2) assert result.converged assert abs(result.root - math.sqrt(2)) < 1e-9 def test_cubic(self): def f(x): return x**3 - x - 2 result = bisection(f, 1, 2) assert result.converged assert abs(f(result.root)) < 1e-9 def test_sign_error(self): def f(x): return x**2 + 1 # No real root with pytest.raises(ValueError): bisection(f, 0, 1) def test_converges_quickly(self): def f(x): return x - 0.5 result = bisection(f, 0, 1) assert result.converged assert result.iterations < 50 def test_exact_root_at_midpoint(self): def f(x): return x result = bisection(f, -1, 1) assert result.converged assert abs(result.root) < 1e-9 class TestNewton: def test_sqrt2(self): def f(x): return x**2 - 2 def df(x): return 2 * x result = newton(f, df, 1.5) assert result.converged assert abs(result.root - math.sqrt(2)) < 1e-9 def test_cubic(self): def f(x): return x**3 - x - 2 def df(x): return 3 * x**2 - 1 result = newton(f, df, 1.5) assert result.converged assert abs(f(result.root)) < 1e-9 def test_faster_than_bisection(self): def f(x): return x**2 - 2 def df(x): return 2 * x newton_result = newton(f, df, 1.5) bisect_result = bisection(f, 1, 2) assert newton_result.iterations < bisect_result.iterations def test_zero_derivative(self): def f(x): return x**3 def df(x): return 3 * x**2 # Zero at x=0 result = newton(f, df, 0.0) # Should fail or converge with difficulty assert not result.converged or abs(result.root) < 1e-9 def test_converges_quadratically(self): def f(x): return x**2 - 2 def df(x): return 2 * x result = newton(f, df, 1.5) assert result.iterations < 10 class TestSecant: def test_sqrt2(self): def f(x): return x**2 - 2 result = secant(f, 1, 2) assert result.converged assert abs(result.root - math.sqrt(2)) < 1e-9 def test_cubic(self): def f(x): return x**3 - x - 2 result = secant(f, 1, 2) assert result.converged assert abs(f(result.root)) < 1e-9 def test_linear(self): def f(x): return 2 * x - 4 result = secant(f, 0, 3) assert result.converged assert abs(result.root - 2) < 1e-9 def test_no_derivative_needed(self): def f(x): return x**4 - x - 1 result = secant(f, 1, 2) assert result.converged assert abs(f(result.root)) < 1e-9 class TestRegulaFalsi: def test_sqrt2(self): def f(x): return x**2 - 2 result = regula_falsi(f, 1, 2) assert result.converged assert abs(result.root - math.sqrt(2)) < 1e-9 def test_cubic(self): def f(x): return x**3 - x - 2 result = regula_falsi(f, 1, 2) assert result.converged assert abs(f(result.root)) < 1e-9 def test_sign_error(self): def f(x): return x**2 + 1 with pytest.raises(ValueError): regula_falsi(f, 0, 1) class TestBrent: def test_sqrt2(self): def f(x): return x**2 - 2 result = brent(f, 1, 2) assert result.converged assert abs(result.root - math.sqrt(2)) < 1e-9 def test_cubic(self): def f(x): return x**3 - x - 2 result = brent(f, 1, 2) assert result.converged assert abs(f(result.root)) < 1e-9 def test_sign_error(self): def f(x): return x**2 + 1 with pytest.raises(ValueError): brent(f, 0, 1) def test_efficient(self): def f(x): return x**2 - 2 result = brent(f, 1, 2) assert result.iterations < 20 class TestFixedPoint: def test_sqrt2(self): def g(x): return (x + 2 / x) / 2 # Babylonian method result = fixed_point(g, 1.5) assert result.converged assert abs(result.root - math.sqrt(2)) < 1e-9 def test_convergent(self): def g(x): return math.cos(x) result = fixed_point(g, 0.5) # Fixed point of cos(x) is ~0.739 assert result.converged assert abs(result.root - 0.7390851332151607) < 1e-9 def test_linear(self): def g(x): return x / 2 + 1 # x = x/2 + 1 => x = 2 result = fixed_point(g, 0.0) assert result.converged assert abs(result.root - 2) < 1e-9 class TestFindAllRoots: def test_sin_roots(self): roots = find_all_roots(math.sin, 0.1, 10) # Start past 0 to avoid edge # Should find roots at pi, 2*pi, 3*pi assert len(roots) >= 2 for r in roots: assert abs(math.sin(r)) < 1e-9 def test_quadratic_two_roots(self): def f(x): return x**2 - 4 # Roots at -2 and 2 roots = find_all_roots(f, -3, 3) assert len(roots) == 2 for r in roots: assert abs(f(r)) < 1e-9 def test_cubic_one_real_root(self): def f(x): return x**3 + x + 1 roots = find_all_roots(f, -2, 2) assert len(roots) >= 1 for r in roots: assert abs(f(r)) < 1e-9 def test_no_roots(self): def f(x): return x**2 + 1 # No real roots roots = find_all_roots(f, -10, 10) assert len(roots) == 0 class TestRootResult: def test_create(self): result = RootResult(1.414, 5, True, 1e-10) assert result.root == 1.414 assert result.iterations == 5 assert result.converged is True assert result.error == 1e-10 def test_not_converged(self): result = RootResult(1.5, 100, False, 0.01) assert not result.converged class TestSimulateRoots: def test_bisection(self): result = simulate_roots(["bisection:"]) assert "root=" in result[0] assert "iter=" in result[0] def test_newton(self): result = simulate_roots(["newton:"]) assert "root=" in result[0] def test_secant(self): result = simulate_roots(["secant:"]) assert "root=" in result[0] def test_sin_roots(self): result = simulate_roots(["sin_roots:"]) assert "roots=" in result[0] def test_multiple_operations(self): result = simulate_roots(["bisection:", "newton:"]) assert len(result) == 2
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_num_roots/test_num_roots_cli.py (7126 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_num_roots/test_num_roots_cli.rs (10331 bytes) ⏱️ Parse time: 50ms 📊 Throughput: 137.6 KB/s ⏱️ Total time: 50ms
true
num_roots
269
5
[ "context_manager", "class_definition" ]
0.652
null
example_numpy_abs
numpy_abs_tool.py
#!/usr/bin/env python3 """NumPy Abs Example - Element-wise abs CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Element-wise abs tool") subs = parser.add_subparsers(dest="cmd", required=True) s3 = subs.add_parser("abs3") s3.add_argument("a", type=float) s3.add_argument("b", type=float) s3.add_argument("c", type=float) s4 = subs.add_parser("abs4") s4.add_argument("a", type=float) s4.add_argument("b", type=float) s4.add_argument("c", type=float) s4.add_argument("d", type=float) s2 = subs.add_parser("abs2") s2.add_argument("a", type=float) s2.add_argument("b", type=float) args = parser.parse_args() if args.cmd == "abs3": arr = np.array([args.a, args.b, args.c]) result = np.abs(arr) print(" ".join(str(x) for x in result)) elif args.cmd == "abs4": arr = np.array([args.a, args.b, args.c, args.d]) result = np.abs(arr) print(" ".join(str(x) for x in result)) elif args.cmd == "abs2": arr = np.array([args.a, args.b]) result = np.abs(arr) print(" ".join(str(x) for x in result)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_abs/numpy_abs_tool.py (1226 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_abs/numpy_abs_tool.rs (2494 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_abs/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 24.3 KB/s ⏱️ Total time: 49ms
true
numpy_abs
44
6
[]
0
null
example_numpy_abs
test_numpy_abs_tool.py
"""Tests for numpy_abs_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_abs_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("abs3 -1 2 -3") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "1.0" in out or abs(float(out.split()[0]) - float("1.0")) < 0.1 def test_2(): r = run("abs4 -5 5 -10 10") assert r.returncode == 0 def test_3(): r = run("abs2 -100 50") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_abs/test_numpy_abs_tool.py (661 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_abs/test_numpy_abs_tool.rs (2154 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_abs/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 13.2 KB/s ⏱️ Total time: 49ms
true
numpy_abs
32
6
[]
0
null
example_numpy_add
numpy_add_tool.py
#!/usr/bin/env python3 """NumPy Add Example - Element-wise add CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Element-wise add tool") subs = parser.add_subparsers(dest="cmd", required=True) a3 = subs.add_parser("add3") a3.add_argument("a1", type=float) a3.add_argument("a2", type=float) a3.add_argument("a3", type=float) a3.add_argument("b1", type=float) a3.add_argument("b2", type=float) a3.add_argument("b3", type=float) a2 = subs.add_parser("add2") a2.add_argument("a1", type=float) a2.add_argument("a2", type=float) a2.add_argument("b1", type=float) a2.add_argument("b2", type=float) a4 = subs.add_parser("add4") a4.add_argument("a1", type=float) a4.add_argument("a2", type=float) a4.add_argument("a3", type=float) a4.add_argument("a4", type=float) a4.add_argument("b1", type=float) a4.add_argument("b2", type=float) a4.add_argument("b3", type=float) a4.add_argument("b4", type=float) args = parser.parse_args() if args.cmd == "add3": a = np.array([args.a1, args.a2, args.a3]) b = np.array([args.b1, args.b2, args.b3]) result = a + b print(" ".join(str(x) for x in result)) elif args.cmd == "add2": a = np.array([args.a1, args.a2]) b = np.array([args.b1, args.b2]) result = a + b print(" ".join(str(x) for x in result)) elif args.cmd == "add4": a = np.array([args.a1, args.a2, args.a3, args.a4]) b = np.array([args.b1, args.b2, args.b3, args.b4]) result = a + b print(" ".join(str(x) for x in result)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_add/numpy_add_tool.py (1712 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_add/numpy_add_tool.rs (3432 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_add/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 34.0 KB/s ⏱️ Total time: 49ms
true
numpy_add
56
6
[]
0
null
example_numpy_add
test_numpy_add_tool.py
"""Tests for numpy_add_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_add_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("add3 1 2 3 4 5 6") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "5.0" in out or abs(float(out.split()[0]) - float("5.0")) < 0.1 def test_2(): r = run("add2 10 20 1 2") assert r.returncode == 0 def test_3(): r = run("add4 1 1 1 1 2 2 2 2") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_add/test_numpy_add_tool.py (671 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_add/test_numpy_add_tool.rs (2164 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_add/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 13.7 KB/s ⏱️ Total time: 48ms
true
numpy_add
32
6
[]
0
null
example_numpy_argmax
numpy_argmax_tool.py
#!/usr/bin/env python3 """NumPy Argmax Example - Argmax index CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Argmax index tool") subs = parser.add_subparsers(dest="cmd", required=True) s3 = subs.add_parser("argmax3") s3.add_argument("a", type=float) s3.add_argument("b", type=float) s3.add_argument("c", type=float) s4 = subs.add_parser("argmax4") s4.add_argument("a", type=float) s4.add_argument("b", type=float) s4.add_argument("c", type=float) s4.add_argument("d", type=float) s5 = subs.add_parser("argmax5") s5.add_argument("a", type=float) s5.add_argument("b", type=float) s5.add_argument("c", type=float) s5.add_argument("d", type=float) s5.add_argument("e", type=float) args = parser.parse_args() if args.cmd == "argmax3": arr = np.array([args.a, args.b, args.c]) print(np.argmax(arr)) elif args.cmd == "argmax4": arr = np.array([args.a, args.b, args.c, args.d]) print(np.argmax(arr)) elif args.cmd == "argmax5": arr = np.array([args.a, args.b, args.c, args.d, args.e]) print(np.argmax(arr)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_argmax/numpy_argmax_tool.py (1233 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_argmax/numpy_argmax_tool.rs (1985 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_argmax/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 25.5 KB/s ⏱️ Total time: 47ms
true
numpy_argmax
44
6
[]
0
null
example_numpy_argmax
test_numpy_argmax_tool.py
"""Tests for numpy_argmax_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_argmax_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("argmax3 1 5 3") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "1" in out or abs(float(out.split()[0]) - float("1")) < 0.1 def test_2(): r = run("argmax4 10 5 20 15") assert r.returncode == 0 def test_3(): r = run("argmax5 1 2 3 4 5") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_argmax/test_numpy_argmax_tool.py (671 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_argmax/test_numpy_argmax_tool.rs (2161 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_argmax/Cargo.toml (2 dependencies) ⏱️ Parse time: 50ms 📊 Throughput: 12.9 KB/s ⏱️ Total time: 51ms
true
numpy_argmax
32
6
[]
0
null
example_numpy_argmin
numpy_argmin_tool.py
#!/usr/bin/env python3 """NumPy Argmin Example - Argmin index CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Argmin index tool") subs = parser.add_subparsers(dest="cmd", required=True) s3 = subs.add_parser("argmin3") s3.add_argument("a", type=float) s3.add_argument("b", type=float) s3.add_argument("c", type=float) s4 = subs.add_parser("argmin4") s4.add_argument("a", type=float) s4.add_argument("b", type=float) s4.add_argument("c", type=float) s4.add_argument("d", type=float) s5 = subs.add_parser("argmin5") s5.add_argument("a", type=float) s5.add_argument("b", type=float) s5.add_argument("c", type=float) s5.add_argument("d", type=float) s5.add_argument("e", type=float) args = parser.parse_args() if args.cmd == "argmin3": arr = np.array([args.a, args.b, args.c]) print(np.argmin(arr)) elif args.cmd == "argmin4": arr = np.array([args.a, args.b, args.c, args.d]) print(np.argmin(arr)) elif args.cmd == "argmin5": arr = np.array([args.a, args.b, args.c, args.d, args.e]) print(np.argmin(arr)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_argmin/numpy_argmin_tool.py (1233 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_argmin/numpy_argmin_tool.rs (1985 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_argmin/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 25.5 KB/s ⏱️ Total time: 47ms
true
numpy_argmin
44
6
[]
0
null
example_numpy_argmin
test_numpy_argmin_tool.py
"""Tests for numpy_argmin_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_argmin_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("argmin3 5 1 3") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "1" in out or abs(float(out.split()[0]) - float("1")) < 0.1 def test_2(): r = run("argmin4 10 5 20 15") assert r.returncode == 0 def test_3(): r = run("argmin5 5 4 3 2 1") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_argmin/test_numpy_argmin_tool.py (671 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_argmin/test_numpy_argmin_tool.rs (2161 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_argmin/Cargo.toml (2 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 13.5 KB/s ⏱️ Total time: 48ms
true
numpy_argmin
32
6
[]
0
null
example_numpy_clip
numpy_clip_tool.py
#!/usr/bin/env python3 """NumPy Clip Example - Clip/clamp CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Clip/clamp tool") subs = parser.add_subparsers(dest="cmd", required=True) c3 = subs.add_parser("clip3") c3.add_argument("a", type=float) c3.add_argument("b", type=float) c3.add_argument("c", type=float) c3.add_argument("lo", type=float) c3.add_argument("hi", type=float) c4 = subs.add_parser("clip4") c4.add_argument("a", type=float) c4.add_argument("b", type=float) c4.add_argument("c", type=float) c4.add_argument("d", type=float) c4.add_argument("lo", type=float) c4.add_argument("hi", type=float) c2 = subs.add_parser("clip2") c2.add_argument("a", type=float) c2.add_argument("b", type=float) c2.add_argument("lo", type=float) c2.add_argument("hi", type=float) args = parser.parse_args() if args.cmd == "clip3": arr = np.array([args.a, args.b, args.c]) result = np.clip(arr, args.lo, args.hi) print(" ".join(str(x) for x in result)) elif args.cmd == "clip4": arr = np.array([args.a, args.b, args.c, args.d]) result = np.clip(arr, args.lo, args.hi) print(" ".join(str(x) for x in result)) elif args.cmd == "clip2": arr = np.array([args.a, args.b]) result = np.clip(arr, args.lo, args.hi) print(" ".join(str(x) for x in result)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_clip/numpy_clip_tool.py (1506 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_clip/numpy_clip_tool.rs (3028 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_clip/Cargo.toml (2 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 30.6 KB/s ⏱️ Total time: 48ms
true
numpy_clip
50
6
[]
0
null
example_numpy_clip
test_numpy_clip_tool.py
"""Tests for numpy_clip_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_clip_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("clip3 -5 50 150 0 100") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "0.0" in out or abs(float(out.split()[0]) - float("0.0")) < 0.1 def test_2(): r = run("clip4 -1 0 1 2 0 1") assert r.returncode == 0 def test_3(): r = run("clip2 -10 10 0 5") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_clip/test_numpy_clip_tool.py (678 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_clip/test_numpy_clip_tool.rs (2170 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_clip/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 13.9 KB/s ⏱️ Total time: 47ms
true
numpy_clip
32
6
[]
0
null
example_numpy_cos
numpy_cos_tool.py
#!/usr/bin/env python3 """NumPy Cos Example - Trigonometric cos CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Trigonometric cos tool") subs = parser.add_subparsers(dest="cmd", required=True) s3 = subs.add_parser("cos3") s3.add_argument("a", type=float) s3.add_argument("b", type=float) s3.add_argument("c", type=float) s2 = subs.add_parser("cos2") s2.add_argument("a", type=float) s2.add_argument("b", type=float) s1 = subs.add_parser("cos1") s1.add_argument("a", type=float) args = parser.parse_args() if args.cmd == "cos3": arr = np.array([args.a, args.b, args.c]) result = np.cos(arr) print(" ".join(str(round(x, 1)) for x in result)) elif args.cmd == "cos2": arr = np.array([args.a, args.b]) result = np.cos(arr) print(" ".join(str(round(x, 1)) for x in result)) elif args.cmd == "cos1": result = np.cos(args.a) print(round(result, 1)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_cos/numpy_cos_tool.py (1067 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_cos/numpy_cos_tool.rs (2037 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_cos/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 20.9 KB/s ⏱️ Total time: 50ms
true
numpy_cos
40
6
[]
0
null
example_numpy_cos
test_numpy_cos_tool.py
"""Tests for numpy_cos_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_cos_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("cos3 0 1.571 3.142") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "1.0" in out or abs(float(out.split()[0]) - float("1.0")) < 0.1 def test_2(): r = run("cos2 0 0") assert r.returncode == 0 def test_3(): r = run("cos1 0") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_cos/test_numpy_cos_tool.py (653 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_cos/test_numpy_cos_tool.rs (2146 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_cos/Cargo.toml (2 dependencies) ⏱️ Parse time: 51ms 📊 Throughput: 12.5 KB/s ⏱️ Total time: 51ms
true
numpy_cos
32
6
[]
0
null
example_numpy_cosine
numpy_cosine_tool.py
#!/usr/bin/env python3 """NumPy Cosine Example - Cosine similarity CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Cosine similarity tool") subs = parser.add_subparsers(dest="cmd", required=True) c3 = subs.add_parser("cosine3") c3.add_argument("a1", type=float) c3.add_argument("a2", type=float) c3.add_argument("a3", type=float) c3.add_argument("b1", type=float) c3.add_argument("b2", type=float) c3.add_argument("b3", type=float) c2 = subs.add_parser("cosine2") c2.add_argument("a1", type=float) c2.add_argument("a2", type=float) c2.add_argument("b1", type=float) c2.add_argument("b2", type=float) c4 = subs.add_parser("cosine4") c4.add_argument("a1", type=float) c4.add_argument("a2", type=float) c4.add_argument("a3", type=float) c4.add_argument("a4", type=float) c4.add_argument("b1", type=float) c4.add_argument("b2", type=float) c4.add_argument("b3", type=float) c4.add_argument("b4", type=float) args = parser.parse_args() if args.cmd == "cosine3": a = np.array([args.a1, args.a2, args.a3]) b = np.array([args.b1, args.b2, args.b3]) dot = np.dot(a, b) norm_a = np.linalg.norm(a) norm_b = np.linalg.norm(b) result = dot / (norm_a * norm_b) if norm_a > 0 and norm_b > 0 else 0 print(round(result, 3)) elif args.cmd == "cosine2": a = np.array([args.a1, args.a2]) b = np.array([args.b1, args.b2]) dot = np.dot(a, b) norm_a = np.linalg.norm(a) norm_b = np.linalg.norm(b) result = dot / (norm_a * norm_b) if norm_a > 0 and norm_b > 0 else 0 print(round(result, 3)) elif args.cmd == "cosine4": a = np.array([args.a1, args.a2, args.a3, args.a4]) b = np.array([args.b1, args.b2, args.b3, args.b4]) dot = np.dot(a, b) norm_a = np.linalg.norm(a) norm_b = np.linalg.norm(b) result = dot / (norm_a * norm_b) if norm_a > 0 and norm_b > 0 else 0 print(round(result, 3)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_cosine/numpy_cosine_tool.py (2140 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_cosine/numpy_cosine_tool.rs (4082 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_cosine/Cargo.toml (2 dependencies) ⏱️ Parse time: 50ms 📊 Throughput: 41.6 KB/s ⏱️ Total time: 50ms
true
numpy_cosine
65
6
[]
0
null
example_numpy_cosine
test_numpy_cosine_tool.py
"""Tests for numpy_cosine_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_cosine_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("cosine3 1 0 0 1 0 0") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "1.0" in out or abs(float(out.split()[0]) - float("1.0")) < 0.1 def test_2(): r = run("cosine2 1 0 0 1") assert r.returncode == 0 def test_3(): r = run("cosine4 1 1 1 1 1 1 1 1") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_cosine/test_numpy_cosine_tool.py (684 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_cosine/test_numpy_cosine_tool.rs (2174 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_cosine/Cargo.toml (2 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 13.7 KB/s ⏱️ Total time: 49ms
true
numpy_cosine
32
6
[]
0
null
example_numpy_distance
numpy_distance_tool.py
#!/usr/bin/env python3 """NumPy Distance Example - Euclidean distance CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Euclidean distance tool") subs = parser.add_subparsers(dest="cmd", required=True) d3 = subs.add_parser("dist3") d3.add_argument("a1", type=float) d3.add_argument("a2", type=float) d3.add_argument("a3", type=float) d3.add_argument("b1", type=float) d3.add_argument("b2", type=float) d3.add_argument("b3", type=float) d2 = subs.add_parser("dist2") d2.add_argument("a1", type=float) d2.add_argument("a2", type=float) d2.add_argument("b1", type=float) d2.add_argument("b2", type=float) d4 = subs.add_parser("dist4") d4.add_argument("a1", type=float) d4.add_argument("a2", type=float) d4.add_argument("a3", type=float) d4.add_argument("a4", type=float) d4.add_argument("b1", type=float) d4.add_argument("b2", type=float) d4.add_argument("b3", type=float) d4.add_argument("b4", type=float) args = parser.parse_args() if args.cmd == "dist3": a = np.array([args.a1, args.a2, args.a3]) b = np.array([args.b1, args.b2, args.b3]) print(round(np.linalg.norm(a - b), 3)) elif args.cmd == "dist2": a = np.array([args.a1, args.a2]) b = np.array([args.b1, args.b2]) print(round(np.linalg.norm(a - b), 3)) elif args.cmd == "dist4": a = np.array([args.a1, args.a2, args.a3, args.a4]) b = np.array([args.b1, args.b2, args.b3, args.b4]) print(round(np.linalg.norm(a - b), 3)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_distance/numpy_distance_tool.py (1655 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_distance/numpy_distance_tool.rs (2697 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_distance/Cargo.toml (2 dependencies) ⏱️ Parse time: 50ms 📊 Throughput: 31.8 KB/s ⏱️ Total time: 51ms
true
numpy_distance
53
6
[]
0
null
example_numpy_distance
test_numpy_distance_tool.py
"""Tests for numpy_distance_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_distance_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("dist3 0 0 0 1 1 1") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "1.73" in out or abs(float(out.split()[0]) - float("1.732")) < 0.1 def test_2(): r = run("dist2 0 0 3 4") assert r.returncode == 0 def test_3(): r = run("dist4 1 1 1 1 2 2 2 2") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_distance/test_numpy_distance_tool.py (685 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_distance/test_numpy_distance_tool.rs (2173 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_distance/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 13.6 KB/s ⏱️ Total time: 49ms
true
numpy_distance
32
6
[]
0
null
example_numpy_dot
numpy_dot_tool.py
#!/usr/bin/env python3 """NumPy Dot Example - Dot product operations CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Dot product tool") subs = parser.add_subparsers(dest="cmd", required=True) d3 = subs.add_parser("dot3") d3.add_argument("a1", type=float) d3.add_argument("a2", type=float) d3.add_argument("a3", type=float) d3.add_argument("b1", type=float) d3.add_argument("b2", type=float) d3.add_argument("b3", type=float) d4 = subs.add_parser("dot4") d4.add_argument("a1", type=float) d4.add_argument("a2", type=float) d4.add_argument("a3", type=float) d4.add_argument("a4", type=float) d4.add_argument("b1", type=float) d4.add_argument("b2", type=float) d4.add_argument("b3", type=float) d4.add_argument("b4", type=float) d2 = subs.add_parser("dot2") d2.add_argument("a1", type=float) d2.add_argument("a2", type=float) d2.add_argument("b1", type=float) d2.add_argument("b2", type=float) args = parser.parse_args() if args.cmd == "dot3": a = np.array([args.a1, args.a2, args.a3]) b = np.array([args.b1, args.b2, args.b3]) print(np.dot(a, b)) elif args.cmd == "dot4": a = np.array([args.a1, args.a2, args.a3, args.a4]) b = np.array([args.b1, args.b2, args.b3, args.b4]) print(np.dot(a, b)) elif args.cmd == "dot2": a = np.array([args.a1, args.a2]) b = np.array([args.b1, args.b2]) print(np.dot(a, b)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_dot/numpy_dot_tool.py (1584 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_dot/numpy_dot_tool.rs (2593 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_dot/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 32.3 KB/s ⏱️ Total time: 48ms
true
numpy_dot
53
6
[]
0
null
example_numpy_dot
test_numpy_dot_tool.py
"""Tests for numpy_dot_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_dot_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_dot3(): r = run("dot3 1 2 3 4 5 6") assert r.returncode == 0 assert r.stdout.strip() == "32.0" def test_dot4(): r = run("dot4 1 1 1 1 1 1 1 1") assert r.returncode == 0 assert r.stdout.strip() == "4.0" def test_dot2(): r = run("dot2 3 4 3 4") assert r.returncode == 0 assert r.stdout.strip() == "25.0"
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_dot/test_numpy_dot_tool.py (654 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_dot/test_numpy_dot_tool.rs (1929 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_dot/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 13.4 KB/s ⏱️ Total time: 48ms
true
numpy_dot
32
6
[]
0
null
example_numpy_exp
numpy_exp_tool.py
#!/usr/bin/env python3 """NumPy Exp Example - Element-wise exp CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Element-wise exp tool") subs = parser.add_subparsers(dest="cmd", required=True) s3 = subs.add_parser("exp3") s3.add_argument("a", type=float) s3.add_argument("b", type=float) s3.add_argument("c", type=float) s2 = subs.add_parser("exp2") s2.add_argument("a", type=float) s2.add_argument("b", type=float) s1 = subs.add_parser("exp1") s1.add_argument("a", type=float) args = parser.parse_args() if args.cmd == "exp3": arr = np.array([args.a, args.b, args.c]) result = np.exp(arr) print(" ".join(str(round(x, 3)) for x in result)) elif args.cmd == "exp2": arr = np.array([args.a, args.b]) result = np.exp(arr) print(" ".join(str(round(x, 3)) for x in result)) elif args.cmd == "exp1": result = np.exp(args.a) print(round(result, 3)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_exp/numpy_exp_tool.py (1065 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_exp/numpy_exp_tool.rs (2036 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_exp/Cargo.toml (2 dependencies) ⏱️ Parse time: 51ms 📊 Throughput: 20.3 KB/s ⏱️ Total time: 51ms
true
numpy_exp
40
6
[]
0
null
example_numpy_exp
test_numpy_exp_tool.py
"""Tests for numpy_exp_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_exp_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("exp3 0 1 2") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "1.0" in out or abs(float(out.split()[0]) - float("1.0")) < 0.1 def test_2(): r = run("exp2 0 0") assert r.returncode == 0 def test_3(): r = run("exp1 1") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_exp/test_numpy_exp_tool.py (645 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_exp/test_numpy_exp_tool.rs (2138 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_exp/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 12.6 KB/s ⏱️ Total time: 50ms
true
numpy_exp
32
6
[]
0
null
example_numpy_log
numpy_log_tool.py
#!/usr/bin/env python3 """NumPy Log Example - Element-wise log CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Element-wise log tool") subs = parser.add_subparsers(dest="cmd", required=True) s3 = subs.add_parser("log3") s3.add_argument("a", type=float) s3.add_argument("b", type=float) s3.add_argument("c", type=float) s2 = subs.add_parser("log2") s2.add_argument("a", type=float) s2.add_argument("b", type=float) s1 = subs.add_parser("log1") s1.add_argument("a", type=float) args = parser.parse_args() if args.cmd == "log3": arr = np.array([args.a, args.b, args.c]) result = np.log(arr) print(" ".join(str(round(x, 3)) for x in result)) elif args.cmd == "log2": arr = np.array([args.a, args.b]) result = np.log(arr) print(" ".join(str(round(x, 3)) for x in result)) elif args.cmd == "log1": result = np.log(args.a) print(round(result, 3)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_log/numpy_log_tool.py (1065 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_log/numpy_log_tool.rs (2033 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_log/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 21.1 KB/s ⏱️ Total time: 49ms
true
numpy_log
40
6
[]
0
null
example_numpy_log
test_numpy_log_tool.py
"""Tests for numpy_log_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_log_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("log3 1 2.718 7.389") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "0.0" in out or abs(float(out.split()[0]) - float("0.0")) < 0.1 def test_2(): r = run("log2 1 1") assert r.returncode == 0 def test_3(): r = run("log1 2.718") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_log/test_numpy_log_tool.py (657 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_log/test_numpy_log_tool.rs (2150 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_log/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 12.9 KB/s ⏱️ Total time: 49ms
true
numpy_log
32
6
[]
0
null
example_numpy_max
numpy_max_tool.py
#!/usr/bin/env python3 """NumPy Max Example - Max reduction CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Max reduction tool") subs = parser.add_subparsers(dest="cmd", required=True) m3 = subs.add_parser("max3") m3.add_argument("a", type=float) m3.add_argument("b", type=float) m3.add_argument("c", type=float) m4 = subs.add_parser("max4") m4.add_argument("a", type=float) m4.add_argument("b", type=float) m4.add_argument("c", type=float) m4.add_argument("d", type=float) m5 = subs.add_parser("max5") m5.add_argument("a", type=float) m5.add_argument("b", type=float) m5.add_argument("c", type=float) m5.add_argument("d", type=float) m5.add_argument("e", type=float) args = parser.parse_args() if args.cmd == "max3": arr = np.array([args.a, args.b, args.c]) print(np.max(arr)) elif args.cmd == "max4": arr = np.array([args.a, args.b, args.c, args.d]) print(np.max(arr)) elif args.cmd == "max5": arr = np.array([args.a, args.b, args.c, args.d, args.e]) print(np.max(arr)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_max/numpy_max_tool.py (1205 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_max/numpy_max_tool.rs (1956 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_max/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 24.7 KB/s ⏱️ Total time: 47ms
true
numpy_max
44
6
[]
0
null
example_numpy_max
test_numpy_max_tool.py
"""Tests for numpy_max_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_max_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_max3(): r = run("max3 1 5 3") assert r.returncode == 0 assert r.stdout.strip() == "5.0" def test_max4(): r = run("max4 -1 -5 -2 -3") assert r.returncode == 0 assert r.stdout.strip() == "-1.0" def test_max5(): r = run("max5 10 20 50 30 40") assert r.returncode == 0 assert r.stdout.strip() == "50.0"
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_max/test_numpy_max_tool.py (651 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_max/test_numpy_max_tool.rs (1926 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_max/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 13.3 KB/s ⏱️ Total time: 47ms
true
numpy_max
32
6
[]
0
null
example_numpy_mean
numpy_mean_tool.py
#!/usr/bin/env python3 """NumPy Mean Example - Mean reduction CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Mean reduction tool") subs = parser.add_subparsers(dest="cmd", required=True) m3 = subs.add_parser("mean3") m3.add_argument("a", type=float) m3.add_argument("b", type=float) m3.add_argument("c", type=float) m4 = subs.add_parser("mean4") m4.add_argument("a", type=float) m4.add_argument("b", type=float) m4.add_argument("c", type=float) m4.add_argument("d", type=float) m5 = subs.add_parser("mean5") m5.add_argument("a", type=float) m5.add_argument("b", type=float) m5.add_argument("c", type=float) m5.add_argument("d", type=float) m5.add_argument("e", type=float) args = parser.parse_args() if args.cmd == "mean3": arr = np.array([args.a, args.b, args.c]) print(np.mean(arr)) elif args.cmd == "mean4": arr = np.array([args.a, args.b, args.c, args.d]) print(np.mean(arr)) elif args.cmd == "mean5": arr = np.array([args.a, args.b, args.c, args.d, args.e]) print(np.mean(arr)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_mean/numpy_mean_tool.py (1217 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_mean/numpy_mean_tool.rs (1967 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_mean/Cargo.toml (2 dependencies) ⏱️ Parse time: 46ms 📊 Throughput: 25.3 KB/s ⏱️ Total time: 47ms
true
numpy_mean
44
6
[]
0
null
example_numpy_mean
test_numpy_mean_tool.py
"""Tests for numpy_mean_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_mean_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_mean3(): r = run("mean3 1 2 3") assert r.returncode == 0 assert r.stdout.strip() == "2.0" def test_mean4(): r = run("mean4 10 20 30 40") assert r.returncode == 0 assert r.stdout.strip() == "25.0" def test_mean5(): r = run("mean5 2 4 6 8 10") assert r.returncode == 0 assert r.stdout.strip() == "6.0"
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_mean/test_numpy_mean_tool.py (654 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_mean/test_numpy_mean_tool.rs (1928 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_mean/Cargo.toml (2 dependencies) ⏱️ Parse time: 50ms 📊 Throughput: 12.7 KB/s ⏱️ Total time: 50ms
true
numpy_mean
32
6
[]
0
null
example_numpy_min
numpy_min_tool.py
#!/usr/bin/env python3 """NumPy Min Example - Min reduction CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Min reduction tool") subs = parser.add_subparsers(dest="cmd", required=True) m3 = subs.add_parser("min3") m3.add_argument("a", type=float) m3.add_argument("b", type=float) m3.add_argument("c", type=float) m4 = subs.add_parser("min4") m4.add_argument("a", type=float) m4.add_argument("b", type=float) m4.add_argument("c", type=float) m4.add_argument("d", type=float) m5 = subs.add_parser("min5") m5.add_argument("a", type=float) m5.add_argument("b", type=float) m5.add_argument("c", type=float) m5.add_argument("d", type=float) m5.add_argument("e", type=float) args = parser.parse_args() if args.cmd == "min3": arr = np.array([args.a, args.b, args.c]) print(np.min(arr)) elif args.cmd == "min4": arr = np.array([args.a, args.b, args.c, args.d]) print(np.min(arr)) elif args.cmd == "min5": arr = np.array([args.a, args.b, args.c, args.d, args.e]) print(np.min(arr)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_min/numpy_min_tool.py (1205 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_min/numpy_min_tool.rs (1956 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_min/Cargo.toml (2 dependencies) ⏱️ Parse time: 46ms 📊 Throughput: 25.1 KB/s ⏱️ Total time: 47ms
true
numpy_min
44
6
[]
0
null
example_numpy_min
test_numpy_min_tool.py
"""Tests for numpy_min_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_min_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_min3(): r = run("min3 1 5 3") assert r.returncode == 0 assert r.stdout.strip() == "1.0" def test_min4(): r = run("min4 -1 -5 -2 -3") assert r.returncode == 0 assert r.stdout.strip() == "-5.0" def test_min5(): r = run("min5 10 20 5 30 40") assert r.returncode == 0 assert r.stdout.strip() == "5.0"
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_min/test_numpy_min_tool.py (649 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_min/test_numpy_min_tool.rs (1924 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_min/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 13.2 KB/s ⏱️ Total time: 48ms
true
numpy_min
32
6
[]
0
null
example_numpy_minmax
numpy_minmax_tool.py
#!/usr/bin/env python3 """NumPy Minmax Example - Min-max normalization CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Min-max normalization tool") subs = parser.add_subparsers(dest="cmd", required=True) m3 = subs.add_parser("minmax3") m3.add_argument("a", type=float) m3.add_argument("b", type=float) m3.add_argument("c", type=float) m4 = subs.add_parser("minmax4") m4.add_argument("a", type=float) m4.add_argument("b", type=float) m4.add_argument("c", type=float) m4.add_argument("d", type=float) m2 = subs.add_parser("minmax2") m2.add_argument("a", type=float) m2.add_argument("b", type=float) args = parser.parse_args() if args.cmd == "minmax3": arr = np.array([args.a, args.b, args.c]) min_val = np.min(arr) max_val = np.max(arr) denom = max_val - min_val result = (arr - min_val) / denom if denom > 0 else arr * 0 print(" ".join(str(round(x, 2)) for x in result)) elif args.cmd == "minmax4": arr = np.array([args.a, args.b, args.c, args.d]) min_val = np.min(arr) max_val = np.max(arr) denom = max_val - min_val result = (arr - min_val) / denom if denom > 0 else arr * 0 print(" ".join(str(round(x, 2)) for x in result)) elif args.cmd == "minmax2": arr = np.array([args.a, args.b]) min_val = np.min(arr) max_val = np.max(arr) denom = max_val - min_val result = (arr - min_val) / denom if denom > 0 else arr * 0 print(" ".join(str(round(x, 2)) for x in result)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_minmax/numpy_minmax_tool.py (1683 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_minmax/numpy_minmax_tool.rs (3829 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_minmax/Cargo.toml (2 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 33.8 KB/s ⏱️ Total time: 48ms
true
numpy_minmax
53
6
[]
0
null
example_numpy_minmax
test_numpy_minmax_tool.py
"""Tests for numpy_minmax_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_minmax_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("minmax3 0 50 100") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "0.0" in out or abs(float(out.split()[0]) - float("0.0")) < 0.1 def test_2(): r = run("minmax4 10 20 30 40") assert r.returncode == 0 def test_3(): r = run("minmax2 0 100") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_minmax/test_numpy_minmax_tool.py (675 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_minmax/test_numpy_minmax_tool.rs (2165 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_minmax/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 13.9 KB/s ⏱️ Total time: 47ms
true
numpy_minmax
32
6
[]
0
null
example_numpy_mul
numpy_mul_tool.py
#!/usr/bin/env python3 """NumPy Mul Example - Element-wise mul CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Element-wise mul tool") subs = parser.add_subparsers(dest="cmd", required=True) a3 = subs.add_parser("mul3") a3.add_argument("a1", type=float) a3.add_argument("a2", type=float) a3.add_argument("a3", type=float) a3.add_argument("b1", type=float) a3.add_argument("b2", type=float) a3.add_argument("b3", type=float) a2 = subs.add_parser("mul2") a2.add_argument("a1", type=float) a2.add_argument("a2", type=float) a2.add_argument("b1", type=float) a2.add_argument("b2", type=float) a4 = subs.add_parser("mul4") a4.add_argument("a1", type=float) a4.add_argument("a2", type=float) a4.add_argument("a3", type=float) a4.add_argument("a4", type=float) a4.add_argument("b1", type=float) a4.add_argument("b2", type=float) a4.add_argument("b3", type=float) a4.add_argument("b4", type=float) args = parser.parse_args() if args.cmd == "mul3": a = np.array([args.a1, args.a2, args.a3]) b = np.array([args.b1, args.b2, args.b3]) result = a * b print(" ".join(str(x) for x in result)) elif args.cmd == "mul2": a = np.array([args.a1, args.a2]) b = np.array([args.b1, args.b2]) result = a * b print(" ".join(str(x) for x in result)) elif args.cmd == "mul4": a = np.array([args.a1, args.a2, args.a3, args.a4]) b = np.array([args.b1, args.b2, args.b3, args.b4]) result = a * b print(" ".join(str(x) for x in result)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_mul/numpy_mul_tool.py (1712 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_mul/numpy_mul_tool.rs (3585 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_mul/Cargo.toml (2 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 34.4 KB/s ⏱️ Total time: 48ms
true
numpy_mul
56
6
[]
0
null
example_numpy_mul
test_numpy_mul_tool.py
"""Tests for numpy_mul_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_mul_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("mul3 1 2 3 2 3 4") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "2.0" in out or abs(float(out.split()[0]) - float("2.0")) < 0.1 def test_2(): r = run("mul2 3 4 5 6") assert r.returncode == 0 def test_3(): r = run("mul4 2 2 2 2 3 3 3 3") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_mul/test_numpy_mul_tool.py (669 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_mul/test_numpy_mul_tool.rs (2162 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_mul/Cargo.toml (2 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 13.5 KB/s ⏱️ Total time: 48ms
true
numpy_mul
32
6
[]
0
null
example_numpy_norm
numpy_norm_tool.py
#!/usr/bin/env python3 """NumPy Norm Example - Vector norm CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Vector norm tool") subs = parser.add_subparsers(dest="cmd", required=True) l2 = subs.add_parser("l2") l2.add_argument("a", type=float) l2.add_argument("b", type=float) l1 = subs.add_parser("l1") l1.add_argument("a", type=float) l1.add_argument("b", type=float) l1.add_argument("c", type=float) li = subs.add_parser("linf") li.add_argument("a", type=float) li.add_argument("b", type=float) li.add_argument("c", type=float) args = parser.parse_args() if args.cmd == "l2": arr = np.array([args.a, args.b]) print(np.linalg.norm(arr)) elif args.cmd == "l1": arr = np.array([args.a, args.b, args.c]) print(np.linalg.norm(arr, ord=1)) elif args.cmd == "linf": arr = np.array([args.a, args.b, args.c]) print(np.linalg.norm(arr, ord=np.inf)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_norm/numpy_norm_tool.py (1057 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_norm/numpy_norm_tool.rs (1557 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_norm/Cargo.toml (2 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 21.1 KB/s ⏱️ Total time: 49ms
true
numpy_norm
40
6
[]
0
null
example_numpy_norm
test_numpy_norm_tool.py
"""Tests for numpy_norm_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_norm_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("l2 3 4") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "5.0" in out or abs(float(out.split()[0]) - float("5.0")) < 0.1 def test_2(): r = run("l1 1 2 3") assert r.returncode == 0 def test_3(): r = run("linf 1 5 3") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_norm/test_numpy_norm_tool.py (647 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_norm/test_numpy_norm_tool.rs (2139 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_norm/Cargo.toml (2 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 13.0 KB/s ⏱️ Total time: 48ms
true
numpy_norm
32
6
[]
0
null
example_numpy_normalize
numpy_normalize_tool.py
#!/usr/bin/env python3 """NumPy Normalize Example - Unit vector normalization CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Unit vector normalization tool") subs = parser.add_subparsers(dest="cmd", required=True) n3 = subs.add_parser("norm3") n3.add_argument("a", type=float) n3.add_argument("b", type=float) n3.add_argument("c", type=float) n2 = subs.add_parser("norm2") n2.add_argument("a", type=float) n2.add_argument("b", type=float) n4 = subs.add_parser("norm4") n4.add_argument("a", type=float) n4.add_argument("b", type=float) n4.add_argument("c", type=float) n4.add_argument("d", type=float) args = parser.parse_args() if args.cmd == "norm3": arr = np.array([args.a, args.b, args.c]) norm = np.linalg.norm(arr) result = arr / norm if norm > 0 else arr print(" ".join(str(round(x, 2)) for x in result)) elif args.cmd == "norm2": arr = np.array([args.a, args.b]) norm = np.linalg.norm(arr) result = arr / norm if norm > 0 else arr print(" ".join(str(round(x, 2)) for x in result)) elif args.cmd == "norm4": arr = np.array([args.a, args.b, args.c, args.d]) norm = np.linalg.norm(arr) result = arr / norm if norm > 0 else arr print(" ".join(str(round(x, 2)) for x in result)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_normalize/numpy_normalize_tool.py (1451 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_normalize/numpy_normalize_tool.rs (3657 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_normalize/Cargo.toml (2 dependencies) ⏱️ Parse time: 46ms 📊 Throughput: 30.2 KB/s ⏱️ Total time: 47ms
true
numpy_normalize
47
6
[]
0
null
example_numpy_normalize
test_numpy_normalize_tool.py
"""Tests for numpy_normalize_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_normalize_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("norm3 3 4 0") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "0.6" in out or abs(float(out.split()[0]) - float("0.6")) < 0.1 def test_2(): r = run("norm2 1 0") assert r.returncode == 0 def test_3(): r = run("norm4 1 1 1 1") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_normalize/test_numpy_normalize_tool.py (666 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_normalize/test_numpy_normalize_tool.rs (2153 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_normalize/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 13.6 KB/s ⏱️ Total time: 47ms
true
numpy_normalize
32
6
[]
0
null
example_numpy_scale
numpy_scale_tool.py
#!/usr/bin/env python3 """NumPy Scale Example - Scalar multiplication CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Scalar multiplication tool") subs = parser.add_subparsers(dest="cmd", required=True) s3 = subs.add_parser("scale3") s3.add_argument("a", type=float) s3.add_argument("b", type=float) s3.add_argument("c", type=float) s3.add_argument("scalar", type=float) s4 = subs.add_parser("scale4") s4.add_argument("a", type=float) s4.add_argument("b", type=float) s4.add_argument("c", type=float) s4.add_argument("d", type=float) s4.add_argument("scalar", type=float) s2 = subs.add_parser("scale2") s2.add_argument("a", type=float) s2.add_argument("b", type=float) s2.add_argument("scalar", type=float) args = parser.parse_args() if args.cmd == "scale3": arr = np.array([args.a, args.b, args.c]) result = arr * args.scalar print(" ".join(str(x) for x in result)) elif args.cmd == "scale4": arr = np.array([args.a, args.b, args.c, args.d]) result = arr * args.scalar print(" ".join(str(x) for x in result)) elif args.cmd == "scale2": arr = np.array([args.a, args.b]) result = arr * args.scalar print(" ".join(str(x) for x in result)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_scale/numpy_scale_tool.py (1394 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_scale/numpy_scale_tool.rs (3016 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_scale/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 28.5 KB/s ⏱️ Total time: 48ms
true
numpy_scale
47
6
[]
0
null
example_numpy_scale
test_numpy_scale_tool.py
"""Tests for numpy_scale_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_scale_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("scale3 1 2 3 2") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "2.0" in out or abs(float(out.split()[0]) - float("2.0")) < 0.1 def test_2(): r = run("scale4 1 2 3 4 10") assert r.returncode == 0 def test_3(): r = run("scale2 5 10 0.5") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_scale/test_numpy_scale_tool.py (671 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_scale/test_numpy_scale_tool.rs (2162 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_scale/Cargo.toml (2 dependencies) ⏱️ Parse time: 46ms 📊 Throughput: 14.1 KB/s ⏱️ Total time: 46ms
true
numpy_scale
32
6
[]
0
null
example_numpy_sin
numpy_sin_tool.py
#!/usr/bin/env python3 """NumPy Sin Example - Trigonometric sin CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Trigonometric sin tool") subs = parser.add_subparsers(dest="cmd", required=True) s3 = subs.add_parser("sin3") s3.add_argument("a", type=float) s3.add_argument("b", type=float) s3.add_argument("c", type=float) s2 = subs.add_parser("sin2") s2.add_argument("a", type=float) s2.add_argument("b", type=float) s1 = subs.add_parser("sin1") s1.add_argument("a", type=float) args = parser.parse_args() if args.cmd == "sin3": arr = np.array([args.a, args.b, args.c]) result = np.sin(arr) print(" ".join(str(round(x, 1)) for x in result)) elif args.cmd == "sin2": arr = np.array([args.a, args.b]) result = np.sin(arr) print(" ".join(str(round(x, 1)) for x in result)) elif args.cmd == "sin1": result = np.sin(args.a) print(round(result, 1)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sin/numpy_sin_tool.py (1067 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sin/numpy_sin_tool.rs (2037 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sin/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 21.1 KB/s ⏱️ Total time: 49ms
true
numpy_sin
40
6
[]
0
null
example_numpy_sin
test_numpy_sin_tool.py
"""Tests for numpy_sin_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_sin_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("sin3 0 1.571 3.142") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "0.0" in out or abs(float(out.split()[0]) - float("0.0")) < 0.1 def test_2(): r = run("sin2 0 0") assert r.returncode == 0 def test_3(): r = run("sin1 0") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sin/test_numpy_sin_tool.py (653 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sin/test_numpy_sin_tool.rs (2146 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sin/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 13.5 KB/s ⏱️ Total time: 47ms
true
numpy_sin
32
6
[]
0
null
example_numpy_sqrt
numpy_sqrt_tool.py
#!/usr/bin/env python3 """NumPy Sqrt Example - Element-wise sqrt CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Element-wise sqrt tool") subs = parser.add_subparsers(dest="cmd", required=True) s3 = subs.add_parser("sqrt3") s3.add_argument("a", type=float) s3.add_argument("b", type=float) s3.add_argument("c", type=float) s4 = subs.add_parser("sqrt4") s4.add_argument("a", type=float) s4.add_argument("b", type=float) s4.add_argument("c", type=float) s4.add_argument("d", type=float) s2 = subs.add_parser("sqrt2") s2.add_argument("a", type=float) s2.add_argument("b", type=float) args = parser.parse_args() if args.cmd == "sqrt3": arr = np.array([args.a, args.b, args.c]) result = np.sqrt(arr) print(" ".join(str(x) for x in result)) elif args.cmd == "sqrt4": arr = np.array([args.a, args.b, args.c, args.d]) result = np.sqrt(arr) print(" ".join(str(x) for x in result)) elif args.cmd == "sqrt2": arr = np.array([args.a, args.b]) result = np.sqrt(arr) print(" ".join(str(x) for x in result)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sqrt/numpy_sqrt_tool.py (1238 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sqrt/numpy_sqrt_tool.rs (2505 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sqrt/Cargo.toml (2 dependencies) ⏱️ Parse time: 46ms 📊 Throughput: 25.8 KB/s ⏱️ Total time: 47ms
true
numpy_sqrt
44
6
[]
0
null
example_numpy_sqrt
test_numpy_sqrt_tool.py
"""Tests for numpy_sqrt_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_sqrt_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("sqrt3 1 4 9") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "1.0" in out or abs(float(out.split()[0]) - float("1.0")) < 0.1 def test_2(): r = run("sqrt4 16 25 36 49") assert r.returncode == 0 def test_3(): r = run("sqrt2 100 144") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sqrt/test_numpy_sqrt_tool.py (664 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sqrt/test_numpy_sqrt_tool.rs (2156 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sqrt/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 13.6 KB/s ⏱️ Total time: 47ms
true
numpy_sqrt
32
6
[]
0
null
example_numpy_std
numpy_std_tool.py
#!/usr/bin/env python3 """NumPy Std Example - Std reduction CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Std reduction tool") subs = parser.add_subparsers(dest="cmd", required=True) s3 = subs.add_parser("std3") s3.add_argument("a", type=float) s3.add_argument("b", type=float) s3.add_argument("c", type=float) s4 = subs.add_parser("std4") s4.add_argument("a", type=float) s4.add_argument("b", type=float) s4.add_argument("c", type=float) s4.add_argument("d", type=float) s5 = subs.add_parser("std5") s5.add_argument("a", type=float) s5.add_argument("b", type=float) s5.add_argument("c", type=float) s5.add_argument("d", type=float) s5.add_argument("e", type=float) args = parser.parse_args() if args.cmd == "std3": arr = np.array([args.a, args.b, args.c]) print(round(np.std(arr), 3)) elif args.cmd == "std4": arr = np.array([args.a, args.b, args.c, args.d]) print(round(np.std(arr), 3)) elif args.cmd == "std5": arr = np.array([args.a, args.b, args.c, args.d, args.e]) print(round(np.std(arr), 3)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_std/numpy_std_tool.py (1235 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_std/numpy_std_tool.rs (2037 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_std/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 24.3 KB/s ⏱️ Total time: 49ms
true
numpy_std
44
6
[]
0
null
example_numpy_std
test_numpy_std_tool.py
"""Tests for numpy_std_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_std_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("std3 1 2 3") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "0.81" in out or abs(float(out.split()[0]) - float("0.816")) < 0.1 def test_2(): r = run("std4 2 4 6 8") assert r.returncode == 0 def test_3(): r = run("std5 10 10 10 10 10") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_std/test_numpy_std_tool.py (665 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_std/test_numpy_std_tool.rs (2158 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_std/Cargo.toml (2 dependencies) ⏱️ Parse time: 50ms 📊 Throughput: 13.0 KB/s ⏱️ Total time: 50ms
true
numpy_std
32
6
[]
0
null
example_numpy_sum
numpy_sum_tool.py
#!/usr/bin/env python3 """NumPy Sum Example - Sum reduction CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Sum reduction tool") subs = parser.add_subparsers(dest="cmd", required=True) s3 = subs.add_parser("sum3") s3.add_argument("a", type=float) s3.add_argument("b", type=float) s3.add_argument("c", type=float) s4 = subs.add_parser("sum4") s4.add_argument("a", type=float) s4.add_argument("b", type=float) s4.add_argument("c", type=float) s4.add_argument("d", type=float) s5 = subs.add_parser("sum5") s5.add_argument("a", type=float) s5.add_argument("b", type=float) s5.add_argument("c", type=float) s5.add_argument("d", type=float) s5.add_argument("e", type=float) args = parser.parse_args() if args.cmd == "sum3": arr = np.array([args.a, args.b, args.c]) print(np.sum(arr)) elif args.cmd == "sum4": arr = np.array([args.a, args.b, args.c, args.d]) print(np.sum(arr)) elif args.cmd == "sum5": arr = np.array([args.a, args.b, args.c, args.d, args.e]) print(np.sum(arr)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sum/numpy_sum_tool.py (1205 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sum/numpy_sum_tool.rs (1956 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sum/Cargo.toml (2 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 24.2 KB/s ⏱️ Total time: 48ms
true
numpy_sum
44
6
[]
0
null
example_numpy_sum
test_numpy_sum_tool.py
"""Tests for numpy_sum_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_sum_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_sum3(): r = run("sum3 1 2 3") assert r.returncode == 0 assert r.stdout.strip() == "6.0" def test_sum4(): r = run("sum4 1 2 3 4") assert r.returncode == 0 assert r.stdout.strip() == "10.0" def test_sum5(): r = run("sum5 10 20 30 40 50") assert r.returncode == 0 assert r.stdout.strip() == "150.0"
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sum/test_numpy_sum_tool.py (648 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sum/test_numpy_sum_tool.rs (1923 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_sum/Cargo.toml (2 dependencies) ⏱️ Parse time: 46ms 📊 Throughput: 13.5 KB/s ⏱️ Total time: 46ms
true
numpy_sum
32
6
[]
0
null
example_numpy_var
numpy_var_tool.py
#!/usr/bin/env python3 """NumPy Var Example - Var reduction CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Var reduction tool") subs = parser.add_subparsers(dest="cmd", required=True) s3 = subs.add_parser("var3") s3.add_argument("a", type=float) s3.add_argument("b", type=float) s3.add_argument("c", type=float) s4 = subs.add_parser("var4") s4.add_argument("a", type=float) s4.add_argument("b", type=float) s4.add_argument("c", type=float) s4.add_argument("d", type=float) s5 = subs.add_parser("var5") s5.add_argument("a", type=float) s5.add_argument("b", type=float) s5.add_argument("c", type=float) s5.add_argument("d", type=float) s5.add_argument("e", type=float) args = parser.parse_args() if args.cmd == "var3": arr = np.array([args.a, args.b, args.c]) print(round(np.var(arr), 3)) elif args.cmd == "var4": arr = np.array([args.a, args.b, args.c, args.d]) print(round(np.var(arr), 3)) elif args.cmd == "var5": arr = np.array([args.a, args.b, args.c, args.d, args.e]) print(round(np.var(arr), 3)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_var/numpy_var_tool.py (1235 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_var/numpy_var_tool.rs (2043 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_var/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 25.4 KB/s ⏱️ Total time: 47ms
true
numpy_var
44
6
[]
0
null
example_numpy_var
test_numpy_var_tool.py
"""Tests for numpy_var_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_var_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("var3 1 2 3") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "0.66" in out or abs(float(out.split()[0]) - float("0.666")) < 0.1 def test_2(): r = run("var4 2 4 6 8") assert r.returncode == 0 def test_3(): r = run("var5 10 10 10 10 10") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_var/test_numpy_var_tool.py (665 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_var/test_numpy_var_tool.rs (2158 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_var/Cargo.toml (2 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 13.3 KB/s ⏱️ Total time: 48ms
true
numpy_var
32
6
[]
0
null
example_numpy_zscore
numpy_zscore_tool.py
#!/usr/bin/env python3 """NumPy Zscore Example - Z-score normalization CLI.""" import argparse import numpy as np def main(): parser = argparse.ArgumentParser(description="Z-score normalization tool") subs = parser.add_subparsers(dest="cmd", required=True) z3 = subs.add_parser("zscore3") z3.add_argument("a", type=float) z3.add_argument("b", type=float) z3.add_argument("c", type=float) z4 = subs.add_parser("zscore4") z4.add_argument("a", type=float) z4.add_argument("b", type=float) z4.add_argument("c", type=float) z4.add_argument("d", type=float) z2 = subs.add_parser("zscore2") z2.add_argument("a", type=float) z2.add_argument("b", type=float) args = parser.parse_args() if args.cmd == "zscore3": arr = np.array([args.a, args.b, args.c]) mean = np.mean(arr) std = np.std(arr) result = (arr - mean) / std if std > 0 else arr - mean print(" ".join(str(round(x, 2)) for x in result)) elif args.cmd == "zscore4": arr = np.array([args.a, args.b, args.c, args.d]) mean = np.mean(arr) std = np.std(arr) result = (arr - mean) / std if std > 0 else arr - mean print(" ".join(str(round(x, 2)) for x in result)) elif args.cmd == "zscore2": arr = np.array([args.a, args.b]) mean = np.mean(arr) std = np.std(arr) result = (arr - mean) / std if std > 0 else arr - mean print(" ".join(str(round(x, 2)) for x in result)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_zscore/numpy_zscore_tool.py (1551 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_zscore/numpy_zscore_tool.rs (4606 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_zscore/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 30.9 KB/s ⏱️ Total time: 49ms
true
numpy_zscore
50
6
[]
0
null
example_numpy_zscore
test_numpy_zscore_tool.py
"""Tests for numpy_zscore_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "numpy_zscore_tool.py" def run(cmd): return subprocess.run( ["uv", "run", "python", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_1(): r = run("zscore3 1 2 3") assert r.returncode == 0 out = r.stdout.strip() # Approximate match for floats assert "-1.2" in out or abs(float(out.split()[0]) - float("-1.22")) < 0.1 def test_2(): r = run("zscore4 10 20 30 40") assert r.returncode == 0 def test_3(): r = run("zscore2 0 10") assert r.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_numpy_zscore/test_numpy_zscore_tool.py (674 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_numpy_zscore/test_numpy_zscore_tool.rs (2164 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_numpy_zscore/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 13.4 KB/s ⏱️ Total time: 49ms
true
numpy_zscore
32
6
[]
0
null
example_operator
op_tool.py
#!/usr/bin/env python3 """Operator Example - Basic arithmetic CLI.""" import argparse def main(): parser = argparse.ArgumentParser(description="Arithmetic operations tool") subs = parser.add_subparsers(dest="cmd", required=True) a = subs.add_parser("add") a.add_argument("x", type=int) a.add_argument("y", type=int) s = subs.add_parser("sub") s.add_argument("x", type=int) s.add_argument("y", type=int) m = subs.add_parser("mul") m.add_argument("x", type=int) m.add_argument("y", type=int) d = subs.add_parser("mod") d.add_argument("x", type=int) d.add_argument("y", type=int) args = parser.parse_args() if args.cmd == "add": print(args.x + args.y) elif args.cmd == "sub": print(args.x - args.y) elif args.cmd == "mul": print(args.x * args.y) elif args.cmd == "mod": print(args.x % args.y) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_operator/op_tool.py (943 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_operator/op_tool.rs (1650 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_operator/Cargo.toml (1 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 19.2 KB/s ⏱️ Total time: 48ms
true
operator
36
6
[]
0
null
example_operator
test_op_tool.py
#!/usr/bin/env python3 """EXTREME TDD: Tests for operator CLI.""" import subprocess SCRIPT = "op_tool.py" def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0]) class TestArith: def test_add(self): assert "8" in run(["add", "5", "3"]).stdout def test_sub(self): assert "2" in run(["sub", "5", "3"]).stdout def test_mul(self): assert "15" in run(["mul", "5", "3"]).stdout def test_mod(self): assert "1" in run(["mod", "7", "3"]).stdout class TestHelp: def test_help(self): assert run(["--help"]).returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_operator/test_op_tool.py (608 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_operator/test_op_tool.rs (2041 bytes) ⏱️ Parse time: 49ms 📊 Throughput: 11.9 KB/s ⏱️ Total time: 50ms
true
operator
15
5
[ "class_definition" ]
0.612
null
example_ord_chr
ord_chr_tool.py
#!/usr/bin/env python3 """Ord Chr Example - Character code operations CLI.""" import argparse def main(): parser = argparse.ArgumentParser(description="Character code tool") subs = parser.add_subparsers(dest="cmd", required=True) o = subs.add_parser("ord") o.add_argument("char") ch = subs.add_parser("chr") ch.add_argument("code", type=int) co = subs.add_parser("code") co.add_argument("text") args = parser.parse_args() if args.cmd == "ord": print(ord(args.char[0])) elif args.cmd == "chr": print(chr(args.code)) elif args.cmd == "code": result = "" i = 0 while i < len(args.text): if i > 0: result = result + " " result = result + str(ord(args.text[i])) i = i + 1 print(result) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_ord_chr/ord_chr_tool.py (874 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_ord_chr/ord_chr_tool.rs (2599 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_ord_chr/Cargo.toml (1 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 17.2 KB/s ⏱️ Total time: 49ms
true
ord_chr
35
6
[]
0
null
example_ord_chr
test_ord_chr_tool.py
"""Tests for ord_chr_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "ord_chr_tool.py" def run(cmd): return subprocess.run( ["python3", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_ord(): r = run("ord A") assert r.returncode == 0 assert r.stdout.strip() == "65" def test_chr(): r = run("chr 65") assert r.returncode == 0 assert r.stdout.strip() == "A" def test_code(): r = run("code hello") assert r.returncode == 0 assert "104" in r.stdout
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_ord_chr/test_ord_chr_tool.py (596 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_ord_chr/test_ord_chr_tool.rs (1803 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_ord_chr/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 12.2 KB/s ⏱️ Total time: 47ms
true
ord_chr
32
6
[]
0
null
example_os
os_tool.py
#!/usr/bin/env python3 """OS Example - Path operations CLI.""" import argparse import os def main(): parser = argparse.ArgumentParser(description="OS path operations tool") subs = parser.add_subparsers(dest="cmd", required=True) j = subs.add_parser("join") j.add_argument("a") j.add_argument("b") b = subs.add_parser("basename") b.add_argument("path") d = subs.add_parser("dirname") d.add_argument("path") args = parser.parse_args() if args.cmd == "join": print(os.path.join(args.a, args.b)) elif args.cmd == "basename": print(os.path.basename(args.path)) elif args.cmd == "dirname": print(os.path.dirname(args.path)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_os/os_tool.py (739 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_os/os_tool.rs (1557 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_os/Cargo.toml (1 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 14.9 KB/s ⏱️ Total time: 48ms
true
os
30
6
[]
0
null
example_os
test_os_tool.py
#!/usr/bin/env python3 """EXTREME TDD: Tests for os CLI.""" import subprocess SCRIPT = "os_tool.py" def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0]) class TestOs: def test_join(self): r = run(["join", "/home", "user"]); assert "/home" in r.stdout and "user" in r.stdout def test_basename(self): r = run(["basename", "/home/user/file.txt"]); assert "file.txt" in r.stdout def test_dirname(self): r = run(["dirname", "/home/user/file.txt"]); assert "/home/user" in r.stdout class TestHelp: def test_help(self): assert run(["--help"]).returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_os/test_os_tool.py (647 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_os/test_os_tool.rs (1982 bytes) ⏱️ Parse time: 46ms 📊 Throughput: 13.7 KB/s ⏱️ Total time: 46ms
true
os
14
5
[ "class_definition" ]
0.612
null
example_pathlib
path_tool.py
#!/usr/bin/env python3 """Pathlib Example - Path manipulation CLI.""" import argparse from pathlib import Path def cmd_info(args): """Show path info. Depyler: proven to terminate""" p = Path(args.path) print(f"Name: {p.name}") print(f"Stem: {p.stem}") print(f"Suffix: {p.suffix}") print(f"Parent: {p.parent}") print(f"Exists: {p.exists()}") def cmd_glob(args): """Glob pattern match. Depyler: proven to terminate""" p = Path(args.directory) for match in p.glob(args.pattern): print(match) def cmd_parts(args): """Show path parts. Depyler: proven to terminate""" p = Path(args.path) for part in p.parts: print(part) def cmd_join(args): """Join path components. Depyler: proven to terminate""" result = Path(args.parts[0]) for part in args.parts[1:]: result = result / part print(result) def main(): parser = argparse.ArgumentParser(description="Path manipulation tool") subparsers = parser.add_subparsers(dest="command", required=True) info = subparsers.add_parser("info") info.add_argument("path") glob = subparsers.add_parser("glob") glob.add_argument("directory") glob.add_argument("pattern") parts = subparsers.add_parser("parts") parts.add_argument("path") join = subparsers.add_parser("join") join.add_argument("parts", nargs="+") args = parser.parse_args() if args.command == "info": cmd_info(args) elif args.command == "glob": cmd_glob(args) elif args.command == "parts": cmd_parts(args) elif args.command == "join": cmd_join(args) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pathlib/path_tool.py (1683 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pathlib/path_tool.rs (4525 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pathlib/Cargo.toml (1 dependencies) ⏱️ Parse time: 50ms 📊 Throughput: 32.4 KB/s ⏱️ Total time: 50ms
true
pathlib
69
6
[]
0
null
example_pathlib
test_path_tool.py
#!/usr/bin/env python3 """EXTREME TDD: Tests for pathlib CLI.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "path_tool.py" SCRIPT = "path_tool.py" def run(args): return subprocess.run(["python3", SCRIPT] + args, capture_output=True, text=True, cwd=__file__.rsplit("/", 1)[0]) class TestPathInfo: def test_info(self): result = run(["info", __file__]) assert result.returncode == 0 assert "Name:" in result.stdout assert "Suffix:" in result.stdout class TestGlob: def test_glob_py(self): result = run(["glob", ".", "*.py"]) assert result.returncode == 0 assert "path_tool.py" in result.stdout class TestParts: def test_parts(self): result = run(["parts", "/usr/local/bin"]) assert result.returncode == 0 assert "usr" in result.stdout class TestJoin: def test_join(self): result = run(["join", "/home", "user", "docs"]) assert result.returncode == 0 assert "/home/user/docs" in result.stdout class TestHelp: def test_help(self): result = run(["--help"]) assert result.returncode == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pathlib/test_path_tool.py (1192 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pathlib/test_path_tool.rs (2988 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pathlib/Cargo.toml (2 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 24.6 KB/s ⏱️ Total time: 47ms
true
pathlib
42
6
[ "class_definition" ]
0.612
null
example_pathlib_basic
pathlib_basic_cli.py
#!/usr/bin/env python3 """Pathlib Basic CLI. Basic path operations using Python's pathlib module. """ import argparse import sys from pathlib import Path def create_path(path_str: str) -> Path: """Create Path object from string.""" return Path(path_str) def get_name(path: Path) -> str: """Get file name.""" return path.name def get_stem(path: Path) -> str: """Get file name without suffix.""" return path.stem def get_suffix(path: Path) -> str: """Get file suffix/extension.""" return path.suffix def get_suffixes(path: Path) -> list[str]: """Get all suffixes (e.g., .tar.gz).""" return path.suffixes def get_parent(path: Path) -> Path: """Get parent directory.""" return path.parent def get_parents(path: Path) -> list[Path]: """Get all parent directories.""" return list(path.parents) def get_parts(path: Path) -> tuple[str, ...]: """Get path components.""" return path.parts def get_anchor(path: Path) -> str: """Get anchor (root + drive).""" return path.anchor def get_root(path: Path) -> str: """Get root.""" return path.root def is_absolute(path: Path) -> bool: """Check if path is absolute.""" return path.is_absolute() def is_relative(path: Path) -> bool: """Check if path is relative.""" return not path.is_absolute() def exists(path: Path) -> bool: """Check if path exists.""" return path.exists() def is_file(path: Path) -> bool: """Check if path is a file.""" return path.is_file() def is_dir(path: Path) -> bool: """Check if path is a directory.""" return path.is_dir() def is_symlink(path: Path) -> bool: """Check if path is a symlink.""" return path.is_symlink() def resolve(path: Path) -> Path: """Resolve path to absolute.""" return path.resolve() def expanduser(path: Path) -> Path: """Expand ~ to home directory.""" return path.expanduser() def absolute(path: Path) -> Path: """Get absolute path.""" return path.absolute() def join_paths(base: Path, *parts: str) -> Path: """Join path components.""" result = base for part in parts: result = result / part return result def with_name(path: Path, name: str) -> Path: """Return path with different name.""" return path.with_name(name) def with_stem(path: Path, stem: str) -> Path: """Return path with different stem.""" return path.with_stem(stem) def with_suffix(path: Path, suffix: str) -> Path: """Return path with different suffix.""" return path.with_suffix(suffix) def relative_to(path: Path, other: Path) -> Path: """Get path relative to other.""" return path.relative_to(other) def is_relative_to(path: Path, other: Path) -> bool: """Check if path is relative to other.""" return path.is_relative_to(other) def match_pattern(path: Path, pattern: str) -> bool: """Check if path matches pattern.""" return path.match(pattern) def as_posix(path: Path) -> str: """Return path with forward slashes.""" return path.as_posix() def as_uri(path: Path) -> str: """Return path as file:// URI.""" return path.as_uri() def home_dir() -> Path: """Get home directory.""" return Path.home() def cwd() -> Path: """Get current working directory.""" return Path.cwd() def parse_path_info(path_str: str) -> dict: """Parse path and return all components.""" path = Path(path_str) return { "path": str(path), "name": path.name, "stem": path.stem, "suffix": path.suffix, "suffixes": path.suffixes, "parent": str(path.parent), "parts": path.parts, "is_absolute": path.is_absolute(), "anchor": path.anchor, } def main() -> int: parser = argparse.ArgumentParser(description="Pathlib basic CLI") subparsers = parser.add_subparsers(dest="command", help="Commands") # info info_p = subparsers.add_parser("info", help="Show path info") info_p.add_argument("path", help="Path to analyze") # exists exists_p = subparsers.add_parser("exists", help="Check if exists") exists_p.add_argument("path", help="Path to check") # type type_p = subparsers.add_parser("type", help="Check path type") type_p.add_argument("path", help="Path to check") # join join_p = subparsers.add_parser("join", help="Join paths") join_p.add_argument("paths", nargs="+", help="Paths to join") # parent parent_p = subparsers.add_parser("parent", help="Get parent") parent_p.add_argument("path", help="Path") parent_p.add_argument("-n", type=int, default=1, help="Levels up") # name name_p = subparsers.add_parser("name", help="Get name/stem/suffix") name_p.add_argument("path", help="Path") # resolve resolve_p = subparsers.add_parser("resolve", help="Resolve path") resolve_p.add_argument("path", help="Path to resolve") # home subparsers.add_parser("home", help="Show home directory") # cwd subparsers.add_parser("cwd", help="Show current directory") args = parser.parse_args() if args.command == "info": info = parse_path_info(args.path) for key, value in info.items(): print(f"{key}: {value}") elif args.command == "exists": path = Path(args.path) if path.exists(): print(f"'{args.path}' exists") else: print(f"'{args.path}' does not exist") elif args.command == "type": path = Path(args.path) if not path.exists(): print("Does not exist") elif path.is_file(): print("File") elif path.is_dir(): print("Directory") elif path.is_symlink(): print("Symlink") else: print("Other") elif args.command == "join": result = Path(args.paths[0]) for p in args.paths[1:]: result = result / p print(result) elif args.command == "parent": path = Path(args.path) for _ in range(args.n): path = path.parent print(path) elif args.command == "name": path = Path(args.path) print(f"Name: {path.name}") print(f"Stem: {path.stem}") print(f"Suffix: {path.suffix}") elif args.command == "resolve": path = Path(args.path) print(path.resolve()) elif args.command == "home": print(home_dir()) elif args.command == "cwd": print(cwd()) else: parser.print_help() return 0 if __name__ == "__main__": sys.exit(main())
false
pathlib_basic
282
0
[ "context_manager" ]
0.652
Error: Unsupported type annotation: Constant(ExprConstant { range: 902..905, value: Ellipsis, kind: None })
example_pathlib_basic
test_pathlib_basic_cli.py
"""Tests for pathlib_basic_cli.py""" import os import tempfile from pathlib import Path from pathlib_basic_cli import ( absolute, as_posix, create_path, cwd, exists, expanduser, get_anchor, get_name, get_parent, get_parents, get_parts, get_root, get_stem, get_suffix, get_suffixes, home_dir, is_absolute, is_dir, is_file, is_relative, is_relative_to, is_symlink, join_paths, match_pattern, parse_path_info, relative_to, resolve, with_name, with_stem, with_suffix, ) class TestCreatePath: def test_create_path(self): path = create_path("/home/user/file.txt") assert isinstance(path, Path) assert str(path) == "/home/user/file.txt" class TestPathComponents: def test_get_name(self): path = Path("/home/user/file.txt") assert get_name(path) == "file.txt" def test_get_stem(self): path = Path("/home/user/file.txt") assert get_stem(path) == "file" def test_get_suffix(self): path = Path("/home/user/file.txt") assert get_suffix(path) == ".txt" def test_get_suffixes(self): path = Path("/home/user/file.tar.gz") assert get_suffixes(path) == [".tar", ".gz"] def test_get_parent(self): path = Path("/home/user/file.txt") assert get_parent(path) == Path("/home/user") def test_get_parents(self): path = Path("/home/user/file.txt") parents = get_parents(path) assert Path("/home/user") in parents assert Path("/home") in parents def test_get_parts(self): path = Path("/home/user/file.txt") parts = get_parts(path) assert "home" in parts assert "user" in parts assert "file.txt" in parts def test_get_anchor(self): path = Path("/home/user/file.txt") assert get_anchor(path) == "/" def test_get_root(self): path = Path("/home/user/file.txt") assert get_root(path) == "/" class TestPathChecks: def test_is_absolute(self): assert is_absolute(Path("/home/user")) is True assert is_absolute(Path("relative/path")) is False def test_is_relative(self): assert is_relative(Path("/home/user")) is False assert is_relative(Path("relative/path")) is True class TestFileSystemChecks: def test_exists_true(self): with tempfile.NamedTemporaryFile() as f: assert exists(Path(f.name)) is True def test_exists_false(self): assert exists(Path("/nonexistent/path/file.txt")) is False def test_is_file(self): with tempfile.NamedTemporaryFile() as f: assert is_file(Path(f.name)) is True assert is_file(Path(os.path.dirname(f.name))) is False def test_is_dir(self): with tempfile.TemporaryDirectory() as d: assert is_dir(Path(d)) is True def test_is_symlink(self): with tempfile.NamedTemporaryFile() as f: assert is_symlink(Path(f.name)) is False class TestPathTransformations: def test_resolve(self): path = Path(".") resolved = resolve(path) assert resolved.is_absolute() def test_expanduser(self): path = Path("~/test") expanded = expanduser(path) assert "~" not in str(expanded) def test_absolute(self): path = Path("relative") abs_path = absolute(path) assert abs_path.is_absolute() class TestPathOperations: def test_join_paths(self): base = Path("/home") result = join_paths(base, "user", "file.txt") assert str(result) == "/home/user/file.txt" def test_with_name(self): path = Path("/home/user/file.txt") new_path = with_name(path, "other.txt") assert new_path == Path("/home/user/other.txt") def test_with_stem(self): path = Path("/home/user/file.txt") new_path = with_stem(path, "newfile") assert new_path == Path("/home/user/newfile.txt") def test_with_suffix(self): path = Path("/home/user/file.txt") new_path = with_suffix(path, ".md") assert new_path == Path("/home/user/file.md") class TestRelativePaths: def test_relative_to(self): path = Path("/home/user/file.txt") base = Path("/home") rel = relative_to(path, base) assert str(rel) == "user/file.txt" def test_is_relative_to(self): path = Path("/home/user/file.txt") assert is_relative_to(path, Path("/home")) is True assert is_relative_to(path, Path("/var")) is False class TestPatternMatching: def test_match_pattern_simple(self): path = Path("/home/user/file.txt") assert match_pattern(path, "*.txt") is True assert match_pattern(path, "*.py") is False def test_match_pattern_glob(self): path = Path("/home/user/data/file.txt") assert match_pattern(path, "*/data/*") is True class TestSpecialPaths: def test_home_dir(self): home = home_dir() assert home.is_absolute() assert home.exists() def test_cwd(self): current = cwd() assert current.is_absolute() assert current.exists() class TestConversions: def test_as_posix(self): path = Path("/home/user/file.txt") assert as_posix(path) == "/home/user/file.txt" class TestParsePathInfo: def test_parse_path_info(self): info = parse_path_info("/home/user/file.tar.gz") assert info["name"] == "file.tar.gz" assert info["stem"] == "file.tar" assert info["suffix"] == ".gz" assert info["suffixes"] == [".tar", ".gz"] assert info["is_absolute"] is True class TestEdgeCases: def test_empty_suffix(self): path = Path("/home/user/Makefile") assert get_suffix(path) == "" assert get_stem(path) == "Makefile" def test_hidden_file(self): path = Path("/home/user/.bashrc") assert get_name(path) == ".bashrc" assert get_suffix(path) == "" def test_multiple_dots(self): path = Path("/home/user/file.name.txt") assert get_suffix(path) == ".txt" assert get_stem(path) == "file.name"
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pathlib_basic/test_pathlib_basic_cli.py (6250 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pathlib_basic/test_pathlib_basic_cli.rs (17146 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pathlib_basic/Cargo.toml (1 dependencies) ⏱️ Parse time: 53ms 📊 Throughput: 114.8 KB/s ⏱️ Total time: 53ms
true
pathlib_basic
228
6
[ "context_manager", "class_definition" ]
0.652
null
example_pathlib_ops
pathlib_ops_cli.py
#!/usr/bin/env python3 """Pathlib Operations CLI. Directory and file operations using Python's pathlib module. """ import argparse import sys from pathlib import Path def mkdir(path: Path, parents: bool = False, exist_ok: bool = False) -> bool: """Create directory.""" try: path.mkdir(parents=parents, exist_ok=exist_ok) return True except FileExistsError: return False except FileNotFoundError: return False def rmdir(path: Path) -> bool: """Remove empty directory.""" try: path.rmdir() return True except (FileNotFoundError, OSError): return False def unlink(path: Path, missing_ok: bool = False) -> bool: """Remove file.""" try: path.unlink(missing_ok=missing_ok) return True except FileNotFoundError: return False def rename(src: Path, dst: Path) -> Path: """Rename file or directory.""" return src.rename(dst) def replace(src: Path, dst: Path) -> Path: """Replace file or directory.""" return src.replace(dst) def touch(path: Path, exist_ok: bool = True) -> bool: """Create file or update timestamp.""" try: path.touch(exist_ok=exist_ok) return True except FileExistsError: return False def glob_pattern(path: Path, pattern: str) -> list[Path]: """Find files matching pattern.""" return list(path.glob(pattern)) def rglob_pattern(path: Path, pattern: str) -> list[Path]: """Recursively find files matching pattern.""" return list(path.rglob(pattern)) def iterdir(path: Path) -> list[Path]: """List directory contents.""" return list(path.iterdir()) def list_files(path: Path) -> list[Path]: """List only files in directory.""" return [p for p in path.iterdir() if p.is_file()] def list_dirs(path: Path) -> list[Path]: """List only directories in directory.""" return [p for p in path.iterdir() if p.is_dir()] def stat_size(path: Path) -> int: """Get file size in bytes.""" return path.stat().st_size def stat_mtime(path: Path) -> float: """Get modification time.""" return path.stat().st_mtime def stat_mode(path: Path) -> int: """Get file mode/permissions.""" return path.stat().st_mode def chmod(path: Path, mode: int) -> None: """Change file permissions.""" path.chmod(mode) def samefile(path1: Path, path2: Path) -> bool: """Check if two paths point to same file.""" return path1.samefile(path2) def read_text(path: Path, encoding: str = "utf-8") -> str: """Read file as text.""" return path.read_text(encoding=encoding) def write_text(path: Path, content: str, encoding: str = "utf-8") -> int: """Write text to file.""" return path.write_text(content, encoding=encoding) def read_bytes(path: Path) -> bytes: """Read file as bytes.""" return path.read_bytes() def write_bytes(path: Path, data: bytes) -> int: """Write bytes to file.""" return path.write_bytes(data) def owner(path: Path) -> str: """Get file owner name.""" return path.owner() def group(path: Path) -> str: """Get file group name.""" return path.group() def hardlink_to(src: Path, dst: Path) -> None: """Create hard link.""" dst.hardlink_to(src) def symlink_to(link: Path, target: Path) -> None: """Create symbolic link.""" link.symlink_to(target) def readlink(path: Path) -> Path: """Read symbolic link target.""" return path.readlink() def count_files(path: Path, pattern: str = "*") -> int: """Count files matching pattern.""" return len([p for p in path.glob(pattern) if p.is_file()]) def count_dirs(path: Path) -> int: """Count subdirectories.""" return len([p for p in path.iterdir() if p.is_dir()]) def total_size(path: Path) -> int: """Get total size of all files in directory.""" return sum(p.stat().st_size for p in path.rglob("*") if p.is_file()) def find_by_suffix(path: Path, suffix: str) -> list[Path]: """Find all files with given suffix.""" return [p for p in path.rglob("*") if p.suffix == suffix] def find_by_name(path: Path, name: str) -> list[Path]: """Find all files with given name.""" return [p for p in path.rglob("*") if p.name == name] def walk_dir(path: Path) -> list[tuple[Path, list[str], list[str]]]: """Walk directory tree (similar to os.walk).""" result = [] dirs = [d.name for d in path.iterdir() if d.is_dir()] files = [f.name for f in path.iterdir() if f.is_file()] result.append((path, dirs, files)) for d in path.iterdir(): if d.is_dir(): result.extend(walk_dir(d)) return result def main() -> int: parser = argparse.ArgumentParser(description="Pathlib operations CLI") subparsers = parser.add_subparsers(dest="command", help="Commands") # mkdir mkdir_p = subparsers.add_parser("mkdir", help="Create directory") mkdir_p.add_argument("path", help="Directory path") mkdir_p.add_argument("-p", "--parents", action="store_true", help="Create parents") mkdir_p.add_argument("--exist-ok", action="store_true", help="OK if exists") # rmdir rmdir_p = subparsers.add_parser("rmdir", help="Remove directory") rmdir_p.add_argument("path", help="Directory path") # touch touch_p = subparsers.add_parser("touch", help="Create file") touch_p.add_argument("path", help="File path") # rm rm_p = subparsers.add_parser("rm", help="Remove file") rm_p.add_argument("path", help="File path") rm_p.add_argument("-f", "--force", action="store_true", help="Ignore missing") # mv mv_p = subparsers.add_parser("mv", help="Move/rename") mv_p.add_argument("src", help="Source path") mv_p.add_argument("dst", help="Destination path") # ls ls_p = subparsers.add_parser("ls", help="List directory") ls_p.add_argument("path", nargs="?", default=".", help="Directory path") ls_p.add_argument("-d", "--dirs", action="store_true", help="Only dirs") ls_p.add_argument("-f", "--files", action="store_true", help="Only files") # glob glob_p = subparsers.add_parser("glob", help="Find files") glob_p.add_argument("path", help="Base directory") glob_p.add_argument("pattern", help="Glob pattern") glob_p.add_argument("-r", "--recursive", action="store_true", help="Recursive") # stat stat_p = subparsers.add_parser("stat", help="File info") stat_p.add_argument("path", help="File path") # count count_p = subparsers.add_parser("count", help="Count files") count_p.add_argument("path", help="Directory path") count_p.add_argument("-p", "--pattern", default="*", help="Pattern") args = parser.parse_args() if args.command == "mkdir": path = Path(args.path) if mkdir(path, parents=args.parents, exist_ok=args.exist_ok): print(f"Created: {path}") else: print(f"Failed to create: {path}") return 1 elif args.command == "rmdir": path = Path(args.path) if rmdir(path): print(f"Removed: {path}") else: print(f"Failed to remove: {path}") return 1 elif args.command == "touch": path = Path(args.path) if touch(path): print(f"Touched: {path}") else: print(f"Failed to touch: {path}") return 1 elif args.command == "rm": path = Path(args.path) if unlink(path, missing_ok=args.force): print(f"Removed: {path}") else: print(f"Failed to remove: {path}") return 1 elif args.command == "mv": src = Path(args.src) dst = Path(args.dst) result = rename(src, dst) print(f"Moved: {src} -> {result}") elif args.command == "ls": path = Path(args.path) if args.dirs: items = list_dirs(path) elif args.files: items = list_files(path) else: items = iterdir(path) for item in sorted(items): print(item.name) elif args.command == "glob": path = Path(args.path) if args.recursive: matches = rglob_pattern(path, args.pattern) else: matches = glob_pattern(path, args.pattern) for m in sorted(matches): print(m) elif args.command == "stat": path = Path(args.path) print(f"Size: {stat_size(path)} bytes") print(f"Mode: {oct(stat_mode(path))}") print(f"Modified: {stat_mtime(path)}") elif args.command == "count": path = Path(args.path) files = count_files(path, args.pattern) dirs = count_dirs(path) print(f"Files: {files}") print(f"Directories: {dirs}") else: parser.print_help() return 0 if __name__ == "__main__": sys.exit(main())
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pathlib_ops/pathlib_ops_cli.py (8885 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pathlib_ops/pathlib_ops_cli.rs (15809 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pathlib_ops/Cargo.toml (2 dependencies) ⏱️ Parse time: 52ms 📊 Throughput: 164.9 KB/s ⏱️ Total time: 52ms
true
pathlib_ops
321
6
[ "context_manager", "exception_handling" ]
0.652
null
example_pathlib_ops
test_pathlib_ops_cli.py
"""Tests for pathlib_ops_cli.py""" import tempfile from pathlib import Path import pytest from pathlib_ops_cli import ( chmod, count_dirs, count_files, find_by_name, find_by_suffix, glob_pattern, iterdir, list_dirs, list_files, mkdir, read_bytes, read_text, rename, replace, rglob_pattern, rmdir, samefile, stat_mode, stat_mtime, stat_size, symlink_to, total_size, touch, unlink, walk_dir, write_bytes, write_text, ) @pytest.fixture def temp_dir(): """Create a temporary directory.""" with tempfile.TemporaryDirectory() as d: yield Path(d) class TestMkdir: def test_mkdir_simple(self, temp_dir): path = temp_dir / "newdir" assert mkdir(path) is True assert path.is_dir() def test_mkdir_exists(self, temp_dir): path = temp_dir / "existsdir" path.mkdir() assert mkdir(path) is False def test_mkdir_exist_ok(self, temp_dir): path = temp_dir / "existsdir" path.mkdir() assert mkdir(path, exist_ok=True) is True def test_mkdir_parents(self, temp_dir): path = temp_dir / "a" / "b" / "c" assert mkdir(path, parents=True) is True assert path.is_dir() def test_mkdir_no_parents(self, temp_dir): path = temp_dir / "a" / "b" / "c" assert mkdir(path, parents=False) is False class TestRmdir: def test_rmdir_empty(self, temp_dir): path = temp_dir / "emptydir" path.mkdir() assert rmdir(path) is True assert not path.exists() def test_rmdir_nonexistent(self, temp_dir): path = temp_dir / "nonexistent" assert rmdir(path) is False def test_rmdir_not_empty(self, temp_dir): path = temp_dir / "notempty" path.mkdir() (path / "file.txt").touch() assert rmdir(path) is False class TestUnlink: def test_unlink_file(self, temp_dir): path = temp_dir / "file.txt" path.touch() assert unlink(path) is True assert not path.exists() def test_unlink_nonexistent(self, temp_dir): path = temp_dir / "nonexistent" assert unlink(path) is False def test_unlink_missing_ok(self, temp_dir): path = temp_dir / "nonexistent" assert unlink(path, missing_ok=True) is True class TestRename: def test_rename_file(self, temp_dir): src = temp_dir / "old.txt" dst = temp_dir / "new.txt" src.touch() result = rename(src, dst) assert result == dst assert dst.exists() assert not src.exists() def test_rename_dir(self, temp_dir): src = temp_dir / "olddir" dst = temp_dir / "newdir" src.mkdir() result = rename(src, dst) assert result == dst assert dst.is_dir() class TestReplace: def test_replace_overwrites(self, temp_dir): src = temp_dir / "src.txt" dst = temp_dir / "dst.txt" src.write_text("source") dst.write_text("destination") replace(src, dst) assert not src.exists() assert dst.read_text() == "source" class TestTouch: def test_touch_new(self, temp_dir): path = temp_dir / "new.txt" assert touch(path) is True assert path.exists() def test_touch_existing(self, temp_dir): path = temp_dir / "existing.txt" path.touch() old_mtime = path.stat().st_mtime import time time.sleep(0.01) touch(path) new_mtime = path.stat().st_mtime assert new_mtime >= old_mtime class TestGlob: def test_glob_pattern(self, temp_dir): (temp_dir / "a.txt").touch() (temp_dir / "b.txt").touch() (temp_dir / "c.py").touch() matches = glob_pattern(temp_dir, "*.txt") assert len(matches) == 2 def test_glob_no_match(self, temp_dir): matches = glob_pattern(temp_dir, "*.xyz") assert len(matches) == 0 class TestRglob: def test_rglob_pattern(self, temp_dir): (temp_dir / "sub").mkdir() (temp_dir / "a.txt").touch() (temp_dir / "sub" / "b.txt").touch() matches = rglob_pattern(temp_dir, "*.txt") assert len(matches) == 2 class TestIterdir: def test_iterdir(self, temp_dir): (temp_dir / "file.txt").touch() (temp_dir / "subdir").mkdir() items = iterdir(temp_dir) assert len(items) == 2 class TestListFilesAndDirs: def test_list_files(self, temp_dir): (temp_dir / "file1.txt").touch() (temp_dir / "file2.txt").touch() (temp_dir / "subdir").mkdir() files = list_files(temp_dir) assert len(files) == 2 assert all(f.is_file() for f in files) def test_list_dirs(self, temp_dir): (temp_dir / "file.txt").touch() (temp_dir / "dir1").mkdir() (temp_dir / "dir2").mkdir() dirs = list_dirs(temp_dir) assert len(dirs) == 2 assert all(d.is_dir() for d in dirs) class TestStat: def test_stat_size(self, temp_dir): path = temp_dir / "file.txt" path.write_text("hello") assert stat_size(path) == 5 def test_stat_mtime(self, temp_dir): path = temp_dir / "file.txt" path.touch() mtime = stat_mtime(path) assert mtime > 0 def test_stat_mode(self, temp_dir): path = temp_dir / "file.txt" path.touch() mode = stat_mode(path) assert mode > 0 class TestChmod: def test_chmod(self, temp_dir): path = temp_dir / "file.txt" path.touch() chmod(path, 0o644) # Check last 3 digits of mode assert stat_mode(path) & 0o777 == 0o644 class TestSamefile: def test_samefile_true(self, temp_dir): path = temp_dir / "file.txt" path.touch() assert samefile(path, path) is True def test_samefile_false(self, temp_dir): path1 = temp_dir / "file1.txt" path2 = temp_dir / "file2.txt" path1.touch() path2.touch() assert samefile(path1, path2) is False class TestReadWrite: def test_read_write_text(self, temp_dir): path = temp_dir / "file.txt" write_text(path, "hello world") assert read_text(path) == "hello world" def test_read_write_bytes(self, temp_dir): path = temp_dir / "file.bin" data = b"\x00\x01\x02\x03" write_bytes(path, data) assert read_bytes(path) == data class TestSymlink: def test_symlink_to(self, temp_dir): target = temp_dir / "target.txt" link = temp_dir / "link.txt" target.write_text("content") symlink_to(link, target) assert link.is_symlink() assert link.read_text() == "content" class TestCount: def test_count_files(self, temp_dir): (temp_dir / "a.txt").touch() (temp_dir / "b.txt").touch() (temp_dir / "c.py").touch() assert count_files(temp_dir) == 3 assert count_files(temp_dir, "*.txt") == 2 def test_count_dirs(self, temp_dir): (temp_dir / "dir1").mkdir() (temp_dir / "dir2").mkdir() (temp_dir / "file.txt").touch() assert count_dirs(temp_dir) == 2 class TestTotalSize: def test_total_size(self, temp_dir): (temp_dir / "a.txt").write_text("hello") # 5 bytes (temp_dir / "b.txt").write_text("world") # 5 bytes assert total_size(temp_dir) == 10 class TestFindBy: def test_find_by_suffix(self, temp_dir): (temp_dir / "sub").mkdir() (temp_dir / "a.txt").touch() (temp_dir / "sub" / "b.txt").touch() (temp_dir / "c.py").touch() found = find_by_suffix(temp_dir, ".txt") assert len(found) == 2 def test_find_by_name(self, temp_dir): (temp_dir / "sub").mkdir() (temp_dir / "target.txt").touch() (temp_dir / "sub" / "target.txt").touch() (temp_dir / "other.txt").touch() found = find_by_name(temp_dir, "target.txt") assert len(found) == 2 class TestWalkDir: def test_walk_dir(self, temp_dir): (temp_dir / "sub").mkdir() (temp_dir / "file1.txt").touch() (temp_dir / "sub" / "file2.txt").touch() result = walk_dir(temp_dir) assert len(result) == 2 root_entry = result[0] assert root_entry[0] == temp_dir assert "sub" in root_entry[1] assert "file1.txt" in root_entry[2] class TestEdgeCases: def test_mkdir_rmdir_cycle(self, temp_dir): path = temp_dir / "cycle" assert mkdir(path) is True assert rmdir(path) is True assert mkdir(path) is True def test_deep_nesting(self, temp_dir): deep = temp_dir / "a" / "b" / "c" / "d" / "e" assert mkdir(deep, parents=True) is True (deep / "file.txt").touch() found = find_by_name(temp_dir, "file.txt") assert len(found) == 1
false
pathlib_ops
330
0
[ "generator", "context_manager", "class_definition", "decorator" ]
0.927
Profiling Report ══════════════════════════════════════════════════ Summary Total estimated instructions: 1 Total estimated allocations: 0 Functions analyzed: 1 Hot Paths [1] temp_dir (100.0% of execution time) Function Metrics 🔥 temp_dir 100.0% time | 1 inst | 0 alloc Performance Predictions • Rust's memory layout is more cache-friendly than Python (1.3x speedup, 70% confidence) 🚀 Estimated overall speedup: 1.3x Error: Expression type not yet supp
example_percent_encode
test_urlencode_cli.py
"""Tests for urlencode_cli.py""" from urlencode_cli import ( decode_path, encode_path, encode_query_param, encode_query_string, is_encoded, parse_query_string, percent_decode, percent_encode, percent_encode_byte, ) class TestPercentEncodeByte: def test_simple(self): assert percent_encode_byte(0x20) == "%20" assert percent_encode_byte(0xFF) == "%FF" assert percent_encode_byte(0x00) == "%00" class TestPercentEncode: def test_safe_chars(self): assert percent_encode("abc123") == "abc123" assert percent_encode("ABC") == "ABC" assert percent_encode("-._~") == "-._~" def test_space(self): assert percent_encode("hello world") == "hello%20world" def test_space_as_plus(self): assert percent_encode("hello world", space_as_plus=True) == "hello+world" def test_special_chars(self): assert percent_encode("a&b") == "a%26b" assert percent_encode("a=b") == "a%3Db" assert percent_encode("a?b") == "a%3Fb" def test_unicode(self): result = percent_encode("héllo") assert "%C3%A9" in result # UTF-8 encoding of é class TestPercentDecode: def test_simple(self): assert percent_decode("hello%20world") == "hello world" def test_plus_as_space(self): assert percent_decode("hello+world", plus_as_space=True) == "hello world" def test_plus_literal(self): assert percent_decode("hello+world", plus_as_space=False) == "hello+world" def test_unicode(self): assert percent_decode("h%C3%A9llo") == "héllo" def test_invalid_encoding(self): # Should not crash on invalid sequences assert percent_decode("hello%ZZ") == "hello%ZZ" def test_truncated(self): assert percent_decode("hello%2") == "hello%2" class TestRoundtrip: def test_roundtrip(self): original = "hello world & goodbye" encoded = percent_encode(original) decoded = percent_decode(encoded) assert decoded == original def test_roundtrip_unicode(self): original = "こんにちは" encoded = percent_encode(original) decoded = percent_decode(encoded) assert decoded == original class TestEncodeQueryParam: def test_simple(self): result = encode_query_param("key", "value") assert result == "key=value" def test_special_chars(self): result = encode_query_param("name", "John Doe") assert "+" in result or "%20" in result assert "=" in result class TestEncodeQueryString: def test_single(self): result = encode_query_string([("a", "1")]) assert result == "a=1" def test_multiple(self): result = encode_query_string([("a", "1"), ("b", "2")]) assert result == "a=1&b=2" def test_with_spaces(self): result = encode_query_string([("name", "John Doe")]) assert "John" in result assert "Doe" in result class TestParseQueryString: def test_simple(self): result = parse_query_string("a=1&b=2") assert result == [("a", "1"), ("b", "2")] def test_encoded(self): result = parse_query_string("name=John+Doe") assert result == [("name", "John Doe")] def test_empty_value(self): result = parse_query_string("key=") assert result == [("key", "")] def test_no_value(self): result = parse_query_string("key") assert result == [("key", "")] def test_empty(self): result = parse_query_string("") assert result == [] class TestEncodePath: def test_simple(self): result = encode_path("/path/to/file") assert result == "/path/to/file" def test_special_chars(self): result = encode_path("/path/to/my file") assert "%20" in result assert result.count("/") == 3 # Slashes preserved class TestDecodePath: def test_simple(self): assert decode_path("/path/to/file") == "/path/to/file" def test_encoded(self): assert decode_path("/path/to/my%20file") == "/path/to/my file" class TestIsEncoded: def test_encoded(self): assert is_encoded("hello%20world") is True assert is_encoded("%2F") is True def test_not_encoded(self): assert is_encoded("hello world") is False assert is_encoded("abc123") is False def test_invalid_percent(self): assert is_encoded("100%") is False assert is_encoded("hello%ZZ") is False
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_percent_encode/test_urlencode_cli.py (4526 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_percent_encode/test_urlencode_cli.rs (9459 bytes) ⏱️ Parse time: 48ms 📊 Throughput: 92.0 KB/s ⏱️ Total time: 48ms
true
percent_encode
158
5
[ "class_definition" ]
0.612
null
example_percent_encode
urlencode_cli.py
#!/usr/bin/env python3 """URL percent-encoding CLI. Encode and decode URL-safe strings. """ import argparse import sys # Characters that are safe (unreserved) in URLs SAFE_CHARS = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") # Additional characters safe in path component PATH_SAFE = SAFE_CHARS | set("!$&'()*+,;=:@/") # Characters safe in query string QUERY_SAFE = SAFE_CHARS | set("!$&'()*+,;=:@/?") def percent_encode_byte(byte: int) -> str: """Encode a single byte as percent-encoded.""" return f"%{byte:02X}" def percent_encode( text: str, safe: set[str] | None = None, space_as_plus: bool = False, ) -> str: """Percent-encode a string. Args: text: String to encode safe: Set of safe characters (default: unreserved chars) space_as_plus: Encode spaces as + (for form data) """ if safe is None: safe = SAFE_CHARS result = [] for char in text: if char == " " and space_as_plus: result.append("+") elif char in safe: result.append(char) else: for byte in char.encode("utf-8"): result.append(percent_encode_byte(byte)) return "".join(result) def percent_decode(text: str, plus_as_space: bool = False) -> str: """Decode percent-encoded string.""" result = [] i = 0 while i < len(text): char = text[i] if char == "+" and plus_as_space: result.append(" ") i += 1 elif char == "%" and i + 2 < len(text): try: byte = int(text[i + 1 : i + 3], 16) result.append(chr(byte)) i += 3 except ValueError: result.append(char) i += 1 else: result.append(char) i += 1 # Handle UTF-8 decoding try: return "".join(result).encode("latin-1").decode("utf-8") except (UnicodeDecodeError, UnicodeEncodeError): return "".join(result) def encode_query_param(key: str, value: str) -> str: """Encode a single query parameter.""" encoded_key = percent_encode(key, space_as_plus=True) encoded_value = percent_encode(value, space_as_plus=True) return f"{encoded_key}={encoded_value}" def encode_query_string(params: list[tuple[str, str]]) -> str: """Encode query parameters into query string.""" return "&".join(encode_query_param(k, v) for k, v in params) def parse_query_string(query: str) -> list[tuple[str, str]]: """Parse query string into list of (key, value) pairs.""" result = [] for part in query.split("&"): if not part: continue if "=" in part: key, value = part.split("=", 1) else: key, value = part, "" decoded_key = percent_decode(key, plus_as_space=True) decoded_value = percent_decode(value, plus_as_space=True) result.append((decoded_key, decoded_value)) return result def encode_path(path: str) -> str: """Encode URL path, preserving structure.""" parts = path.split("/") return "/".join(percent_encode(p, safe=SAFE_CHARS) for p in parts) def decode_path(path: str) -> str: """Decode URL path.""" return percent_decode(path) def is_encoded(text: str) -> bool: """Check if text contains percent-encoding.""" i = 0 while i < len(text): if text[i] == "%": if i + 2 < len(text): try: int(text[i + 1 : i + 3], 16) return True except ValueError: pass i += 1 return False def main() -> int: parser = argparse.ArgumentParser(description="URL percent-encoding tool") parser.add_argument("text", nargs="?", help="Text to encode/decode") parser.add_argument("-d", "--decode", action="store_true", help="Decode instead of encode") parser.add_argument("--path", action="store_true", help="Encode/decode as URL path") parser.add_argument("--query", action="store_true", help="Encode/decode as query string") parser.add_argument( "--param", metavar="KEY=VALUE", action="append", help="Encode query parameter (can repeat)" ) parser.add_argument("--plus", action="store_true", help="Use + for spaces (form encoding)") parser.add_argument("--auto", action="store_true", help="Auto-detect encode/decode") args = parser.parse_args() # Build query from params if args.param: params = [] for p in args.param: if "=" in p: key, value = p.split("=", 1) else: key, value = p, "" params.append((key, value)) print(encode_query_string(params)) return 0 # Read text if args.text is None: text = sys.stdin.read().rstrip("\n") else: text = args.text # Auto-detect if args.auto: args.decode = is_encoded(text) # Process if args.decode: if args.query: params = parse_query_string(text) for key, value in params: print(f"{key}={value}") elif args.path: print(decode_path(text)) else: print(percent_decode(text, plus_as_space=args.plus)) else: if args.query: # Encode as query value print(percent_encode(text, space_as_plus=True)) elif args.path: print(encode_path(text)) else: print(percent_encode(text, space_as_plus=args.plus)) return 0 if __name__ == "__main__": sys.exit(main())
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_percent_encode/urlencode_cli.py (5654 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_percent_encode/urlencode_cli.rs (12622 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_percent_encode/Cargo.toml (3 dependencies) ⏱️ Parse time: 53ms 📊 Throughput: 103.2 KB/s ⏱️ Total time: 53ms
true
percent_encode
199
6
[ "exception_handling", "stdin_usage", "decorator", "multiprocessing" ]
0.577
null
example_polynomial
poly_cli.py
#!/usr/bin/env python3 """Polynomial Operations CLI. Pure Python polynomial operations without external dependencies. """ import argparse import sys from dataclasses import dataclass @dataclass class Polynomial: """Polynomial representation using coefficients.""" coeffs: list[float] # coeffs[i] is coefficient of x^i def __post_init__(self): # Remove trailing zeros while len(self.coeffs) > 1 and self.coeffs[-1] == 0: self.coeffs.pop() @property def degree(self) -> int: """Get polynomial degree.""" return len(self.coeffs) - 1 def __str__(self) -> str: """Format polynomial as string.""" if not self.coeffs or all(c == 0 for c in self.coeffs): return "0" terms = [] for i, c in enumerate(self.coeffs): if c == 0: continue if i == 0: terms.append(f"{c}") elif i == 1: if c == 1: terms.append("x") elif c == -1: terms.append("-x") else: terms.append(f"{c}x") else: if c == 1: terms.append(f"x^{i}") elif c == -1: terms.append(f"-x^{i}") else: terms.append(f"{c}x^{i}") if not terms: return "0" result = terms[-1] for term in reversed(terms[:-1]): if term.startswith("-"): result += f" - {term[1:]}" else: result += f" + {term}" return result def add(p1: Polynomial, p2: Polynomial) -> Polynomial: """Add two polynomials.""" max_len = max(len(p1.coeffs), len(p2.coeffs)) result = [0.0] * max_len for i, c in enumerate(p1.coeffs): result[i] += c for i, c in enumerate(p2.coeffs): result[i] += c return Polynomial(result) def subtract(p1: Polynomial, p2: Polynomial) -> Polynomial: """Subtract p2 from p1.""" max_len = max(len(p1.coeffs), len(p2.coeffs)) result = [0.0] * max_len for i, c in enumerate(p1.coeffs): result[i] += c for i, c in enumerate(p2.coeffs): result[i] -= c return Polynomial(result) def multiply(p1: Polynomial, p2: Polynomial) -> Polynomial: """Multiply two polynomials.""" if not p1.coeffs or not p2.coeffs: return Polynomial([0]) result = [0.0] * (len(p1.coeffs) + len(p2.coeffs) - 1) for i, c1 in enumerate(p1.coeffs): for j, c2 in enumerate(p2.coeffs): result[i + j] += c1 * c2 return Polynomial(result) def scalar_multiply(p: Polynomial, scalar: float) -> Polynomial: """Multiply polynomial by scalar.""" return Polynomial([c * scalar for c in p.coeffs]) def evaluate(p: Polynomial, x: float) -> float: """Evaluate polynomial at x using Horner's method.""" if not p.coeffs: return 0.0 result = p.coeffs[-1] for i in range(len(p.coeffs) - 2, -1, -1): result = result * x + p.coeffs[i] return result def derivative(p: Polynomial) -> Polynomial: """Calculate derivative of polynomial.""" if len(p.coeffs) <= 1: return Polynomial([0]) result = [i * p.coeffs[i] for i in range(1, len(p.coeffs))] return Polynomial(result) def integrate(p: Polynomial, constant: float = 0) -> Polynomial: """Calculate indefinite integral of polynomial.""" result = [constant] for i, c in enumerate(p.coeffs): result.append(c / (i + 1)) return Polynomial(result) def definite_integral(p: Polynomial, a: float, b: float) -> float: """Calculate definite integral from a to b.""" integral = integrate(p) return evaluate(integral, b) - evaluate(integral, a) def power(p: Polynomial, n: int) -> Polynomial: """Raise polynomial to power n.""" if n < 0: raise ValueError("Negative powers not supported") if n == 0: return Polynomial([1]) result = Polynomial(p.coeffs[:]) for _ in range(n - 1): result = multiply(result, p) return result def divide(dividend: Polynomial, divisor: Polynomial) -> tuple[Polynomial, Polynomial]: """Polynomial long division. Returns (quotient, remainder).""" if all(c == 0 for c in divisor.coeffs): raise ValueError("Division by zero polynomial") if dividend.degree < divisor.degree: return Polynomial([0]), dividend quotient = [0.0] * (dividend.degree - divisor.degree + 1) remainder = dividend.coeffs[:] divisor_lead = divisor.coeffs[-1] for i in range(len(quotient) - 1, -1, -1): if len(remainder) > divisor.degree + i: coeff = remainder[divisor.degree + i] / divisor_lead quotient[i] = coeff for j, c in enumerate(divisor.coeffs): remainder[i + j] -= coeff * c return Polynomial(quotient), Polynomial(remainder) def gcd(p1: Polynomial, p2: Polynomial) -> Polynomial: """Calculate GCD of two polynomials using Euclidean algorithm.""" while any(c != 0 for c in p2.coeffs): _, remainder = divide(p1, p2) p1 = p2 p2 = remainder # Normalize leading coefficient to 1 if p1.coeffs and p1.coeffs[-1] != 0: lead = p1.coeffs[-1] return Polynomial([c / lead for c in p1.coeffs]) return p1 def compose(outer: Polynomial, inner: Polynomial) -> Polynomial: """Compose polynomials: outer(inner(x)).""" result = Polynomial([0]) for i, c in enumerate(outer.coeffs): term = scalar_multiply(power(inner, i), c) result = add(result, term) return result def find_roots_quadratic(p: Polynomial) -> list[complex]: """Find roots of quadratic polynomial.""" if p.degree != 2: raise ValueError("Polynomial must be quadratic") c, b, a = p.coeffs[0], p.coeffs[1], p.coeffs[2] discriminant = b * b - 4 * a * c if discriminant >= 0: sqrt_d = discriminant**0.5 return [(-b + sqrt_d) / (2 * a), (-b - sqrt_d) / (2 * a)] else: sqrt_d = (-discriminant) ** 0.5 return [ complex(-b / (2 * a), sqrt_d / (2 * a)), complex(-b / (2 * a), -sqrt_d / (2 * a)), ] def find_root_newton(p: Polynomial, x0: float, tol: float = 1e-10, max_iter: int = 100) -> float: """Find a root using Newton's method.""" dp = derivative(p) x = x0 for _ in range(max_iter): fx = evaluate(p, x) if abs(fx) < tol: return x dfx = evaluate(dp, x) if abs(dfx) < 1e-15: raise ValueError("Derivative too small") x = x - fx / dfx raise ValueError("Did not converge") def interpolate_lagrange(points: list[tuple[float, float]]) -> Polynomial: """Lagrange polynomial interpolation.""" n = len(points) result = Polynomial([0]) for i in range(n): xi, yi = points[i] # Build basis polynomial L_i basis = Polynomial([1]) for j in range(n): if i != j: xj = points[j][0] factor = Polynomial([-xj / (xi - xj), 1 / (xi - xj)]) basis = multiply(basis, factor) result = add(result, scalar_multiply(basis, yi)) return result def from_roots(roots: list[float]) -> Polynomial: """Create polynomial from its roots.""" result = Polynomial([1]) for r in roots: factor = Polynomial([-r, 1]) # (x - r) result = multiply(result, factor) return result def parse_polynomial(s: str) -> Polynomial: """Parse polynomial from string like '1,2,3' -> 1 + 2x + 3x^2.""" coeffs = [float(c) for c in s.split(",")] return Polynomial(coeffs) def main() -> int: parser = argparse.ArgumentParser(description="Polynomial operations") parser.add_argument( "--mode", choices=[ "eval", "add", "mult", "deriv", "integ", "roots", "divide", "interpolate", "demo", ], default="demo", help="Operation mode", ) parser.add_argument("--p", help="Polynomial coefficients (comma-separated)") parser.add_argument("--q", help="Second polynomial") parser.add_argument("--x", type=float, help="Value to evaluate at") parser.add_argument("--points", help="Points for interpolation (x1:y1,x2:y2,...)") args = parser.parse_args() if args.mode == "demo": print("Polynomial Operations Demo\n") p = Polynomial([1, 2, 3]) # 1 + 2x + 3x^2 q = Polynomial([2, 1]) # 2 + x print(f"P(x) = {p}") print(f"Q(x) = {q}") print(f"\nP(2) = {evaluate(p, 2)}") print(f"P + Q = {add(p, q)}") print(f"P * Q = {multiply(p, q)}") print(f"P' = {derivative(p)}") print(f"∫P dx = {integrate(p)}") quadratic = Polynomial([6, -5, 1]) # x^2 - 5x + 6 = (x-2)(x-3) print(f"\nRoots of {quadratic}: {find_roots_quadratic(quadratic)}") elif args.p: p = parse_polynomial(args.p) if args.mode == "eval" and args.x is not None: result = evaluate(p, args.x) print(f"P({args.x}) = {result}") elif args.mode == "add" and args.q: q = parse_polynomial(args.q) result = add(p, q) print(f"P + Q = {result}") elif args.mode == "mult" and args.q: q = parse_polynomial(args.q) result = multiply(p, q) print(f"P * Q = {result}") elif args.mode == "deriv": result = derivative(p) print(f"P' = {result}") elif args.mode == "integ": result = integrate(p) print(f"∫P dx = {result}") elif args.mode == "roots" and p.degree == 2: roots = find_roots_quadratic(p) print(f"Roots: {roots}") elif args.mode == "divide" and args.q: q = parse_polynomial(args.q) quot, rem = divide(p, q) print(f"P / Q = {quot}") print(f"Remainder = {rem}") elif args.mode == "interpolate" and args.points: points = [] for pt in args.points.split(","): x, y = pt.split(":") points.append((float(x), float(y))) result = interpolate_lagrange(points) print(f"Interpolating polynomial: {result}") return 0 if __name__ == "__main__": sys.exit(main())
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_polynomial/poly_cli.py (10542 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_polynomial/poly_cli.rs (21449 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_polynomial/Cargo.toml (1 dependencies) ⏱️ Parse time: 61ms 📊 Throughput: 166.4 KB/s ⏱️ Total time: 62ms
true
polynomial
379
6
[ "class_definition", "exception_handling", "decorator" ]
0.612
null
example_polynomial
test_poly_cli.py
"""Tests for poly_cli.py""" import pytest from poly_cli import ( Polynomial, add, compose, definite_integral, derivative, divide, evaluate, find_root_newton, find_roots_quadratic, from_roots, gcd, integrate, interpolate_lagrange, multiply, power, scalar_multiply, subtract, ) class TestPolynomial: def test_creation(self): p = Polynomial([1, 2, 3]) assert p.coeffs == [1, 2, 3] assert p.degree == 2 def test_trailing_zeros(self): p = Polynomial([1, 2, 0, 0]) assert p.coeffs == [1, 2] def test_str_simple(self): p = Polynomial([1, 2, 3]) s = str(p) assert "3x^2" in s assert "2x" in s assert "1" in s def test_str_zero(self): p = Polynomial([0]) assert str(p) == "0" class TestAdd: def test_same_degree(self): p1 = Polynomial([1, 2, 3]) p2 = Polynomial([4, 5, 6]) result = add(p1, p2) assert result.coeffs == [5, 7, 9] def test_different_degrees(self): p1 = Polynomial([1, 2, 3]) p2 = Polynomial([1, 1]) result = add(p1, p2) assert result.coeffs == [2, 3, 3] class TestSubtract: def test_basic(self): p1 = Polynomial([5, 6, 7]) p2 = Polynomial([1, 2, 3]) result = subtract(p1, p2) assert result.coeffs == [4, 4, 4] class TestMultiply: def test_basic(self): # (1 + x) * (1 + x) = 1 + 2x + x^2 p1 = Polynomial([1, 1]) p2 = Polynomial([1, 1]) result = multiply(p1, p2) assert result.coeffs == [1, 2, 1] def test_by_constant(self): p = Polynomial([1, 2, 3]) c = Polynomial([2]) result = multiply(p, c) assert result.coeffs == [2, 4, 6] class TestScalarMultiply: def test_basic(self): p = Polynomial([1, 2, 3]) result = scalar_multiply(p, 2) assert result.coeffs == [2, 4, 6] def test_zero(self): p = Polynomial([1, 2, 3]) result = scalar_multiply(p, 0) assert result.coeffs == [0] class TestEvaluate: def test_constant(self): p = Polynomial([5]) assert evaluate(p, 10) == 5 def test_linear(self): p = Polynomial([1, 2]) # 1 + 2x assert evaluate(p, 3) == 7 def test_quadratic(self): p = Polynomial([1, 2, 3]) # 1 + 2x + 3x^2 # At x=2: 1 + 4 + 12 = 17 assert evaluate(p, 2) == 17 def test_at_zero(self): p = Polynomial([5, 3, 2]) assert evaluate(p, 0) == 5 class TestDerivative: def test_constant(self): p = Polynomial([5]) result = derivative(p) assert result.coeffs == [0] def test_linear(self): p = Polynomial([1, 2]) # 1 + 2x result = derivative(p) assert result.coeffs == [2] def test_quadratic(self): p = Polynomial([1, 2, 3]) # 1 + 2x + 3x^2 result = derivative(p) assert result.coeffs == [2, 6] class TestIntegrate: def test_constant(self): p = Polynomial([2]) # 2 result = integrate(p) # ∫2 dx = 2x + C assert result.coeffs == [0, 2] def test_linear(self): p = Polynomial([2, 3]) # 2 + 3x result = integrate(p) # ∫(2 + 3x) dx = 2x + 1.5x^2 + C assert result.coeffs[0] == 0 # C=0 assert result.coeffs[1] == 2 assert result.coeffs[2] == pytest.approx(1.5) class TestDefiniteIntegral: def test_basic(self): p = Polynomial([0, 1]) # x # ∫_0^2 x dx = [x^2/2]_0^2 = 2 result = definite_integral(p, 0, 2) assert result == pytest.approx(2) class TestPower: def test_zero_power(self): p = Polynomial([1, 2, 3]) result = power(p, 0) assert result.coeffs == [1] def test_first_power(self): p = Polynomial([1, 2]) result = power(p, 1) assert result.coeffs == p.coeffs def test_square(self): p = Polynomial([1, 1]) # 1 + x result = power(p, 2) # (1 + x)^2 = 1 + 2x + x^2 assert result.coeffs == [1, 2, 1] class TestDivide: def test_exact(self): # (x^2 - 1) / (x - 1) = (x + 1) dividend = Polynomial([-1, 0, 1]) # x^2 - 1 divisor = Polynomial([-1, 1]) # x - 1 quotient, remainder = divide(dividend, divisor) assert quotient.coeffs == pytest.approx([1, 1]) assert all(abs(c) < 1e-10 for c in remainder.coeffs) def test_with_remainder(self): # x^2 / (x - 1) dividend = Polynomial([0, 0, 1]) # x^2 divisor = Polynomial([-1, 1]) # x - 1 quotient, remainder = divide(dividend, divisor) # Verify: quotient * divisor + remainder = dividend class TestGCD: def test_basic(self): # GCD of (x-1)(x-2) and (x-1)(x-3) p1 = from_roots([1, 2]) p2 = from_roots([1, 3]) result = gcd(p1, p2) # Should be (x-1), normalized assert result.degree == 1 class TestCompose: def test_basic(self): # f(x) = x^2, g(x) = x + 1 # f(g(x)) = (x + 1)^2 = 1 + 2x + x^2 f = Polynomial([0, 0, 1]) # x^2 g = Polynomial([1, 1]) # x + 1 result = compose(f, g) assert result.coeffs == [1, 2, 1] class TestFindRootsQuadratic: def test_real_roots(self): # x^2 - 5x + 6 = (x-2)(x-3) p = Polynomial([6, -5, 1]) roots = find_roots_quadratic(p) assert len(roots) == 2 assert 2 in [pytest.approx(r, abs=0.01) for r in roots] assert 3 in [pytest.approx(r, abs=0.01) for r in roots] def test_complex_roots(self): # x^2 + 1 p = Polynomial([1, 0, 1]) roots = find_roots_quadratic(p) assert len(roots) == 2 assert all(isinstance(r, complex) for r in roots) class TestFindRootNewton: def test_simple(self): # x^2 - 4 = 0, root at x=2 p = Polynomial([-4, 0, 1]) root = find_root_newton(p, 1.5) assert root == pytest.approx(2.0, abs=0.01) def test_cubic(self): # x^3 - 1 = 0, root at x=1 p = Polynomial([-1, 0, 0, 1]) root = find_root_newton(p, 0.5) assert root == pytest.approx(1.0, abs=0.01) class TestInterpolateLagrange: def test_two_points(self): # Line through (0, 0) and (1, 1): y = x points = [(0, 0), (1, 1)] result = interpolate_lagrange(points) assert evaluate(result, 0) == pytest.approx(0) assert evaluate(result, 1) == pytest.approx(1) assert evaluate(result, 0.5) == pytest.approx(0.5) def test_three_points(self): # Parabola through (0, 0), (1, 1), (2, 4) points = [(0, 0), (1, 1), (2, 4)] result = interpolate_lagrange(points) assert evaluate(result, 0) == pytest.approx(0) assert evaluate(result, 1) == pytest.approx(1) assert evaluate(result, 2) == pytest.approx(4) class TestFromRoots: def test_single_root(self): result = from_roots([2]) # Should be (x - 2) assert evaluate(result, 2) == pytest.approx(0) def test_multiple_roots(self): result = from_roots([1, 2, 3]) # Should be (x-1)(x-2)(x-3) assert evaluate(result, 1) == pytest.approx(0) assert evaluate(result, 2) == pytest.approx(0) assert evaluate(result, 3) == pytest.approx(0)
false
polynomial
281
0
[ "class_definition" ]
0.612
Error: Expression type not yet supported: GeneratorExp { element: Binary { op: Lt, left: Call { func: "abs", args: [Var("c")], kwargs: [] }, right: Literal(Float(1e-10)) }, generators: [HirComprehension { target: "c", iter: Attribute { value: Var("remainder"), attr: "coeffs" }, conditions: [] }] }
example_positional
positional_args.py
#!/usr/bin/env python3 """ Positional Arguments Example Demonstrates argparse positional arguments: - command: Required positional with choices (start, stop, restart) - targets: Optional positional with nargs='*' (multiple values) This shows how to handle positional arguments with validation. """ import argparse def main(): """ Main entry point for the positional args CLI Parses command and optional targets, displays them. """ parser = argparse.ArgumentParser( description="Positional arguments example with command and targets", prog="positional_args.py", ) # Required positional argument with choices parser.add_argument( "command", choices=["start", "stop", "restart"], help="Command to execute (start, stop, or restart)", ) # Optional positional argument with nargs parser.add_argument( "targets", nargs="*", # Zero or more arguments default=["all"], help="Targets to apply command to (default: all)", ) parser.add_argument("--version", action="version", version="1.0.0") args = parser.parse_args() # Display parsed arguments print(f"Command: {args.command}") print(f"Targets: {args.targets}") if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_positional/positional_args.py (1294 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_positional/positional_args.rs (820 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_positional/Cargo.toml (1 dependencies) ⏱️ Parse time: 46ms 📊 Throughput: 27.3 KB/s ⏱️ Total time: 46ms
true
positional
51
6
[ "context_manager" ]
0.652
null
example_positional
test_positional_args.py
""" Test suite for positional_args.py Tests positional arguments with choices and nargs Following extreme TDD methodology """ import subprocess from pathlib import Path import pytest SCRIPT = Path(__file__).parent / "positional_args.py" def run_cli(*args): """Helper to run CLI and capture output""" result = subprocess.run(["python3", str(SCRIPT), *args], capture_output=True, text=True) return result class TestPositionalArgs: """Test suite for positional_args.py""" def test_help_flag(self): """Test --help displays usage""" result = run_cli("--help") assert result.returncode == 0 assert "usage:" in result.stdout.lower() assert "command" in result.stdout.lower() assert "targets" in result.stdout.lower() def test_version_flag(self): """Test --version displays version""" result = run_cli("--version") assert result.returncode == 0 assert "1.0.0" in result.stdout def test_start_command_no_targets(self): """Test 'start' command with no targets (uses default)""" result = run_cli("start") assert result.returncode == 0 assert "Command: start" in result.stdout assert "Targets: ['all']" in result.stdout def test_start_command_single_target(self): """Test 'start' command with single target""" result = run_cli("start", "web") assert result.returncode == 0 assert "Command: start" in result.stdout assert "Targets: ['web']" in result.stdout def test_start_command_multiple_targets(self): """Test 'start' command with multiple targets""" result = run_cli("start", "web", "db", "cache") assert result.returncode == 0 assert "Command: start" in result.stdout assert "'web'" in result.stdout assert "'db'" in result.stdout assert "'cache'" in result.stdout def test_stop_command_no_targets(self): """Test 'stop' command with no targets""" result = run_cli("stop") assert result.returncode == 0 assert "Command: stop" in result.stdout assert "Targets: ['all']" in result.stdout def test_stop_command_single_target(self): """Test 'stop' command with single target""" result = run_cli("stop", "db") assert result.returncode == 0 assert "Command: stop" in result.stdout assert "Targets: ['db']" in result.stdout def test_restart_command_no_targets(self): """Test 'restart' command with no targets""" result = run_cli("restart") assert result.returncode == 0 assert "Command: restart" in result.stdout assert "Targets: ['all']" in result.stdout def test_restart_command_multiple_targets(self): """Test 'restart' command with multiple targets""" result = run_cli("restart", "web", "api") assert result.returncode == 0 assert "Command: restart" in result.stdout assert "'web'" in result.stdout assert "'api'" in result.stdout def test_invalid_command(self): """Test error handling for invalid command""" result = run_cli("invalid") assert result.returncode != 0 assert "invalid choice" in result.stderr.lower() def test_missing_command(self): """Test error handling when command is missing""" result = run_cli() assert result.returncode != 0 assert ( "required" in result.stderr.lower() or "following arguments are required" in result.stderr.lower() ) @pytest.mark.parametrize("command", ["start", "stop", "restart"]) def test_all_commands_valid(self, command): """Test that all three commands work""" result = run_cli(command) assert result.returncode == 0 assert f"Command: {command}" in result.stdout def test_command_case_sensitive(self): """Test that commands are case-sensitive""" result = run_cli("START") # Capital letters assert result.returncode != 0 assert "invalid choice" in result.stderr.lower() def test_targets_order_preserved(self): """Test that target order is preserved""" result = run_cli("start", "web", "db", "cache") assert result.returncode == 0 # Check that order is maintained in output output = result.stdout web_pos = output.find("'web'") db_pos = output.find("'db'") cache_pos = output.find("'cache'") assert web_pos < db_pos < cache_pos, "Order should be preserved" def test_duplicate_targets_allowed(self): """Test that duplicate targets are allowed (argparse doesn't prevent)""" result = run_cli("start", "web", "web") assert result.returncode == 0 assert "'web'" in result.stdout def test_many_targets(self): """Test with many targets""" targets = ["target" + str(i) for i in range(10)] result = run_cli("start", *targets) assert result.returncode == 0 for target in targets: assert f"'{target}'" in result.stdout def test_targets_with_special_chars(self): """Test targets with hyphens and underscores""" result = run_cli("start", "web-server", "db_cache") assert result.returncode == 0 assert "'web-server'" in result.stdout assert "'db_cache'" in result.stdout def test_stderr_empty_on_success(self): """Test that stderr is empty on success""" result = run_cli("start", "web") assert result.returncode == 0 assert result.stderr == "" def test_deterministic_output(self): """Test that output is deterministic""" results = [run_cli("start", "web", "db") for _ in range(3)] assert all(r.returncode == 0 for r in results) first_output = results[0].stdout assert all(r.stdout == first_output for r in results) class TestEdgeCases: """Additional edge case tests""" def test_help_with_command(self): """Test that --help works even with command specified""" result = run_cli("--help", "start") assert result.returncode == 0 assert "usage:" in result.stdout.lower() def test_version_with_command(self): """Test that --version works even with command specified""" result = run_cli("--version", "start") assert result.returncode == 0 assert "1.0.0" in result.stdout def test_empty_string_target(self): """Test behavior with empty string as target""" result = run_cli("start", "") assert result.returncode == 0 # Argparse should accept empty string as valid assert "Command: start" in result.stdout def test_only_help_choices_shown(self): """Test that help shows only valid choices""" result = run_cli("--help") assert result.returncode == 0 assert "start" in result.stdout assert "stop" in result.stdout assert "restart" in result.stdout # Should show choices in help assert ( "{start,stop,restart}" in result.stdout or "start, stop, restart" in result.stdout.lower() )
false
positional
198
0
[ "context_manager", "class_definition", "decorator" ]
0.652
Performance Warnings ══════════════════════════════════════════════════ [1] [Medium] Large value 'args' passed by copy Location: run_cli, line 0 Impact: Complexity: O(n), Scales: Yes, Hot path: No Why: Passing large values by copy is inefficient Fix: Consider passing by reference (&) or using Box/Arc for large types Summary: Found 1 warnings (0 critical, 0 high severity) Profiling Report ══════════════════════════════════════════════════ Summary Total estimated instructions:
example_pow
pow_tool.py
#!/usr/bin/env python3 """Pow Example - Power operations CLI. Examples: >>> square(5) 25 >>> cube(3) 27 >>> power(2, 10) 1024 """ import argparse def square(x: int) -> int: """Compute square of integer. >>> square(0) 0 >>> square(4) 16 >>> square(-3) 9 """ return x * x def cube(x: int) -> int: """Compute cube of integer. >>> cube(0) 0 >>> cube(2) 8 >>> cube(-2) -8 """ return x * x * x def power(base: int, exp: int) -> int: """Compute base raised to exp. >>> power(2, 0) 1 >>> power(2, 3) 8 >>> power(3, 4) 81 """ result = 1 i = 0 while i < exp: result = result * base i = i + 1 return result def main(): parser = argparse.ArgumentParser(description="Power operations tool") subs = parser.add_subparsers(dest="cmd", required=True) s = subs.add_parser("square") s.add_argument("x", type=int) c = subs.add_parser("cube") c.add_argument("x", type=int) p = subs.add_parser("power") p.add_argument("base", type=int) p.add_argument("exp", type=int) args = parser.parse_args() if args.cmd == "square": print(square(args.x)) elif args.cmd == "cube": print(cube(args.x)) elif args.cmd == "power": print(power(args.base, args.exp)) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pow/pow_tool.py (1416 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pow/pow_tool.rs (2376 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pow/Cargo.toml (1 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 28.5 KB/s ⏱️ Total time: 48ms
true
pow
82
6
[]
0
null
example_pow
test_pow_tool.py
"""Tests for pow_tool - EXTREME TDD.""" import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "pow_tool.py" def run(cmd): return subprocess.run( ["python3", str(SCRIPT)] + cmd.split(), capture_output=True, text=True, ) def test_square(): r = run("square 5") assert r.returncode == 0 assert r.stdout.strip() == "25" def test_cube(): r = run("cube 3") assert r.returncode == 0 assert r.stdout.strip() == "27" def test_power(): r = run("power 2 10") assert r.returncode == 0 assert r.stdout.strip() == "1024"
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pow/test_pow_tool.py (606 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pow/test_pow_tool.rs (1816 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pow/Cargo.toml (2 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 12.1 KB/s ⏱️ Total time: 49ms
true
pow
32
6
[]
0
null
example_prime_factors
prime_cli.py
#!/usr/bin/env python3 """Prime Factorization CLI. Prime number operations and factorization without external dependencies. """ import argparse import sys from math import isqrt def is_prime(n: int) -> bool: """Check if n is prime.""" if n < 2: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, isqrt(n) + 1, 2): if n % i == 0: return False return True def sieve_of_eratosthenes(limit: int) -> list[int]: """Generate all primes up to limit.""" if limit < 2: return [] is_prime_arr = [True] * (limit + 1) is_prime_arr[0] = is_prime_arr[1] = False for i in range(2, isqrt(limit) + 1): if is_prime_arr[i]: for j in range(i * i, limit + 1, i): is_prime_arr[j] = False return [i for i in range(limit + 1) if is_prime_arr[i]] def prime_factors(n: int) -> list[int]: """Find prime factors (with repetition).""" if n < 2: return [] factors = [] d = 2 while d * d <= n: while n % d == 0: factors.append(d) n //= d d += 1 if n > 1: factors.append(n) return factors def prime_factorization(n: int) -> dict[int, int]: """Get prime factorization as {prime: exponent}.""" factors = prime_factors(n) result: dict[int, int] = {} for p in factors: result[p] = result.get(p, 0) + 1 return result def count_divisors(n: int) -> int: """Count the number of divisors.""" factorization = prime_factorization(n) count = 1 for exp in factorization.values(): count *= exp + 1 return count def sum_of_divisors(n: int) -> int: """Calculate sum of all divisors.""" factorization = prime_factorization(n) total = 1 for p, exp in factorization.items(): # Sum of geometric series: 1 + p + p^2 + ... + p^exp total *= (p ** (exp + 1) - 1) // (p - 1) return total def divisors(n: int) -> list[int]: """Find all divisors of n.""" if n < 1: return [] result = [] for i in range(1, isqrt(n) + 1): if n % i == 0: result.append(i) if i != n // i: result.append(n // i) return sorted(result) def gcd(a: int, b: int) -> int: """Calculate GCD using Euclidean algorithm.""" while b: a, b = b, a % b return a def lcm(a: int, b: int) -> int: """Calculate LCM.""" return abs(a * b) // gcd(a, b) def gcd_multiple(numbers: list[int]) -> int: """Calculate GCD of multiple numbers.""" result = numbers[0] for n in numbers[1:]: result = gcd(result, n) return result def lcm_multiple(numbers: list[int]) -> int: """Calculate LCM of multiple numbers.""" result = numbers[0] for n in numbers[1:]: result = lcm(result, n) return result def extended_gcd(a: int, b: int) -> tuple[int, int, int]: """Extended Euclidean algorithm. Returns (gcd, x, y) where ax + by = gcd.""" if b == 0: return a, 1, 0 g, x1, y1 = extended_gcd(b, a % b) x = y1 y = x1 - (a // b) * y1 return g, x, y def mod_inverse(a: int, m: int) -> int: """Calculate modular multiplicative inverse.""" g, x, _ = extended_gcd(a, m) if g != 1: raise ValueError("Modular inverse doesn't exist") return x % m def euler_totient(n: int) -> int: """Calculate Euler's totient function (phi).""" if n < 1: return 0 result = n factorization = prime_factorization(n) for p in factorization.keys(): result -= result // p return result def is_coprime(a: int, b: int) -> bool: """Check if two numbers are coprime.""" return gcd(a, b) == 1 def next_prime(n: int) -> int: """Find the next prime after n.""" if n < 2: return 2 candidate = n + 1 while not is_prime(candidate): candidate += 1 return candidate def prev_prime(n: int) -> int: """Find the previous prime before n.""" if n <= 2: raise ValueError("No prime before 2") candidate = n - 1 while candidate > 1 and not is_prime(candidate): candidate -= 1 if candidate < 2: raise ValueError("No prime found") return candidate def nth_prime(n: int) -> int: """Find the nth prime number (1-indexed).""" if n < 1: raise ValueError("n must be positive") count = 0 candidate = 1 while count < n: candidate += 1 if is_prime(candidate): count += 1 return candidate def prime_counting(n: int) -> int: """Count primes up to n (pi function).""" return len(sieve_of_eratosthenes(n)) def is_perfect_number(n: int) -> bool: """Check if n is a perfect number.""" if n < 2: return False return sum_of_divisors(n) - n == n def is_abundant(n: int) -> bool: """Check if n is an abundant number.""" if n < 2: return False return sum_of_divisors(n) - n > n def is_deficient(n: int) -> bool: """Check if n is a deficient number.""" if n < 2: return False return sum_of_divisors(n) - n < n def radical(n: int) -> int: """Calculate the radical (product of distinct prime factors).""" return product_of_list(list(prime_factorization(n).keys())) def product_of_list(lst: list[int]) -> int: """Calculate product of list elements.""" result = 1 for x in lst: result *= x return result def mobius(n: int) -> int: """Calculate Möbius function.""" if n < 1: return 0 factorization = prime_factorization(n) # Check for squared prime factors for exp in factorization.values(): if exp > 1: return 0 # (-1)^k where k is number of prime factors k = len(factorization) return (-1) ** k def format_factorization(n: int) -> str: """Format prime factorization as string.""" factorization = prime_factorization(n) if not factorization: return str(n) parts = [] for p, exp in sorted(factorization.items()): if exp == 1: parts.append(str(p)) else: parts.append(f"{p}^{exp}") return " × ".join(parts) def main() -> int: parser = argparse.ArgumentParser(description="Prime number operations") parser.add_argument("values", nargs="*", type=int, help="Numbers to process") parser.add_argument( "--mode", choices=[ "factor", "check", "sieve", "divisors", "gcd", "lcm", "totient", "nth", "count", "classify", ], default="factor", help="Operation mode", ) parser.add_argument("--limit", type=int, default=100, help="Limit for sieve") args = parser.parse_args() if args.mode == "sieve": primes = sieve_of_eratosthenes(args.limit) print(f"Primes up to {args.limit}: {primes}") print(f"Count: {len(primes)}") elif args.mode == "nth" and args.values: for n in args.values: p = nth_prime(n) print(f"Prime #{n}: {p}") elif args.mode == "count" and args.values: for n in args.values: count = prime_counting(n) print(f"π({n}) = {count}") elif args.values: if args.mode == "factor": for n in args.values: print(f"{n} = {format_factorization(n)}") factors = prime_factors(n) print(f" Factors: {factors}") print(f" Divisors: {divisors(n)}") elif args.mode == "check": for n in args.values: result = "prime" if is_prime(n) else "composite" print(f"{n}: {result}") elif args.mode == "divisors": for n in args.values: d = divisors(n) print(f"Divisors of {n}: {d}") print(f" Count: {len(d)}") print(f" Sum: {sum(d)}") elif args.mode == "gcd": result = gcd_multiple(args.values) print(f"GCD({', '.join(map(str, args.values))}) = {result}") elif args.mode == "lcm": result = lcm_multiple(args.values) print(f"LCM({', '.join(map(str, args.values))}) = {result}") elif args.mode == "totient": for n in args.values: phi = euler_totient(n) print(f"φ({n}) = {phi}") elif args.mode == "classify": for n in args.values: classifications = [] if is_prime(n): classifications.append("prime") if is_perfect_number(n): classifications.append("perfect") if is_abundant(n): classifications.append("abundant") if is_deficient(n): classifications.append("deficient") print(f"{n}: {', '.join(classifications) or 'n/a'}") return 0 if __name__ == "__main__": sys.exit(main())
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_prime_factors/prime_cli.py (9153 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_prime_factors/prime_cli.rs (27689 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_prime_factors/Cargo.toml (1 dependencies) ⏱️ Parse time: 60ms 📊 Throughput: 147.8 KB/s ⏱️ Total time: 60ms
true
prime_factors
385
6
[ "context_manager", "exception_handling" ]
0.652
null
example_prime_factors
test_prime_cli.py
"""Tests for prime_cli.py""" import pytest from prime_cli import ( count_divisors, divisors, euler_totient, extended_gcd, gcd, gcd_multiple, is_abundant, is_coprime, is_deficient, is_perfect_number, is_prime, lcm, lcm_multiple, mobius, mod_inverse, next_prime, nth_prime, prev_prime, prime_counting, prime_factorization, prime_factors, radical, sieve_of_eratosthenes, sum_of_divisors, ) class TestIsPrime: def test_small_primes(self): assert is_prime(2) is True assert is_prime(3) is True assert is_prime(5) is True assert is_prime(7) is True assert is_prime(11) is True def test_small_composites(self): assert is_prime(4) is False assert is_prime(6) is False assert is_prime(8) is False assert is_prime(9) is False def test_edge_cases(self): assert is_prime(0) is False assert is_prime(1) is False def test_larger_primes(self): assert is_prime(97) is True assert is_prime(101) is True def test_larger_composites(self): assert is_prime(100) is False class TestSieve: def test_small(self): primes = sieve_of_eratosthenes(10) assert primes == [2, 3, 5, 7] def test_30(self): primes = sieve_of_eratosthenes(30) assert primes == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] def test_zero(self): assert sieve_of_eratosthenes(0) == [] def test_one(self): assert sieve_of_eratosthenes(1) == [] class TestPrimeFactors: def test_prime(self): assert prime_factors(7) == [7] def test_power_of_two(self): assert prime_factors(8) == [2, 2, 2] def test_composite(self): assert prime_factors(12) == [2, 2, 3] def test_large(self): assert prime_factors(100) == [2, 2, 5, 5] def test_one(self): assert prime_factors(1) == [] class TestPrimeFactorization: def test_basic(self): result = prime_factorization(12) assert result == {2: 2, 3: 1} def test_prime(self): result = prime_factorization(7) assert result == {7: 1} def test_power_of_prime(self): result = prime_factorization(32) assert result == {2: 5} class TestCountDivisors: def test_prime(self): assert count_divisors(7) == 2 # 1 and 7 def test_composite(self): assert count_divisors(12) == 6 # 1, 2, 3, 4, 6, 12 def test_power_of_two(self): assert count_divisors(8) == 4 # 1, 2, 4, 8 class TestSumOfDivisors: def test_prime(self): assert sum_of_divisors(7) == 8 # 1 + 7 def test_composite(self): assert sum_of_divisors(12) == 28 # 1+2+3+4+6+12 class TestDivisors: def test_prime(self): assert divisors(7) == [1, 7] def test_composite(self): assert divisors(12) == [1, 2, 3, 4, 6, 12] def test_one(self): assert divisors(1) == [1] class TestGCD: def test_basic(self): assert gcd(12, 8) == 4 def test_coprime(self): assert gcd(7, 11) == 1 def test_same(self): assert gcd(5, 5) == 5 def test_with_one(self): assert gcd(7, 1) == 1 class TestLCM: def test_basic(self): assert lcm(4, 6) == 12 def test_coprime(self): assert lcm(3, 5) == 15 def test_same(self): assert lcm(7, 7) == 7 class TestMultiple: def test_gcd(self): assert gcd_multiple([12, 18, 24]) == 6 def test_lcm(self): assert lcm_multiple([2, 3, 4]) == 12 class TestExtendedGCD: def test_basic(self): g, x, y = extended_gcd(12, 8) assert g == 4 assert 12 * x + 8 * y == g def test_coprime(self): g, x, y = extended_gcd(7, 11) assert g == 1 assert 7 * x + 11 * y == g class TestModInverse: def test_basic(self): # 3 * 4 = 12 = 1 (mod 11) inv = mod_inverse(3, 11) assert (3 * inv) % 11 == 1 def test_no_inverse(self): with pytest.raises(ValueError): mod_inverse(2, 4) # gcd(2, 4) != 1 class TestEulerTotient: def test_prime(self): assert euler_totient(7) == 6 def test_power_of_prime(self): # φ(p^k) = p^(k-1) * (p-1) assert euler_totient(8) == 4 # 2^2 * 1 def test_composite(self): assert euler_totient(10) == 4 # 1, 3, 7, 9 class TestCoprime: def test_coprime(self): assert is_coprime(7, 11) is True def test_not_coprime(self): assert is_coprime(6, 9) is False class TestNextPrime: def test_basic(self): assert next_prime(7) == 11 def test_from_composite(self): assert next_prime(8) == 11 def test_from_zero(self): assert next_prime(0) == 2 class TestPrevPrime: def test_basic(self): assert prev_prime(11) == 7 def test_from_composite(self): assert prev_prime(10) == 7 def test_from_three(self): assert prev_prime(3) == 2 class TestNthPrime: def test_first_few(self): assert nth_prime(1) == 2 assert nth_prime(2) == 3 assert nth_prime(3) == 5 assert nth_prime(4) == 7 assert nth_prime(5) == 11 class TestPrimeCounting: def test_small(self): assert prime_counting(10) == 4 # 2, 3, 5, 7 def test_30(self): assert prime_counting(30) == 10 class TestPerfectNumber: def test_perfect(self): assert is_perfect_number(6) is True # 1+2+3 = 6 assert is_perfect_number(28) is True def test_not_perfect(self): assert is_perfect_number(10) is False class TestAbundantDeficient: def test_abundant(self): assert is_abundant(12) is True # 1+2+3+4+6 = 16 > 12 def test_deficient(self): assert is_deficient(8) is True # 1+2+4 = 7 < 8 def test_prime_deficient(self): assert is_deficient(7) is True class TestRadical: def test_basic(self): assert radical(12) == 6 # 2 * 3 def test_prime(self): assert radical(7) == 7 def test_power(self): assert radical(8) == 2 class TestMobius: def test_one(self): assert mobius(1) == 1 def test_prime(self): assert mobius(2) == -1 assert mobius(3) == -1 def test_square_free_even(self): assert mobius(6) == 1 # 2 * 3, two factors def test_not_square_free(self): assert mobius(4) == 0 assert mobius(12) == 0
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_prime_factors/test_prime_cli.py (6515 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_prime_factors/test_prime_cli.rs (15879 bytes) ⏱️ Parse time: 52ms 📊 Throughput: 120.4 KB/s ⏱️ Total time: 53ms
true
prime_factors
294
5
[ "context_manager", "class_definition" ]
0.652
null
example_proto_http
proto_http_cli.py
"""HTTP/1.1 Protocol Parser CLI. Demonstrates HTTP request/response parsing with headers and body handling. """ import sys from dataclasses import dataclass, field from enum import Enum, auto class HttpMethod(Enum): """HTTP methods.""" GET = auto() POST = auto() PUT = auto() DELETE = auto() PATCH = auto() HEAD = auto() OPTIONS = auto() TRACE = auto() CONNECT = auto() @dataclass class HttpRequest: """HTTP request.""" method: HttpMethod path: str version: str headers: dict[str, str] = field(default_factory=dict) body: bytes = b"" def header(self, name: str) -> str | None: """Get header value (case-insensitive).""" name_lower = name.lower() for k, v in self.headers.items(): if k.lower() == name_lower: return v return None def content_length(self) -> int: """Get content length.""" cl = self.header("Content-Length") return int(cl) if cl else 0 def content_type(self) -> str | None: """Get content type.""" return self.header("Content-Type") def is_keep_alive(self) -> bool: """Check if connection should be kept alive.""" conn = self.header("Connection") if conn: return conn.lower() == "keep-alive" return self.version == "HTTP/1.1" def to_bytes(self) -> bytes: """Serialize to bytes.""" lines = [f"{self.method.name} {self.path} {self.version}"] for k, v in self.headers.items(): lines.append(f"{k}: {v}") lines.append("") header_bytes = "\r\n".join(lines).encode() + b"\r\n" return header_bytes + self.body @dataclass class HttpResponse: """HTTP response.""" version: str status_code: int reason: str headers: dict[str, str] = field(default_factory=dict) body: bytes = b"" def header(self, name: str) -> str | None: """Get header value (case-insensitive).""" name_lower = name.lower() for k, v in self.headers.items(): if k.lower() == name_lower: return v return None def content_length(self) -> int: """Get content length.""" cl = self.header("Content-Length") return int(cl) if cl else 0 def is_success(self) -> bool: """Check if response is successful (2xx).""" return 200 <= self.status_code < 300 def is_redirect(self) -> bool: """Check if response is redirect (3xx).""" return 300 <= self.status_code < 400 def is_error(self) -> bool: """Check if response is error (4xx or 5xx).""" return self.status_code >= 400 def to_bytes(self) -> bytes: """Serialize to bytes.""" lines = [f"{self.version} {self.status_code} {self.reason}"] for k, v in self.headers.items(): lines.append(f"{k}: {v}") lines.append("") header_bytes = "\r\n".join(lines).encode() + b"\r\n" return header_bytes + self.body class HttpParseError(Exception): """HTTP parsing error.""" pass class HttpParser: """HTTP protocol parser.""" METHODS = { "GET": HttpMethod.GET, "POST": HttpMethod.POST, "PUT": HttpMethod.PUT, "DELETE": HttpMethod.DELETE, "PATCH": HttpMethod.PATCH, "HEAD": HttpMethod.HEAD, "OPTIONS": HttpMethod.OPTIONS, "TRACE": HttpMethod.TRACE, "CONNECT": HttpMethod.CONNECT, } def __init__(self) -> None: self.buffer = b"" def feed(self, data: bytes) -> None: """Feed data to parser.""" self.buffer += data def parse_request(self) -> HttpRequest | None: """Parse HTTP request from buffer.""" # Find end of headers header_end = self.buffer.find(b"\r\n\r\n") if header_end == -1: return None header_bytes = self.buffer[:header_end] lines = header_bytes.decode("utf-8").split("\r\n") if not lines: raise HttpParseError("Empty request") # Parse request line request_line = lines[0].split(" ") if len(request_line) < 3: raise HttpParseError("Invalid request line") method_str, path, version = request_line[0], request_line[1], request_line[2] if method_str not in self.METHODS: raise HttpParseError(f"Unknown method: {method_str}") method = self.METHODS[method_str] # Parse headers headers: dict[str, str] = {} for line in lines[1:]: if ":" in line: key, value = line.split(":", 1) headers[key.strip()] = value.strip() # Create request request = HttpRequest(method, path, version, headers) # Check for body body_start = header_end + 4 content_length = request.content_length() if content_length > 0: if len(self.buffer) < body_start + content_length: return None # Need more data request.body = self.buffer[body_start : body_start + content_length] self.buffer = self.buffer[body_start + content_length :] else: self.buffer = self.buffer[body_start:] return request def parse_response(self) -> HttpResponse | None: """Parse HTTP response from buffer.""" # Find end of headers header_end = self.buffer.find(b"\r\n\r\n") if header_end == -1: return None header_bytes = self.buffer[:header_end] lines = header_bytes.decode("utf-8").split("\r\n") if not lines: raise HttpParseError("Empty response") # Parse status line status_line = lines[0].split(" ", 2) if len(status_line) < 3: raise HttpParseError("Invalid status line") version = status_line[0] status_code = int(status_line[1]) reason = status_line[2] # Parse headers headers: dict[str, str] = {} for line in lines[1:]: if ":" in line: key, value = line.split(":", 1) headers[key.strip()] = value.strip() # Create response response = HttpResponse(version, status_code, reason, headers) # Check for body body_start = header_end + 4 content_length = response.content_length() if content_length > 0: if len(self.buffer) < body_start + content_length: return None # Need more data response.body = self.buffer[body_start : body_start + content_length] self.buffer = self.buffer[body_start + content_length :] else: self.buffer = self.buffer[body_start:] return response def parse_request(data: bytes) -> HttpRequest: """Parse HTTP request.""" parser = HttpParser() parser.feed(data) request = parser.parse_request() if request is None: raise HttpParseError("Incomplete request") return request def parse_response(data: bytes) -> HttpResponse: """Parse HTTP response.""" parser = HttpParser() parser.feed(data) response = parser.parse_response() if response is None: raise HttpParseError("Incomplete response") return response def build_request( method: str, path: str, headers: dict[str, str] | None = None, body: bytes = b"", ) -> bytes: """Build HTTP request.""" method_enum = HttpParser.METHODS.get(method.upper()) if method_enum is None: raise ValueError(f"Unknown method: {method}") hdrs = headers or {} if body and "Content-Length" not in hdrs: hdrs["Content-Length"] = str(len(body)) request = HttpRequest(method_enum, path, "HTTP/1.1", hdrs, body) return request.to_bytes() def build_response( status_code: int, reason: str, headers: dict[str, str] | None = None, body: bytes = b"", ) -> bytes: """Build HTTP response.""" hdrs = headers or {} if body and "Content-Length" not in hdrs: hdrs["Content-Length"] = str(len(body)) response = HttpResponse("HTTP/1.1", status_code, reason, hdrs, body) return response.to_bytes() def simulate_http(operations: list[str]) -> list[str]: """Simulate HTTP operations.""" results: list[str] = [] parser = HttpParser() for op in operations: parts = op.split(":", 1) cmd = parts[0] if cmd == "parse_request": try: data = parts[1].encode().replace(b"\\r\\n", b"\r\n") parser.feed(data) req = parser.parse_request() if req: results.append(f"{req.method.name} {req.path}") else: results.append("incomplete") except HttpParseError as e: results.append(f"error:{e}") elif cmd == "parse_response": try: data = parts[1].encode().replace(b"\\r\\n", b"\r\n") parser.feed(data) resp = parser.parse_response() if resp: results.append(f"{resp.status_code} {resp.reason}") else: results.append("incomplete") except HttpParseError as e: results.append(f"error:{e}") elif cmd == "build_request": method, path = parts[1].split(" ", 1) data = build_request(method, path) results.append(data.decode().replace("\r\n", "\\r\\n")) elif cmd == "build_response": code, reason = parts[1].split(" ", 1) data = build_response(int(code), reason) results.append(data.decode().replace("\r\n", "\\r\\n")) return results def main() -> int: """CLI entry point.""" if len(sys.argv) < 2: print("Usage: proto_http_cli.py <command> [args]") print("Commands: parse-request, parse-response, build-request, build-response") return 1 cmd = sys.argv[1] if cmd == "parse-request" and len(sys.argv) > 2: data = sys.argv[2].encode().replace(b"\\r\\n", b"\r\n") try: req = parse_request(data) print(f"Method: {req.method.name}") print(f"Path: {req.path}") print(f"Version: {req.version}") for k, v in req.headers.items(): print(f"Header: {k}: {v}") except HttpParseError as e: print(f"Error: {e}") return 1 elif cmd == "parse-response" and len(sys.argv) > 2: data = sys.argv[2].encode().replace(b"\\r\\n", b"\r\n") try: resp = parse_response(data) print(f"Status: {resp.status_code} {resp.reason}") for k, v in resp.headers.items(): print(f"Header: {k}: {v}") except HttpParseError as e: print(f"Error: {e}") return 1 else: print("Unknown command or missing arguments") return 1 return 0 if __name__ == "__main__": sys.exit(main())
false
proto_http
373
0
[ "context_manager", "class_definition", "exception_handling", "decorator" ]
0.652
Type inference hints: Hint: str for variable 'method' [Medium] (usage patterns suggest this type) Type inference hints: Hint: str for variable 'e' [High] (usage patterns suggest this type) Hint: str for variable 'code' [Medium] (usage patterns suggest this type) Hint: str for variable 'op' [Medium] (usage patterns suggest this type) Hint: list[Any] for variable 'parts' [High] (usage patterns suggest this type) Hint: list[Any] for variable 'results' [High] (usage patterns suggest this type) Typ
example_proto_http
test_proto_http_cli.py
"""Tests for proto_http_cli.py""" import pytest from proto_http_cli import ( HttpMethod, HttpParseError, HttpParser, HttpRequest, HttpResponse, build_request, build_response, parse_request, parse_response, simulate_http, ) class TestHttpMethod: def test_methods_exist(self): assert HttpMethod.GET assert HttpMethod.POST assert HttpMethod.PUT assert HttpMethod.DELETE assert HttpMethod.PATCH class TestHttpRequest: def test_create(self): req = HttpRequest(HttpMethod.GET, "/", "HTTP/1.1") assert req.method == HttpMethod.GET assert req.path == "/" assert req.version == "HTTP/1.1" def test_headers(self): req = HttpRequest( HttpMethod.GET, "/", "HTTP/1.1", {"Content-Type": "text/html"} ) assert req.header("Content-Type") == "text/html" def test_header_case_insensitive(self): req = HttpRequest( HttpMethod.GET, "/", "HTTP/1.1", {"Content-Type": "text/html"} ) assert req.header("content-type") == "text/html" def test_header_missing(self): req = HttpRequest(HttpMethod.GET, "/", "HTTP/1.1") assert req.header("X-Missing") is None def test_content_length(self): req = HttpRequest( HttpMethod.POST, "/", "HTTP/1.1", {"Content-Length": "42"} ) assert req.content_length() == 42 def test_content_length_missing(self): req = HttpRequest(HttpMethod.GET, "/", "HTTP/1.1") assert req.content_length() == 0 def test_content_type(self): req = HttpRequest( HttpMethod.POST, "/", "HTTP/1.1", {"Content-Type": "application/json"} ) assert req.content_type() == "application/json" def test_keep_alive_http11(self): req = HttpRequest(HttpMethod.GET, "/", "HTTP/1.1") assert req.is_keep_alive() def test_keep_alive_http10(self): req = HttpRequest(HttpMethod.GET, "/", "HTTP/1.0") assert not req.is_keep_alive() def test_keep_alive_header(self): req = HttpRequest( HttpMethod.GET, "/", "HTTP/1.0", {"Connection": "keep-alive"} ) assert req.is_keep_alive() def test_to_bytes(self): req = HttpRequest(HttpMethod.GET, "/test", "HTTP/1.1") data = req.to_bytes() assert b"GET /test HTTP/1.1" in data def test_to_bytes_with_body(self): req = HttpRequest( HttpMethod.POST, "/", "HTTP/1.1", {}, b"hello" ) data = req.to_bytes() assert data.endswith(b"hello") class TestHttpResponse: def test_create(self): resp = HttpResponse("HTTP/1.1", 200, "OK") assert resp.status_code == 200 assert resp.reason == "OK" def test_is_success(self): assert HttpResponse("HTTP/1.1", 200, "OK").is_success() assert HttpResponse("HTTP/1.1", 201, "Created").is_success() assert not HttpResponse("HTTP/1.1", 404, "Not Found").is_success() def test_is_redirect(self): assert HttpResponse("HTTP/1.1", 301, "Moved").is_redirect() assert HttpResponse("HTTP/1.1", 302, "Found").is_redirect() assert not HttpResponse("HTTP/1.1", 200, "OK").is_redirect() def test_is_error(self): assert HttpResponse("HTTP/1.1", 404, "Not Found").is_error() assert HttpResponse("HTTP/1.1", 500, "Server Error").is_error() assert not HttpResponse("HTTP/1.1", 200, "OK").is_error() def test_to_bytes(self): resp = HttpResponse("HTTP/1.1", 200, "OK") data = resp.to_bytes() assert b"HTTP/1.1 200 OK" in data class TestHttpParser: def test_parse_simple_request(self): parser = HttpParser() parser.feed(b"GET / HTTP/1.1\r\n\r\n") req = parser.parse_request() assert req is not None assert req.method == HttpMethod.GET assert req.path == "/" def test_parse_request_with_headers(self): parser = HttpParser() parser.feed(b"GET /test HTTP/1.1\r\nHost: example.com\r\n\r\n") req = parser.parse_request() assert req is not None assert req.header("Host") == "example.com" def test_parse_request_with_body(self): parser = HttpParser() data = b"POST / HTTP/1.1\r\nContent-Length: 5\r\n\r\nhello" parser.feed(data) req = parser.parse_request() assert req is not None assert req.body == b"hello" def test_parse_incomplete_request(self): parser = HttpParser() parser.feed(b"GET / HTTP/1.1\r\n") # Missing final \r\n req = parser.parse_request() assert req is None def test_parse_simple_response(self): parser = HttpParser() parser.feed(b"HTTP/1.1 200 OK\r\n\r\n") resp = parser.parse_response() assert resp is not None assert resp.status_code == 200 assert resp.reason == "OK" def test_parse_response_with_body(self): parser = HttpParser() data = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello" parser.feed(data) resp = parser.parse_response() assert resp is not None assert resp.body == b"hello" def test_parse_all_methods(self): methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"] for method in methods: parser = HttpParser() parser.feed(f"{method} / HTTP/1.1\r\n\r\n".encode()) req = parser.parse_request() assert req is not None assert req.method.name == method def test_parse_invalid_method(self): parser = HttpParser() parser.feed(b"INVALID / HTTP/1.1\r\n\r\n") with pytest.raises(HttpParseError): parser.parse_request() def test_incremental_parsing(self): parser = HttpParser() parser.feed(b"GET / ") assert parser.parse_request() is None parser.feed(b"HTTP/1.1\r\n") assert parser.parse_request() is None parser.feed(b"\r\n") req = parser.parse_request() assert req is not None class TestParseRequest: def test_simple(self): req = parse_request(b"GET / HTTP/1.1\r\n\r\n") assert req.method == HttpMethod.GET def test_with_headers(self): data = b"GET / HTTP/1.1\r\nHost: test.com\r\nAccept: */*\r\n\r\n" req = parse_request(data) assert req.header("Host") == "test.com" assert req.header("Accept") == "*/*" def test_incomplete_raises(self): with pytest.raises(HttpParseError): parse_request(b"GET / HTTP/1.1\r\n") class TestParseResponse: def test_simple(self): resp = parse_response(b"HTTP/1.1 200 OK\r\n\r\n") assert resp.status_code == 200 def test_with_body(self): data = b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest" resp = parse_response(data) assert resp.body == b"test" class TestBuildRequest: def test_simple(self): data = build_request("GET", "/") assert b"GET / HTTP/1.1" in data def test_with_body(self): data = build_request("POST", "/", body=b"data") assert b"Content-Length: 4" in data assert data.endswith(b"data") def test_with_headers(self): data = build_request("GET", "/", {"X-Custom": "value"}) assert b"X-Custom: value" in data def test_unknown_method(self): with pytest.raises(ValueError): build_request("UNKNOWN", "/") class TestBuildResponse: def test_simple(self): data = build_response(200, "OK") assert b"HTTP/1.1 200 OK" in data def test_with_body(self): data = build_response(200, "OK", body=b"hello") assert b"Content-Length: 5" in data assert data.endswith(b"hello") class TestSimulateHttp: def test_parse_request(self): result = simulate_http(["parse_request:GET / HTTP/1.1\\r\\n\\r\\n"]) assert result == ["GET /"] def test_parse_response(self): result = simulate_http(["parse_response:HTTP/1.1 200 OK\\r\\n\\r\\n"]) assert result == ["200 OK"] def test_build_request(self): result = simulate_http(["build_request:GET /test"]) assert "GET /test HTTP/1.1" in result[0] def test_build_response(self): result = simulate_http(["build_response:404 Not Found"]) assert "404 Not Found" in result[0] class TestStatusCodes: def test_informational(self): resp = HttpResponse("HTTP/1.1", 100, "Continue") assert not resp.is_success() assert not resp.is_redirect() assert not resp.is_error() def test_success_range(self): for code in [200, 201, 204, 299]: resp = HttpResponse("HTTP/1.1", code, "OK") assert resp.is_success() def test_redirect_range(self): for code in [301, 302, 303, 307, 308]: resp = HttpResponse("HTTP/1.1", code, "Redirect") assert resp.is_redirect() def test_client_error_range(self): for code in [400, 401, 403, 404, 429]: resp = HttpResponse("HTTP/1.1", code, "Error") assert resp.is_error() def test_server_error_range(self): for code in [500, 502, 503, 504]: resp = HttpResponse("HTTP/1.1", code, "Error") assert resp.is_error()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_proto_http/test_proto_http_cli.py (9406 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_proto_http/test_proto_http_cli.rs (16867 bytes) ⏱️ Parse time: 51ms 📊 Throughput: 179.9 KB/s ⏱️ Total time: 51ms
true
proto_http
292
5
[ "context_manager", "class_definition" ]
0.652
null
example_proto_memcached
proto_memcached_cli.py
"""Memcached Binary Protocol Parser CLI. Demonstrates Memcached binary protocol encoding/decoding. """ import sys from dataclasses import dataclass from enum import IntEnum class Opcode(IntEnum): """Memcached opcodes.""" GET = 0x00 SET = 0x01 ADD = 0x02 REPLACE = 0x03 DELETE = 0x04 INCREMENT = 0x05 DECREMENT = 0x06 QUIT = 0x07 FLUSH = 0x08 GETQ = 0x09 NOOP = 0x0A VERSION = 0x0B GETK = 0x0C GETKQ = 0x0D APPEND = 0x0E PREPEND = 0x0F class Status(IntEnum): """Response status codes.""" NO_ERROR = 0x0000 KEY_NOT_FOUND = 0x0001 KEY_EXISTS = 0x0002 VALUE_TOO_LARGE = 0x0003 INVALID_ARGUMENTS = 0x0004 ITEM_NOT_STORED = 0x0005 NON_NUMERIC_VALUE = 0x0006 UNKNOWN_COMMAND = 0x0081 OUT_OF_MEMORY = 0x0082 class Magic(IntEnum): """Magic bytes.""" REQUEST = 0x80 RESPONSE = 0x81 HEADER_SIZE = 24 @dataclass class RequestHeader: """Binary protocol request header.""" opcode: Opcode key_length: int = 0 extras_length: int = 0 data_type: int = 0 vbucket_id: int = 0 total_body_length: int = 0 opaque: int = 0 cas: int = 0 def to_bytes(self) -> bytes: """Serialize header to bytes.""" return bytes( [ Magic.REQUEST, self.opcode, (self.key_length >> 8) & 0xFF, self.key_length & 0xFF, self.extras_length, self.data_type, (self.vbucket_id >> 8) & 0xFF, self.vbucket_id & 0xFF, (self.total_body_length >> 24) & 0xFF, (self.total_body_length >> 16) & 0xFF, (self.total_body_length >> 8) & 0xFF, self.total_body_length & 0xFF, (self.opaque >> 24) & 0xFF, (self.opaque >> 16) & 0xFF, (self.opaque >> 8) & 0xFF, self.opaque & 0xFF, (self.cas >> 56) & 0xFF, (self.cas >> 48) & 0xFF, (self.cas >> 40) & 0xFF, (self.cas >> 32) & 0xFF, (self.cas >> 24) & 0xFF, (self.cas >> 16) & 0xFF, (self.cas >> 8) & 0xFF, self.cas & 0xFF, ] ) @dataclass class ResponseHeader: """Binary protocol response header.""" opcode: Opcode key_length: int extras_length: int data_type: int status: Status total_body_length: int opaque: int cas: int @classmethod def from_bytes(cls, data: bytes) -> "ResponseHeader": """Parse header from bytes.""" if len(data) < HEADER_SIZE: raise ValueError("Insufficient data for header") if data[0] != Magic.RESPONSE: raise ValueError(f"Invalid magic byte: {data[0]:#x}") return cls( opcode=Opcode(data[1]), key_length=(data[2] << 8) | data[3], extras_length=data[4], data_type=data[5], status=Status((data[6] << 8) | data[7]), total_body_length=((data[8] << 24) | (data[9] << 16) | (data[10] << 8) | data[11]), opaque=(data[12] << 24) | (data[13] << 16) | (data[14] << 8) | data[15], cas=int.from_bytes(data[16:24], "big"), ) @dataclass class GetRequest: """GET request.""" key: str opaque: int = 0 def to_bytes(self) -> bytes: """Serialize to bytes.""" key_bytes = self.key.encode("utf-8") header = RequestHeader( opcode=Opcode.GET, key_length=len(key_bytes), total_body_length=len(key_bytes), opaque=self.opaque, ) return header.to_bytes() + key_bytes @dataclass class SetRequest: """SET request.""" key: str value: bytes flags: int = 0 expiration: int = 0 opaque: int = 0 cas: int = 0 def to_bytes(self) -> bytes: """Serialize to bytes.""" key_bytes = self.key.encode("utf-8") extras = bytes( [ (self.flags >> 24) & 0xFF, (self.flags >> 16) & 0xFF, (self.flags >> 8) & 0xFF, self.flags & 0xFF, (self.expiration >> 24) & 0xFF, (self.expiration >> 16) & 0xFF, (self.expiration >> 8) & 0xFF, self.expiration & 0xFF, ] ) header = RequestHeader( opcode=Opcode.SET, key_length=len(key_bytes), extras_length=8, total_body_length=8 + len(key_bytes) + len(self.value), opaque=self.opaque, cas=self.cas, ) return header.to_bytes() + extras + key_bytes + self.value @dataclass class DeleteRequest: """DELETE request.""" key: str opaque: int = 0 def to_bytes(self) -> bytes: """Serialize to bytes.""" key_bytes = self.key.encode("utf-8") header = RequestHeader( opcode=Opcode.DELETE, key_length=len(key_bytes), total_body_length=len(key_bytes), opaque=self.opaque, ) return header.to_bytes() + key_bytes @dataclass class IncrDecrRequest: """INCREMENT/DECREMENT request.""" key: str delta: int initial: int = 0 expiration: int = 0 opaque: int = 0 is_increment: bool = True def to_bytes(self) -> bytes: """Serialize to bytes.""" key_bytes = self.key.encode("utf-8") extras = ( self.delta.to_bytes(8, "big") + self.initial.to_bytes(8, "big") + self.expiration.to_bytes(4, "big") ) opcode = Opcode.INCREMENT if self.is_increment else Opcode.DECREMENT header = RequestHeader( opcode=opcode, key_length=len(key_bytes), extras_length=20, total_body_length=20 + len(key_bytes), opaque=self.opaque, ) return header.to_bytes() + extras + key_bytes @dataclass class Response: """Generic response.""" header: ResponseHeader extras: bytes key: bytes value: bytes @classmethod def from_bytes(cls, data: bytes) -> "Response": """Parse response from bytes.""" header = ResponseHeader.from_bytes(data) pos = HEADER_SIZE extras = data[pos : pos + header.extras_length] pos += header.extras_length key = data[pos : pos + header.key_length] pos += header.key_length value_length = header.total_body_length - header.extras_length - header.key_length value = data[pos : pos + value_length] return cls(header, extras, key, value) def is_success(self) -> bool: """Check if response indicates success.""" return self.header.status == Status.NO_ERROR class MemcachedClient: """Simple memcached protocol client (encoder/decoder).""" @staticmethod def encode_get(key: str) -> bytes: """Encode GET request.""" return GetRequest(key).to_bytes() @staticmethod def encode_set(key: str, value: bytes, flags: int = 0, expiry: int = 0) -> bytes: """Encode SET request.""" return SetRequest(key, value, flags, expiry).to_bytes() @staticmethod def encode_delete(key: str) -> bytes: """Encode DELETE request.""" return DeleteRequest(key).to_bytes() @staticmethod def encode_incr(key: str, delta: int = 1) -> bytes: """Encode INCREMENT request.""" return IncrDecrRequest(key, delta, is_increment=True).to_bytes() @staticmethod def encode_decr(key: str, delta: int = 1) -> bytes: """Encode DECREMENT request.""" return IncrDecrRequest(key, delta, is_increment=False).to_bytes() @staticmethod def encode_flush() -> bytes: """Encode FLUSH request.""" header = RequestHeader(opcode=Opcode.FLUSH) return header.to_bytes() @staticmethod def encode_noop() -> bytes: """Encode NOOP request.""" header = RequestHeader(opcode=Opcode.NOOP) return header.to_bytes() @staticmethod def encode_version() -> bytes: """Encode VERSION request.""" header = RequestHeader(opcode=Opcode.VERSION) return header.to_bytes() @staticmethod def encode_quit() -> bytes: """Encode QUIT request.""" header = RequestHeader(opcode=Opcode.QUIT) return header.to_bytes() @staticmethod def decode_response(data: bytes) -> Response: """Decode response.""" return Response.from_bytes(data) def simulate_memcached(operations: list[str]) -> list[str]: """Simulate memcached operations.""" results: list[str] = [] client = MemcachedClient() for op in operations: parts = op.split(":", 1) cmd = parts[0] if cmd == "get": data = client.encode_get(parts[1]) results.append(f"GET key={parts[1]} len={len(data)}") elif cmd == "set": key, value = parts[1].split(",", 1) data = client.encode_set(key, value.encode()) results.append(f"SET key={key} len={len(data)}") elif cmd == "delete": data = client.encode_delete(parts[1]) results.append(f"DELETE key={parts[1]} len={len(data)}") elif cmd == "incr": key = parts[1] if len(parts) > 1 else "counter" data = client.encode_incr(key) results.append(f"INCR key={key} len={len(data)}") elif cmd == "decr": key = parts[1] if len(parts) > 1 else "counter" data = client.encode_decr(key) results.append(f"DECR key={key} len={len(data)}") elif cmd == "flush": data = client.encode_flush() results.append(f"FLUSH len={len(data)}") elif cmd == "noop": data = client.encode_noop() results.append(f"NOOP len={len(data)}") elif cmd == "version": data = client.encode_version() results.append(f"VERSION len={len(data)}") return results def main() -> int: """CLI entry point.""" if len(sys.argv) < 2: print("Usage: proto_memcached_cli.py <command> [args]") return 1 cmd = sys.argv[1] client = MemcachedClient() if cmd == "get" and len(sys.argv) > 2: data = client.encode_get(sys.argv[2]) print(f"GET request: {len(data)} bytes") print(f"Hex: {data.hex()}") elif cmd == "set" and len(sys.argv) > 3: data = client.encode_set(sys.argv[2], sys.argv[3].encode()) print(f"SET request: {len(data)} bytes") else: print("Unknown command") return 1 return 0 if __name__ == "__main__": sys.exit(main())
false
proto_memcached
388
0
[ "class_definition", "exception_handling", "decorator" ]
0.612
Error: Unsupported type annotation: Constant(ExprConstant { range: 2611..2627, value: Str("ResponseHeader"), kind: None })
example_proto_memcached
test_proto_memcached_cli.py
"""Tests for proto_memcached_cli.py""" import pytest from proto_memcached_cli import ( HEADER_SIZE, DeleteRequest, GetRequest, IncrDecrRequest, Magic, MemcachedClient, Opcode, RequestHeader, Response, ResponseHeader, SetRequest, Status, simulate_memcached, ) class TestOpcode: def test_values(self): assert Opcode.GET == 0x00 assert Opcode.SET == 0x01 assert Opcode.DELETE == 0x04 assert Opcode.INCREMENT == 0x05 assert Opcode.DECREMENT == 0x06 class TestStatus: def test_values(self): assert Status.NO_ERROR == 0x0000 assert Status.KEY_NOT_FOUND == 0x0001 assert Status.KEY_EXISTS == 0x0002 class TestMagic: def test_values(self): assert Magic.REQUEST == 0x80 assert Magic.RESPONSE == 0x81 class TestRequestHeader: def test_create(self): header = RequestHeader(opcode=Opcode.GET) assert header.opcode == Opcode.GET assert header.key_length == 0 def test_to_bytes_length(self): header = RequestHeader(opcode=Opcode.GET) data = header.to_bytes() assert len(data) == HEADER_SIZE def test_to_bytes_magic(self): header = RequestHeader(opcode=Opcode.GET) data = header.to_bytes() assert data[0] == Magic.REQUEST def test_to_bytes_opcode(self): header = RequestHeader(opcode=Opcode.SET) data = header.to_bytes() assert data[1] == Opcode.SET def test_to_bytes_key_length(self): header = RequestHeader(opcode=Opcode.GET, key_length=256) data = header.to_bytes() assert data[2] == 1 # High byte assert data[3] == 0 # Low byte def test_to_bytes_extras_length(self): header = RequestHeader(opcode=Opcode.SET, extras_length=8) data = header.to_bytes() assert data[4] == 8 def test_to_bytes_body_length(self): header = RequestHeader(opcode=Opcode.SET, total_body_length=100) data = header.to_bytes() assert data[11] == 100 class TestResponseHeader: def test_from_bytes(self): data = bytes([ Magic.RESPONSE, # Magic Opcode.GET, # Opcode 0, 0, # Key length 0, # Extras length 0, # Data type 0, 0, # Status 0, 0, 0, 5, # Body length 0, 0, 0, 1, # Opaque 0, 0, 0, 0, 0, 0, 0, 0, # CAS ]) header = ResponseHeader.from_bytes(data) assert header.opcode == Opcode.GET assert header.status == Status.NO_ERROR assert header.total_body_length == 5 assert header.opaque == 1 def test_from_bytes_with_status(self): data = bytes([ Magic.RESPONSE, Opcode.GET, 0, 0, 0, 0, 0, 1, # KEY_NOT_FOUND 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]) header = ResponseHeader.from_bytes(data) assert header.status == Status.KEY_NOT_FOUND def test_from_bytes_invalid_magic(self): data = bytes([0x00] + [0] * 23) with pytest.raises(ValueError): ResponseHeader.from_bytes(data) def test_from_bytes_too_short(self): with pytest.raises(ValueError): ResponseHeader.from_bytes(b"\x81\x00") class TestGetRequest: def test_create(self): req = GetRequest("mykey") assert req.key == "mykey" def test_to_bytes(self): req = GetRequest("test") data = req.to_bytes() assert len(data) == HEADER_SIZE + 4 assert data[0] == Magic.REQUEST assert data[1] == Opcode.GET assert b"test" in data def test_key_length_in_header(self): req = GetRequest("hello") data = req.to_bytes() # Key length is bytes 2-3 (big endian) assert data[2] == 0 assert data[3] == 5 class TestSetRequest: def test_create(self): req = SetRequest("key", b"value") assert req.key == "key" assert req.value == b"value" def test_to_bytes(self): req = SetRequest("k", b"v") data = req.to_bytes() assert data[0] == Magic.REQUEST assert data[1] == Opcode.SET assert data[4] == 8 # Extras length def test_flags_and_expiry(self): req = SetRequest("k", b"v", flags=0x0001, expiration=3600) data = req.to_bytes() # Flags are in extras at offset 24 assert data[27] == 1 # Low byte of flags def test_body_contains_key_and_value(self): req = SetRequest("mykey", b"myvalue") data = req.to_bytes() assert b"mykey" in data assert b"myvalue" in data class TestDeleteRequest: def test_create(self): req = DeleteRequest("key") assert req.key == "key" def test_to_bytes(self): req = DeleteRequest("delme") data = req.to_bytes() assert data[1] == Opcode.DELETE assert b"delme" in data class TestIncrDecrRequest: def test_increment(self): req = IncrDecrRequest("counter", delta=5, is_increment=True) data = req.to_bytes() assert data[1] == Opcode.INCREMENT def test_decrement(self): req = IncrDecrRequest("counter", delta=1, is_increment=False) data = req.to_bytes() assert data[1] == Opcode.DECREMENT def test_extras_length(self): req = IncrDecrRequest("c", delta=1) data = req.to_bytes() assert data[4] == 20 # Extras length class TestResponse: def test_from_bytes(self): # Build a simple response header_bytes = bytes([ Magic.RESPONSE, Opcode.GET, 0, 0, # Key length 0, # Extras length 0, # Data type 0, 0, # Status OK 0, 0, 0, 5, # Body length = 5 0, 0, 0, 0, # Opaque 0, 0, 0, 0, 0, 0, 0, 0, # CAS ]) data = header_bytes + b"hello" resp = Response.from_bytes(data) assert resp.value == b"hello" assert resp.is_success() def test_is_success_true(self): header = ResponseHeader( Opcode.GET, 0, 0, 0, Status.NO_ERROR, 0, 0, 0 ) resp = Response(header, b"", b"", b"") assert resp.is_success() def test_is_success_false(self): header = ResponseHeader( Opcode.GET, 0, 0, 0, Status.KEY_NOT_FOUND, 0, 0, 0 ) resp = Response(header, b"", b"", b"") assert not resp.is_success() class TestMemcachedClient: def test_encode_get(self): data = MemcachedClient.encode_get("key") assert data[1] == Opcode.GET assert b"key" in data def test_encode_set(self): data = MemcachedClient.encode_set("key", b"value") assert data[1] == Opcode.SET assert b"key" in data assert b"value" in data def test_encode_set_with_flags(self): data = MemcachedClient.encode_set("k", b"v", flags=1) assert data[1] == Opcode.SET def test_encode_delete(self): data = MemcachedClient.encode_delete("key") assert data[1] == Opcode.DELETE def test_encode_incr(self): data = MemcachedClient.encode_incr("counter", 10) assert data[1] == Opcode.INCREMENT def test_encode_decr(self): data = MemcachedClient.encode_decr("counter", 5) assert data[1] == Opcode.DECREMENT def test_encode_flush(self): data = MemcachedClient.encode_flush() assert data[1] == Opcode.FLUSH def test_encode_noop(self): data = MemcachedClient.encode_noop() assert data[1] == Opcode.NOOP def test_encode_version(self): data = MemcachedClient.encode_version() assert data[1] == Opcode.VERSION def test_encode_quit(self): data = MemcachedClient.encode_quit() assert data[1] == Opcode.QUIT class TestSimulateMemcached: def test_get(self): result = simulate_memcached(["get:mykey"]) assert "GET" in result[0] assert "mykey" in result[0] def test_set(self): result = simulate_memcached(["set:key,value"]) assert "SET" in result[0] def test_delete(self): result = simulate_memcached(["delete:key"]) assert "DELETE" in result[0] def test_incr(self): result = simulate_memcached(["incr:counter"]) assert "INCR" in result[0] def test_decr(self): result = simulate_memcached(["decr:counter"]) assert "DECR" in result[0] def test_flush(self): result = simulate_memcached(["flush:"]) assert "FLUSH" in result[0] def test_noop(self): result = simulate_memcached(["noop:"]) assert "NOOP" in result[0] def test_version(self): result = simulate_memcached(["version:"]) assert "VERSION" in result[0] class TestHeaderSize: def test_constant(self): assert HEADER_SIZE == 24 def test_request_header_size(self): header = RequestHeader(Opcode.GET) assert len(header.to_bytes()) == HEADER_SIZE
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_proto_memcached/test_proto_memcached_cli.py (9183 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_proto_memcached/test_proto_memcached_cli.rs (16064 bytes) ⏱️ Parse time: 52ms 📊 Throughput: 169.7 KB/s ⏱️ Total time: 53ms
true
proto_memcached
321
5
[ "context_manager", "class_definition" ]
0.652
null
example_proto_mqtt
proto_mqtt_cli.py
"""MQTT Protocol Parser CLI. Demonstrates MQTT packet parsing and encoding. """ import sys from dataclasses import dataclass, field from enum import IntEnum from typing import Any class PacketType(IntEnum): """MQTT packet types.""" CONNECT = 1 CONNACK = 2 PUBLISH = 3 PUBACK = 4 PUBREC = 5 PUBREL = 6 PUBCOMP = 7 SUBSCRIBE = 8 SUBACK = 9 UNSUBSCRIBE = 10 UNSUBACK = 11 PINGREQ = 12 PINGRESP = 13 DISCONNECT = 14 class QoS(IntEnum): """MQTT QoS levels.""" AT_MOST_ONCE = 0 AT_LEAST_ONCE = 1 EXACTLY_ONCE = 2 class ConnectReturnCode(IntEnum): """CONNECT return codes.""" ACCEPTED = 0 UNACCEPTABLE_PROTOCOL = 1 IDENTIFIER_REJECTED = 2 SERVER_UNAVAILABLE = 3 BAD_CREDENTIALS = 4 NOT_AUTHORIZED = 5 class MqttError(Exception): """MQTT parsing error.""" pass @dataclass class ConnectPacket: """MQTT CONNECT packet.""" client_id: str clean_session: bool = True keep_alive: int = 60 username: str | None = None password: str | None = None will_topic: str | None = None will_message: bytes | None = None will_qos: QoS = QoS.AT_MOST_ONCE will_retain: bool = False @dataclass class ConnackPacket: """MQTT CONNACK packet.""" session_present: bool return_code: ConnectReturnCode @dataclass class PublishPacket: """MQTT PUBLISH packet.""" topic: str payload: bytes qos: QoS = QoS.AT_MOST_ONCE retain: bool = False dup: bool = False packet_id: int | None = None @dataclass class SubscribePacket: """MQTT SUBSCRIBE packet.""" packet_id: int topics: list[tuple[str, QoS]] = field(default_factory=list) @dataclass class SubackPacket: """MQTT SUBACK packet.""" packet_id: int return_codes: list[int] = field(default_factory=list) @dataclass class UnsubscribePacket: """MQTT UNSUBSCRIBE packet.""" packet_id: int topics: list[str] = field(default_factory=list) MqttPacket = ( ConnectPacket | ConnackPacket | PublishPacket | SubscribePacket | SubackPacket | UnsubscribePacket | None ) class MqttEncoder: """MQTT packet encoder.""" @staticmethod def encode_remaining_length(length: int) -> bytes: """Encode variable length field.""" result = bytearray() while True: byte = length % 128 length //= 128 if length > 0: byte |= 0x80 result.append(byte) if length == 0: break return bytes(result) @staticmethod def encode_string(s: str) -> bytes: """Encode MQTT string.""" encoded = s.encode("utf-8") return len(encoded).to_bytes(2, "big") + encoded @staticmethod def encode_connect(packet: ConnectPacket) -> bytes: """Encode CONNECT packet.""" # Variable header var_header = bytearray() var_header.extend(MqttEncoder.encode_string("MQTT")) # Protocol name var_header.append(4) # Protocol level (MQTT 3.1.1) # Connect flags flags = 0 if packet.clean_session: flags |= 0x02 if packet.will_topic: flags |= 0x04 flags |= (packet.will_qos & 0x03) << 3 if packet.will_retain: flags |= 0x20 if packet.password: flags |= 0x40 if packet.username: flags |= 0x80 var_header.append(flags) var_header.extend(packet.keep_alive.to_bytes(2, "big")) # Payload payload = bytearray() payload.extend(MqttEncoder.encode_string(packet.client_id)) if packet.will_topic: payload.extend(MqttEncoder.encode_string(packet.will_topic)) will_msg = packet.will_message or b"" payload.extend(len(will_msg).to_bytes(2, "big")) payload.extend(will_msg) if packet.username: payload.extend(MqttEncoder.encode_string(packet.username)) if packet.password: payload.extend(MqttEncoder.encode_string(packet.password)) # Fixed header remaining = bytes(var_header) + bytes(payload) fixed = bytes([PacketType.CONNECT << 4]) fixed += MqttEncoder.encode_remaining_length(len(remaining)) return fixed + remaining @staticmethod def encode_connack(packet: ConnackPacket) -> bytes: """Encode CONNACK packet.""" flags = 0x01 if packet.session_present else 0x00 return bytes([PacketType.CONNACK << 4, 2, flags, packet.return_code]) @staticmethod def encode_publish(packet: PublishPacket) -> bytes: """Encode PUBLISH packet.""" # Fixed header flags flags = packet.qos << 1 if packet.retain: flags |= 0x01 if packet.dup: flags |= 0x08 # Variable header var_header = MqttEncoder.encode_string(packet.topic) if packet.qos > 0 and packet.packet_id is not None: var_header += packet.packet_id.to_bytes(2, "big") # Build packet remaining = var_header + packet.payload fixed = bytes([(PacketType.PUBLISH << 4) | flags]) fixed += MqttEncoder.encode_remaining_length(len(remaining)) return fixed + remaining @staticmethod def encode_subscribe(packet: SubscribePacket) -> bytes: """Encode SUBSCRIBE packet.""" var_header = packet.packet_id.to_bytes(2, "big") payload = bytearray() for topic, qos in packet.topics: payload.extend(MqttEncoder.encode_string(topic)) payload.append(qos) remaining = var_header + bytes(payload) fixed = bytes([(PacketType.SUBSCRIBE << 4) | 0x02]) fixed += MqttEncoder.encode_remaining_length(len(remaining)) return fixed + remaining @staticmethod def encode_pingreq() -> bytes: """Encode PINGREQ packet.""" return bytes([PacketType.PINGREQ << 4, 0]) @staticmethod def encode_pingresp() -> bytes: """Encode PINGRESP packet.""" return bytes([PacketType.PINGRESP << 4, 0]) @staticmethod def encode_disconnect() -> bytes: """Encode DISCONNECT packet.""" return bytes([PacketType.DISCONNECT << 4, 0]) class MqttDecoder: """MQTT packet decoder.""" def __init__(self) -> None: self.buffer = b"" def feed(self, data: bytes) -> None: """Feed data to decoder.""" self.buffer += data def decode_remaining_length(self, pos: int) -> tuple[int, int]: """Decode variable length field. Returns (length, bytes_consumed).""" multiplier = 1 value = 0 consumed = 0 while pos + consumed < len(self.buffer): byte = self.buffer[pos + consumed] value += (byte & 0x7F) * multiplier consumed += 1 if (byte & 0x80) == 0: return value, consumed multiplier *= 128 if multiplier > 128 * 128 * 128: raise MqttError("Malformed remaining length") return -1, 0 # Need more data def decode_string(self, pos: int) -> tuple[str, int]: """Decode MQTT string. Returns (string, bytes_consumed).""" if pos + 2 > len(self.buffer): raise MqttError("Incomplete string length") length = int.from_bytes(self.buffer[pos : pos + 2], "big") if pos + 2 + length > len(self.buffer): raise MqttError("Incomplete string data") s = self.buffer[pos + 2 : pos + 2 + length].decode("utf-8") return s, 2 + length def decode(self) -> tuple[MqttPacket, int]: """Decode packet. Returns (packet, bytes_consumed) or (None, 0).""" if len(self.buffer) < 2: return None, 0 fixed_byte = self.buffer[0] packet_type = PacketType(fixed_byte >> 4) flags = fixed_byte & 0x0F remaining_length, length_bytes = self.decode_remaining_length(1) if remaining_length < 0: return None, 0 total_length = 1 + length_bytes + remaining_length if len(self.buffer) < total_length: return None, 0 pos = 1 + length_bytes if packet_type == PacketType.CONNACK: session_present = bool(self.buffer[pos] & 0x01) return_code = ConnectReturnCode(self.buffer[pos + 1]) return ConnackPacket(session_present, return_code), total_length elif packet_type == PacketType.PUBLISH: topic, consumed = self.decode_string(pos) pos += consumed qos = QoS((flags >> 1) & 0x03) retain = bool(flags & 0x01) dup = bool(flags & 0x08) packet_id = None if qos > 0: packet_id = int.from_bytes(self.buffer[pos : pos + 2], "big") pos += 2 payload_end = 1 + length_bytes + remaining_length payload = self.buffer[pos:payload_end] return ( PublishPacket(topic, payload, qos, retain, dup, packet_id), total_length, ) elif packet_type == PacketType.SUBACK: packet_id = int.from_bytes(self.buffer[pos : pos + 2], "big") pos += 2 end = 1 + length_bytes + remaining_length return_codes = list(self.buffer[pos:end]) return SubackPacket(packet_id, return_codes), total_length elif packet_type == PacketType.PINGREQ: return None, total_length # Simple packet elif packet_type == PacketType.PINGRESP: return None, total_length return None, total_length def consume(self, length: int) -> None: """Remove consumed bytes from buffer.""" self.buffer = self.buffer[length:] def encode_connect(client_id: str, **kwargs: Any) -> bytes: """Encode CONNECT packet.""" packet = ConnectPacket(client_id, **kwargs) return MqttEncoder.encode_connect(packet) def encode_publish(topic: str, payload: bytes, qos: int = 0) -> bytes: """Encode PUBLISH packet.""" packet = PublishPacket(topic, payload, QoS(qos)) return MqttEncoder.encode_publish(packet) def encode_subscribe(packet_id: int, topics: list[tuple[str, int]]) -> bytes: """Encode SUBSCRIBE packet.""" packet = SubscribePacket(packet_id, [(t, QoS(q)) for t, q in topics]) return MqttEncoder.encode_subscribe(packet) def decode_packet(data: bytes) -> MqttPacket: """Decode MQTT packet.""" decoder = MqttDecoder() decoder.feed(data) packet, _ = decoder.decode() return packet def simulate_mqtt(operations: list[str]) -> list[str]: """Simulate MQTT operations.""" results: list[str] = [] for op in operations: parts = op.split(":", 1) cmd = parts[0] if cmd == "connect": data = encode_connect(parts[1]) results.append(f"CONNECT len={len(data)}") elif cmd == "publish": topic, payload = parts[1].split(",", 1) data = encode_publish(topic, payload.encode()) results.append(f"PUBLISH len={len(data)}") elif cmd == "subscribe": topic = parts[1] data = encode_subscribe(1, [(topic, 0)]) results.append(f"SUBSCRIBE len={len(data)}") elif cmd == "ping": data = MqttEncoder.encode_pingreq() results.append(f"PINGREQ len={len(data)}") elif cmd == "disconnect": data = MqttEncoder.encode_disconnect() results.append(f"DISCONNECT len={len(data)}") return results def main() -> int: """CLI entry point.""" if len(sys.argv) < 2: print("Usage: proto_mqtt_cli.py <command> [args]") return 1 cmd = sys.argv[1] if cmd == "connect" and len(sys.argv) > 2: data = encode_connect(sys.argv[2]) print(f"CONNECT packet: {len(data)} bytes") elif cmd == "publish" and len(sys.argv) > 3: data = encode_publish(sys.argv[2], sys.argv[3].encode()) print(f"PUBLISH packet: {len(data)} bytes") else: print("Unknown command") return 1 return 0 if __name__ == "__main__": sys.exit(main())
false
proto_mqtt
426
0
[ "class_definition", "exception_handling", "decorator" ]
0.612
Type inference hints: Hint: list[Any] for variable 'data' [High] (usage patterns suggest this type) Hint: str for variable 'op' [Medium] (usage patterns suggest this type) Hint: list[Any] for variable 'results' [High] (usage patterns suggest this type) Hint: list[Any] for variable 'parts' [High] (usage patterns suggest this type) Type inference hints: Hint: list[Any] for variable 'data' [High] (usage patterns suggest this type) Migration Suggestions ═══════════════════════════════════════════
example_proto_mqtt
test_proto_mqtt_cli.py
"""Tests for proto_mqtt_cli.py""" from proto_mqtt_cli import ( ConnackPacket, ConnectPacket, ConnectReturnCode, MqttDecoder, MqttEncoder, PacketType, PublishPacket, QoS, SubackPacket, SubscribePacket, decode_packet, encode_connect, encode_publish, encode_subscribe, simulate_mqtt, ) class TestPacketType: def test_values(self): assert PacketType.CONNECT == 1 assert PacketType.PUBLISH == 3 assert PacketType.SUBSCRIBE == 8 assert PacketType.DISCONNECT == 14 class TestQoS: def test_values(self): assert QoS.AT_MOST_ONCE == 0 assert QoS.AT_LEAST_ONCE == 1 assert QoS.EXACTLY_ONCE == 2 class TestConnectReturnCode: def test_values(self): assert ConnectReturnCode.ACCEPTED == 0 assert ConnectReturnCode.BAD_CREDENTIALS == 4 class TestConnectPacket: def test_create(self): packet = ConnectPacket("client1") assert packet.client_id == "client1" assert packet.clean_session is True assert packet.keep_alive == 60 def test_with_auth(self): packet = ConnectPacket("client1", username="user", password="pass") assert packet.username == "user" assert packet.password == "pass" def test_with_will(self): packet = ConnectPacket( "client1", will_topic="last/will", will_message=b"goodbye", will_qos=QoS.AT_LEAST_ONCE, ) assert packet.will_topic == "last/will" assert packet.will_message == b"goodbye" class TestPublishPacket: def test_create(self): packet = PublishPacket("topic/test", b"hello") assert packet.topic == "topic/test" assert packet.payload == b"hello" assert packet.qos == QoS.AT_MOST_ONCE def test_with_qos(self): packet = PublishPacket("topic", b"data", QoS.EXACTLY_ONCE, packet_id=42) assert packet.qos == QoS.EXACTLY_ONCE assert packet.packet_id == 42 class TestMqttEncoder: def test_encode_remaining_length_small(self): assert MqttEncoder.encode_remaining_length(0) == b"\x00" assert MqttEncoder.encode_remaining_length(127) == b"\x7f" def test_encode_remaining_length_medium(self): assert MqttEncoder.encode_remaining_length(128) == b"\x80\x01" assert MqttEncoder.encode_remaining_length(16383) == b"\xff\x7f" def test_encode_remaining_length_large(self): result = MqttEncoder.encode_remaining_length(16384) assert result == b"\x80\x80\x01" def test_encode_string(self): assert MqttEncoder.encode_string("") == b"\x00\x00" assert MqttEncoder.encode_string("AB") == b"\x00\x02AB" assert MqttEncoder.encode_string("test") == b"\x00\x04test" def test_encode_connect_simple(self): packet = ConnectPacket("client1") data = MqttEncoder.encode_connect(packet) assert data[0] >> 4 == PacketType.CONNECT assert b"MQTT" in data assert b"client1" in data def test_encode_connect_with_auth(self): packet = ConnectPacket("client1", username="user", password="pass") data = MqttEncoder.encode_connect(packet) assert b"user" in data assert b"pass" in data def test_encode_connack(self): packet = ConnackPacket(False, ConnectReturnCode.ACCEPTED) data = MqttEncoder.encode_connack(packet) assert data[0] >> 4 == PacketType.CONNACK assert data[2] == 0 # No session present assert data[3] == 0 # Accepted def test_encode_connack_session_present(self): packet = ConnackPacket(True, ConnectReturnCode.ACCEPTED) data = MqttEncoder.encode_connack(packet) assert data[2] == 1 # Session present def test_encode_publish_qos0(self): packet = PublishPacket("topic", b"data") data = MqttEncoder.encode_publish(packet) assert data[0] >> 4 == PacketType.PUBLISH assert b"topic" in data assert b"data" in data def test_encode_publish_qos1(self): packet = PublishPacket("topic", b"data", QoS.AT_LEAST_ONCE, packet_id=1) data = MqttEncoder.encode_publish(packet) # QoS 1 should be in flags assert (data[0] & 0x06) >> 1 == 1 def test_encode_publish_retain(self): packet = PublishPacket("topic", b"data", retain=True) data = MqttEncoder.encode_publish(packet) assert data[0] & 0x01 == 1 def test_encode_subscribe(self): packet = SubscribePacket(1, [("topic/+", QoS.AT_LEAST_ONCE)]) data = MqttEncoder.encode_subscribe(packet) assert data[0] >> 4 == PacketType.SUBSCRIBE assert b"topic/+" in data def test_encode_pingreq(self): data = MqttEncoder.encode_pingreq() assert data == bytes([PacketType.PINGREQ << 4, 0]) def test_encode_pingresp(self): data = MqttEncoder.encode_pingresp() assert data == bytes([PacketType.PINGRESP << 4, 0]) def test_encode_disconnect(self): data = MqttEncoder.encode_disconnect() assert data == bytes([PacketType.DISCONNECT << 4, 0]) class TestMqttDecoder: def test_decode_remaining_length(self): decoder = MqttDecoder() decoder.feed(b"\x00") length, consumed = decoder.decode_remaining_length(0) assert length == 0 assert consumed == 1 def test_decode_remaining_length_two_bytes(self): decoder = MqttDecoder() decoder.feed(b"\x80\x01") length, consumed = decoder.decode_remaining_length(0) assert length == 128 assert consumed == 2 def test_decode_string(self): decoder = MqttDecoder() decoder.feed(b"\x00\x05hello") s, consumed = decoder.decode_string(0) assert s == "hello" assert consumed == 7 def test_decode_connack(self): data = MqttEncoder.encode_connack( ConnackPacket(True, ConnectReturnCode.ACCEPTED) ) decoder = MqttDecoder() decoder.feed(data) packet, consumed = decoder.decode() assert isinstance(packet, ConnackPacket) assert packet.session_present is True assert packet.return_code == ConnectReturnCode.ACCEPTED def test_decode_publish_qos0(self): original = PublishPacket("test/topic", b"hello world") data = MqttEncoder.encode_publish(original) decoder = MqttDecoder() decoder.feed(data) packet, consumed = decoder.decode() assert isinstance(packet, PublishPacket) assert packet.topic == "test/topic" assert packet.payload == b"hello world" def test_decode_publish_qos1(self): original = PublishPacket( "topic", b"data", QoS.AT_LEAST_ONCE, packet_id=123 ) data = MqttEncoder.encode_publish(original) decoder = MqttDecoder() decoder.feed(data) packet, consumed = decoder.decode() assert isinstance(packet, PublishPacket) assert packet.qos == QoS.AT_LEAST_ONCE assert packet.packet_id == 123 def test_decode_suback(self): data = bytes([PacketType.SUBACK << 4, 4, 0, 1, 0, 1]) decoder = MqttDecoder() decoder.feed(data) packet, consumed = decoder.decode() assert isinstance(packet, SubackPacket) assert packet.packet_id == 1 assert packet.return_codes == [0, 1] def test_decode_incomplete(self): decoder = MqttDecoder() decoder.feed(b"\x30") # Incomplete PUBLISH packet, consumed = decoder.decode() assert packet is None assert consumed == 0 def test_consume(self): decoder = MqttDecoder() decoder.feed(b"\x00\x00\x00\x00") decoder.consume(2) assert len(decoder.buffer) == 2 class TestEncodeConnect: def test_simple(self): data = encode_connect("myclient") assert b"myclient" in data assert data[0] >> 4 == PacketType.CONNECT def test_with_keepalive(self): data = encode_connect("client", keep_alive=120) assert len(data) > 0 class TestEncodePublish: def test_simple(self): data = encode_publish("topic", b"message") assert b"topic" in data assert b"message" in data def test_with_qos(self): data = encode_publish("topic", b"msg", qos=1) assert (data[0] & 0x06) >> 1 == 1 class TestEncodeSubscribe: def test_single_topic(self): data = encode_subscribe(1, [("topic/#", 0)]) assert b"topic/#" in data def test_multiple_topics(self): data = encode_subscribe(1, [("topic1", 0), ("topic2", 1)]) assert b"topic1" in data assert b"topic2" in data class TestDecodePacket: def test_connack(self): data = MqttEncoder.encode_connack( ConnackPacket(False, ConnectReturnCode.ACCEPTED) ) packet = decode_packet(data) assert isinstance(packet, ConnackPacket) def test_publish(self): data = encode_publish("test", b"data") packet = decode_packet(data) assert isinstance(packet, PublishPacket) class TestSimulateMqtt: def test_connect(self): result = simulate_mqtt(["connect:client1"]) assert "CONNECT" in result[0] def test_publish(self): result = simulate_mqtt(["publish:topic,message"]) assert "PUBLISH" in result[0] def test_subscribe(self): result = simulate_mqtt(["subscribe:topic/#"]) assert "SUBSCRIBE" in result[0] def test_ping(self): result = simulate_mqtt(["ping:"]) assert "PINGREQ" in result[0] def test_disconnect(self): result = simulate_mqtt(["disconnect:"]) assert "DISCONNECT" in result[0] class TestWildcards: def test_single_level(self): data = encode_subscribe(1, [("sensors/+/temperature", 0)]) assert b"sensors/+/temperature" in data def test_multi_level(self): data = encode_subscribe(1, [("sensors/#", 0)]) assert b"sensors/#" in data class TestRoundTrip: def test_publish_roundtrip(self): original = PublishPacket("test/topic", b"test payload", QoS.AT_MOST_ONCE) encoded = MqttEncoder.encode_publish(original) decoded = decode_packet(encoded) assert isinstance(decoded, PublishPacket) assert decoded.topic == original.topic assert decoded.payload == original.payload def test_connack_roundtrip(self): original = ConnackPacket(True, ConnectReturnCode.ACCEPTED) encoded = MqttEncoder.encode_connack(original) decoded = decode_packet(encoded) assert isinstance(decoded, ConnackPacket) assert decoded.session_present == original.session_present assert decoded.return_code == original.return_code
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_proto_mqtt/test_proto_mqtt_cli.py (10857 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_proto_mqtt/test_proto_mqtt_cli.rs (18078 bytes) ⏱️ Parse time: 50ms 📊 Throughput: 209.5 KB/s ⏱️ Total time: 50ms
true
proto_mqtt
332
5
[ "class_definition" ]
0.612
null
example_proto_redis
proto_redis_cli.py
"""Redis RESP Protocol Parser CLI. Demonstrates RESP (Redis Serialization Protocol) encoding/decoding. """ import sys from dataclasses import dataclass from enum import Enum, auto from typing import Union class RespType(Enum): """RESP data types.""" SIMPLE_STRING = auto() # + ERROR = auto() # - INTEGER = auto() # : BULK_STRING = auto() # $ ARRAY = auto() # * NULL = auto() RespValue = Union[str, int, bytes, list, None, "RespError"] @dataclass class RespError: """RESP error type.""" message: str def __str__(self) -> str: return f"ERR {self.message}" class RespParseError(Exception): """RESP parsing error.""" pass class RespEncoder: """RESP protocol encoder.""" @staticmethod def encode(value: RespValue) -> bytes: """Encode value to RESP format.""" if value is None: return b"$-1\r\n" elif isinstance(value, RespError): return f"-{value.message}\r\n".encode() elif isinstance(value, str): return f"+{value}\r\n".encode() elif isinstance(value, int): return f":{value}\r\n".encode() elif isinstance(value, bytes): return f"${len(value)}\r\n".encode() + value + b"\r\n" elif isinstance(value, list): parts = [f"*{len(value)}\r\n".encode()] for item in value: parts.append(RespEncoder.encode(item)) return b"".join(parts) else: raise ValueError(f"Cannot encode type: {type(value)}") @staticmethod def encode_command(cmd: str, *args: str) -> bytes: """Encode Redis command as RESP array.""" parts: list[RespValue] = [cmd.encode()] for arg in args: parts.append(arg.encode()) return RespEncoder.encode(parts) class RespDecoder: """RESP protocol decoder.""" def __init__(self) -> None: self.buffer = b"" self.pos = 0 def feed(self, data: bytes) -> None: """Feed data to decoder.""" self.buffer += data def decode(self) -> tuple[RespValue, bool]: """Decode next value from buffer. Returns (value, success) where success is False if more data needed. """ if self.pos >= len(self.buffer): return None, False type_byte = chr(self.buffer[self.pos]) if type_byte == "+": return self._decode_simple_string() elif type_byte == "-": return self._decode_error() elif type_byte == ":": return self._decode_integer() elif type_byte == "$": return self._decode_bulk_string() elif type_byte == "*": return self._decode_array() else: raise RespParseError(f"Unknown type byte: {type_byte}") def _read_line(self) -> tuple[str, bool]: """Read until CRLF.""" crlf_pos = self.buffer.find(b"\r\n", self.pos) if crlf_pos == -1: return "", False line = self.buffer[self.pos : crlf_pos].decode("utf-8") self.pos = crlf_pos + 2 return line, True def _decode_simple_string(self) -> tuple[str | None, bool]: """Decode simple string (+).""" self.pos += 1 # Skip + line, ok = self._read_line() if not ok: self.pos -= 1 return None, False return line, True def _decode_error(self) -> tuple[RespError | None, bool]: """Decode error (-).""" self.pos += 1 # Skip - line, ok = self._read_line() if not ok: self.pos -= 1 return None, False return RespError(line), True def _decode_integer(self) -> tuple[int | None, bool]: """Decode integer (:).""" self.pos += 1 # Skip : line, ok = self._read_line() if not ok: self.pos -= 1 return None, False return int(line), True def _decode_bulk_string(self) -> tuple[bytes | None, bool]: """Decode bulk string ($).""" start_pos = self.pos self.pos += 1 # Skip $ line, ok = self._read_line() if not ok: self.pos = start_pos return None, False length = int(line) if length == -1: return None, True # Null bulk string if self.pos + length + 2 > len(self.buffer): self.pos = start_pos return None, False data = self.buffer[self.pos : self.pos + length] self.pos += length + 2 # Skip data and CRLF return data, True def _decode_array(self) -> tuple[list | None, bool]: """Decode array (*).""" start_pos = self.pos self.pos += 1 # Skip * line, ok = self._read_line() if not ok: self.pos = start_pos return None, False count = int(line) if count == -1: return None, True # Null array items: list[RespValue] = [] for _ in range(count): item, ok = self.decode() if not ok: self.pos = start_pos return None, False items.append(item) return items, True def consume(self) -> None: """Remove decoded data from buffer.""" self.buffer = self.buffer[self.pos :] self.pos = 0 def encode(value: RespValue) -> bytes: """Encode value to RESP.""" return RespEncoder.encode(value) def decode(data: bytes) -> RespValue: """Decode RESP data.""" decoder = RespDecoder() decoder.feed(data) value, ok = decoder.decode() if not ok: raise RespParseError("Incomplete data") return value def encode_command(cmd: str, *args: str) -> bytes: """Encode Redis command.""" return RespEncoder.encode_command(cmd, *args) def parse_command(data: bytes) -> tuple[str, list[bytes]]: """Parse Redis command from RESP array.""" value = decode(data) if not isinstance(value, list) or len(value) == 0: raise RespParseError("Expected non-empty array") cmd = value[0] if isinstance(cmd, bytes): cmd = cmd.decode("utf-8") elif not isinstance(cmd, str): raise RespParseError("Command must be string or bytes") args: list[bytes] = [] for arg in value[1:]: if isinstance(arg, bytes): args.append(arg) elif isinstance(arg, str): args.append(arg.encode()) else: args.append(str(arg).encode()) return cmd.upper(), args def simulate_resp(operations: list[str]) -> list[str]: """Simulate RESP operations.""" results: list[str] = [] for op in operations: parts = op.split(":", 1) cmd = parts[0] if cmd == "encode_string": data = encode(parts[1]) results.append(data.decode().replace("\r\n", "\\r\\n")) elif cmd == "encode_int": data = encode(int(parts[1])) results.append(data.decode().replace("\r\n", "\\r\\n")) elif cmd == "encode_bulk": data = encode(parts[1].encode()) results.append(repr(data)) elif cmd == "encode_array": items = parts[1].split(",") data = encode(items) results.append(data.decode().replace("\r\n", "\\r\\n")) elif cmd == "encode_cmd": cmd_parts = parts[1].split(" ") data = encode_command(cmd_parts[0], *cmd_parts[1:]) results.append(repr(data)) elif cmd == "decode": data = parts[1].encode().replace(b"\\r\\n", b"\r\n") value = decode(data) results.append(repr(value)) elif cmd == "parse_cmd": data = parts[1].encode().replace(b"\\r\\n", b"\r\n") cmd_name, args = parse_command(data) results.append(f"{cmd_name} {args}") return results def main() -> int: """CLI entry point.""" if len(sys.argv) < 2: print("Usage: proto_redis_cli.py <command> [args]") print("Commands: encode, decode, command") return 1 cmd = sys.argv[1] if cmd == "encode" and len(sys.argv) > 2: value = sys.argv[2] if value.isdigit() or (value.startswith("-") and value[1:].isdigit()): data = encode(int(value)) else: data = encode(value) print(repr(data)) elif cmd == "decode" and len(sys.argv) > 2: data = sys.argv[2].encode().replace(b"\\r\\n", b"\r\n") value = decode(data) print(repr(value)) elif cmd == "command" and len(sys.argv) > 2: parts = sys.argv[2:] data = encode_command(parts[0], *parts[1:]) print(repr(data)) else: print("Unknown command or missing arguments") return 1 return 0 if __name__ == "__main__": sys.exit(main())
false
proto_redis
308
0
[ "class_definition", "exception_handling", "decorator" ]
0.612
Error: Unsupported type annotation: Constant(ExprConstant { range: 462..473, value: Str("RespError"), kind: None })
example_proto_redis
test_proto_redis_cli.py
"""Tests for proto_redis_cli.py""" import pytest from proto_redis_cli import ( RespDecoder, RespEncoder, RespError, RespParseError, RespType, decode, encode, encode_command, parse_command, simulate_resp, ) class TestRespType: def test_types_exist(self): assert RespType.SIMPLE_STRING assert RespType.ERROR assert RespType.INTEGER assert RespType.BULK_STRING assert RespType.ARRAY assert RespType.NULL class TestRespError: def test_create(self): err = RespError("something went wrong") assert err.message == "something went wrong" def test_str(self): err = RespError("oops") assert str(err) == "ERR oops" class TestRespEncoder: def test_encode_simple_string(self): assert RespEncoder.encode("OK") == b"+OK\r\n" assert RespEncoder.encode("hello") == b"+hello\r\n" def test_encode_error(self): err = RespError("ERR unknown command") assert RespEncoder.encode(err) == b"-ERR unknown command\r\n" def test_encode_integer(self): assert RespEncoder.encode(0) == b":0\r\n" assert RespEncoder.encode(42) == b":42\r\n" assert RespEncoder.encode(-1) == b":-1\r\n" def test_encode_bulk_string(self): assert RespEncoder.encode(b"hello") == b"$5\r\nhello\r\n" assert RespEncoder.encode(b"") == b"$0\r\n\r\n" def test_encode_null(self): assert RespEncoder.encode(None) == b"$-1\r\n" def test_encode_array(self): assert RespEncoder.encode([]) == b"*0\r\n" assert RespEncoder.encode(["OK"]) == b"*1\r\n+OK\r\n" def test_encode_nested_array(self): data = RespEncoder.encode([[1, 2], [3, 4]]) assert data == b"*2\r\n*2\r\n:1\r\n:2\r\n*2\r\n:3\r\n:4\r\n" def test_encode_mixed_array(self): data = RespEncoder.encode(["OK", 42, b"data"]) assert b"*3\r\n" in data assert b"+OK\r\n" in data assert b":42\r\n" in data def test_encode_command(self): data = RespEncoder.encode_command("GET", "key") assert data == b"*2\r\n$3\r\nGET\r\n$3\r\nkey\r\n" def test_encode_command_multiple_args(self): data = RespEncoder.encode_command("SET", "key", "value") assert b"*3\r\n" in data def test_encode_invalid_type(self): with pytest.raises(ValueError): RespEncoder.encode({"dict": "value"}) class TestRespDecoder: def test_decode_simple_string(self): decoder = RespDecoder() decoder.feed(b"+OK\r\n") value, ok = decoder.decode() assert ok assert value == "OK" def test_decode_error(self): decoder = RespDecoder() decoder.feed(b"-ERR unknown\r\n") value, ok = decoder.decode() assert ok assert isinstance(value, RespError) assert value.message == "ERR unknown" def test_decode_integer(self): decoder = RespDecoder() decoder.feed(b":42\r\n") value, ok = decoder.decode() assert ok assert value == 42 def test_decode_negative_integer(self): decoder = RespDecoder() decoder.feed(b":-1\r\n") value, ok = decoder.decode() assert ok assert value == -1 def test_decode_bulk_string(self): decoder = RespDecoder() decoder.feed(b"$5\r\nhello\r\n") value, ok = decoder.decode() assert ok assert value == b"hello" def test_decode_empty_bulk_string(self): decoder = RespDecoder() decoder.feed(b"$0\r\n\r\n") value, ok = decoder.decode() assert ok assert value == b"" def test_decode_null_bulk_string(self): decoder = RespDecoder() decoder.feed(b"$-1\r\n") value, ok = decoder.decode() assert ok assert value is None def test_decode_array(self): decoder = RespDecoder() decoder.feed(b"*2\r\n+OK\r\n:1\r\n") value, ok = decoder.decode() assert ok assert value == ["OK", 1] def test_decode_empty_array(self): decoder = RespDecoder() decoder.feed(b"*0\r\n") value, ok = decoder.decode() assert ok assert value == [] def test_decode_null_array(self): decoder = RespDecoder() decoder.feed(b"*-1\r\n") value, ok = decoder.decode() assert ok assert value is None def test_decode_nested_array(self): decoder = RespDecoder() decoder.feed(b"*2\r\n*1\r\n:1\r\n*1\r\n:2\r\n") value, ok = decoder.decode() assert ok assert value == [[1], [2]] def test_decode_incomplete_simple_string(self): decoder = RespDecoder() decoder.feed(b"+OK") # Missing CRLF value, ok = decoder.decode() assert not ok def test_decode_incomplete_bulk_string(self): decoder = RespDecoder() decoder.feed(b"$5\r\nhel") # Missing data value, ok = decoder.decode() assert not ok def test_decode_incomplete_array(self): decoder = RespDecoder() decoder.feed(b"*2\r\n+OK\r\n") # Missing second element value, ok = decoder.decode() assert not ok def test_decode_unknown_type(self): decoder = RespDecoder() decoder.feed(b"?unknown\r\n") with pytest.raises(RespParseError): decoder.decode() def test_incremental_feed(self): decoder = RespDecoder() decoder.feed(b"+") value, ok = decoder.decode() assert not ok decoder.feed(b"OK") decoder.pos = 0 value, ok = decoder.decode() assert not ok decoder.feed(b"\r\n") decoder.pos = 0 value, ok = decoder.decode() assert ok assert value == "OK" def test_consume(self): decoder = RespDecoder() decoder.feed(b"+OK\r\n+NEXT\r\n") value, ok = decoder.decode() assert ok decoder.consume() value, ok = decoder.decode() assert ok assert value == "NEXT" class TestEncode: def test_string(self): assert encode("hello") == b"+hello\r\n" def test_int(self): assert encode(123) == b":123\r\n" def test_bytes(self): assert encode(b"data") == b"$4\r\ndata\r\n" def test_none(self): assert encode(None) == b"$-1\r\n" def test_list(self): assert encode([1, 2]) == b"*2\r\n:1\r\n:2\r\n" class TestDecode: def test_string(self): assert decode(b"+hello\r\n") == "hello" def test_int(self): assert decode(b":42\r\n") == 42 def test_bulk(self): assert decode(b"$3\r\nfoo\r\n") == b"foo" def test_incomplete_raises(self): with pytest.raises(RespParseError): decode(b"+incomplete") class TestEncodeCommand: def test_get(self): data = encode_command("GET", "mykey") assert b"GET" in data assert b"mykey" in data def test_set(self): data = encode_command("SET", "key", "value") assert b"*3\r\n" in data def test_lpush_multiple(self): data = encode_command("LPUSH", "list", "a", "b", "c") assert b"*5\r\n" in data class TestParseCommand: def test_get(self): data = encode_command("GET", "mykey") cmd, args = parse_command(data) assert cmd == "GET" assert args == [b"mykey"] def test_set(self): data = encode_command("set", "key", "value") cmd, args = parse_command(data) assert cmd == "SET" # Uppercased assert args == [b"key", b"value"] def test_ping(self): data = encode_command("PING") cmd, args = parse_command(data) assert cmd == "PING" assert args == [] def test_invalid_empty_array(self): with pytest.raises(RespParseError): parse_command(b"*0\r\n") class TestSimulateResp: def test_encode_string(self): result = simulate_resp(["encode_string:OK"]) assert result == ["+OK\\r\\n"] def test_encode_int(self): result = simulate_resp(["encode_int:42"]) assert result == [":42\\r\\n"] def test_decode(self): result = simulate_resp(["decode:+hello\\r\\n"]) assert result == ["'hello'"] def test_encode_cmd(self): result = simulate_resp(["encode_cmd:GET key"]) assert "GET" in result[0] class TestRealWorldCommands: def test_info(self): cmd = encode_command("INFO") parsed_cmd, args = parse_command(cmd) assert parsed_cmd == "INFO" def test_hset(self): cmd = encode_command("HSET", "hash", "field", "value") parsed_cmd, args = parse_command(cmd) assert parsed_cmd == "HSET" assert len(args) == 3 def test_zadd(self): cmd = encode_command("ZADD", "zset", "1", "member") parsed_cmd, args = parse_command(cmd) assert parsed_cmd == "ZADD" def test_multi(self): # Test MULTI/EXEC transaction commands multi = encode_command("MULTI") exec_cmd = encode_command("EXEC") assert b"MULTI" in multi assert b"EXEC" in exec_cmd
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_proto_redis/test_proto_redis_cli.py (9226 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_proto_redis/test_proto_redis_cli.rs (15803 bytes) ⏱️ Parse time: 50ms 📊 Throughput: 180.0 KB/s ⏱️ Total time: 50ms
true
proto_redis
326
5
[ "context_manager", "class_definition" ]
0.652
null
example_proto_syslog
proto_syslog_cli.py
"""Syslog Protocol Parser CLI (RFC 5424). Demonstrates syslog message parsing and formatting. """ import sys from dataclasses import dataclass, field from datetime import datetime from enum import IntEnum class Facility(IntEnum): """Syslog facilities.""" KERN = 0 USER = 1 MAIL = 2 DAEMON = 3 AUTH = 4 SYSLOG = 5 LPR = 6 NEWS = 7 UUCP = 8 CRON = 9 AUTHPRIV = 10 FTP = 11 NTP = 12 AUDIT = 13 ALERT = 14 CLOCK = 15 LOCAL0 = 16 LOCAL1 = 17 LOCAL2 = 18 LOCAL3 = 19 LOCAL4 = 20 LOCAL5 = 21 LOCAL6 = 22 LOCAL7 = 23 class Severity(IntEnum): """Syslog severities.""" EMERGENCY = 0 ALERT = 1 CRITICAL = 2 ERROR = 3 WARNING = 4 NOTICE = 5 INFO = 6 DEBUG = 7 @dataclass class StructuredDataElement: """RFC 5424 structured data element.""" sd_id: str params: dict[str, str] = field(default_factory=dict) def to_string(self) -> str: """Format as string.""" if not self.params: return f"[{self.sd_id}]" params_str = " ".join(f'{k}="{self._escape(v)}"' for k, v in self.params.items()) return f"[{self.sd_id} {params_str}]" @staticmethod def _escape(value: str) -> str: """Escape special characters.""" return value.replace("\\", "\\\\").replace('"', '\\"').replace("]", "\\]") @dataclass class SyslogMessage: """RFC 5424 syslog message.""" facility: Facility severity: Severity timestamp: datetime | None = None hostname: str = "-" app_name: str = "-" proc_id: str = "-" msg_id: str = "-" structured_data: list[StructuredDataElement] = field(default_factory=list) message: str = "" @property def priority(self) -> int: """Calculate PRI value.""" return (self.facility * 8) + self.severity def to_rfc5424(self) -> str: """Format as RFC 5424 message.""" # PRI pri = f"<{self.priority}>" # VERSION version = "1" # TIMESTAMP if self.timestamp: ts = self.timestamp.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" else: ts = "-" # STRUCTURED-DATA if self.structured_data: sd = "".join(elem.to_string() for elem in self.structured_data) else: sd = "-" # Build message header = f"{pri}{version} {ts} {self.hostname} {self.app_name} {self.proc_id} {self.msg_id}" if self.message: return f"{header} {sd} {self.message}" return f"{header} {sd}" def to_rfc3164(self) -> str: """Format as RFC 3164 (BSD) message.""" pri = f"<{self.priority}>" if self.timestamp: ts = self.timestamp.strftime("%b %d %H:%M:%S") else: ts = datetime.now().strftime("%b %d %H:%M:%S") tag = self.app_name if self.proc_id != "-": tag = f"{self.app_name}[{self.proc_id}]" return f"{pri}{ts} {self.hostname} {tag}: {self.message}" class SyslogParseError(Exception): """Syslog parsing error.""" pass class SyslogParser: """Syslog message parser.""" def __init__(self) -> None: self.pos = 0 self.data = "" def parse(self, data: str) -> SyslogMessage: """Parse syslog message.""" self.data = data self.pos = 0 # Parse PRI if not self.data.startswith("<"): raise SyslogParseError("Missing PRI") end_pri = self.data.find(">") if end_pri == -1: raise SyslogParseError("Invalid PRI") try: pri = int(self.data[1:end_pri]) except ValueError: raise SyslogParseError("Invalid PRI value") from None facility = Facility(pri // 8) severity = Severity(pri % 8) self.pos = end_pri + 1 # Check if RFC 5424 (starts with version) if self.pos < len(self.data) and self.data[self.pos] == "1": return self._parse_rfc5424(facility, severity) else: return self._parse_rfc3164(facility, severity) def _parse_rfc5424(self, facility: Facility, severity: Severity) -> SyslogMessage: """Parse RFC 5424 format.""" self.pos += 1 # Skip version self._skip_space() # TIMESTAMP timestamp = self._parse_timestamp() self._skip_space() # HOSTNAME hostname = self._parse_field() self._skip_space() # APP-NAME app_name = self._parse_field() self._skip_space() # PROCID proc_id = self._parse_field() self._skip_space() # MSGID msg_id = self._parse_field() self._skip_space() # STRUCTURED-DATA structured_data = self._parse_structured_data() # MESSAGE message = "" if self.pos < len(self.data): self._skip_space() message = self.data[self.pos :] return SyslogMessage( facility=facility, severity=severity, timestamp=timestamp, hostname=hostname, app_name=app_name, proc_id=proc_id, msg_id=msg_id, structured_data=structured_data, message=message, ) def _parse_rfc3164(self, facility: Facility, severity: Severity) -> SyslogMessage: """Parse RFC 3164 (BSD) format.""" # TIMESTAMP (Mmm dd hh:mm:ss) timestamp = None try: ts_str = self.data[self.pos : self.pos + 15] # Prepend current year to avoid deprecation warning for strptime without year current_year = datetime.now().year ts_with_year = f"{current_year} {ts_str}" timestamp = datetime.strptime(ts_with_year, "%Y %b %d %H:%M:%S") self.pos += 15 except (ValueError, IndexError): pass self._skip_space() # HOSTNAME hostname = self._parse_field() self._skip_space() # TAG (app_name[proc_id]:) app_name = "-" proc_id = "-" tag_end = self.data.find(":", self.pos) if tag_end != -1: tag = self.data[self.pos : tag_end] self.pos = tag_end + 1 bracket = tag.find("[") if bracket != -1: app_name = tag[:bracket] proc_id = tag[bracket + 1 : -1] if tag.endswith("]") else tag[bracket + 1 :] else: app_name = tag self._skip_space() message = self.data[self.pos :] return SyslogMessage( facility=facility, severity=severity, timestamp=timestamp, hostname=hostname, app_name=app_name, proc_id=proc_id, message=message, ) def _skip_space(self) -> None: """Skip whitespace.""" while self.pos < len(self.data) and self.data[self.pos] == " ": self.pos += 1 def _parse_field(self) -> str: """Parse a space-delimited field.""" start = self.pos while self.pos < len(self.data) and self.data[self.pos] not in " \n": self.pos += 1 return self.data[start : self.pos] def _parse_timestamp(self) -> datetime | None: """Parse RFC 5424 timestamp.""" field = self._parse_field() if field == "-": return None try: # Handle various timestamp formats if "." in field: ts_str = field.rstrip("Z") if len(ts_str) > 26: ts_str = ts_str[:26] return datetime.strptime(ts_str, "%Y-%m-%dT%H:%M:%S.%f") else: return datetime.strptime(field.rstrip("Z"), "%Y-%m-%dT%H:%M:%S") except ValueError: return None def _parse_structured_data(self) -> list[StructuredDataElement]: """Parse structured data elements.""" elements: list[StructuredDataElement] = [] if self.pos >= len(self.data) or self.data[self.pos] == "-": if self.pos < len(self.data) and self.data[self.pos] == "-": self.pos += 1 return elements while self.pos < len(self.data) and self.data[self.pos] == "[": elem = self._parse_sd_element() if elem: elements.append(elem) return elements def _parse_sd_element(self) -> StructuredDataElement | None: """Parse a single SD element.""" if self.data[self.pos] != "[": return None self.pos += 1 # Skip [ # Parse SD-ID sd_id_start = self.pos while self.pos < len(self.data) and self.data[self.pos] not in " ]": self.pos += 1 sd_id = self.data[sd_id_start : self.pos] params: dict[str, str] = {} # Parse params while self.pos < len(self.data) and self.data[self.pos] != "]": self._skip_space() if self.data[self.pos] == "]": break # Parse param name name_start = self.pos while self.pos < len(self.data) and self.data[self.pos] != "=": self.pos += 1 name = self.data[name_start : self.pos] self.pos += 1 # Skip = # Parse param value (quoted) if self.pos < len(self.data) and self.data[self.pos] == '"': self.pos += 1 # Skip opening quote value_start = self.pos while self.pos < len(self.data): if self.data[self.pos] == "\\" and self.pos + 1 < len(self.data): self.pos += 2 # Skip escaped char elif self.data[self.pos] == '"': break else: self.pos += 1 value = self.data[value_start : self.pos] self.pos += 1 # Skip closing quote params[name] = value.replace('\\"', '"').replace("\\\\", "\\") if self.pos < len(self.data) and self.data[self.pos] == "]": self.pos += 1 # Skip ] return StructuredDataElement(sd_id, params) def parse(data: str) -> SyslogMessage: """Parse syslog message.""" parser = SyslogParser() return parser.parse(data) def format_message( message: str, facility: Facility = Facility.USER, severity: Severity = Severity.INFO, app_name: str = "app", hostname: str = "localhost", ) -> str: """Format a syslog message.""" msg = SyslogMessage( facility=facility, severity=severity, timestamp=datetime.now(), hostname=hostname, app_name=app_name, message=message, ) return msg.to_rfc5424() def simulate_syslog(operations: list[str]) -> list[str]: """Simulate syslog operations.""" results: list[str] = [] for op in operations: parts = op.split(":", 1) cmd = parts[0] if cmd == "parse": try: msg = parse(parts[1]) results.append(f"facility={msg.facility.name} severity={msg.severity.name}") except SyslogParseError as e: results.append(f"error:{e}") elif cmd == "format": formatted = format_message(parts[1]) results.append(formatted[:50] + "...") elif cmd == "priority": pri = int(parts[1]) fac = Facility(pri // 8) sev = Severity(pri % 8) results.append(f"{fac.name}.{sev.name}") return results def main() -> int: """CLI entry point.""" if len(sys.argv) < 2: print("Usage: proto_syslog_cli.py <command> [args]") return 1 cmd = sys.argv[1] if cmd == "parse" and len(sys.argv) > 2: try: msg = parse(sys.argv[2]) print(f"Facility: {msg.facility.name}") print(f"Severity: {msg.severity.name}") print(f"Hostname: {msg.hostname}") print(f"App: {msg.app_name}") print(f"Message: {msg.message}") except SyslogParseError as e: print(f"Error: {e}") return 1 elif cmd == "format" and len(sys.argv) > 2: print(format_message(sys.argv[2])) else: print("Unknown command") return 1 return 0 if __name__ == "__main__": sys.exit(main())
false
proto_syslog
446
0
[ "context_manager", "class_definition", "exception_handling", "decorator" ]
0.652
Type inference hints: Hint: list[Any] for variable 'formatted' [High] (usage patterns suggest this type) Hint: str for variable 'op' [Medium] (usage patterns suggest this type) Hint: list[Any] for variable 'parts' [High] (usage patterns suggest this type) Hint: str for variable 'e' [Medium] (usage patterns suggest this type) Hint: list[Any] for variable 'results' [High] (usage patterns suggest this type) Type inference hints: Hint: str for variable 'e' [Medium] (usage patterns suggest this type
example_proto_syslog
test_proto_syslog_cli.py
"""Tests for proto_syslog_cli.py""" import pytest from proto_syslog_cli import ( Facility, Severity, StructuredDataElement, SyslogMessage, SyslogParseError, SyslogParser, format_message, parse, simulate_syslog, ) class TestFacility: def test_values(self): assert Facility.KERN == 0 assert Facility.USER == 1 assert Facility.DAEMON == 3 assert Facility.LOCAL0 == 16 assert Facility.LOCAL7 == 23 def test_all_facilities(self): assert len(Facility) == 24 class TestSeverity: def test_values(self): assert Severity.EMERGENCY == 0 assert Severity.ALERT == 1 assert Severity.CRITICAL == 2 assert Severity.ERROR == 3 assert Severity.WARNING == 4 assert Severity.NOTICE == 5 assert Severity.INFO == 6 assert Severity.DEBUG == 7 def test_all_severities(self): assert len(Severity) == 8 class TestStructuredDataElement: def test_create(self): elem = StructuredDataElement("exampleID") assert elem.sd_id == "exampleID" assert elem.params == {} def test_with_params(self): elem = StructuredDataElement("test", {"key": "value"}) assert elem.params["key"] == "value" def test_to_string_no_params(self): elem = StructuredDataElement("myid") assert elem.to_string() == "[myid]" def test_to_string_with_params(self): elem = StructuredDataElement("id", {"key": "val"}) assert elem.to_string() == '[id key="val"]' def test_escape_quotes(self): elem = StructuredDataElement("id", {"msg": 'say "hello"'}) result = elem.to_string() assert '\\"' in result def test_escape_backslash(self): elem = StructuredDataElement("id", {"path": "C:\\test"}) result = elem.to_string() assert "\\\\" in result class TestSyslogMessage: def test_create(self): msg = SyslogMessage(Facility.USER, Severity.INFO) assert msg.facility == Facility.USER assert msg.severity == Severity.INFO def test_priority_calculation(self): # USER (1) * 8 + INFO (6) = 14 msg = SyslogMessage(Facility.USER, Severity.INFO) assert msg.priority == 14 # LOCAL0 (16) * 8 + ERROR (3) = 131 msg = SyslogMessage(Facility.LOCAL0, Severity.ERROR) assert msg.priority == 131 def test_to_rfc5424_minimal(self): msg = SyslogMessage(Facility.USER, Severity.INFO) result = msg.to_rfc5424() assert result.startswith("<14>1") assert "- - - - - -" in result def test_to_rfc5424_with_hostname(self): msg = SyslogMessage(Facility.USER, Severity.INFO, hostname="myhost") result = msg.to_rfc5424() assert "myhost" in result def test_to_rfc5424_with_message(self): msg = SyslogMessage( Facility.USER, Severity.INFO, message="Test message" ) result = msg.to_rfc5424() assert "Test message" in result def test_to_rfc5424_with_structured_data(self): elem = StructuredDataElement("exampleSDID", {"key": "value"}) msg = SyslogMessage( Facility.USER, Severity.INFO, structured_data=[elem] ) result = msg.to_rfc5424() assert "[exampleSDID" in result assert 'key="value"' in result def test_to_rfc3164(self): msg = SyslogMessage( Facility.USER, Severity.INFO, hostname="localhost", app_name="test", message="hello", ) result = msg.to_rfc3164() assert "<14>" in result assert "localhost" in result assert "test" in result assert "hello" in result def test_to_rfc3164_with_procid(self): msg = SyslogMessage( Facility.USER, Severity.INFO, hostname="host", app_name="app", proc_id="1234", message="msg", ) result = msg.to_rfc3164() assert "app[1234]" in result class TestSyslogParser: def test_parse_rfc5424_minimal(self): parser = SyslogParser() msg = parser.parse("<14>1 - - - - - -") assert msg.facility == Facility.USER assert msg.severity == Severity.INFO def test_parse_rfc5424_full(self): data = "<14>1 2023-01-15T10:30:00.000Z myhost myapp 1234 ID47 - Test message" msg = parse(data) assert msg.hostname == "myhost" assert msg.app_name == "myapp" assert msg.proc_id == "1234" assert msg.msg_id == "ID47" assert msg.message == "Test message" def test_parse_rfc5424_structured_data(self): data = '<14>1 - - - - - [exampleSDID@32473 key="value"] msg' msg = parse(data) assert len(msg.structured_data) == 1 assert msg.structured_data[0].sd_id == "exampleSDID@32473" assert msg.structured_data[0].params["key"] == "value" def test_parse_rfc3164(self): data = "<14>Jan 15 10:30:00 myhost myapp[1234]: Test message" msg = parse(data) assert msg.facility == Facility.USER assert msg.hostname == "myhost" assert msg.app_name == "myapp" assert msg.proc_id == "1234" assert msg.message == "Test message" def test_parse_invalid_pri_missing(self): parser = SyslogParser() with pytest.raises(SyslogParseError): parser.parse("No PRI here") def test_parse_invalid_pri_unclosed(self): parser = SyslogParser() with pytest.raises(SyslogParseError): parser.parse("<14 unclosed") def test_parse_various_priorities(self): for fac in [Facility.KERN, Facility.USER, Facility.LOCAL7]: for sev in [Severity.EMERGENCY, Severity.INFO, Severity.DEBUG]: pri = fac * 8 + sev msg = parse(f"<{pri}>1 - - - - - -") assert msg.facility == fac assert msg.severity == sev class TestParse: def test_simple(self): msg = parse("<14>1 - - - - - - hello") assert msg.message == "hello" def test_timestamp(self): msg = parse("<14>1 2023-06-15T12:00:00Z host app - - - msg") assert msg.timestamp is not None assert msg.timestamp.year == 2023 assert msg.timestamp.month == 6 def test_timestamp_with_microseconds(self): msg = parse("<14>1 2023-06-15T12:00:00.123456Z host app - - - msg") assert msg.timestamp is not None class TestFormatMessage: def test_simple(self): result = format_message("Hello world") assert "Hello world" in result assert result.startswith("<") def test_custom_facility(self): result = format_message( "Test", facility=Facility.LOCAL0, severity=Severity.ERROR ) # LOCAL0 (16) * 8 + ERROR (3) = 131 assert "<131>" in result def test_custom_app_name(self): result = format_message("Test", app_name="myapp") assert "myapp" in result class TestSimulateSyslog: def test_parse(self): result = simulate_syslog(["parse:<14>1 - - - - - -"]) assert "facility=USER" in result[0] assert "severity=INFO" in result[0] def test_format(self): result = simulate_syslog(["format:Test message"]) assert "..." in result[0] def test_priority(self): result = simulate_syslog(["priority:14"]) assert "USER.INFO" in result[0] def test_priority_local(self): result = simulate_syslog(["priority:131"]) # LOCAL0.ERROR assert "LOCAL0.ERROR" in result[0] class TestRoundTrip: def test_rfc5424_roundtrip(self): original = SyslogMessage( facility=Facility.USER, severity=Severity.WARNING, hostname="testhost", app_name="testapp", proc_id="999", msg_id="MSGID", message="Test roundtrip", ) formatted = original.to_rfc5424() parsed = parse(formatted) assert parsed.facility == original.facility assert parsed.severity == original.severity assert parsed.hostname == original.hostname assert parsed.app_name == original.app_name assert parsed.message == original.message class TestMultipleStructuredData: def test_multiple_elements(self): elem1 = StructuredDataElement("id1", {"a": "1"}) elem2 = StructuredDataElement("id2", {"b": "2"}) msg = SyslogMessage( Facility.USER, Severity.INFO, structured_data=[elem1, elem2] ) result = msg.to_rfc5424() assert "[id1" in result assert "[id2" in result class TestEdgeCases: def test_empty_message(self): msg = SyslogMessage(Facility.USER, Severity.INFO, message="") result = msg.to_rfc5424() assert result.endswith("-") def test_special_chars_in_message(self): msg = SyslogMessage( Facility.USER, Severity.INFO, message="Test: special chars <>&\"'", ) result = msg.to_rfc5424() assert "<>&" in result def test_nilvalue_fields(self): msg = SyslogMessage( Facility.USER, Severity.INFO, hostname="-", app_name="-", proc_id="-", msg_id="-", ) result = msg.to_rfc5424() assert "- - - -" in result
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_proto_syslog/test_proto_syslog_cli.py (9499 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_proto_syslog/test_proto_syslog_cli.rs (15485 bytes) ⏱️ Parse time: 50ms 📊 Throughput: 182.0 KB/s ⏱️ Total time: 51ms
true
proto_syslog
305
5
[ "context_manager", "class_definition", "decorator" ]
0.652
null
example_pytorch_adam
adam_tool.py
#!/usr/bin/env python3 """Adam optimizer CLI tool. A CLI for PyTorch-style Adam optimizer. Designed for Python-to-Rust transpilation via depyler → aprender. Academic Reference: Kingma & Ba (2015) Adam optimizer [4] Usage: echo '{"params": [1.0], "grads": [0.1], "lr": 0.001}' | python adam_tool.py step """ import argparse import json import math import sys def adam_step( params: list[float], grads: list[float], m: list[float], v: list[float], t: int, lr: float = 0.001, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8, ) -> tuple: """Adam optimizer step. Updates parameters and returns new params, m, v. """ new_params = [] new_m = [] new_v = [] for i in range(len(params)): # Update biased first moment estimate m_i = beta1 * m[i] + (1 - beta1) * grads[i] # Update biased second moment estimate v_i = beta2 * v[i] + (1 - beta2) * (grads[i] ** 2) # Bias correction m_hat = m_i / (1 - beta1**t) v_hat = v_i / (1 - beta2**t) # Update parameter param_i = params[i] - lr * m_hat / (math.sqrt(v_hat) + eps) new_params.append(param_i) new_m.append(m_i) new_v.append(v_i) return new_params, new_m, new_v def init_adam(n_params: int) -> dict: """Initialize Adam optimizer state.""" return { "m": [0.0] * n_params, "v": [0.0] * n_params, "t": 0, } def cmd_step(args: argparse.Namespace) -> None: """Handle step subcommand.""" try: data = json.load(sys.stdin) except json.JSONDecodeError as e: print(f"Error: Invalid JSON: {e}", file=sys.stderr) sys.exit(1) if "params" not in data or "grads" not in data: print("Error: Missing 'params' or 'grads'", file=sys.stderr) sys.exit(1) params = data["params"] grads = data["grads"] lr = data.get("lr", 0.001) beta1 = data.get("beta1", 0.9) beta2 = data.get("beta2", 0.999) eps = data.get("eps", 1e-8) m = data.get("m", [0.0] * len(params)) v = data.get("v", [0.0] * len(params)) t = data.get("t", 1) if lr == 0: print(json.dumps({"params": params, "m": m, "v": v, "t": t})) return new_params, new_m, new_v = adam_step(params, grads, m, v, t, lr, beta1, beta2, eps) print(json.dumps({"params": new_params, "m": new_m, "v": new_v, "t": t + 1})) def cmd_init(args: argparse.Namespace) -> None: """Handle init subcommand.""" try: data = json.load(sys.stdin) except json.JSONDecodeError as e: print(f"Error: Invalid JSON: {e}", file=sys.stderr) sys.exit(1) n_params = data.get("n_params", 1) lr = data.get("lr", 0.001) state = init_adam(n_params) state["lr"] = lr print(json.dumps(state)) def main() -> None: """Main entry point.""" parser = argparse.ArgumentParser(description="Adam CLI - Adam optimizer (PyTorch-compatible)") subparsers = parser.add_subparsers(dest="command", help="Available commands") subparsers.add_parser("step", help="Optimizer step").set_defaults(func=cmd_step) subparsers.add_parser("init", help="Initialize optimizer state").set_defaults(func=cmd_init) args = parser.parse_args() if args.command is None: parser.print_help() sys.exit(0) args.func(args) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_adam/adam_tool.py (3421 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_adam/adam_tool.rs (7377 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_adam/Cargo.toml (3 dependencies) ⏱️ Parse time: 55ms 📊 Throughput: 60.6 KB/s ⏱️ Total time: 55ms
true
pytorch_adam
129
6
[ "exception_handling", "stdin_usage" ]
0.577
null
example_pytorch_adam
test_adam_tool.py
#!/usr/bin/env python3 """EXTREME TDD: Tests for PyTorch Adam optimizer CLI. Academic Reference: Kingma & Ba (2015) Adam optimizer [4] Tests Adam optimizer step updates. """ import json import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "adam_tool.py" def run(args, input_data=None): """Run the CLI and return (stdout, stderr, returncode).""" result = subprocess.run( ["python3", str(SCRIPT)] + args, capture_output=True, text=True, input=input_data, ) return result.stdout, result.stderr, result.returncode class TestAdamStep: """Test Adam optimizer step.""" def test_step_updates_params(self): """Test that step updates parameters.""" data = json.dumps({ "params": [1.0, 2.0, 3.0], "grads": [0.1, 0.2, 0.3], "lr": 0.001 }) stdout, stderr, code = run(["step"], data) assert code == 0 result = json.loads(stdout) assert "params" in result # Params should change assert result["params"] != [1.0, 2.0, 3.0] def test_step_with_momentum(self): """Test Adam with momentum (beta1, beta2).""" data = json.dumps({ "params": [1.0], "grads": [0.1], "lr": 0.01, "beta1": 0.9, "beta2": 0.999, "m": [0.0], # First moment "v": [0.0], # Second moment "t": 1 }) stdout, stderr, code = run(["step"], data) assert code == 0 result = json.loads(stdout) assert "m" in result assert "v" in result class TestAdamInit: """Test Adam initialization.""" def test_init_creates_state(self): """Test that init creates optimizer state.""" data = json.dumps({ "n_params": 3, "lr": 0.001 }) stdout, stderr, code = run(["init"], data) assert code == 0 result = json.loads(stdout) assert "m" in result assert "v" in result assert len(result["m"]) == 3 assert len(result["v"]) == 3 class TestAdamMultiStep: """Test multiple optimization steps.""" def test_multiple_steps_converge(self): """Test that multiple steps move params toward minimum.""" # Start at x=10, gradient points toward origin data = json.dumps({ "params": [10.0], "grads": [2.0], # Gradient of x^2 at x=10 is 2*10=20, using smaller "lr": 0.1, "m": [0.0], "v": [0.0], "t": 1 }) # Take one step stdout, _, code = run(["step"], data) assert code == 0 result = json.loads(stdout) # Should move toward 0 assert result["params"][0] < 10.0 class TestHelp: """Test help messages.""" def test_help(self): """Test --help flag.""" stdout, stderr, code = run(["--help"]) assert code == 0 assert "Adam" in stdout or "adam" in stdout.lower() class TestEdgeCases: """Test edge cases.""" def test_invalid_json_fails(self): """Test invalid JSON fails.""" stdout, stderr, code = run(["step"], "not json") assert code == 1 def test_zero_learning_rate(self): """Test zero learning rate doesn't update.""" data = json.dumps({ "params": [1.0], "grads": [0.1], "lr": 0.0 }) stdout, stderr, code = run(["step"], data) assert code == 0 result = json.loads(stdout) assert result["params"] == [1.0]
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_adam/test_adam_tool.py (3622 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_adam/test_adam_tool.rs (5080 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_adam/Cargo.toml (2 dependencies) ⏱️ Parse time: 52ms 📊 Throughput: 67.2 KB/s ⏱️ Total time: 52ms
true
pytorch_adam
130
6
[ "context_manager", "class_definition" ]
0.652
null
example_pytorch_autograd
autograd_flat.py
#!/usr/bin/env python3 """Autograd CLI - flat structure for depyler compatibility. Demonstrates gradient computation for simple functions. """ import argparse def main(): """Main entry point.""" parser = argparse.ArgumentParser(description="Autograd CLI") parser.add_argument( "--mode", type=str, required=True, choices=["power", "linear", "product"], help="Mode" ) parser.add_argument("--x", type=float, default=3.0, help="Input x") parser.add_argument("--n", type=float, default=2.0, help="Power n (for power mode)") parser.add_argument("--a", type=float, default=2.0, help="Coefficient a (for linear mode)") parser.add_argument("--b", type=float, default=1.0, help="Bias b (for linear mode)") parser.add_argument("--w", type=float, default=4.0, help="Weight w (for product mode)") args = parser.parse_args() x = args.x n = args.n a = args.a b = args.b w = args.w if args.mode == "power": # f(x) = x^n, df/dx = n * x^(n-1) # Compute x^(n-1) manually result = 1.0 power = n - 1.0 i = 0.0 while i < power: result = result * x i = i + 1.0 grad = n * result # Compute value x^n value = result * x print(f"value={value} grad={grad}") elif args.mode == "linear": # f(x) = a*x + b, df/dx = a value = a * x + b grad = a print(f"value={value} grad={grad}") elif args.mode == "product": # f(x,w) = x * w, df/dx = w, df/dw = x value = x * w grad_x = w grad_w = x print(f"value={value} grad_x={grad_x} grad_w={grad_w}") if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_autograd/autograd_flat.py (1713 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_autograd/autograd_flat.rs (2131 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_autograd/Cargo.toml (1 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 35.5 KB/s ⏱️ Total time: 47ms
true
pytorch_autograd
57
6
[]
0
null
example_pytorch_autograd
autograd_tool.py
#!/usr/bin/env python3 """Autograd CLI tool. A CLI for PyTorch-style automatic differentiation. Designed for Python-to-Rust transpilation via depyler → aprender. Academic Reference: Baydin et al. (2018) Automatic Differentiation [3] Usage: echo '{"expression": "x**2", "x": 3.0}' | python autograd_tool.py backward """ import argparse import json import sys def numerical_gradient(f, x: float, h: float = 1e-5) -> float: """Compute gradient numerically using central difference.""" return (f(x + h) - f(x - h)) / (2 * h) def backward_power(x: float, n: int) -> float: """Gradient of x^n is n * x^(n-1).""" return n * (x ** (n - 1)) def backward_sum(x: list[float]) -> list[float]: """Gradient of sum is all ones.""" return [1.0] * len(x) def backward_linear(a: float, b: float, x: float) -> float: """Gradient of ax + b is a.""" return a def backward_product(x: float, w: float) -> tuple: """Gradient of x*w: d/dx = w, d/dw = x.""" return w, x def parse_and_differentiate(expression: str, variables: dict) -> dict: """Parse expression and compute gradients.""" expression = expression.strip() # Handle x**n pattern if "**" in expression: parts = expression.split("**") if parts[0].strip() == "x": n = int(parts[1].strip()) x = variables["x"] grad = backward_power(x, n) return {"grad": grad, "value": x**n} # Handle sum pattern if expression == "sum": x = variables["x"] grad = backward_sum(x) value = sum(x) return {"grad": grad, "value": value} # Handle x * w pattern (product of two variables) if "x * w" in expression or "x*w" in expression: x = variables["x"] w = variables["w"] grad_x, grad_w = backward_product(x, w) return {"grad_x": grad_x, "grad_w": grad_w, "value": x * w} # Handle a*x + b pattern if "*x" in expression: # Parse "a*x + b" if "+ " in expression: parts = expression.split("+") ax_part = parts[0].strip() b = float(parts[1].strip()) a = float(ax_part.split("*")[0].strip()) x = variables["x"] grad = backward_linear(a, b, x) return {"grad": grad, "value": a * x + b} raise ValueError(f"Unsupported expression: {expression}") def cmd_backward(args: argparse.Namespace) -> None: """Handle backward subcommand.""" try: data = json.load(sys.stdin) except json.JSONDecodeError as e: print(f"Error: Invalid JSON: {e}", file=sys.stderr) sys.exit(1) if "expression" not in data: print("Error: Missing 'expression'", file=sys.stderr) sys.exit(1) try: result = parse_and_differentiate(data["expression"], data) print(json.dumps(result)) except (ValueError, KeyError) as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) def main() -> None: """Main entry point.""" parser = argparse.ArgumentParser( description="Autograd CLI - automatic differentiation (PyTorch-compatible)" ) subparsers = parser.add_subparsers(dest="command", help="Available commands") subparsers.add_parser("backward", help="Compute gradients via backward pass").set_defaults( func=cmd_backward ) args = parser.parse_args() if args.command is None: parser.print_help() sys.exit(0) args.func(args) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_autograd/autograd_tool.py (3535 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_autograd/autograd_tool.rs (8893 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_autograd/Cargo.toml (3 dependencies) ⏱️ Parse time: 53ms 📊 Throughput: 64.2 KB/s ⏱️ Total time: 53ms
true
pytorch_autograd
124
6
[ "exception_handling", "stdin_usage" ]
0.577
null
example_pytorch_autograd
test_autograd_tool.py
#!/usr/bin/env python3 """EXTREME TDD: Tests for PyTorch autograd CLI. Academic Reference: Baydin et al. (2018) Automatic Differentiation [3] Tests backward pass and gradient computation. """ import json import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "autograd_tool.py" def run(args, input_data=None): """Run the CLI and return (stdout, stderr, returncode).""" result = subprocess.run( ["python3", str(SCRIPT)] + args, capture_output=True, text=True, input=input_data, ) return result.stdout, result.stderr, result.returncode class TestBackward: """Test backward pass.""" def test_backward_simple(self): """Test gradient of y = x^2.""" # y = x^2, dy/dx = 2x data = json.dumps({ "expression": "x**2", "x": 3.0 }) stdout, stderr, code = run(["backward"], data) assert code == 0 result = json.loads(stdout) assert "grad" in result assert abs(result["grad"] - 6.0) < 0.01 # 2*3 = 6 def test_backward_chain(self): """Test chain rule: y = (x^2)^2 = x^4.""" data = json.dumps({ "expression": "x**4", "x": 2.0 }) stdout, stderr, code = run(["backward"], data) assert code == 0 result = json.loads(stdout) # dy/dx = 4x^3 = 4*8 = 32 assert abs(result["grad"] - 32.0) < 0.01 def test_backward_sum(self): """Test gradient of sum.""" data = json.dumps({ "expression": "sum", "x": [1.0, 2.0, 3.0] }) stdout, stderr, code = run(["backward"], data) assert code == 0 result = json.loads(stdout) # Gradient of sum is all ones assert result["grad"] == [1.0, 1.0, 1.0] class TestGradient: """Test gradient computation.""" def test_gradient_linear(self): """Test gradient of linear function y = 2x + 1.""" data = json.dumps({ "expression": "2*x + 1", "x": 5.0 }) stdout, stderr, code = run(["backward"], data) assert code == 0 result = json.loads(stdout) assert abs(result["grad"] - 2.0) < 0.01 def test_gradient_product(self): """Test gradient of product y = x * w.""" data = json.dumps({ "expression": "x * w", "x": 3.0, "w": 4.0 }) stdout, stderr, code = run(["backward"], data) assert code == 0 result = json.loads(stdout) # dy/dx = w = 4, dy/dw = x = 3 assert abs(result["grad_x"] - 4.0) < 0.01 assert abs(result["grad_w"] - 3.0) < 0.01 class TestHelp: """Test help messages.""" def test_help(self): """Test --help flag.""" stdout, stderr, code = run(["--help"]) assert code == 0 assert "autograd" in stdout.lower() or "gradient" in stdout.lower() class TestEdgeCases: """Test edge cases.""" def test_invalid_json_fails(self): """Test invalid JSON fails.""" stdout, stderr, code = run(["backward"], "not json") assert code == 1
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_autograd/test_autograd_tool.py (3170 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_autograd/test_autograd_tool.rs (5004 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_autograd/Cargo.toml (2 dependencies) ⏱️ Parse time: 51ms 📊 Throughput: 59.8 KB/s ⏱️ Total time: 51ms
true
pytorch_autograd
112
6
[ "class_definition" ]
0.612
null
example_pytorch_batchnorm
batchnorm_tool.py
#!/usr/bin/env python3 """BatchNorm1d CLI tool - batch normalization (PyTorch-compatible).""" import argparse import json import math import sys def batchnorm( x: list[list[float]], gamma: list[float], beta: list[float], eps: float = 1e-5 ) -> list[list[float]]: """Batch normalization forward pass.""" n_samples = len(x) n_features = len(x[0]) # Compute mean and variance per feature mean = [sum(x[i][j] for i in range(n_samples)) / n_samples for j in range(n_features)] var = [ sum((x[i][j] - mean[j]) ** 2 for i in range(n_samples)) / n_samples for j in range(n_features) ] # Normalize and scale output = [] for i in range(n_samples): row = [] for j in range(n_features): x_norm = (x[i][j] - mean[j]) / math.sqrt(var[j] + eps) row.append(gamma[j] * x_norm + beta[j]) output.append(row) return output def cmd_forward(args: argparse.Namespace) -> None: try: data = json.load(sys.stdin) except json.JSONDecodeError as e: print(f"Error: Invalid JSON: {e}", file=sys.stderr) sys.exit(1) try: output = batchnorm(data["x"], data["gamma"], data["beta"]) print(json.dumps({"output": output})) except (ValueError, KeyError) as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) def main() -> None: parser = argparse.ArgumentParser(description="BatchNorm1d CLI (PyTorch-compatible)") subparsers = parser.add_subparsers(dest="command", help="Available commands") subparsers.add_parser("forward", help="Forward pass").set_defaults(func=cmd_forward) args = parser.parse_args() if args.command is None: parser.print_help() sys.exit(0) args.func(args) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_batchnorm/batchnorm_tool.py (1817 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_batchnorm/batchnorm_tool.rs (5747 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_batchnorm/Cargo.toml (3 dependencies) ⏱️ Parse time: 52ms 📊 Throughput: 33.8 KB/s ⏱️ Total time: 52ms
true
pytorch_batchnorm
64
6
[ "exception_handling", "stdin_usage" ]
0.577
null
example_pytorch_batchnorm
test_batchnorm_tool.py
#!/usr/bin/env python3 """EXTREME TDD: Tests for PyTorch BatchNorm1d CLI.""" import json import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "batchnorm_tool.py" def run(args, input_data=None): result = subprocess.run( ["python3", str(SCRIPT)] + args, capture_output=True, text=True, input=input_data, ) return result.stdout, result.stderr, result.returncode class TestBatchNormForward: def test_forward_normalizes(self): """Test that batch norm normalizes.""" data = json.dumps({ "x": [[1, 2], [3, 4], [5, 6]], # 3 samples, 2 features "gamma": [1, 1], "beta": [0, 0] }) stdout, stderr, code = run(["forward"], data) assert code == 0 result = json.loads(stdout) assert "output" in result # Normalized output should have ~zero mean output = result["output"] mean0 = sum(row[0] for row in output) / len(output) assert abs(mean0) < 0.1 class TestHelp: def test_help(self): stdout, stderr, code = run(["--help"]) assert code == 0 class TestEdgeCases: def test_invalid_json_fails(self): stdout, stderr, code = run(["forward"], "not json") assert code == 1
false
pytorch_batchnorm
48
0
[ "class_definition" ]
0.612
Type inference hints: Hint: int for parameter 'args' [Low] (numeric operations) Hint: int for variable 'args' [Medium] (usage patterns suggest this type) Profiling Report ══════════════════════════════════════════════════ Summary Total estimated instructions: 4 Total estimated allocations: 0 Functions analyzed: 1 Hot Paths [1] run (100.0% of execution time) Function Metrics 🔥 run 100.0% time | 4 inst | 0 alloc Performance Predictions • Rust's m
example_pytorch_conv
conv_tool.py
#!/usr/bin/env python3 """Conv2d CLI tool - 2D convolution (PyTorch-compatible).""" import argparse import json import sys def conv2d(x: list, kernel: list, bias: list, stride: int = 1, padding: int = 0) -> list: """2D convolution forward pass.""" in_ch, h, w = len(x), len(x[0]), len(x[0][0]) out_ch, _, kh, kw = len(kernel), len(kernel[0]), len(kernel[0][0]), len(kernel[0][0][0]) out_h = (h + 2 * padding - kh) // stride + 1 out_w = (w + 2 * padding - kw) // stride + 1 output = [[[0.0 for _ in range(out_w)] for _ in range(out_h)] for _ in range(out_ch)] for oc in range(out_ch): for oh in range(out_h): for ow in range(out_w): val = bias[oc] if bias else 0 for ic in range(in_ch): for kh_i in range(kh): for kw_i in range(kw): ih = oh * stride + kh_i - padding iw = ow * stride + kw_i - padding if 0 <= ih < h and 0 <= iw < w: val += x[ic][ih][iw] * kernel[oc][ic][kh_i][kw_i] output[oc][oh][ow] = val return output def cmd_forward(args: argparse.Namespace) -> None: try: data = json.load(sys.stdin) except json.JSONDecodeError as e: print(f"Error: Invalid JSON: {e}", file=sys.stderr) sys.exit(1) try: output = conv2d(data["x"], data["kernel"], data.get("bias", [0])) print(json.dumps({"output": output})) except (ValueError, KeyError) as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) def main() -> None: parser = argparse.ArgumentParser(description="Conv2d CLI - 2D convolution (PyTorch-compatible)") subparsers = parser.add_subparsers(dest="command", help="Available commands") subparsers.add_parser("forward", help="Forward pass").set_defaults(func=cmd_forward) args = parser.parse_args() if args.command is None: parser.print_help() sys.exit(0) args.func(args) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_conv/conv_tool.py (2103 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_conv/conv_tool.rs (7597 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_conv/Cargo.toml (3 dependencies) ⏱️ Parse time: 50ms 📊 Throughput: 40.5 KB/s ⏱️ Total time: 50ms
true
pytorch_conv
63
6
[ "exception_handling", "stdin_usage" ]
0.577
null
example_pytorch_conv
test_conv_tool.py
#!/usr/bin/env python3 """EXTREME TDD: Tests for PyTorch Conv2d CLI.""" import json import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "conv_tool.py" def run(args, input_data=None): result = subprocess.run( ["python3", str(SCRIPT)] + args, capture_output=True, text=True, input=input_data, ) return result.stdout, result.stderr, result.returncode class TestConv2dForward: def test_forward_simple(self): """Test 2D convolution.""" data = json.dumps({ "x": [[[1, 2, 3], [4, 5, 6], [7, 8, 9]]], # 1x3x3 "kernel": [[[[1, 0], [0, 1]]]], # 1x1x2x2 "bias": [0] }) stdout, stderr, code = run(["forward"], data) assert code == 0 result = json.loads(stdout) assert "output" in result class TestHelp: def test_help(self): stdout, stderr, code = run(["--help"]) assert code == 0 assert "Conv" in stdout or "conv" in stdout.lower() class TestEdgeCases: def test_invalid_json_fails(self): stdout, stderr, code = run(["forward"], "not json") assert code == 1
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_conv/test_conv_tool.py (1169 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_conv/test_conv_tool.rs (2555 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_conv/Cargo.toml (2 dependencies) ⏱️ Parse time: 49ms 📊 Throughput: 22.9 KB/s ⏱️ Total time: 49ms
true
pytorch_conv
45
6
[ "class_definition" ]
0.612
null
example_pytorch_dropout
dropout_tool.py
#!/usr/bin/env python3 """Dropout CLI tool - dropout regularization (PyTorch-compatible).""" import argparse import json import random import sys def dropout(x: list[float], p: float, training: bool, random_state: int = None) -> list[float]: """Dropout forward pass.""" if not training: return x if random_state is not None: random.seed(random_state) # Scale by 1/(1-p) to maintain expected value scale = 1.0 / (1.0 - p) if p < 1 else 0 output = [] for xi in x: if random.random() < p: output.append(0.0) else: output.append(xi * scale) return output def cmd_forward(args: argparse.Namespace) -> None: try: data = json.load(sys.stdin) except json.JSONDecodeError as e: print(f"Error: Invalid JSON: {e}", file=sys.stderr) sys.exit(1) try: output = dropout( data["x"], data.get("p", 0.5), data.get("training", True), data.get("random_state", None), ) print(json.dumps({"output": output})) except (ValueError, KeyError) as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) def main() -> None: parser = argparse.ArgumentParser(description="Dropout CLI (PyTorch-compatible)") subparsers = parser.add_subparsers(dest="command", help="Available commands") subparsers.add_parser("forward", help="Forward pass").set_defaults(func=cmd_forward) args = parser.parse_args() if args.command is None: parser.print_help() sys.exit(0) args.func(args) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_dropout/dropout_tool.py (1645 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_dropout/dropout_tool.rs (3459 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_dropout/Cargo.toml (4 dependencies) ⏱️ Parse time: 47ms 📊 Throughput: 33.7 KB/s ⏱️ Total time: 47ms
true
pytorch_dropout
63
6
[ "exception_handling", "stdin_usage" ]
0.577
null
example_pytorch_dropout
test_dropout_tool.py
#!/usr/bin/env python3 """EXTREME TDD: Tests for PyTorch Dropout CLI.""" import json import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "dropout_tool.py" def run(args, input_data=None): result = subprocess.run( ["python3", str(SCRIPT)] + args, capture_output=True, text=True, input=input_data, ) return result.stdout, result.stderr, result.returncode class TestDropoutForward: def test_forward_train_drops_some(self): """Test that dropout zeros some values in training.""" data = json.dumps({ "x": [1.0] * 100, "p": 0.5, "training": True, "random_state": 42 }) stdout, stderr, code = run(["forward"], data) assert code == 0 result = json.loads(stdout) # Some values should be zero zeros = sum(1 for v in result["output"] if v == 0) assert zeros > 20 # Roughly 50% should be zero def test_forward_eval_no_drop(self): """Test that dropout doesn't drop in eval mode.""" data = json.dumps({ "x": [1.0, 2.0, 3.0], "p": 0.5, "training": False }) stdout, stderr, code = run(["forward"], data) assert code == 0 result = json.loads(stdout) assert result["output"] == [1.0, 2.0, 3.0] class TestHelp: def test_help(self): stdout, stderr, code = run(["--help"]) assert code == 0 class TestEdgeCases: def test_invalid_json_fails(self): stdout, stderr, code = run(["forward"], "not json") assert code == 1
false
pytorch_dropout
59
0
[ "class_definition" ]
0.612
Type inference hints: Hint: int for parameter 'args' [Low] (numeric operations) Hint: int for variable 'args' [Medium] (usage patterns suggest this type) Profiling Report ══════════════════════════════════════════════════ Summary Total estimated instructions: 4 Total estimated allocations: 0 Functions analyzed: 1 Hot Paths [1] run (100.0% of execution time) Function Metrics 🔥 run 100.0% time | 4 inst | 0 alloc Performance Predictions • Rust's m
example_pytorch_linear
linear_flat.py
#!/usr/bin/env python3 """Linear layer CLI - flat structure for depyler compatibility. Implements y = Wx + b for 2D input/output. """ import argparse def main(): """Main entry point.""" parser = argparse.ArgumentParser(description="Linear layer CLI") parser.add_argument( "--mode", type=str, required=True, choices=["forward", "backward"], help="Mode" ) # Input vector (2D) parser.add_argument("--x0", type=float, default=1.0, help="Input x[0]") parser.add_argument("--x1", type=float, default=2.0, help="Input x[1]") # Weight matrix (2x2) parser.add_argument("--w00", type=float, default=1.0, help="W[0,0]") parser.add_argument("--w01", type=float, default=0.0, help="W[0,1]") parser.add_argument("--w10", type=float, default=0.0, help="W[1,0]") parser.add_argument("--w11", type=float, default=1.0, help="W[1,1]") # Bias (2D) parser.add_argument("--b0", type=float, default=0.0, help="Bias b[0]") parser.add_argument("--b1", type=float, default=0.0, help="Bias b[1]") # Upstream gradient for backward (2D) parser.add_argument("--dy0", type=float, default=1.0, help="Grad dy[0]") parser.add_argument("--dy1", type=float, default=1.0, help="Grad dy[1]") args = parser.parse_args() x0 = args.x0 x1 = args.x1 w00 = args.w00 w01 = args.w01 w10 = args.w10 w11 = args.w11 b0 = args.b0 b1 = args.b1 dy0 = args.dy0 dy1 = args.dy1 if args.mode == "forward": # y = Wx + b y0 = w00 * x0 + w01 * x1 + b0 y1 = w10 * x0 + w11 * x1 + b1 print(f"y0={y0} y1={y1}") elif args.mode == "backward": # dx = W^T @ dy dx0 = w00 * dy0 + w10 * dy1 dx1 = w01 * dy0 + w11 * dy1 # dW = dy @ x^T dw00 = dy0 * x0 dw01 = dy0 * x1 dw10 = dy1 * x0 dw11 = dy1 * x1 # db = dy db0 = dy0 db1 = dy1 print( f"dx0={dx0} dx1={dx1} dw00={dw00} dw01={dw01} dw10={dw10} dw11={dw11} db0={db0} db1={db1}" ) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_linear/linear_flat.py (2088 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_linear/linear_flat.rs (2910 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_linear/Cargo.toml (1 dependencies) ⏱️ Parse time: 48ms 📊 Throughput: 42.4 KB/s ⏱️ Total time: 48ms
true
pytorch_linear
67
6
[ "decorator" ]
0.5
null
example_pytorch_linear
linear_tool.py
#!/usr/bin/env python3 """Linear layer CLI tool. A CLI for PyTorch-style nn.Linear layer. Designed for Python-to-Rust transpilation via depyler → aprender. Academic Reference: He et al. (2015) Weight initialization [5] Usage: echo '{"x": [1,2], "weight": [[1,0],[0,1]], "bias": [0,0]}' | python linear_tool.py forward """ import argparse import json import math import random import sys def forward( x: list[float] | list[list[float]], weight: list[list[float]], bias: list[float] ) -> list[float] | list[list[float]]: """Forward pass: y = Wx + b.""" # Handle batch input if x and isinstance(x[0], list): return [forward_single(xi, weight, bias) for xi in x] return forward_single(x, weight, bias) def forward_single(x: list[float], weight: list[list[float]], bias: list[float]) -> list[float]: """Forward pass for single sample.""" out_features = len(weight) in_features = len(weight[0]) if len(x) != in_features: raise ValueError(f"Shape mismatch: x has {len(x)}, weight expects {in_features}") output = [] for i in range(out_features): val = bias[i] for j in range(in_features): val += weight[i][j] * x[j] output.append(val) return output def init_weights(in_features: int, out_features: int, random_state: int = None) -> dict: """Initialize weights using Kaiming uniform.""" if random_state is not None: random.seed(random_state) # Kaiming initialization: std = sqrt(2/in_features) std = math.sqrt(2.0 / in_features) bound = math.sqrt(3.0) * std weight = [ [random.uniform(-bound, bound) for _ in range(in_features)] for _ in range(out_features) ] # Bias uniform in [-1/sqrt(in), 1/sqrt(in)] bias_bound = 1.0 / math.sqrt(in_features) bias = [random.uniform(-bias_bound, bias_bound) for _ in range(out_features)] return {"weight": weight, "bias": bias} def cmd_forward(args: argparse.Namespace) -> None: """Handle forward subcommand.""" try: data = json.load(sys.stdin) except json.JSONDecodeError as e: print(f"Error: Invalid JSON: {e}", file=sys.stderr) sys.exit(1) required = ["x", "weight", "bias"] for field in required: if field not in data: print(f"Error: Missing '{field}'", file=sys.stderr) sys.exit(1) try: output = forward(data["x"], data["weight"], data["bias"]) print(json.dumps({"output": output})) except ValueError as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) def cmd_init(args: argparse.Namespace) -> None: """Handle init subcommand.""" try: data = json.load(sys.stdin) except json.JSONDecodeError as e: print(f"Error: Invalid JSON: {e}", file=sys.stderr) sys.exit(1) in_features = data.get("in_features", 1) out_features = data.get("out_features", 1) random_state = data.get("random_state", None) result = init_weights(in_features, out_features, random_state) print(json.dumps(result)) def main() -> None: """Main entry point.""" parser = argparse.ArgumentParser( description="Linear CLI - nn.Linear layer (PyTorch-compatible)" ) subparsers = parser.add_subparsers(dest="command", help="Available commands") subparsers.add_parser("forward", help="Forward pass").set_defaults(func=cmd_forward) subparsers.add_parser("init", help="Initialize weights").set_defaults(func=cmd_init) args = parser.parse_args() if args.command is None: parser.print_help() sys.exit(0) args.func(args) if __name__ == "__main__": main()
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_linear/linear_tool.py (3675 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_linear/linear_tool.rs (8341 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_linear/Cargo.toml (4 dependencies) ⏱️ Parse time: 50ms 📊 Throughput: 71.3 KB/s ⏱️ Total time: 50ms
true
pytorch_linear
122
6
[ "exception_handling", "stdin_usage" ]
0.577
null
example_pytorch_linear
test_linear_tool.py
#!/usr/bin/env python3 """EXTREME TDD: Tests for PyTorch nn.Linear CLI. Academic Reference: He et al. (2015) Weight initialization [5] Tests dense/linear layer forward pass. """ import json import subprocess from pathlib import Path SCRIPT = Path(__file__).parent / "linear_tool.py" def run(args, input_data=None): """Run the CLI and return (stdout, stderr, returncode).""" result = subprocess.run( ["python3", str(SCRIPT)] + args, capture_output=True, text=True, input=input_data, ) return result.stdout, result.stderr, result.returncode class TestLinearForward: """Test forward pass.""" def test_forward_simple(self): """Test y = Wx + b.""" data = json.dumps({ "x": [1.0, 2.0], "weight": [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], # 3x2 "bias": [0.0, 0.0, 0.0] }) stdout, stderr, code = run(["forward"], data) assert code == 0 result = json.loads(stdout) assert "output" in result # W @ x = [1, 2, 3] assert result["output"] == [1.0, 2.0, 3.0] def test_forward_with_bias(self): """Test with non-zero bias.""" data = json.dumps({ "x": [1.0, 1.0], "weight": [[1.0, 1.0]], "bias": [1.0] }) stdout, stderr, code = run(["forward"], data) assert code == 0 result = json.loads(stdout) # 1*1 + 1*1 + 1 = 3 assert result["output"] == [3.0] def test_forward_batch(self): """Test batch input.""" data = json.dumps({ "x": [[1.0, 0.0], [0.0, 1.0]], # 2 samples "weight": [[1.0, 2.0]], # 1x2 "bias": [0.0] }) stdout, stderr, code = run(["forward"], data) assert code == 0 result = json.loads(stdout) # [1*1+0*2, 0*1+1*2] = [1, 2] assert result["output"] == [[1.0], [2.0]] class TestLinearInit: """Test weight initialization.""" def test_init_creates_weights(self): """Test that init creates weight and bias.""" data = json.dumps({ "in_features": 3, "out_features": 2 }) stdout, stderr, code = run(["init"], data) assert code == 0 result = json.loads(stdout) assert "weight" in result assert "bias" in result assert len(result["weight"]) == 2 assert len(result["weight"][0]) == 3 assert len(result["bias"]) == 2 class TestLinearHelp: """Test help messages.""" def test_help(self): """Test --help flag.""" stdout, stderr, code = run(["--help"]) assert code == 0 assert "Linear" in stdout or "linear" in stdout.lower() class TestLinearEdgeCases: """Test edge cases.""" def test_invalid_json_fails(self): """Test invalid JSON fails.""" stdout, stderr, code = run(["forward"], "not json") assert code == 1 def test_shape_mismatch_fails(self): """Test shape mismatch fails.""" data = json.dumps({ "x": [1.0, 2.0, 3.0], # 3 features "weight": [[1.0, 1.0]], # expects 2 features "bias": [0.0] }) stdout, stderr, code = run(["forward"], data) assert code == 1
📄 Source: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_linear/test_linear_tool.py (3303 bytes) 📝 Output: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_linear/test_linear_tool.rs (5231 bytes) 📦 Cargo.toml: /home/noah/src/reprorusted-python-cli/examples/example_pytorch_linear/Cargo.toml (2 dependencies) ⏱️ Parse time: 50ms 📊 Throughput: 63.7 KB/s ⏱️ Total time: 50ms
true
pytorch_linear
115
6
[ "context_manager", "class_definition", "decorator" ]
0.652
null