Files
metabuilder/dbal/shared/seeds/database/pastebin_snippets.json
2026-03-09 22:30:41 +00:00

593 lines
35 KiB
JSON
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
[
{
"entity": "Snippet",
"version": "1.0",
"description": "demo — Python Recipes",
"records": [
{
"id": "d0100000-0000-0000-0000-000000000001",
"title": "Fibonacci (memoized)",
"language": "python",
"category": "algorithms",
"description": "Recursive Fibonacci with lru_cache — O(n) time, O(n) space.",
"code": "from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef fib(n: int) -> int:\n if n < 2:\n return n\n return fib(n - 1) + fib(n - 2)\n\nprint([fib(i) for i in range(15)])\n",
"functionName": "fib",
"entryPoint": "fib",
"inputParameters": "[{\"name\":\"n\",\"type\":\"integer\",\"default\":10,\"label\":\"n\"}]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "d0000001-0000-0000-0000-000000000002",
"userId": "11111111-1111-1111-1111-111111111111",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "d0100000-0000-0000-0000-000000000002",
"title": "Flatten nested list",
"language": "python",
"category": "data structures",
"description": "Recursively flatten arbitrarily nested lists into a single flat list.",
"code": "from typing import Any\n\ndef flatten(lst: list[Any]) -> list[Any]:\n result = []\n for item in lst:\n if isinstance(item, list):\n result.extend(flatten(item))\n else:\n result.append(item)\n return result\n\nprint(flatten([1, [2, [3, 4]], [5, [6, [7]]]]))\n",
"functionName": "flatten",
"entryPoint": "flatten",
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "d0000001-0000-0000-0000-000000000002",
"userId": "11111111-1111-1111-1111-111111111111",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "d0100000-0000-0000-0000-000000000003",
"title": "CSV → list of dicts",
"language": "python",
"category": "data",
"description": "Read a CSV file into a list of dicts using the header row as keys.",
"code": "import csv\nfrom io import StringIO\n\ndef csv_to_dicts(csv_text: str) -> list[dict]:\n reader = csv.DictReader(StringIO(csv_text))\n return list(reader)\n\nsample = \"\"\"name,age,city\nAlice,30,NYC\nBob,25,LA\nCarol,35,Chicago\"\"\"\nprint(csv_to_dicts(sample))\n",
"functionName": "csv_to_dicts",
"entryPoint": "csv_to_dicts",
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "d0000001-0000-0000-0000-000000000002",
"userId": "11111111-1111-1111-1111-111111111111",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "d0100000-0000-0000-0000-000000000004",
"title": "HTTP GET with retry",
"language": "python",
"category": "networking",
"description": "Retry a GET request up to n times with exponential back-off.",
"code": "import time\nimport urllib.request\nimport urllib.error\n\ndef get_with_retry(url: str, retries: int = 3, delay: float = 1.0) -> str:\n for attempt in range(retries):\n try:\n with urllib.request.urlopen(url, timeout=5) as resp:\n return resp.read().decode()\n except Exception as e:\n if attempt == retries - 1:\n raise\n print(f'Attempt {attempt + 1} failed: {e}. Retrying in {delay}s...')\n time.sleep(delay)\n delay *= 2\n return ''\n\n# Example — uncomment to run:\n# print(get_with_retry('https://httpbin.org/get'))\nprint('get_with_retry ready')\n",
"functionName": "get_with_retry",
"entryPoint": "get_with_retry",
"inputParameters": "[{\"name\":\"url\",\"type\":\"string\",\"default\":\"https://httpbin.org/get\",\"label\":\"URL\"},{\"name\":\"retries\",\"type\":\"integer\",\"default\":3,\"label\":\"Retries\"}]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "d0000001-0000-0000-0000-000000000002",
"userId": "11111111-1111-1111-1111-111111111111",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "d0100000-0000-0000-0000-000000000005",
"title": "Timer decorator",
"language": "python",
"category": "meta",
"description": "Decorator that prints how long a function takes to run.",
"code": "import time\nfrom functools import wraps\n\ndef timer(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n start = time.perf_counter()\n result = fn(*args, **kwargs)\n elapsed = time.perf_counter() - start\n print(f'{fn.__name__!r} took {elapsed * 1000:.2f} ms')\n return result\n return wrapper\n\n@timer\ndef slow_sum(n: int) -> int:\n return sum(range(n))\n\nprint(slow_sum(1_000_000))\n",
"functionName": "timer",
"entryPoint": "timer",
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "d0000001-0000-0000-0000-000000000002",
"userId": "11111111-1111-1111-1111-111111111111",
"tenantId": "pastebin",
"createdAt": 0
}
],
"metadata": { "useCurrentTimestamp": true, "timestampField": "createdAt" }
},
{
"entity": "Snippet",
"version": "1.0",
"description": "demo — SQL Patterns",
"records": [
{
"id": "d0200000-0000-0000-0000-000000000001",
"title": "Keyset pagination",
"language": "sql",
"category": "patterns",
"description": "Efficient cursor-based pagination using the last seen ID — avoids OFFSET slowdowns on large tables.",
"code": "-- Forward page: fetch rows after a known cursor\nSELECT id, created_at, title\nFROM posts\nWHERE id > :last_seen_id -- cursor from previous page\nORDER BY id ASC\nLIMIT :page_size;\n\n-- First page (no cursor)\nSELECT id, created_at, title\nFROM posts\nORDER BY id ASC\nLIMIT :page_size;\n",
"functionName": null,
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "d0000001-0000-0000-0000-000000000003",
"userId": "11111111-1111-1111-1111-111111111111",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "d0200000-0000-0000-0000-000000000002",
"title": "Running total (window)",
"language": "sql",
"category": "analytics",
"description": "Cumulative sum using a window function — no self-join needed.",
"code": "SELECT\n order_date,\n amount,\n SUM(amount) OVER (\n ORDER BY order_date\n ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW\n ) AS running_total\nFROM orders\nORDER BY order_date;\n",
"functionName": null,
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "d0000001-0000-0000-0000-000000000003",
"userId": "11111111-1111-1111-1111-111111111111",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "d0200000-0000-0000-0000-000000000003",
"title": "Upsert (INSERT … ON CONFLICT)",
"language": "sql",
"category": "patterns",
"description": "Idempotent insert-or-update for PostgreSQL and SQLite.",
"code": "-- PostgreSQL / SQLite syntax\nINSERT INTO user_settings (user_id, theme, locale)\nVALUES (:user_id, :theme, :locale)\nON CONFLICT (user_id) DO UPDATE\n SET theme = EXCLUDED.theme,\n locale = EXCLUDED.locale,\n updated_at = now();\n",
"functionName": null,
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "d0000001-0000-0000-0000-000000000003",
"userId": "11111111-1111-1111-1111-111111111111",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "d0200000-0000-0000-0000-000000000004",
"title": "Find duplicate rows",
"language": "sql",
"category": "data quality",
"description": "Detect rows with duplicate values across one or more columns.",
"code": "-- Find duplicate emails\nSELECT email, COUNT(*) AS cnt\nFROM users\nGROUP BY email\nHAVING COUNT(*) > 1\nORDER BY cnt DESC;\n\n-- Full duplicate rows (all columns identical)\nSELECT *, COUNT(*) OVER (PARTITION BY col1, col2, col3) AS dup_count\nFROM my_table\nQUALIFY dup_count > 1;\n",
"functionName": null,
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "d0000001-0000-0000-0000-000000000003",
"userId": "11111111-1111-1111-1111-111111111111",
"tenantId": "pastebin",
"createdAt": 0
}
],
"metadata": { "useCurrentTimestamp": true, "timestampField": "createdAt" }
},
{
"entity": "Snippet",
"version": "1.0",
"description": "demo — Utilities",
"records": [
{
"id": "d0300000-0000-0000-0000-000000000001",
"title": "Slugify string",
"language": "python",
"category": "text",
"description": "Convert any string to a URL-safe slug.",
"code": "import re\nimport unicodedata\n\ndef slugify(text: str, separator: str = '-') -> str:\n text = unicodedata.normalize('NFKD', text)\n text = text.encode('ascii', 'ignore').decode('ascii')\n text = re.sub(r'[^\\w\\s-]', '', text).strip().lower()\n return re.sub(r'[-\\s]+', separator, text)\n\nprint(slugify('Hello, World! This is a Test.'))\nprint(slugify('Ångström & Co. 2024'))\n",
"functionName": "slugify",
"entryPoint": "slugify",
"inputParameters": "[{\"name\":\"text\",\"type\":\"string\",\"default\":\"Hello World 2024!\",\"label\":\"Text\"}]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "d0000001-0000-0000-0000-000000000004",
"userId": "11111111-1111-1111-1111-111111111111",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "d0300000-0000-0000-0000-000000000002",
"title": "Chunk list into batches",
"language": "python",
"category": "data structures",
"description": "Split any iterable into fixed-size chunks — useful for bulk API calls.",
"code": "from typing import TypeVar, Iterator\n\nT = TypeVar('T')\n\ndef chunks(lst: list[T], size: int) -> Iterator[list[T]]:\n for i in range(0, len(lst), size):\n yield lst[i:i + size]\n\ndata = list(range(17))\nfor batch in chunks(data, 5):\n print(batch)\n",
"functionName": "chunks",
"entryPoint": "chunks",
"inputParameters": "[{\"name\":\"size\",\"type\":\"integer\",\"default\":5,\"label\":\"Batch size\"}]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "d0000001-0000-0000-0000-000000000004",
"userId": "11111111-1111-1111-1111-111111111111",
"tenantId": "pastebin",
"createdAt": 0
}
],
"metadata": { "useCurrentTimestamp": true, "timestampField": "createdAt" }
},
{
"entity": "Snippet",
"version": "1.0",
"description": "alice — React Components",
"records": [
{
"id": "a0100000-0000-0000-0000-000000000001",
"title": "useLocalStorage hook",
"language": "typescript",
"category": "hooks",
"description": "Persists state to localStorage and stays in sync across tabs.",
"code": "import { useState, useEffect, useCallback } from 'react'\n\nexport function useLocalStorage<T>(key: string, initialValue: T) {\n const [value, setValue] = useState<T>(() => {\n try {\n const item = window.localStorage.getItem(key)\n return item ? (JSON.parse(item) as T) : initialValue\n } catch {\n return initialValue\n }\n })\n\n const setStoredValue = useCallback((val: T | ((prev: T) => T)) => {\n setValue(prev => {\n const next = typeof val === 'function' ? (val as (p: T) => T)(prev) : val\n try { window.localStorage.setItem(key, JSON.stringify(next)) } catch {}\n return next\n })\n }, [key])\n\n useEffect(() => {\n const handler = (e: StorageEvent) => {\n if (e.key === key && e.newValue !== null)\n setValue(JSON.parse(e.newValue) as T)\n }\n window.addEventListener('storage', handler)\n return () => window.removeEventListener('storage', handler)\n }, [key])\n\n return [value, setStoredValue] as const\n}\n",
"functionName": "useLocalStorage",
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "a0000002-0000-0000-0000-000000000002",
"userId": "22222222-2222-2222-2222-222222222222",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "a0100000-0000-0000-0000-000000000002",
"title": "useDebounce hook",
"language": "typescript",
"category": "hooks",
"description": "Delays updating a value until after a specified delay — ideal for search inputs.",
"code": "import { useState, useEffect } from 'react'\n\nexport function useDebounce<T>(value: T, delay = 300): T {\n const [debounced, setDebounced] = useState(value)\n useEffect(() => {\n const id = setTimeout(() => setDebounced(value), delay)\n return () => clearTimeout(id)\n }, [value, delay])\n return debounced\n}\n\n// Usage:\n// const query = useDebounce(inputValue, 300)\n// useEffect(() => { fetchResults(query) }, [query])\n",
"functionName": "useDebounce",
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "a0000002-0000-0000-0000-000000000002",
"userId": "22222222-2222-2222-2222-222222222222",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "a0100000-0000-0000-0000-000000000003",
"title": "React Counter (live preview)",
"language": "jsx",
"category": "components",
"description": "Minimal counter with increment / decrement — live preview enabled.",
"code": "function Counter() {\n const [count, setCount] = React.useState(0)\n return (\n <div style={{ fontFamily: 'sans-serif', textAlign: 'center', padding: '2rem' }}>\n <h2 style={{ fontSize: '3rem', margin: '0 0 1rem' }}>{count}</h2>\n <button onClick={() => setCount(c => c - 1)}\n style={{ marginRight: '1rem', padding: '.5rem 1.5rem', fontSize: '1.2rem', cursor: 'pointer' }}></button>\n <button onClick={() => setCount(c => c + 1)}\n style={{ padding: '.5rem 1.5rem', fontSize: '1.2rem', cursor: 'pointer' }}>+</button>\n <button onClick={() => setCount(0)}\n style={{ marginLeft: '1rem', padding: '.5rem 1rem', fontSize: '1rem', cursor: 'pointer', opacity: 0.6 }}>reset</button>\n </div>\n )\n}\n",
"functionName": "Counter",
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": true,
"isTemplate": false,
"namespaceId": "a0000002-0000-0000-0000-000000000002",
"userId": "22222222-2222-2222-2222-222222222222",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "a0100000-0000-0000-0000-000000000004",
"title": "Dark card component",
"language": "jsx",
"category": "components",
"description": "Glassmorphism dark card with gradient border — live preview enabled.",
"code": "function DarkCard({ title = 'Card Title', body = 'Some content goes here.', badge = 'New' }) {\n return (\n <div style={{\n minHeight: '100vh', display: 'flex', alignItems: 'center',\n justifyContent: 'center', background: '#0f0f13'\n }}>\n <div style={{\n background: 'linear-gradient(135deg,#1e1e2e,#16162a)',\n border: '1px solid rgba(139,92,246,.35)',\n borderRadius: '16px', padding: '2rem', width: '300px',\n boxShadow: '0 8px 32px rgba(139,92,246,.15)',\n fontFamily: 'system-ui,sans-serif', color: '#e2e8f0'\n }}>\n <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1rem' }}>\n <h3 style={{ margin: 0, fontSize: '1.1rem' }}>{title}</h3>\n <span style={{ background: '#7c3aed', borderRadius: '999px',\n padding: '2px 10px', fontSize: '.75rem', color: '#fff' }}>{badge}</span>\n </div>\n <p style={{ margin: 0, color: '#94a3b8', lineHeight: 1.6 }}>{body}</p>\n </div>\n </div>\n )\n}\n",
"functionName": "DarkCard",
"entryPoint": null,
"inputParameters": "[{\"name\":\"title\",\"type\":\"string\",\"default\":\"Card Title\",\"label\":\"Title\"},{\"name\":\"body\",\"type\":\"string\",\"default\":\"Some content goes here.\",\"label\":\"Body\"},{\"name\":\"badge\",\"type\":\"string\",\"default\":\"New\",\"label\":\"Badge\"}]",
"hasPreview": true,
"isTemplate": false,
"namespaceId": "a0000002-0000-0000-0000-000000000002",
"userId": "22222222-2222-2222-2222-222222222222",
"tenantId": "pastebin",
"createdAt": 0
}
],
"metadata": { "useCurrentTimestamp": true, "timestampField": "createdAt" }
},
{
"entity": "Snippet",
"version": "1.0",
"description": "alice — JS Utilities",
"records": [
{
"id": "a0200000-0000-0000-0000-000000000001",
"title": "Deep clone (structuredClone)",
"language": "javascript",
"category": "utilities",
"description": "Deep-copy any serialisable value using the native structuredClone API.",
"code": "// Native deep clone — handles Date, Map, Set, ArrayBuffer, etc.\n// Falls back to JSON for older environments.\nfunction deepClone(value) {\n if (typeof structuredClone === 'function') return structuredClone(value)\n return JSON.parse(JSON.stringify(value))\n}\n\nconst original = { a: 1, b: { c: [1, 2, 3] }, d: new Date() }\nconst copy = deepClone(original)\ncopy.b.c.push(99)\nconsole.log(original.b.c) // [1, 2, 3] — unchanged\nconsole.log(copy.b.c) // [1, 2, 3, 99]\n",
"functionName": "deepClone",
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "a0000002-0000-0000-0000-000000000004",
"userId": "22222222-2222-2222-2222-222222222222",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "a0200000-0000-0000-0000-000000000002",
"title": "Pick object keys",
"language": "typescript",
"category": "utilities",
"description": "Return a new object with only the specified keys — type-safe alternative to lodash.pick.",
"code": "export function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {\n return Object.fromEntries(\n keys.filter(k => k in obj).map(k => [k, obj[k]])\n ) as Pick<T, K>\n}\n\n// Example\nconst user = { id: 1, name: 'Alice', password: 'secret', role: 'admin' }\nconst safe = pick(user, ['id', 'name', 'role'])\nconsole.log(safe) // { id: 1, name: 'Alice', role: 'admin' }\n",
"functionName": "pick",
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "a0000002-0000-0000-0000-000000000004",
"userId": "22222222-2222-2222-2222-222222222222",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "a0200000-0000-0000-0000-000000000003",
"title": "Format relative time",
"language": "typescript",
"category": "utilities",
"description": "Human-readable relative timestamps using Intl.RelativeTimeFormat — no libraries needed.",
"code": "const UNITS: [Intl.RelativeTimeFormatUnit, number][] = [\n ['year', 365 * 24 * 60 * 60 * 1000],\n ['month', 30 * 24 * 60 * 60 * 1000],\n ['week', 7 * 24 * 60 * 60 * 1000],\n ['day', 24 * 60 * 60 * 1000],\n ['hour', 60 * 60 * 1000],\n ['minute', 60 * 1000],\n ['second', 1000],\n]\n\nconst rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' })\n\nexport function timeAgo(date: Date | number): string {\n const ms = (date instanceof Date ? date.getTime() : date) - Date.now()\n for (const [unit, size] of UNITS) {\n if (Math.abs(ms) >= size || unit === 'second')\n return rtf.format(Math.round(ms / size), unit)\n }\n return 'just now'\n}\n\nconsole.log(timeAgo(Date.now() - 90000)) // '2 minutes ago'\nconsole.log(timeAgo(Date.now() + 86400000)) // 'tomorrow'\n",
"functionName": "timeAgo",
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "a0000002-0000-0000-0000-000000000004",
"userId": "22222222-2222-2222-2222-222222222222",
"tenantId": "pastebin",
"createdAt": 0
}
],
"metadata": { "useCurrentTimestamp": true, "timestampField": "createdAt" }
},
{
"entity": "Snippet",
"version": "1.0",
"description": "alice — CSS Tricks",
"records": [
{
"id": "a0300000-0000-0000-0000-000000000001",
"title": "CSS design tokens (variables)",
"language": "css",
"category": "theming",
"description": "Minimal set of CSS custom properties for a dark/light theme with one class toggle.",
"code": ":root {\n --color-bg: #ffffff;\n --color-surface: #f4f4f5;\n --color-border: #e4e4e7;\n --color-text: #18181b;\n --color-muted: #71717a;\n --color-primary: #7c3aed;\n --color-primary-h: #6d28d9;\n --radius-sm: 4px;\n --radius-md: 8px;\n --radius-lg: 16px;\n --shadow-sm: 0 1px 3px rgba(0,0,0,.08);\n --shadow-md: 0 4px 16px rgba(0,0,0,.12);\n}\n\n[data-theme='dark'] {\n --color-bg: #09090b;\n --color-surface: #18181b;\n --color-border: #27272a;\n --color-text: #fafafa;\n --color-muted: #a1a1aa;\n}\n",
"functionName": null,
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "a0000002-0000-0000-0000-000000000003",
"userId": "22222222-2222-2222-2222-222222222222",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "a0300000-0000-0000-0000-000000000002",
"title": "Responsive auto-fill grid",
"language": "css",
"category": "layout",
"description": "Self-adjusting grid that fills columns as wide as possible without media queries.",
"code": ".grid {\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(min(100%, 280px), 1fr));\n gap: 1.5rem;\n}\n\n/* Masonry-style layout (Chrome 131+) */\n.masonry {\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));\n grid-template-rows: masonry;\n gap: 1rem;\n}\n",
"functionName": null,
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "a0000002-0000-0000-0000-000000000003",
"userId": "22222222-2222-2222-2222-222222222222",
"tenantId": "pastebin",
"createdAt": 0
}
],
"metadata": { "useCurrentTimestamp": true, "timestampField": "createdAt" }
},
{
"entity": "Snippet",
"version": "1.0",
"description": "bob — Bash Scripts",
"records": [
{
"id": "b0100000-0000-0000-0000-000000000001",
"title": "Find large files",
"language": "bash",
"category": "sysadmin",
"description": "List the top-N largest files under a directory, human-readable sizes.",
"code": "#!/usr/bin/env bash\n# Usage: ./large-files.sh [dir] [top-n]\nDIR=${1:-.}\nTOP=${2:-20}\n\nfind \"$DIR\" -type f -printf '%s\\t%p\\n' 2>/dev/null \\\n | sort -rn \\\n | head -\"$TOP\" \\\n | awk '{ printf \"%8.1f MB %s\\n\", $1/1048576, $2 }'\n",
"functionName": null,
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "b0000003-0000-0000-0000-000000000003",
"userId": "33333333-3333-3333-3333-333333333333",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "b0100000-0000-0000-0000-000000000002",
"title": "Git — prune merged branches",
"language": "bash",
"category": "git",
"description": "Delete all local branches that have already been merged into main.",
"code": "#!/usr/bin/env bash\n# Delete local branches merged into main (safe — skips current & main)\ngit fetch --prune\ngit branch --merged main \\\n | grep -Ev '^(\\*|\\s*(main|master|develop)$)' \\\n | xargs -r git branch -d\necho 'Done. Remaining branches:'\ngit branch\n",
"functionName": null,
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "b0000003-0000-0000-0000-000000000003",
"userId": "33333333-3333-3333-3333-333333333333",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "b0100000-0000-0000-0000-000000000003",
"title": "Docker full cleanup",
"language": "bash",
"category": "docker",
"description": "Remove stopped containers, dangling images, unused volumes and networks.",
"code": "#!/usr/bin/env bash\nset -euo pipefail\n\necho '=== Stopping all running containers ==='\ndocker ps -q | xargs -r docker stop\n\necho '=== Removing containers ==='\ndocker ps -aq | xargs -r docker rm\n\necho '=== Removing dangling images ==='\ndocker images -qf dangling=true | xargs -r docker rmi\n\necho '=== Pruning volumes + networks ==='\ndocker volume prune -f\ndocker network prune -f\n\necho '=== Done ==='\ndocker system df\n",
"functionName": null,
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "b0000003-0000-0000-0000-000000000003",
"userId": "33333333-3333-3333-3333-333333333333",
"tenantId": "pastebin",
"createdAt": 0
}
],
"metadata": { "useCurrentTimestamp": true, "timestampField": "createdAt" }
},
{
"entity": "Snippet",
"version": "1.0",
"description": "bob — Go Patterns",
"records": [
{
"id": "b0200000-0000-0000-0000-000000000001",
"title": "Parallel fetch with errgroup",
"language": "go",
"category": "concurrency",
"description": "Fan-out multiple HTTP requests concurrently and collect results; first error cancels the rest.",
"code": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"sync\"\n\n\t\"golang.org/x/sync/errgroup\"\n)\n\nfunc fetchAll(ctx context.Context, urls []string) ([]string, error) {\n\tresults := make([]string, len(urls))\n\tvar mu sync.Mutex\n\tg, ctx := errgroup.WithContext(ctx)\n\n\tfor i, url := range urls {\n\t\ti, url := i, url // capture\n\t\tg.Go(func() error {\n\t\t\treq, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)\n\t\t\tresp, err := http.DefaultClient.Do(req)\n\t\t\tif err != nil { return err }\n\t\t\tdefer resp.Body.Close()\n\t\t\tbody, err := io.ReadAll(resp.Body)\n\t\t\tif err != nil { return err }\n\t\t\tmu.Lock()\n\t\t\tresults[i] = fmt.Sprintf(\"%s: %d bytes\", url, len(body))\n\t\t\tmu.Unlock()\n\t\t\treturn nil\n\t\t})\n\t}\n\treturn results, g.Wait()\n}\n",
"functionName": "fetchAll",
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "b0000003-0000-0000-0000-000000000002",
"userId": "33333333-3333-3333-3333-333333333333",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "b0200000-0000-0000-0000-000000000002",
"title": "Retry with exponential back-off",
"language": "go",
"category": "resilience",
"description": "Generic retry wrapper with configurable attempts and exponential back-off.",
"code": "package retry\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"math\"\n\t\"time\"\n)\n\nvar ErrMaxRetries = errors.New(\"max retries exceeded\")\n\nfunc Do(ctx context.Context, attempts int, base time.Duration, fn func() error) error {\n\tfor i := range attempts {\n\t\tif err := fn(); err == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif i == attempts-1 {\n\t\t\treturn ErrMaxRetries\n\t\t}\n\t\tdelay := base * time.Duration(math.Pow(2, float64(i)))\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-time.After(delay):\n\t\t}\n\t}\n\treturn nil\n}\n",
"functionName": "Do",
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "b0000003-0000-0000-0000-000000000002",
"userId": "33333333-3333-3333-3333-333333333333",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "b0200000-0000-0000-0000-000000000003",
"title": "Generic filter",
"language": "go",
"category": "generics",
"description": "Type-safe filter function using Go generics — returns elements satisfying a predicate.",
"code": "package slices\n\nfunc Filter[T any](s []T, predicate func(T) bool) []T {\n\tout := make([]T, 0, len(s))\n\tfor _, v := range s {\n\t\tif predicate(v) {\n\t\t\tout = append(out, v)\n\t\t}\n\t}\n\treturn out\n}\n\n// Example:\n// evens := Filter([]int{1,2,3,4,5,6}, func(n int) bool { return n%2 == 0 })\n// => [2 4 6]\n",
"functionName": "Filter",
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "b0000003-0000-0000-0000-000000000002",
"userId": "33333333-3333-3333-3333-333333333333",
"tenantId": "pastebin",
"createdAt": 0
}
],
"metadata": { "useCurrentTimestamp": true, "timestampField": "createdAt" }
},
{
"entity": "Snippet",
"version": "1.0",
"description": "bob — API Design",
"records": [
{
"id": "b0300000-0000-0000-0000-000000000001",
"title": "Token bucket rate limiter",
"language": "python",
"category": "middleware",
"description": "Thread-safe in-process token bucket — use as Flask/FastAPI middleware or decorator.",
"code": "import threading\nimport time\n\nclass TokenBucket:\n def __init__(self, capacity: int, refill_rate: float):\n \"\"\"capacity: max tokens; refill_rate: tokens per second.\"\"\"\n self.capacity = capacity\n self.refill_rate = refill_rate\n self._tokens = float(capacity)\n self._last = time.monotonic()\n self._lock = threading.Lock()\n\n def consume(self, n: int = 1) -> bool:\n with self._lock:\n now = time.monotonic()\n self._tokens = min(\n self.capacity,\n self._tokens + (now - self._last) * self.refill_rate\n )\n self._last = now\n if self._tokens >= n:\n self._tokens -= n\n return True\n return False\n\n# Example\nbucket = TokenBucket(capacity=10, refill_rate=2)\nfor i in range(15):\n allowed = bucket.consume()\n print(f'Request {i+1:2d}: {\"OK\" if allowed else \"RATE LIMITED\"}')\n time.sleep(0.1)\n",
"functionName": "TokenBucket",
"entryPoint": "TokenBucket",
"inputParameters": "[{\"name\":\"capacity\",\"type\":\"integer\",\"default\":10,\"label\":\"Capacity\"},{\"name\":\"refill_rate\",\"type\":\"number\",\"default\":2,\"label\":\"Refill rate (req/s)\"}]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "b0000003-0000-0000-0000-000000000004",
"userId": "33333333-3333-3333-3333-333333333333",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "b0300000-0000-0000-0000-000000000002",
"title": "Health check endpoint (Flask)",
"language": "python",
"category": "api",
"description": "Structured /health endpoint that reports database and cache status.",
"code": "from flask import Flask, jsonify\nimport time\n\napp = Flask(__name__)\n\nSTART_TIME = time.time()\n\ndef check_db() -> dict:\n # Replace with a real DB ping\n return {'status': 'ok', 'latency_ms': 1}\n\ndef check_cache() -> dict:\n # Replace with a real cache ping\n return {'status': 'ok', 'latency_ms': 0}\n\n@app.route('/health')\ndef health():\n db = check_db()\n cache = check_cache()\n ok = all(c['status'] == 'ok' for c in [db, cache])\n return jsonify({\n 'status': 'healthy' if ok else 'degraded',\n 'uptime_s': round(time.time() - START_TIME, 1),\n 'checks': {'db': db, 'cache': cache},\n }), 200 if ok else 503\n\nprint('Health endpoint defined at /health')\n",
"functionName": "health",
"entryPoint": "health",
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "b0000003-0000-0000-0000-000000000004",
"userId": "33333333-3333-3333-3333-333333333333",
"tenantId": "pastebin",
"createdAt": 0
}
],
"metadata": { "useCurrentTimestamp": true, "timestampField": "createdAt" }
},
{
"entity": "Snippet",
"version": "1.0",
"description": "playwright — Default namespace snippets",
"records": [
{
"id": "e0100000-0000-0000-0000-000000000001",
"title": "Hello World (Python)",
"language": "python",
"category": "basics",
"description": "Simple hello world for E2E testing.",
"code": "print('Hello, World!')\n",
"functionName": null,
"entryPoint": null,
"inputParameters": "[]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "e0000004-0000-0000-0000-000000000001",
"userId": "44444444-4444-4444-4444-444444444444",
"tenantId": "pastebin",
"createdAt": 0
},
{
"id": "e0100000-0000-0000-0000-000000000002",
"title": "Greeting Function",
"language": "javascript",
"category": "basics",
"description": "A simple greeting function for E2E testing.",
"code": "function greet(name) {\n return `Hello, ${name}!`;\n}\n\nconsole.log(greet('Playwright'));\n",
"functionName": "greet",
"entryPoint": null,
"inputParameters": "[{\"name\":\"name\",\"type\":\"string\",\"default\":\"World\",\"label\":\"Name\"}]",
"hasPreview": false,
"isTemplate": false,
"namespaceId": "e0000004-0000-0000-0000-000000000001",
"userId": "44444444-4444-4444-4444-444444444444",
"tenantId": "pastebin",
"createdAt": 0
}
],
"metadata": { "useCurrentTimestamp": true, "timestampField": "createdAt" }
}
]