SalutefaceAAC's picture
Upload test.jsonl with huggingface_hub
aaae2de verified
Raw History Blame Contribute Delete
12.2 kB
{"language": "java", "library": "okhttp", "error_type": "response_body_not_closed", "error_message": "Socket not closed: response body leaked", "broken_code": "Response response = client.newCall(request).execute();\nif (!response.isSuccessful()) throw new IOException(\"Unexpected: \" + response);\nString body = response.body().string();", "explanation": "The response body must be closed even on error paths to avoid leaking sockets.", "fixed_code": "try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected: \" + response);\n return response.body().string();\n}", "key_insight": "Wrap OkHttp Response in try-with-resources to ensure the body is always closed.", "tags": ["java", "okhttp", "resource-leak"], "id": 149}
{"language": "python", "library": "openai", "error_type": "context_length_exceeded", "error_message": "openai.BadRequestError: maximum context length exceeded", "broken_code": "messages = build_messages(entire_document)\nresp = client.chat.completions.create(model=\"gpt-4o\", messages=messages)", "explanation": "The prompt exceeds the model context window. Chunk the input or summarize earlier context.", "fixed_code": "import tiktoken\nenc = tiktoken.encoding_for_model(\"gpt-4o\")\nMAX_TOKENS = 100_000\n\ndef trim_messages(messages, max_tokens):\n total = sum(len(enc.encode(m[\"content\"])) for m in messages)\n while total > max_tokens and len(messages) > 1:\n removed = messages.pop(1)\n total -= len(enc.encode(removed[\"content\"]))\n return messages\n\nmessages = trim_messages(build_messages(entire_document), MAX_TOKENS)\nresp = client.chat.completions.create(model=\"gpt-4o\", messages=messages)", "key_insight": "Count tokens with tiktoken and trim/chunk the conversation before it exceeds the context window.", "tags": ["openai", "context-length", "tokens"], "id": 150}
{"language": "python", "library": "requests", "error_type": "response_encoding", "error_message": "UnicodeDecodeError when reading resp.text", "broken_code": "resp = requests.get(\"https://api.example.com/data\")\ntext = resp.text # garbage characters", "explanation": "The server sends a non-UTF-8 charset but requests auto-detects it incorrectly.", "fixed_code": "resp = requests.get(\"https://api.example.com/data\")\nresp.encoding = resp.apparent_encoding\ntext = resp.text", "key_insight": "Set resp.encoding = resp.apparent_encoding when server omits or mis-states Content-Type charset.", "tags": ["encoding", "charset"], "id": 151}
{"language": "python", "library": "requests", "error_type": "retry_on_failure", "error_message": "requests.exceptions.ConnectionError on transient failures", "broken_code": "resp = requests.get(\"https://api.example.com/data\") # no retry", "explanation": "Transient network errors cause permanent failures without retry logic.", "fixed_code": "from requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\n\nsession = requests.Session()\nretry = Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503, 504])\nadapter = HTTPAdapter(max_retries=retry)\nsession.mount(\"https://\", adapter)\nresp = session.get(\"https://api.example.com/data\")\nresp.raise_for_status()", "key_insight": "Mount a Retry adapter on a requests.Session to auto-retry on transient errors with exponential backoff.", "tags": ["retry", "resilience", "requests"], "id": 152}
{"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.slack.com/api/chat.postMessage\")", "explanation": "No timeout set on call to slack endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.slack.com/api/chat.postMessage\", timeout=60)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "slack"], "id": 153}
{"language": "javascript", "library": "fetch", "error_type": "no_error_check", "error_message": "Silently receives 4xx/5xx without throwing", "broken_code": "const resp = await fetch(\"https://api.openai.com/v1/embeddings\");\nconst data = await resp.json();", "explanation": "fetch() resolves even on HTTP errors from openai-rest. Status must be checked manually.", "fixed_code": "const resp = await fetch(\"https://api.openai.com/v1/embeddings\");\nif (!resp.ok) throw new Error(`HTTP ${resp.status} from openai-rest`);\nconst data = await resp.json();", "key_insight": "fetch() only rejects on network failure; always check resp.ok for HTTP-level errors.", "tags": ["fetch", "error-handling", "openai-rest"], "id": 154}
{"language": "python", "library": "openai", "error_type": "no_api_key", "error_message": "openai.AuthenticationError: No API key provided", "broken_code": "import openai\nclient = openai.OpenAI()\nresp = client.chat.completions.create(model=\"gpt-4o\", messages=[{\"role\":\"user\",\"content\":\"hi\"}])", "explanation": "The OpenAI client looks for OPENAI_API_KEY env var or explicit key argument.", "fixed_code": "import openai, os\nclient = openai.OpenAI(api_key=os.environ[\"OPENAI_API_KEY\"])\nresp = client.chat.completions.create(model=\"gpt-4o\", messages=[{\"role\":\"user\",\"content\":\"hi\"}])\nprint(resp.choices[0].message.content)", "key_insight": "Set OPENAI_API_KEY in env, or pass api_key= explicitly to the OpenAI client constructor.", "tags": ["openai", "auth", "api-key"], "id": 155}
{"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\")", "explanation": "The twilio API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Bearer {TOKEN}\"}\nresp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "twilio"], "id": 156}
{"language": "python", "library": "openai", "error_type": "embeddings_batch_size", "error_message": "openai.BadRequestError: too many inputs, maximum is 2048", "broken_code": "texts = get_all_documents() # 10000 texts\nresp = client.embeddings.create(model=\"text-embedding-3-small\", input=texts)", "explanation": "The embeddings endpoint limits batch size. Split large lists into chunks.", "fixed_code": "def batch(lst, size):\n for i in range(0, len(lst), size):\n yield lst[i:i+size]\n\nall_embeddings = []\nfor chunk in batch(texts, 100):\n resp = client.embeddings.create(model=\"text-embedding-3-small\", input=chunk)\n all_embeddings.extend([e.embedding for e in resp.data])", "key_insight": "Split embedding requests into batches of \u22642048 texts; process and collect incrementally.", "tags": ["openai", "embeddings", "batch-size"], "id": 157}
{"language": "javascript", "library": "fetch", "error_type": "no_error_check", "error_message": "Silently receives 404/500 without throwing", "broken_code": "const resp = await fetch(\"https://api.example.com/data\");\nconst data = await resp.json();", "explanation": "fetch() only rejects on network failure. HTTP error codes (4xx, 5xx) resolve successfully.", "fixed_code": "const resp = await fetch(\"https://api.example.com/data\");\nif (!resp.ok) {\n throw new Error(`HTTP error: ${resp.status} ${resp.statusText}`);\n}\nconst data = await resp.json();", "key_insight": "Always check resp.ok (or resp.status) after fetch; it resolves on HTTP errors unlike axios.", "tags": ["fetch", "error-handling", "http-status"], "id": 158}
{"language": "java", "library": "okhttp", "error_type": "singleton_client", "error_message": "Too many threads: OkHttpClient created per request", "broken_code": "void makeRequest(String url) {\n OkHttpClient client = new OkHttpClient();\n // ...\n}", "explanation": "Creating a new OkHttpClient per request creates new thread pools each time.", "fixed_code": "private static final OkHttpClient CLIENT = new OkHttpClient.Builder()\n .connectTimeout(10, TimeUnit.SECONDS)\n .readTimeout(30, TimeUnit.SECONDS)\n .build();\n\nvoid makeRequest(String url) {\n // use CLIENT\n}", "key_insight": "Create a single OkHttpClient instance and reuse it; it manages its own connection pool and thread pool.", "tags": ["java", "okhttp", "performance", "singleton"], "id": 159}
{"language": "rest", "library": "generic", "error_type": "cursor_pagination", "error_message": "Offset pagination inconsistency when new items are inserted", "broken_code": "GET /api/posts?page=2&per_page=20\n# New post inserted -> page 2 shifts, item missed or duplicated", "explanation": "Offset-based pagination is unstable when items are inserted or deleted during traversal.", "fixed_code": "GET /api/posts?cursor=eyJpZCI6MTAwfQ&per_page=20\n# Server returns: {\"data\": [...], \"next_cursor\": \"eyJpZCI6ODJ9\"}", "key_insight": "Use cursor-based pagination (keyset) for stable traversal on live data; offset pagination skips/duplicates on mutations.", "tags": ["rest", "pagination", "cursor"], "id": 160}
{"language": "python", "library": "redis", "error_type": "datetime_serialization", "error_message": "TypeError: cannot serialize datetime to JSON", "broken_code": "import json, redis\nr = redis.Redis()\nr.set(\"event\", json.dumps({\"ts\": datetime.utcnow()}))", "explanation": "The standard json module cannot serialize datetime objects.", "fixed_code": "import json, redis\nfrom datetime import datetime, timezone\n\nr = redis.Redis()\n\nclass DateTimeEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, datetime):\n return obj.isoformat()\n return super().default(obj)\n\nr.set(\"event\", json.dumps({\"ts\": datetime.now(timezone.utc)}, cls=DateTimeEncoder))", "key_insight": "Use a custom JSONEncoder or orjson to serialize datetime objects before caching in Redis.", "tags": ["redis", "serialization", "datetime"], "id": 161}
{"language": "python", "library": "requests", "error_type": "session_reuse", "error_message": "Performance: each call opens a new TCP connection", "broken_code": "for url in urls:\n resp = requests.get(url)\n process(resp.json())", "explanation": "Creating a new connection per request is wasteful. Use a Session to reuse connections.", "fixed_code": "with requests.Session() as session:\n for url in urls:\n resp = session.get(url)\n resp.raise_for_status()\n process(resp.json())", "key_insight": "Use requests.Session() to pool TCP connections across multiple requests to the same host.", "tags": ["performance", "session"], "id": 162}
{"language": "python", "library": "anthropic", "error_type": "no_api_key", "error_message": "anthropic.AuthenticationError: invalid x-api-key", "broken_code": "import anthropic\nclient = anthropic.Anthropic()", "explanation": "The Anthropic client reads ANTHROPIC_API_KEY from env; if missing or wrong it raises AuthenticationError.", "fixed_code": "import anthropic, os\nclient = anthropic.Anthropic(api_key=os.environ[\"ANTHROPIC_API_KEY\"])", "key_insight": "Export ANTHROPIC_API_KEY in your shell or pass it explicitly; never hard-code keys in source.", "tags": ["anthropic", "auth"], "id": 163}
{"language": "python", "library": "requests", "error_type": "json_body", "error_message": "415 Unsupported Media Type", "broken_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\", data=payload)", "explanation": "data= sends form-encoded body to mapbox. Use json= for JSON requests.", "fixed_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\", json=payload)\nresp.raise_for_status()", "key_insight": "Use json= not data= to send JSON; requests sets Content-Type automatically.", "tags": ["json", "content-type", "415", "mapbox"], "id": 164}