id
stringlengths 12
12
| task_type
stringclasses 10
values | difficulty
stringclasses 4
values | prompt
stringlengths 227
393
| response
stringclasses 32
values | metadata
dict |
|---|---|---|---|---|---|
pygod_097801
|
bugfix
|
expert
|
Fix a subtle bug in a Python module used for telemetry ingestion.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must include type hints, must be memory-efficient, stdlib-only.
Difficulty: expert. Avoid quadratic behavior on large inputs.
|
Deliverable: implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097802
|
bugfix
|
medium
|
Fix a subtle bug in a Python module used for time series.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: stdlib-only, must be memory-efficient.
Difficulty: medium. Handle empty inputs and malformed records gracefully.
|
Deliverable: production-ready reference solution.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097803
|
bugfix
|
medium
|
Fix a subtle bug in a Python module used for caching layer.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must provide clear error messages, must include tests.
Difficulty: medium. Include a small CLI example if relevant.
|
Deliverable: implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097804
|
bugfix
|
hard
|
Fix a subtle bug in a Python module used for log processing.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must be memory-efficient, must be easy to extend.
Difficulty: hard. Provide helpful exceptions with actionable messages.
|
Deliverable: implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097805
|
bugfix
|
easy
|
Fix a subtle bug in a Python module used for telemetry ingestion.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must avoid global state, must be memory-efficient.
Difficulty: easy. Avoid quadratic behavior on large inputs.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097806
|
bugfix
|
medium
|
Fix a subtle bug in a Python module used for caching layer.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must include docstrings, stdlib-only, must be memory-efficient.
Difficulty: medium. Avoid quadratic behavior on large inputs.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097807
|
bugfix
|
medium
|
Fix a subtle bug in a Python module used for event dispatching.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must handle Windows paths safely, must be streaming-friendly, must include type hints, stdlib-only.
Difficulty: medium. Support both Windows and POSIX paths correctly.
|
Deliverable: production-ready reference solution.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097808
|
bugfix
|
medium
|
Fix a subtle bug in a Python module used for task scheduling.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must be streaming-friendly, must include tests, must provide clear error messages.
Difficulty: medium. Support both Windows and POSIX paths correctly.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097809
|
bugfix
|
easy
|
Fix a subtle bug in a Python module used for telemetry ingestion.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: stdlib-only, must include docstrings, must provide clear error messages.
Difficulty: easy. Include a small CLI example if relevant.
|
Deliverable: production-ready reference solution.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097810
|
bugfix
|
expert
|
Fix a subtle bug in a Python module used for event dispatching.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must include tests, must handle Windows paths safely.
Difficulty: expert. Avoid quadratic behavior on large inputs.
|
Deliverable: API + reference implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097811
|
bugfix
|
medium
|
Fix a subtle bug in a Python module used for validation.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: stdlib-only, must handle Windows paths safely, must include docstrings.
Difficulty: medium. Provide helpful exceptions with actionable messages.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097812
|
bugfix
|
easy
|
Fix a subtle bug in a Python module used for validation.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: stdlib-only, must be streaming-friendly, must handle Windows paths safely, must avoid global state.
Difficulty: easy. Support both Windows and POSIX paths correctly.
|
Deliverable: implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097813
|
bugfix
|
easy
|
Fix a subtle bug in a Python module used for ETL pipelines.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must avoid global state, must include tests.
Difficulty: easy. Avoid quadratic behavior on large inputs.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097814
|
bugfix
|
hard
|
Fix a subtle bug in a Python module used for event dispatching.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must handle Windows paths safely, must avoid global state, must include type hints, must be memory-efficient.
Difficulty: hard. Include a small CLI example if relevant.
|
Deliverable: API + reference implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097815
|
bugfix
|
expert
|
Fix a subtle bug in a Python module used for log processing.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must handle Windows paths safely, must provide clear error messages.
Difficulty: expert. Avoid quadratic behavior on large inputs.
|
Deliverable: implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097816
|
bugfix
|
easy
|
Fix a subtle bug in a Python module used for validation.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must include tests, must handle Windows paths safely, must include type hints, must be streaming-friendly.
Difficulty: easy. Provide helpful exceptions with actionable messages.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097817
|
bugfix
|
expert
|
Fix a subtle bug in a Python module used for caching layer.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must handle Windows paths safely, must avoid global state, must provide clear error messages, must include tests.
Difficulty: expert. Avoid quadratic behavior on large inputs.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097818
|
bugfix
|
medium
|
Fix a subtle bug in a Python module used for configuration loading.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must include tests, must avoid global state, stdlib-only.
Difficulty: medium. Guarantee deterministic output ordering.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097819
|
bugfix
|
expert
|
Fix a subtle bug in a Python module used for file synchronization.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must be streaming-friendly, must include docstrings, must be easy to extend.
Difficulty: expert. Guarantee deterministic output ordering.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097820
|
refactor
|
expert
|
Refactor a Python module used for metrics aggregation into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must be easy to extend, must be memory-efficient, must provide clear error messages.
Difficulty: expert. Handle empty inputs and malformed records gracefully.
|
Deliverable: production-ready reference solution.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097821
|
refactor
|
expert
|
Refactor a Python module used for rate limiting into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must include tests, must handle Windows paths safely.
Difficulty: expert. Guarantee deterministic output ordering.
|
Deliverable: production-ready reference solution.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097822
|
refactor
|
medium
|
Refactor a Python module used for parsing into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must include tests, must avoid global state, must provide clear error messages.
Difficulty: medium. Handle empty inputs and malformed records gracefully.
|
Deliverable: production-ready reference solution.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097823
|
refactor
|
hard
|
Refactor a Python module used for time series into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must handle Windows paths safely, must include docstrings, must be memory-efficient, stdlib-only.
Difficulty: hard. Guarantee deterministic output ordering.
|
Deliverable: implementation + tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097824
|
refactor
|
expert
|
Refactor a Python module used for log processing into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must be streaming-friendly, must avoid global state, must handle Windows paths safely, stdlib-only.
Difficulty: expert. Avoid quadratic behavior on large inputs.
|
Deliverable: production-ready reference solution.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097825
|
refactor
|
expert
|
Refactor a Python module used for time series into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must be memory-efficient, stdlib-only, must include type hints, must be streaming-friendly.
Difficulty: expert. Include a small CLI example if relevant.
|
Deliverable: implementation + tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097826
|
refactor
|
hard
|
Refactor a Python module used for data modeling into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must include tests, must avoid global state.
Difficulty: hard. Handle empty inputs and malformed records gracefully.
|
Deliverable: production-ready reference solution.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097827
|
refactor
|
expert
|
Refactor a Python module used for event dispatching into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must include docstrings, must be easy to extend, must include tests, must avoid global state.
Difficulty: expert. Provide helpful exceptions with actionable messages.
|
Deliverable: API + reference implementation + tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097828
|
refactor
|
medium
|
Refactor a Python module used for log processing into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must handle Windows paths safely, must avoid global state, must be memory-efficient, must include tests.
Difficulty: medium. Include a small CLI example if relevant.
|
Deliverable: corrected code and verification tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097829
|
refactor
|
expert
|
Refactor a Python module used for file synchronization into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must be memory-efficient, must include type hints, must include tests.
Difficulty: expert. Ensure the API is testable via dependency injection.
|
Deliverable: API + reference implementation + tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097830
|
refactor
|
easy
|
Refactor a Python module used for data modeling into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: stdlib-only, must include tests.
Difficulty: easy. Guarantee deterministic output ordering.
|
Deliverable: corrected code and verification tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097831
|
refactor
|
easy
|
Refactor a Python module used for caching layer into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must be memory-efficient, stdlib-only.
Difficulty: easy. Ensure the API is testable via dependency injection.
|
Deliverable: production-ready reference solution.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097832
|
refactor
|
medium
|
Refactor a Python module used for event dispatching into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must handle Windows paths safely, must avoid global state, must include type hints.
Difficulty: medium. Include a small CLI example if relevant.
|
Deliverable: implementation + tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097833
|
refactor
|
medium
|
Refactor a Python module used for configuration loading into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must provide clear error messages, must include type hints, stdlib-only, must be easy to extend.
Difficulty: medium. Avoid quadratic behavior on large inputs.
|
Deliverable: corrected code and verification tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097834
|
refactor
|
easy
|
Refactor a Python module used for metrics aggregation into a clean, extensible design.
Requirements: outline the new architecture briefly, then provide the refactored code and tests.
Constraints: must handle Windows paths safely, must include tests.
Difficulty: easy. Support both Windows and POSIX paths correctly.
|
Deliverable: corrected code and verification tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"architecture",
"clean-code"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097835
|
tests
|
hard
|
Write a thorough test suite for a Python component used for validation.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must handle Windows paths safely, must provide clear error messages.
Difficulty: hard. Handle empty inputs and malformed records gracefully.
|
Deliverable: corrected code and verification tests.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097836
|
tests
|
hard
|
Write a thorough test suite for a Python component used for file synchronization.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must avoid global state, must be streaming-friendly, must be easy to extend.
Difficulty: hard. Avoid quadratic behavior on large inputs.
|
Deliverable: API + reference implementation + tests.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097837
|
tests
|
easy
|
Write a thorough test suite for a Python component used for CLI tooling.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must include docstrings, must include type hints, must avoid global state.
Difficulty: easy. Include a small CLI example if relevant.
|
Deliverable: corrected code and verification tests.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097838
|
tests
|
expert
|
Write a thorough test suite for a Python component used for file synchronization.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must include type hints, stdlib-only, must include docstrings, must handle Windows paths safely.
Difficulty: expert. Provide helpful exceptions with actionable messages.
|
Deliverable: implementation + tests.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097839
|
tests
|
medium
|
Write a thorough test suite for a Python component used for data modeling.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must avoid global state, must handle Windows paths safely, must include docstrings.
Difficulty: medium. Handle empty inputs and malformed records gracefully.
|
Deliverable: production-ready reference solution.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097840
|
tests
|
hard
|
Write a thorough test suite for a Python component used for ETL pipelines.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must include tests, must provide clear error messages, must avoid global state.
Difficulty: hard. Include a small CLI example if relevant.
|
Deliverable: production-ready reference solution.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097841
|
tests
|
medium
|
Write a thorough test suite for a Python component used for parsing.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must be streaming-friendly, must include type hints, must provide clear error messages, must include tests.
Difficulty: medium. Support both Windows and POSIX paths correctly.
|
Deliverable: API + reference implementation + tests.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097842
|
tests
|
hard
|
Write a thorough test suite for a Python component used for CLI tooling.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must be streaming-friendly, must include docstrings.
Difficulty: hard. Avoid quadratic behavior on large inputs.
|
Deliverable: API + reference implementation + tests.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097843
|
tests
|
expert
|
Write a thorough test suite for a Python component used for time series.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must be streaming-friendly, must be memory-efficient, must include docstrings.
Difficulty: expert. Include a small CLI example if relevant.
|
Deliverable: corrected code and verification tests.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097844
|
tests
|
medium
|
Write a thorough test suite for a Python component used for log processing.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must provide clear error messages, must include docstrings, must avoid global state, must handle Windows paths safely.
Difficulty: medium. Avoid quadratic behavior on large inputs.
|
Deliverable: implementation + tests.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097845
|
tests
|
expert
|
Write a thorough test suite for a Python component used for validation.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must be streaming-friendly, must include type hints.
Difficulty: expert. Support both Windows and POSIX paths correctly.
|
Deliverable: implementation + tests.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097846
|
tests
|
hard
|
Write a thorough test suite for a Python component used for configuration loading.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must provide clear error messages, must be streaming-friendly, must be memory-efficient.
Difficulty: hard. Handle empty inputs and malformed records gracefully.
|
Deliverable: production-ready reference solution.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097847
|
tests
|
hard
|
Write a thorough test suite for a Python component used for log processing.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: stdlib-only, must be easy to extend.
Difficulty: hard. Ensure the API is testable via dependency injection.
|
Deliverable: implementation + tests.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097848
|
tests
|
medium
|
Write a thorough test suite for a Python component used for data modeling.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: stdlib-only, must include type hints, must be memory-efficient.
Difficulty: medium. Support both Windows and POSIX paths correctly.
|
Deliverable: API + reference implementation + tests.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097849
|
tests
|
medium
|
Write a thorough test suite for a Python component used for caching layer.
Requirements: cover edge cases, invalid inputs, and behavior invariants.
Constraints: must be memory-efficient, must be streaming-friendly, must provide clear error messages, must be easy to extend.
Difficulty: medium. Support both Windows and POSIX paths correctly.
|
Deliverable: API + reference implementation + tests.
```python
# tests (pytest-style) for a module providing: normalize(), parse_lines(), compute_stats()
import math
import pytest
def test_normalize_idempotent(module_under_test):
x = " A\tB "
assert module_under_test.normalize(module_under_test.normalize(x)) == module_under_test.normalize(x)
def test_parse_lines_rejects_invalid(module_under_test):
with pytest.raises(ValueError):
module_under_test.parse_lines(["", "???", None]) # type: ignore[arg-type]
def test_compute_stats_basic(module_under_test):
data = [1, 2, 3, 4]
s = module_under_test.compute_stats(data)
assert s.count == 4
assert s.total == 10
assert math.isclose(s.mean, 2.5)
```
|
{
"tags": [
"python",
"pytest_style",
"unittesting"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097850
|
algorithms
|
easy
|
Design and implement an algorithm for rate limiting.
Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests.
Constraints: must be easy to extend, must be streaming-friendly, must be memory-efficient.
Difficulty: easy. Include a small CLI example if relevant.
|
Deliverable: implementation + tests.
Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.
Complexity: sorting O(n log n); window maintenance O(n); memory O(k).
```python
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from typing import Iterable, List, Tuple
@dataclass(frozen=True, slots=True)
class Event:
ts: int
value: int
def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:
if window_s < 0:
raise ValueError("window_s must be >= 0")
evs = sorted(events, key=lambda e: e.ts)
q: deque[Event] = deque()
s = 0
out: List[Tuple[int,int]] = []
for e in evs:
q.append(e)
s += e.value
cutoff = e.ts - window_s
while q and q[0].ts < cutoff:
old = q.popleft()
s -= old.value
out.append((e.ts, s))
return out
```
```python
import pytest
from module_under_test import Event, rolling_sum
def test_rolling_sum():
ev = [Event(10,1), Event(11,2), Event(20,5)]
assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]
```
|
{
"tags": [
"python",
"complexity",
"correctness"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097851
|
algorithms
|
hard
|
Design and implement an algorithm for CLI tooling.
Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests.
Constraints: stdlib-only, must handle Windows paths safely.
Difficulty: hard. Guarantee deterministic output ordering.
|
Deliverable: implementation + tests.
Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.
Complexity: sorting O(n log n); window maintenance O(n); memory O(k).
```python
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from typing import Iterable, List, Tuple
@dataclass(frozen=True, slots=True)
class Event:
ts: int
value: int
def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:
if window_s < 0:
raise ValueError("window_s must be >= 0")
evs = sorted(events, key=lambda e: e.ts)
q: deque[Event] = deque()
s = 0
out: List[Tuple[int,int]] = []
for e in evs:
q.append(e)
s += e.value
cutoff = e.ts - window_s
while q and q[0].ts < cutoff:
old = q.popleft()
s -= old.value
out.append((e.ts, s))
return out
```
```python
import pytest
from module_under_test import Event, rolling_sum
def test_rolling_sum():
ev = [Event(10,1), Event(11,2), Event(20,5)]
assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]
```
|
{
"tags": [
"python",
"complexity",
"correctness"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097852
|
algorithms
|
hard
|
Design and implement an algorithm for ETL pipelines.
Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests.
Constraints: must include type hints, must be memory-efficient.
Difficulty: hard. Ensure the API is testable via dependency injection.
|
Deliverable: production-ready reference solution.
Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.
Complexity: sorting O(n log n); window maintenance O(n); memory O(k).
```python
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from typing import Iterable, List, Tuple
@dataclass(frozen=True, slots=True)
class Event:
ts: int
value: int
def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:
if window_s < 0:
raise ValueError("window_s must be >= 0")
evs = sorted(events, key=lambda e: e.ts)
q: deque[Event] = deque()
s = 0
out: List[Tuple[int,int]] = []
for e in evs:
q.append(e)
s += e.value
cutoff = e.ts - window_s
while q and q[0].ts < cutoff:
old = q.popleft()
s -= old.value
out.append((e.ts, s))
return out
```
```python
import pytest
from module_under_test import Event, rolling_sum
def test_rolling_sum():
ev = [Event(10,1), Event(11,2), Event(20,5)]
assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]
```
|
{
"tags": [
"python",
"complexity",
"correctness"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097853
|
algorithms
|
hard
|
Design and implement an algorithm for caching layer.
Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests.
Constraints: must be streaming-friendly, must include tests, must avoid global state.
Difficulty: hard. Handle empty inputs and malformed records gracefully.
|
Deliverable: implementation + tests.
Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.
Complexity: sorting O(n log n); window maintenance O(n); memory O(k).
```python
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from typing import Iterable, List, Tuple
@dataclass(frozen=True, slots=True)
class Event:
ts: int
value: int
def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:
if window_s < 0:
raise ValueError("window_s must be >= 0")
evs = sorted(events, key=lambda e: e.ts)
q: deque[Event] = deque()
s = 0
out: List[Tuple[int,int]] = []
for e in evs:
q.append(e)
s += e.value
cutoff = e.ts - window_s
while q and q[0].ts < cutoff:
old = q.popleft()
s -= old.value
out.append((e.ts, s))
return out
```
```python
import pytest
from module_under_test import Event, rolling_sum
def test_rolling_sum():
ev = [Event(10,1), Event(11,2), Event(20,5)]
assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]
```
|
{
"tags": [
"python",
"complexity",
"correctness"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097854
|
algorithms
|
easy
|
Design and implement an algorithm for time series.
Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests.
Constraints: must include docstrings, stdlib-only, must be easy to extend.
Difficulty: easy. Support both Windows and POSIX paths correctly.
|
Deliverable: implementation + tests.
Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.
Complexity: sorting O(n log n); window maintenance O(n); memory O(k).
```python
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from typing import Iterable, List, Tuple
@dataclass(frozen=True, slots=True)
class Event:
ts: int
value: int
def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:
if window_s < 0:
raise ValueError("window_s must be >= 0")
evs = sorted(events, key=lambda e: e.ts)
q: deque[Event] = deque()
s = 0
out: List[Tuple[int,int]] = []
for e in evs:
q.append(e)
s += e.value
cutoff = e.ts - window_s
while q and q[0].ts < cutoff:
old = q.popleft()
s -= old.value
out.append((e.ts, s))
return out
```
```python
import pytest
from module_under_test import Event, rolling_sum
def test_rolling_sum():
ev = [Event(10,1), Event(11,2), Event(20,5)]
assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]
```
|
{
"tags": [
"python",
"complexity",
"correctness"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097855
|
algorithms
|
expert
|
Design and implement an algorithm for log processing.
Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests.
Constraints: stdlib-only, must avoid global state, must include tests.
Difficulty: expert. Avoid quadratic behavior on large inputs.
|
Deliverable: API + reference implementation + tests.
Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.
Complexity: sorting O(n log n); window maintenance O(n); memory O(k).
```python
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from typing import Iterable, List, Tuple
@dataclass(frozen=True, slots=True)
class Event:
ts: int
value: int
def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:
if window_s < 0:
raise ValueError("window_s must be >= 0")
evs = sorted(events, key=lambda e: e.ts)
q: deque[Event] = deque()
s = 0
out: List[Tuple[int,int]] = []
for e in evs:
q.append(e)
s += e.value
cutoff = e.ts - window_s
while q and q[0].ts < cutoff:
old = q.popleft()
s -= old.value
out.append((e.ts, s))
return out
```
```python
import pytest
from module_under_test import Event, rolling_sum
def test_rolling_sum():
ev = [Event(10,1), Event(11,2), Event(20,5)]
assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]
```
|
{
"tags": [
"python",
"complexity",
"correctness"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097856
|
algorithms
|
easy
|
Design and implement an algorithm for ETL pipelines.
Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests.
Constraints: must be memory-efficient, must provide clear error messages.
Difficulty: easy. Guarantee deterministic output ordering.
|
Deliverable: production-ready reference solution.
Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.
Complexity: sorting O(n log n); window maintenance O(n); memory O(k).
```python
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from typing import Iterable, List, Tuple
@dataclass(frozen=True, slots=True)
class Event:
ts: int
value: int
def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:
if window_s < 0:
raise ValueError("window_s must be >= 0")
evs = sorted(events, key=lambda e: e.ts)
q: deque[Event] = deque()
s = 0
out: List[Tuple[int,int]] = []
for e in evs:
q.append(e)
s += e.value
cutoff = e.ts - window_s
while q and q[0].ts < cutoff:
old = q.popleft()
s -= old.value
out.append((e.ts, s))
return out
```
```python
import pytest
from module_under_test import Event, rolling_sum
def test_rolling_sum():
ev = [Event(10,1), Event(11,2), Event(20,5)]
assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]
```
|
{
"tags": [
"python",
"complexity",
"correctness"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097857
|
algorithms
|
medium
|
Design and implement an algorithm for ETL pipelines.
Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests.
Constraints: stdlib-only, must include tests, must include docstrings.
Difficulty: medium. Ensure the API is testable via dependency injection.
|
Deliverable: API + reference implementation + tests.
Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.
Complexity: sorting O(n log n); window maintenance O(n); memory O(k).
```python
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from typing import Iterable, List, Tuple
@dataclass(frozen=True, slots=True)
class Event:
ts: int
value: int
def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:
if window_s < 0:
raise ValueError("window_s must be >= 0")
evs = sorted(events, key=lambda e: e.ts)
q: deque[Event] = deque()
s = 0
out: List[Tuple[int,int]] = []
for e in evs:
q.append(e)
s += e.value
cutoff = e.ts - window_s
while q and q[0].ts < cutoff:
old = q.popleft()
s -= old.value
out.append((e.ts, s))
return out
```
```python
import pytest
from module_under_test import Event, rolling_sum
def test_rolling_sum():
ev = [Event(10,1), Event(11,2), Event(20,5)]
assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]
```
|
{
"tags": [
"python",
"complexity",
"correctness"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097858
|
algorithms
|
hard
|
Design and implement an algorithm for report generation.
Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests.
Constraints: must provide clear error messages, must be easy to extend, must include type hints.
Difficulty: hard. Ensure the API is testable via dependency injection.
|
Deliverable: production-ready reference solution.
Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.
Complexity: sorting O(n log n); window maintenance O(n); memory O(k).
```python
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from typing import Iterable, List, Tuple
@dataclass(frozen=True, slots=True)
class Event:
ts: int
value: int
def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:
if window_s < 0:
raise ValueError("window_s must be >= 0")
evs = sorted(events, key=lambda e: e.ts)
q: deque[Event] = deque()
s = 0
out: List[Tuple[int,int]] = []
for e in evs:
q.append(e)
s += e.value
cutoff = e.ts - window_s
while q and q[0].ts < cutoff:
old = q.popleft()
s -= old.value
out.append((e.ts, s))
return out
```
```python
import pytest
from module_under_test import Event, rolling_sum
def test_rolling_sum():
ev = [Event(10,1), Event(11,2), Event(20,5)]
assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]
```
|
{
"tags": [
"python",
"complexity",
"correctness"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097859
|
algorithms
|
expert
|
Design and implement an algorithm for CLI tooling.
Requirements: define inputs/outputs, implement solution with complexity analysis, and include tests.
Constraints: must be easy to extend, must be memory-efficient, must handle Windows paths safely.
Difficulty: expert. Ensure the API is testable via dependency injection.
|
Deliverable: corrected code and verification tests.
Problem: compute rolling sums over events (ts:int,value:int) with window W seconds. Events may be out-of-order.
Complexity: sorting O(n log n); window maintenance O(n); memory O(k).
```python
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from typing import Iterable, List, Tuple
@dataclass(frozen=True, slots=True)
class Event:
ts: int
value: int
def rolling_sum(events: Iterable[Event], window_s: int) -> List[Tuple[int,int]]:
if window_s < 0:
raise ValueError("window_s must be >= 0")
evs = sorted(events, key=lambda e: e.ts)
q: deque[Event] = deque()
s = 0
out: List[Tuple[int,int]] = []
for e in evs:
q.append(e)
s += e.value
cutoff = e.ts - window_s
while q and q[0].ts < cutoff:
old = q.popleft()
s -= old.value
out.append((e.ts, s))
return out
```
```python
import pytest
from module_under_test import Event, rolling_sum
def test_rolling_sum():
ev = [Event(10,1), Event(11,2), Event(20,5)]
assert rolling_sum(ev, 5) == [(10,1),(11,3),(20,5)]
```
|
{
"tags": [
"python",
"complexity",
"correctness"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097860
|
typing
|
expert
|
Improve typing and robustness of a Python module used for file synchronization.
Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.
Constraints: stdlib-only, must be memory-efficient, must avoid global state, must provide clear error messages.
Difficulty: expert. Include a small CLI example if relevant.
|
Deliverable: API + reference implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, Iterable, Protocol, TypeVar
T = TypeVar("T")
R = TypeVar("R")
class Mapper(Protocol[T, R]):
def __call__(self, x: T) -> R: ...
@dataclass(frozen=True, slots=True)
class Batch(Generic[T]):
items: tuple[T, ...]
def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:
return Batch(items=tuple(fn(x) for x in batch.items))
def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:
if size <= 0:
raise ValueError("size must be > 0")
buf: list[T] = []
for x in xs:
buf.append(x)
if len(buf) == size:
yield Batch(items=tuple(buf))
buf.clear()
if buf:
yield Batch(items=tuple(buf))
```
```python
import pytest
from module_under_test import Batch, map_batch, chunked
def test_map_batch():
b = Batch(items=(1,2,3))
assert map_batch(b, lambda x: x*2).items == (2,4,6)
def test_chunked():
out = list(chunked([1,2,3,4,5], 2))
assert [b.items for b in out] == [(1,2),(3,4),(5,)]
```
|
{
"tags": [
"python",
"mypy",
"typing"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097861
|
typing
|
expert
|
Improve typing and robustness of a Python module used for telemetry ingestion.
Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.
Constraints: stdlib-only, must be streaming-friendly.
Difficulty: expert. Guarantee deterministic output ordering.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, Iterable, Protocol, TypeVar
T = TypeVar("T")
R = TypeVar("R")
class Mapper(Protocol[T, R]):
def __call__(self, x: T) -> R: ...
@dataclass(frozen=True, slots=True)
class Batch(Generic[T]):
items: tuple[T, ...]
def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:
return Batch(items=tuple(fn(x) for x in batch.items))
def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:
if size <= 0:
raise ValueError("size must be > 0")
buf: list[T] = []
for x in xs:
buf.append(x)
if len(buf) == size:
yield Batch(items=tuple(buf))
buf.clear()
if buf:
yield Batch(items=tuple(buf))
```
```python
import pytest
from module_under_test import Batch, map_batch, chunked
def test_map_batch():
b = Batch(items=(1,2,3))
assert map_batch(b, lambda x: x*2).items == (2,4,6)
def test_chunked():
out = list(chunked([1,2,3,4,5], 2))
assert [b.items for b in out] == [(1,2),(3,4),(5,)]
```
|
{
"tags": [
"python",
"mypy",
"typing"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097862
|
typing
|
expert
|
Improve typing and robustness of a Python module used for task scheduling.
Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.
Constraints: must include docstrings, must include tests, must handle Windows paths safely.
Difficulty: expert. Ensure the API is testable via dependency injection.
|
Deliverable: API + reference implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, Iterable, Protocol, TypeVar
T = TypeVar("T")
R = TypeVar("R")
class Mapper(Protocol[T, R]):
def __call__(self, x: T) -> R: ...
@dataclass(frozen=True, slots=True)
class Batch(Generic[T]):
items: tuple[T, ...]
def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:
return Batch(items=tuple(fn(x) for x in batch.items))
def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:
if size <= 0:
raise ValueError("size must be > 0")
buf: list[T] = []
for x in xs:
buf.append(x)
if len(buf) == size:
yield Batch(items=tuple(buf))
buf.clear()
if buf:
yield Batch(items=tuple(buf))
```
```python
import pytest
from module_under_test import Batch, map_batch, chunked
def test_map_batch():
b = Batch(items=(1,2,3))
assert map_batch(b, lambda x: x*2).items == (2,4,6)
def test_chunked():
out = list(chunked([1,2,3,4,5], 2))
assert [b.items for b in out] == [(1,2),(3,4),(5,)]
```
|
{
"tags": [
"python",
"mypy",
"typing"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097863
|
typing
|
expert
|
Improve typing and robustness of a Python module used for report generation.
Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.
Constraints: must be streaming-friendly, must include tests.
Difficulty: expert. Guarantee deterministic output ordering.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, Iterable, Protocol, TypeVar
T = TypeVar("T")
R = TypeVar("R")
class Mapper(Protocol[T, R]):
def __call__(self, x: T) -> R: ...
@dataclass(frozen=True, slots=True)
class Batch(Generic[T]):
items: tuple[T, ...]
def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:
return Batch(items=tuple(fn(x) for x in batch.items))
def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:
if size <= 0:
raise ValueError("size must be > 0")
buf: list[T] = []
for x in xs:
buf.append(x)
if len(buf) == size:
yield Batch(items=tuple(buf))
buf.clear()
if buf:
yield Batch(items=tuple(buf))
```
```python
import pytest
from module_under_test import Batch, map_batch, chunked
def test_map_batch():
b = Batch(items=(1,2,3))
assert map_batch(b, lambda x: x*2).items == (2,4,6)
def test_chunked():
out = list(chunked([1,2,3,4,5], 2))
assert [b.items for b in out] == [(1,2),(3,4),(5,)]
```
|
{
"tags": [
"python",
"mypy",
"typing"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097864
|
typing
|
medium
|
Improve typing and robustness of a Python module used for rate limiting.
Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.
Constraints: must be easy to extend, must avoid global state, must include type hints, stdlib-only.
Difficulty: medium. Ensure the API is testable via dependency injection.
|
Deliverable: production-ready reference solution.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, Iterable, Protocol, TypeVar
T = TypeVar("T")
R = TypeVar("R")
class Mapper(Protocol[T, R]):
def __call__(self, x: T) -> R: ...
@dataclass(frozen=True, slots=True)
class Batch(Generic[T]):
items: tuple[T, ...]
def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:
return Batch(items=tuple(fn(x) for x in batch.items))
def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:
if size <= 0:
raise ValueError("size must be > 0")
buf: list[T] = []
for x in xs:
buf.append(x)
if len(buf) == size:
yield Batch(items=tuple(buf))
buf.clear()
if buf:
yield Batch(items=tuple(buf))
```
```python
import pytest
from module_under_test import Batch, map_batch, chunked
def test_map_batch():
b = Batch(items=(1,2,3))
assert map_batch(b, lambda x: x*2).items == (2,4,6)
def test_chunked():
out = list(chunked([1,2,3,4,5], 2))
assert [b.items for b in out] == [(1,2),(3,4),(5,)]
```
|
{
"tags": [
"python",
"mypy",
"typing"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097865
|
typing
|
medium
|
Improve typing and robustness of a Python module used for task scheduling.
Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.
Constraints: must avoid global state, must be easy to extend, must include type hints.
Difficulty: medium. Ensure the API is testable via dependency injection.
|
Deliverable: API + reference implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, Iterable, Protocol, TypeVar
T = TypeVar("T")
R = TypeVar("R")
class Mapper(Protocol[T, R]):
def __call__(self, x: T) -> R: ...
@dataclass(frozen=True, slots=True)
class Batch(Generic[T]):
items: tuple[T, ...]
def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:
return Batch(items=tuple(fn(x) for x in batch.items))
def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:
if size <= 0:
raise ValueError("size must be > 0")
buf: list[T] = []
for x in xs:
buf.append(x)
if len(buf) == size:
yield Batch(items=tuple(buf))
buf.clear()
if buf:
yield Batch(items=tuple(buf))
```
```python
import pytest
from module_under_test import Batch, map_batch, chunked
def test_map_batch():
b = Batch(items=(1,2,3))
assert map_batch(b, lambda x: x*2).items == (2,4,6)
def test_chunked():
out = list(chunked([1,2,3,4,5], 2))
assert [b.items for b in out] == [(1,2),(3,4),(5,)]
```
|
{
"tags": [
"python",
"mypy",
"typing"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097866
|
typing
|
hard
|
Improve typing and robustness of a Python module used for metrics aggregation.
Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.
Constraints: must be easy to extend, stdlib-only, must include docstrings.
Difficulty: hard. Support both Windows and POSIX paths correctly.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, Iterable, Protocol, TypeVar
T = TypeVar("T")
R = TypeVar("R")
class Mapper(Protocol[T, R]):
def __call__(self, x: T) -> R: ...
@dataclass(frozen=True, slots=True)
class Batch(Generic[T]):
items: tuple[T, ...]
def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:
return Batch(items=tuple(fn(x) for x in batch.items))
def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:
if size <= 0:
raise ValueError("size must be > 0")
buf: list[T] = []
for x in xs:
buf.append(x)
if len(buf) == size:
yield Batch(items=tuple(buf))
buf.clear()
if buf:
yield Batch(items=tuple(buf))
```
```python
import pytest
from module_under_test import Batch, map_batch, chunked
def test_map_batch():
b = Batch(items=(1,2,3))
assert map_batch(b, lambda x: x*2).items == (2,4,6)
def test_chunked():
out = list(chunked([1,2,3,4,5], 2))
assert [b.items for b in out] == [(1,2),(3,4),(5,)]
```
|
{
"tags": [
"python",
"mypy",
"typing"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097867
|
typing
|
hard
|
Improve typing and robustness of a Python module used for caching layer.
Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.
Constraints: stdlib-only, must include docstrings, must be streaming-friendly, must include tests.
Difficulty: hard. Provide helpful exceptions with actionable messages.
|
Deliverable: production-ready reference solution.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, Iterable, Protocol, TypeVar
T = TypeVar("T")
R = TypeVar("R")
class Mapper(Protocol[T, R]):
def __call__(self, x: T) -> R: ...
@dataclass(frozen=True, slots=True)
class Batch(Generic[T]):
items: tuple[T, ...]
def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:
return Batch(items=tuple(fn(x) for x in batch.items))
def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:
if size <= 0:
raise ValueError("size must be > 0")
buf: list[T] = []
for x in xs:
buf.append(x)
if len(buf) == size:
yield Batch(items=tuple(buf))
buf.clear()
if buf:
yield Batch(items=tuple(buf))
```
```python
import pytest
from module_under_test import Batch, map_batch, chunked
def test_map_batch():
b = Batch(items=(1,2,3))
assert map_batch(b, lambda x: x*2).items == (2,4,6)
def test_chunked():
out = list(chunked([1,2,3,4,5], 2))
assert [b.items for b in out] == [(1,2),(3,4),(5,)]
```
|
{
"tags": [
"python",
"mypy",
"typing"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097868
|
typing
|
expert
|
Improve typing and robustness of a Python module used for event dispatching.
Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.
Constraints: must be easy to extend, must be memory-efficient.
Difficulty: expert. Support both Windows and POSIX paths correctly.
|
Deliverable: implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, Iterable, Protocol, TypeVar
T = TypeVar("T")
R = TypeVar("R")
class Mapper(Protocol[T, R]):
def __call__(self, x: T) -> R: ...
@dataclass(frozen=True, slots=True)
class Batch(Generic[T]):
items: tuple[T, ...]
def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:
return Batch(items=tuple(fn(x) for x in batch.items))
def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:
if size <= 0:
raise ValueError("size must be > 0")
buf: list[T] = []
for x in xs:
buf.append(x)
if len(buf) == size:
yield Batch(items=tuple(buf))
buf.clear()
if buf:
yield Batch(items=tuple(buf))
```
```python
import pytest
from module_under_test import Batch, map_batch, chunked
def test_map_batch():
b = Batch(items=(1,2,3))
assert map_batch(b, lambda x: x*2).items == (2,4,6)
def test_chunked():
out = list(chunked([1,2,3,4,5], 2))
assert [b.items for b in out] == [(1,2),(3,4),(5,)]
```
|
{
"tags": [
"python",
"mypy",
"typing"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097869
|
typing
|
expert
|
Improve typing and robustness of a Python module used for ETL pipelines.
Requirements: provide type-safe APIs (generics/protocols where appropriate) and include tests.
Constraints: must include type hints, must avoid global state, must be memory-efficient.
Difficulty: expert. Handle empty inputs and malformed records gracefully.
|
Deliverable: production-ready reference solution.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, Iterable, Protocol, TypeVar
T = TypeVar("T")
R = TypeVar("R")
class Mapper(Protocol[T, R]):
def __call__(self, x: T) -> R: ...
@dataclass(frozen=True, slots=True)
class Batch(Generic[T]):
items: tuple[T, ...]
def map_batch(batch: Batch[T], fn: Mapper[T, R]) -> Batch[R]:
return Batch(items=tuple(fn(x) for x in batch.items))
def chunked(xs: Iterable[T], size: int) -> Iterable[Batch[T]]:
if size <= 0:
raise ValueError("size must be > 0")
buf: list[T] = []
for x in xs:
buf.append(x)
if len(buf) == size:
yield Batch(items=tuple(buf))
buf.clear()
if buf:
yield Batch(items=tuple(buf))
```
```python
import pytest
from module_under_test import Batch, map_batch, chunked
def test_map_batch():
b = Batch(items=(1,2,3))
assert map_batch(b, lambda x: x*2).items == (2,4,6)
def test_chunked():
out = list(chunked([1,2,3,4,5], 2))
assert [b.items for b in out] == [(1,2),(3,4),(5,)]
```
|
{
"tags": [
"python",
"mypy",
"typing"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097870
|
performance
|
hard
|
Optimize a Python workflow for rate limiting.
Requirements: provide an optimized implementation and a small benchmark harness.
Constraints: must include tests, must handle Windows paths safely.
Difficulty: hard. Ensure the API is testable via dependency injection.
|
Deliverable: production-ready reference solution.
Strategy:
- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import time
@dataclass(frozen=True, slots=True)
class Stats:
count: int
total: int
def compute_stats_stream(values: Iterable[int]) -> Stats:
c = 0
t = 0
for v in values:
c += 1
t += v
return Stats(c, t)
def bench(n: int = 1_000_00) -> float:
data = range(n)
t0 = time.perf_counter()
_ = compute_stats_stream(data)
return time.perf_counter() - t0
```
```python
from module_under_test import bench
def test_bench_runs_fast_enough():
# Sanity: should run quickly on typical machines; adjust threshold for CI.
assert bench(50_000) < 0.5
```
|
{
"tags": [
"python",
"profiling",
"optimization"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097871
|
performance
|
easy
|
Optimize a Python workflow for telemetry ingestion.
Requirements: provide an optimized implementation and a small benchmark harness.
Constraints: must include type hints, must handle Windows paths safely.
Difficulty: easy. Support both Windows and POSIX paths correctly.
|
Deliverable: API + reference implementation + tests.
Strategy:
- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import time
@dataclass(frozen=True, slots=True)
class Stats:
count: int
total: int
def compute_stats_stream(values: Iterable[int]) -> Stats:
c = 0
t = 0
for v in values:
c += 1
t += v
return Stats(c, t)
def bench(n: int = 1_000_00) -> float:
data = range(n)
t0 = time.perf_counter()
_ = compute_stats_stream(data)
return time.perf_counter() - t0
```
```python
from module_under_test import bench
def test_bench_runs_fast_enough():
# Sanity: should run quickly on typical machines; adjust threshold for CI.
assert bench(50_000) < 0.5
```
|
{
"tags": [
"python",
"profiling",
"optimization"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097872
|
performance
|
expert
|
Optimize a Python workflow for file synchronization.
Requirements: provide an optimized implementation and a small benchmark harness.
Constraints: must include type hints, must be memory-efficient, must be easy to extend.
Difficulty: expert. Support both Windows and POSIX paths correctly.
|
Deliverable: corrected code and verification tests.
Strategy:
- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import time
@dataclass(frozen=True, slots=True)
class Stats:
count: int
total: int
def compute_stats_stream(values: Iterable[int]) -> Stats:
c = 0
t = 0
for v in values:
c += 1
t += v
return Stats(c, t)
def bench(n: int = 1_000_00) -> float:
data = range(n)
t0 = time.perf_counter()
_ = compute_stats_stream(data)
return time.perf_counter() - t0
```
```python
from module_under_test import bench
def test_bench_runs_fast_enough():
# Sanity: should run quickly on typical machines; adjust threshold for CI.
assert bench(50_000) < 0.5
```
|
{
"tags": [
"python",
"profiling",
"optimization"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097873
|
performance
|
easy
|
Optimize a Python workflow for configuration loading.
Requirements: provide an optimized implementation and a small benchmark harness.
Constraints: must include tests, must handle Windows paths safely, must include docstrings, must include type hints.
Difficulty: easy. Handle empty inputs and malformed records gracefully.
|
Deliverable: production-ready reference solution.
Strategy:
- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import time
@dataclass(frozen=True, slots=True)
class Stats:
count: int
total: int
def compute_stats_stream(values: Iterable[int]) -> Stats:
c = 0
t = 0
for v in values:
c += 1
t += v
return Stats(c, t)
def bench(n: int = 1_000_00) -> float:
data = range(n)
t0 = time.perf_counter()
_ = compute_stats_stream(data)
return time.perf_counter() - t0
```
```python
from module_under_test import bench
def test_bench_runs_fast_enough():
# Sanity: should run quickly on typical machines; adjust threshold for CI.
assert bench(50_000) < 0.5
```
|
{
"tags": [
"python",
"profiling",
"optimization"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097874
|
performance
|
easy
|
Optimize a Python workflow for time series.
Requirements: provide an optimized implementation and a small benchmark harness.
Constraints: must handle Windows paths safely, must be streaming-friendly, must include docstrings.
Difficulty: easy. Guarantee deterministic output ordering.
|
Deliverable: implementation + tests.
Strategy:
- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import time
@dataclass(frozen=True, slots=True)
class Stats:
count: int
total: int
def compute_stats_stream(values: Iterable[int]) -> Stats:
c = 0
t = 0
for v in values:
c += 1
t += v
return Stats(c, t)
def bench(n: int = 1_000_00) -> float:
data = range(n)
t0 = time.perf_counter()
_ = compute_stats_stream(data)
return time.perf_counter() - t0
```
```python
from module_under_test import bench
def test_bench_runs_fast_enough():
# Sanity: should run quickly on typical machines; adjust threshold for CI.
assert bench(50_000) < 0.5
```
|
{
"tags": [
"python",
"profiling",
"optimization"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097875
|
performance
|
expert
|
Optimize a Python workflow for time series.
Requirements: provide an optimized implementation and a small benchmark harness.
Constraints: must include type hints, must be easy to extend.
Difficulty: expert. Avoid quadratic behavior on large inputs.
|
Deliverable: API + reference implementation + tests.
Strategy:
- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import time
@dataclass(frozen=True, slots=True)
class Stats:
count: int
total: int
def compute_stats_stream(values: Iterable[int]) -> Stats:
c = 0
t = 0
for v in values:
c += 1
t += v
return Stats(c, t)
def bench(n: int = 1_000_00) -> float:
data = range(n)
t0 = time.perf_counter()
_ = compute_stats_stream(data)
return time.perf_counter() - t0
```
```python
from module_under_test import bench
def test_bench_runs_fast_enough():
# Sanity: should run quickly on typical machines; adjust threshold for CI.
assert bench(50_000) < 0.5
```
|
{
"tags": [
"python",
"profiling",
"optimization"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097876
|
performance
|
expert
|
Optimize a Python workflow for log processing.
Requirements: provide an optimized implementation and a small benchmark harness.
Constraints: must be memory-efficient, must provide clear error messages, must be easy to extend.
Difficulty: expert. Ensure the API is testable via dependency injection.
|
Deliverable: implementation + tests.
Strategy:
- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import time
@dataclass(frozen=True, slots=True)
class Stats:
count: int
total: int
def compute_stats_stream(values: Iterable[int]) -> Stats:
c = 0
t = 0
for v in values:
c += 1
t += v
return Stats(c, t)
def bench(n: int = 1_000_00) -> float:
data = range(n)
t0 = time.perf_counter()
_ = compute_stats_stream(data)
return time.perf_counter() - t0
```
```python
from module_under_test import bench
def test_bench_runs_fast_enough():
# Sanity: should run quickly on typical machines; adjust threshold for CI.
assert bench(50_000) < 0.5
```
|
{
"tags": [
"python",
"profiling",
"optimization"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097877
|
performance
|
medium
|
Optimize a Python workflow for report generation.
Requirements: provide an optimized implementation and a small benchmark harness.
Constraints: stdlib-only, must include type hints.
Difficulty: medium. Support both Windows and POSIX paths correctly.
|
Deliverable: implementation + tests.
Strategy:
- Avoid repeated parsing; precompile regex if needed; use local variables; stream processing.
```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import time
@dataclass(frozen=True, slots=True)
class Stats:
count: int
total: int
def compute_stats_stream(values: Iterable[int]) -> Stats:
c = 0
t = 0
for v in values:
c += 1
t += v
return Stats(c, t)
def bench(n: int = 1_000_00) -> float:
data = range(n)
t0 = time.perf_counter()
_ = compute_stats_stream(data)
return time.perf_counter() - t0
```
```python
from module_under_test import bench
def test_bench_runs_fast_enough():
# Sanity: should run quickly on typical machines; adjust threshold for CI.
assert bench(50_000) < 0.5
```
|
{
"tags": [
"python",
"profiling",
"optimization"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097878
|
concurrency
|
hard
|
Implement a concurrent Python solution for rate limiting.
Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.
Constraints: must include docstrings, must provide clear error messages, must handle Windows paths safely, must be streaming-friendly.
Difficulty: hard. Avoid quadratic behavior on large inputs.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
import asyncio
from dataclasses import dataclass
from typing import Awaitable, Callable, Iterable, Optional
@dataclass(frozen=True, slots=True)
class JobResult:
ok: bool
value: Optional[int]
error: Optional[str]
async def run_bounded(
factories: Iterable[Callable[[], Awaitable[int]]],
*,
limit: int = 10,
timeout_s: float = 5.0,
) -> list[JobResult]:
if limit <= 0:
raise ValueError("limit must be > 0")
sem = asyncio.Semaphore(limit)
results: list[JobResult] = []
async def one(factory: Callable[[], Awaitable[int]]) -> None:
async with sem:
try:
v = await asyncio.wait_for(factory(), timeout=timeout_s)
results.append(JobResult(True, v, None))
except Exception as e:
results.append(JobResult(False, None, str(e)))
tasks = [asyncio.create_task(one(f)) for f in factories]
try:
await asyncio.gather(*tasks)
finally:
for t in tasks:
if not t.done():
t.cancel()
return results
```
```python
import asyncio
import pytest
from module_under_test import run_bounded
@pytest.mark.asyncio
async def test_run_bounded_collects():
async def work(x: int) -> int:
await asyncio.sleep(0.01)
return x
fs = [(lambda i=i: work(i)) for i in range(30)]
out = await run_bounded(fs, limit=5, timeout_s=1.0)
assert len(out) == 30
assert all(r.ok for r in out)
```
|
{
"tags": [
"python",
"asyncio",
"threading"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097879
|
concurrency
|
hard
|
Implement a concurrent Python solution for caching layer.
Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.
Constraints: must be streaming-friendly, must include tests.
Difficulty: hard. Include a small CLI example if relevant.
|
Deliverable: implementation + tests.
```python
from __future__ import annotations
import asyncio
from dataclasses import dataclass
from typing import Awaitable, Callable, Iterable, Optional
@dataclass(frozen=True, slots=True)
class JobResult:
ok: bool
value: Optional[int]
error: Optional[str]
async def run_bounded(
factories: Iterable[Callable[[], Awaitable[int]]],
*,
limit: int = 10,
timeout_s: float = 5.0,
) -> list[JobResult]:
if limit <= 0:
raise ValueError("limit must be > 0")
sem = asyncio.Semaphore(limit)
results: list[JobResult] = []
async def one(factory: Callable[[], Awaitable[int]]) -> None:
async with sem:
try:
v = await asyncio.wait_for(factory(), timeout=timeout_s)
results.append(JobResult(True, v, None))
except Exception as e:
results.append(JobResult(False, None, str(e)))
tasks = [asyncio.create_task(one(f)) for f in factories]
try:
await asyncio.gather(*tasks)
finally:
for t in tasks:
if not t.done():
t.cancel()
return results
```
```python
import asyncio
import pytest
from module_under_test import run_bounded
@pytest.mark.asyncio
async def test_run_bounded_collects():
async def work(x: int) -> int:
await asyncio.sleep(0.01)
return x
fs = [(lambda i=i: work(i)) for i in range(30)]
out = await run_bounded(fs, limit=5, timeout_s=1.0)
assert len(out) == 30
assert all(r.ok for r in out)
```
|
{
"tags": [
"python",
"asyncio",
"threading"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097880
|
concurrency
|
medium
|
Implement a concurrent Python solution for task scheduling.
Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.
Constraints: must be streaming-friendly, must handle Windows paths safely.
Difficulty: medium. Support both Windows and POSIX paths correctly.
|
Deliverable: implementation + tests.
```python
from __future__ import annotations
import asyncio
from dataclasses import dataclass
from typing import Awaitable, Callable, Iterable, Optional
@dataclass(frozen=True, slots=True)
class JobResult:
ok: bool
value: Optional[int]
error: Optional[str]
async def run_bounded(
factories: Iterable[Callable[[], Awaitable[int]]],
*,
limit: int = 10,
timeout_s: float = 5.0,
) -> list[JobResult]:
if limit <= 0:
raise ValueError("limit must be > 0")
sem = asyncio.Semaphore(limit)
results: list[JobResult] = []
async def one(factory: Callable[[], Awaitable[int]]) -> None:
async with sem:
try:
v = await asyncio.wait_for(factory(), timeout=timeout_s)
results.append(JobResult(True, v, None))
except Exception as e:
results.append(JobResult(False, None, str(e)))
tasks = [asyncio.create_task(one(f)) for f in factories]
try:
await asyncio.gather(*tasks)
finally:
for t in tasks:
if not t.done():
t.cancel()
return results
```
```python
import asyncio
import pytest
from module_under_test import run_bounded
@pytest.mark.asyncio
async def test_run_bounded_collects():
async def work(x: int) -> int:
await asyncio.sleep(0.01)
return x
fs = [(lambda i=i: work(i)) for i in range(30)]
out = await run_bounded(fs, limit=5, timeout_s=1.0)
assert len(out) == 30
assert all(r.ok for r in out)
```
|
{
"tags": [
"python",
"asyncio",
"threading"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097881
|
concurrency
|
expert
|
Implement a concurrent Python solution for file synchronization.
Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.
Constraints: must be streaming-friendly, must include tests.
Difficulty: expert. Support both Windows and POSIX paths correctly.
|
Deliverable: production-ready reference solution.
```python
from __future__ import annotations
import asyncio
from dataclasses import dataclass
from typing import Awaitable, Callable, Iterable, Optional
@dataclass(frozen=True, slots=True)
class JobResult:
ok: bool
value: Optional[int]
error: Optional[str]
async def run_bounded(
factories: Iterable[Callable[[], Awaitable[int]]],
*,
limit: int = 10,
timeout_s: float = 5.0,
) -> list[JobResult]:
if limit <= 0:
raise ValueError("limit must be > 0")
sem = asyncio.Semaphore(limit)
results: list[JobResult] = []
async def one(factory: Callable[[], Awaitable[int]]) -> None:
async with sem:
try:
v = await asyncio.wait_for(factory(), timeout=timeout_s)
results.append(JobResult(True, v, None))
except Exception as e:
results.append(JobResult(False, None, str(e)))
tasks = [asyncio.create_task(one(f)) for f in factories]
try:
await asyncio.gather(*tasks)
finally:
for t in tasks:
if not t.done():
t.cancel()
return results
```
```python
import asyncio
import pytest
from module_under_test import run_bounded
@pytest.mark.asyncio
async def test_run_bounded_collects():
async def work(x: int) -> int:
await asyncio.sleep(0.01)
return x
fs = [(lambda i=i: work(i)) for i in range(30)]
out = await run_bounded(fs, limit=5, timeout_s=1.0)
assert len(out) == 30
assert all(r.ok for r in out)
```
|
{
"tags": [
"python",
"asyncio",
"threading"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097882
|
concurrency
|
hard
|
Implement a concurrent Python solution for log processing.
Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.
Constraints: must avoid global state, must handle Windows paths safely, must include docstrings.
Difficulty: hard. Ensure the API is testable via dependency injection.
|
Deliverable: API + reference implementation + tests.
```python
from __future__ import annotations
import asyncio
from dataclasses import dataclass
from typing import Awaitable, Callable, Iterable, Optional
@dataclass(frozen=True, slots=True)
class JobResult:
ok: bool
value: Optional[int]
error: Optional[str]
async def run_bounded(
factories: Iterable[Callable[[], Awaitable[int]]],
*,
limit: int = 10,
timeout_s: float = 5.0,
) -> list[JobResult]:
if limit <= 0:
raise ValueError("limit must be > 0")
sem = asyncio.Semaphore(limit)
results: list[JobResult] = []
async def one(factory: Callable[[], Awaitable[int]]) -> None:
async with sem:
try:
v = await asyncio.wait_for(factory(), timeout=timeout_s)
results.append(JobResult(True, v, None))
except Exception as e:
results.append(JobResult(False, None, str(e)))
tasks = [asyncio.create_task(one(f)) for f in factories]
try:
await asyncio.gather(*tasks)
finally:
for t in tasks:
if not t.done():
t.cancel()
return results
```
```python
import asyncio
import pytest
from module_under_test import run_bounded
@pytest.mark.asyncio
async def test_run_bounded_collects():
async def work(x: int) -> int:
await asyncio.sleep(0.01)
return x
fs = [(lambda i=i: work(i)) for i in range(30)]
out = await run_bounded(fs, limit=5, timeout_s=1.0)
assert len(out) == 30
assert all(r.ok for r in out)
```
|
{
"tags": [
"python",
"asyncio",
"threading"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097883
|
concurrency
|
expert
|
Implement a concurrent Python solution for file synchronization.
Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.
Constraints: must be streaming-friendly, must include docstrings, must be easy to extend, must include type hints.
Difficulty: expert. Provide helpful exceptions with actionable messages.
|
Deliverable: production-ready reference solution.
```python
from __future__ import annotations
import asyncio
from dataclasses import dataclass
from typing import Awaitable, Callable, Iterable, Optional
@dataclass(frozen=True, slots=True)
class JobResult:
ok: bool
value: Optional[int]
error: Optional[str]
async def run_bounded(
factories: Iterable[Callable[[], Awaitable[int]]],
*,
limit: int = 10,
timeout_s: float = 5.0,
) -> list[JobResult]:
if limit <= 0:
raise ValueError("limit must be > 0")
sem = asyncio.Semaphore(limit)
results: list[JobResult] = []
async def one(factory: Callable[[], Awaitable[int]]) -> None:
async with sem:
try:
v = await asyncio.wait_for(factory(), timeout=timeout_s)
results.append(JobResult(True, v, None))
except Exception as e:
results.append(JobResult(False, None, str(e)))
tasks = [asyncio.create_task(one(f)) for f in factories]
try:
await asyncio.gather(*tasks)
finally:
for t in tasks:
if not t.done():
t.cancel()
return results
```
```python
import asyncio
import pytest
from module_under_test import run_bounded
@pytest.mark.asyncio
async def test_run_bounded_collects():
async def work(x: int) -> int:
await asyncio.sleep(0.01)
return x
fs = [(lambda i=i: work(i)) for i in range(30)]
out = await run_bounded(fs, limit=5, timeout_s=1.0)
assert len(out) == 30
assert all(r.ok for r in out)
```
|
{
"tags": [
"python",
"asyncio",
"threading"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097884
|
concurrency
|
medium
|
Implement a concurrent Python solution for parsing.
Requirements: choose appropriate concurrency model, handle cancellation/timeouts, include tests.
Constraints: must be memory-efficient, must include type hints.
Difficulty: medium. Include a small CLI example if relevant.
|
Deliverable: API + reference implementation + tests.
```python
from __future__ import annotations
import asyncio
from dataclasses import dataclass
from typing import Awaitable, Callable, Iterable, Optional
@dataclass(frozen=True, slots=True)
class JobResult:
ok: bool
value: Optional[int]
error: Optional[str]
async def run_bounded(
factories: Iterable[Callable[[], Awaitable[int]]],
*,
limit: int = 10,
timeout_s: float = 5.0,
) -> list[JobResult]:
if limit <= 0:
raise ValueError("limit must be > 0")
sem = asyncio.Semaphore(limit)
results: list[JobResult] = []
async def one(factory: Callable[[], Awaitable[int]]) -> None:
async with sem:
try:
v = await asyncio.wait_for(factory(), timeout=timeout_s)
results.append(JobResult(True, v, None))
except Exception as e:
results.append(JobResult(False, None, str(e)))
tasks = [asyncio.create_task(one(f)) for f in factories]
try:
await asyncio.gather(*tasks)
finally:
for t in tasks:
if not t.done():
t.cancel()
return results
```
```python
import asyncio
import pytest
from module_under_test import run_bounded
@pytest.mark.asyncio
async def test_run_bounded_collects():
async def work(x: int) -> int:
await asyncio.sleep(0.01)
return x
fs = [(lambda i=i: work(i)) for i in range(30)]
out = await run_bounded(fs, limit=5, timeout_s=1.0)
assert len(out) == 30
assert all(r.ok for r in out)
```
|
{
"tags": [
"python",
"asyncio",
"threading"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097885
|
api_design
|
medium
|
Design a small, production-grade Python API for rate limiting.
Requirements: define data models and interfaces, implement reference version, include tests.
Constraints: must avoid global state, must handle Windows paths safely, must be easy to extend, must include type hints.
Difficulty: medium. Guarantee deterministic output ordering.
|
Deliverable: implementation + tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"interfaces",
"dataclasses"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097886
|
api_design
|
medium
|
Design a small, production-grade Python API for report generation.
Requirements: define data models and interfaces, implement reference version, include tests.
Constraints: must be easy to extend, must include tests, must include type hints.
Difficulty: medium. Include a small CLI example if relevant.
|
Deliverable: corrected code and verification tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"interfaces",
"dataclasses"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097887
|
api_design
|
easy
|
Design a small, production-grade Python API for CLI tooling.
Requirements: define data models and interfaces, implement reference version, include tests.
Constraints: must avoid global state, must be easy to extend, must provide clear error messages, must include type hints.
Difficulty: easy. Avoid quadratic behavior on large inputs.
|
Deliverable: production-ready reference solution.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"interfaces",
"dataclasses"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097888
|
api_design
|
medium
|
Design a small, production-grade Python API for caching layer.
Requirements: define data models and interfaces, implement reference version, include tests.
Constraints: must be streaming-friendly, must include tests, must include docstrings, must avoid global state.
Difficulty: medium. Support both Windows and POSIX paths correctly.
|
Deliverable: API + reference implementation + tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"interfaces",
"dataclasses"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097889
|
api_design
|
hard
|
Design a small, production-grade Python API for event dispatching.
Requirements: define data models and interfaces, implement reference version, include tests.
Constraints: must be memory-efficient, must be streaming-friendly.
Difficulty: hard. Provide helpful exceptions with actionable messages.
|
Deliverable: implementation + tests.
Architecture:
- Public facade class coordinating concerns (parsing, validation, persistence)
- Small pure functions for testability
- No global state; dependency injection for filesystem I/O
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Protocol, Iterable
import json
class Store(Protocol):
def write_text(self, path: Path, data: str) -> None: ...
class FSStore:
def write_text(self, path: Path, data: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data, encoding="utf-8")
@dataclass(frozen=True, slots=True)
class Item:
name: str
qty: int
def parse_items(lines: Iterable[str]) -> list[Item]:
out: list[Item] = []
for i, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
obj = json.loads(s)
if not isinstance(obj, dict):
raise ValueError(f"line {i}: expected object")
name = obj.get("name")
qty = obj.get("qty")
if not isinstance(name, str) or not name:
raise ValueError(f"line {i}: name must be str")
if not isinstance(qty, int) or qty < 0:
raise ValueError(f"line {i}: qty must be non-negative int")
out.append(Item(name, qty))
return out
class InventoryWriter:
def __init__(self, base_dir: Path, store: Store | None = None) -> None:
self._base = base_dir
self._store: Store = store or FSStore()
def write(self, rel_path: str, items: list[Item]) -> Path:
dst = (self._base / rel_path).resolve()
base = self._base.resolve()
if dst != base and base not in dst.parents:
raise ValueError("unsafe path traversal")
payload = json.dumps([item.__dict__ for item in items], ensure_ascii=False)
self._store.write_text(dst, payload)
return dst
```
```python
import json
from pathlib import Path
import pytest
from module_under_test import InventoryWriter, parse_items
def test_parse_items_valid():
lines = [json.dumps({"name":"x","qty":1})]
assert parse_items(lines)[0].name == "x"
def test_writer_blocks_traversal(tmp_path: Path):
w = InventoryWriter(tmp_path)
with pytest.raises(ValueError):
w.write("../evil.json", [])
```
|
{
"tags": [
"python",
"interfaces",
"dataclasses"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097890
|
packaging
|
expert
|
Create a small, production-ready Python package for event dispatching.
Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml.
Constraints: must be memory-efficient, must avoid global state, stdlib-only.
Difficulty: expert. Avoid quadratic behavior on large inputs.
|
Deliverable: production-ready reference solution.
Package layout:
- mypkg/core.py
- mypkg/cli.py
- pyproject.toml
```python
# mypkg/core.py
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import logging
log = logging.getLogger(__name__)
@dataclass(frozen=True, slots=True)
class Result:
total: int
count: int
def aggregate(values: Iterable[int]) -> Result:
total = 0
count = 0
for v in values:
if not isinstance(v, int):
raise TypeError("values must be ints")
total += v
count += 1
log.debug("aggregate count=%s total=%s", count, total)
return Result(total, count)
```
```python
# mypkg/cli.py
from __future__ import annotations
import argparse
import logging
import sys
from .core import aggregate
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(prog="mypkg")
p.add_argument("--log-level", default="WARNING")
args = p.parse_args(argv)
logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING))
data: list[int] = []
for line in sys.stdin:
line = line.strip()
if line:
data.append(int(line))
r = aggregate(data)
print(f"count={r.count} total={r.total}")
return 0
```
```toml
# pyproject.toml
[project]
name = "mypkg"
version = "0.1.0"
requires-python = ">=3.10"
[project.scripts]
mypkg = "mypkg.cli:main"
```
|
{
"tags": [
"python",
"cli",
"pyproject"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097891
|
packaging
|
medium
|
Create a small, production-ready Python package for file synchronization.
Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml.
Constraints: must include tests, must handle Windows paths safely.
Difficulty: medium. Ensure the API is testable via dependency injection.
|
Deliverable: implementation + tests.
Package layout:
- mypkg/core.py
- mypkg/cli.py
- pyproject.toml
```python
# mypkg/core.py
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import logging
log = logging.getLogger(__name__)
@dataclass(frozen=True, slots=True)
class Result:
total: int
count: int
def aggregate(values: Iterable[int]) -> Result:
total = 0
count = 0
for v in values:
if not isinstance(v, int):
raise TypeError("values must be ints")
total += v
count += 1
log.debug("aggregate count=%s total=%s", count, total)
return Result(total, count)
```
```python
# mypkg/cli.py
from __future__ import annotations
import argparse
import logging
import sys
from .core import aggregate
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(prog="mypkg")
p.add_argument("--log-level", default="WARNING")
args = p.parse_args(argv)
logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING))
data: list[int] = []
for line in sys.stdin:
line = line.strip()
if line:
data.append(int(line))
r = aggregate(data)
print(f"count={r.count} total={r.total}")
return 0
```
```toml
# pyproject.toml
[project]
name = "mypkg"
version = "0.1.0"
requires-python = ">=3.10"
[project.scripts]
mypkg = "mypkg.cli:main"
```
|
{
"tags": [
"python",
"cli",
"pyproject"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097892
|
packaging
|
easy
|
Create a small, production-ready Python package for file synchronization.
Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml.
Constraints: must include type hints, must avoid global state.
Difficulty: easy. Handle empty inputs and malformed records gracefully.
|
Deliverable: API + reference implementation + tests.
Package layout:
- mypkg/core.py
- mypkg/cli.py
- pyproject.toml
```python
# mypkg/core.py
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import logging
log = logging.getLogger(__name__)
@dataclass(frozen=True, slots=True)
class Result:
total: int
count: int
def aggregate(values: Iterable[int]) -> Result:
total = 0
count = 0
for v in values:
if not isinstance(v, int):
raise TypeError("values must be ints")
total += v
count += 1
log.debug("aggregate count=%s total=%s", count, total)
return Result(total, count)
```
```python
# mypkg/cli.py
from __future__ import annotations
import argparse
import logging
import sys
from .core import aggregate
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(prog="mypkg")
p.add_argument("--log-level", default="WARNING")
args = p.parse_args(argv)
logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING))
data: list[int] = []
for line in sys.stdin:
line = line.strip()
if line:
data.append(int(line))
r = aggregate(data)
print(f"count={r.count} total={r.total}")
return 0
```
```toml
# pyproject.toml
[project]
name = "mypkg"
version = "0.1.0"
requires-python = ">=3.10"
[project.scripts]
mypkg = "mypkg.cli:main"
```
|
{
"tags": [
"python",
"cli",
"pyproject"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097893
|
packaging
|
expert
|
Create a small, production-ready Python package for event dispatching.
Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml.
Constraints: must be memory-efficient, stdlib-only, must include type hints.
Difficulty: expert. Avoid quadratic behavior on large inputs.
|
Deliverable: production-ready reference solution.
Package layout:
- mypkg/core.py
- mypkg/cli.py
- pyproject.toml
```python
# mypkg/core.py
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import logging
log = logging.getLogger(__name__)
@dataclass(frozen=True, slots=True)
class Result:
total: int
count: int
def aggregate(values: Iterable[int]) -> Result:
total = 0
count = 0
for v in values:
if not isinstance(v, int):
raise TypeError("values must be ints")
total += v
count += 1
log.debug("aggregate count=%s total=%s", count, total)
return Result(total, count)
```
```python
# mypkg/cli.py
from __future__ import annotations
import argparse
import logging
import sys
from .core import aggregate
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(prog="mypkg")
p.add_argument("--log-level", default="WARNING")
args = p.parse_args(argv)
logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING))
data: list[int] = []
for line in sys.stdin:
line = line.strip()
if line:
data.append(int(line))
r = aggregate(data)
print(f"count={r.count} total={r.total}")
return 0
```
```toml
# pyproject.toml
[project]
name = "mypkg"
version = "0.1.0"
requires-python = ">=3.10"
[project.scripts]
mypkg = "mypkg.cli:main"
```
|
{
"tags": [
"python",
"cli",
"pyproject"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097894
|
packaging
|
hard
|
Create a small, production-ready Python package for task scheduling.
Requirements: include module code, CLI entrypoint, logging, and a minimal pyproject.toml.
Constraints: must be easy to extend, must avoid global state, must provide clear error messages, must include tests.
Difficulty: hard. Guarantee deterministic output ordering.
|
Deliverable: API + reference implementation + tests.
Package layout:
- mypkg/core.py
- mypkg/cli.py
- pyproject.toml
```python
# mypkg/core.py
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
import logging
log = logging.getLogger(__name__)
@dataclass(frozen=True, slots=True)
class Result:
total: int
count: int
def aggregate(values: Iterable[int]) -> Result:
total = 0
count = 0
for v in values:
if not isinstance(v, int):
raise TypeError("values must be ints")
total += v
count += 1
log.debug("aggregate count=%s total=%s", count, total)
return Result(total, count)
```
```python
# mypkg/cli.py
from __future__ import annotations
import argparse
import logging
import sys
from .core import aggregate
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(prog="mypkg")
p.add_argument("--log-level", default="WARNING")
args = p.parse_args(argv)
logging.basicConfig(level=getattr(logging, args.log_level.upper(), logging.WARNING))
data: list[int] = []
for line in sys.stdin:
line = line.strip()
if line:
data.append(int(line))
r = aggregate(data)
print(f"count={r.count} total={r.total}")
return 0
```
```toml
# pyproject.toml
[project]
name = "mypkg"
version = "0.1.0"
requires-python = ">=3.10"
[project.scripts]
mypkg = "mypkg.cli:main"
```
|
{
"tags": [
"python",
"cli",
"pyproject"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097895
|
security_safe
|
easy
|
Write secure, defensive Python code for CLI tooling.
Requirements: input validation, safe file handling, prevent path traversal, include tests.
Constraints: must include type hints, must be easy to extend, stdlib-only, must be streaming-friendly.
Difficulty: easy. Guarantee deterministic output ordering.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"security",
"validation"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097896
|
security_safe
|
expert
|
Write secure, defensive Python code for log processing.
Requirements: input validation, safe file handling, prevent path traversal, include tests.
Constraints: must be easy to extend, must handle Windows paths safely, must be memory-efficient.
Difficulty: expert. Avoid quadratic behavior on large inputs.
|
Deliverable: corrected code and verification tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"security",
"validation"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097897
|
security_safe
|
medium
|
Write secure, defensive Python code for log processing.
Requirements: input validation, safe file handling, prevent path traversal, include tests.
Constraints: must handle Windows paths safely, must include tests, stdlib-only.
Difficulty: medium. Provide helpful exceptions with actionable messages.
|
Deliverable: implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"security",
"validation"
],
"has_code": true,
"requires_thinking": false,
"seed": 1337
}
|
pygod_097898
|
security_safe
|
hard
|
Write secure, defensive Python code for data modeling.
Requirements: input validation, safe file handling, prevent path traversal, include tests.
Constraints: must be streaming-friendly, stdlib-only, must provide clear error messages, must handle Windows paths safely.
Difficulty: hard. Handle empty inputs and malformed records gracefully.
|
Deliverable: production-ready reference solution.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"security",
"validation"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097899
|
security_safe
|
expert
|
Write secure, defensive Python code for telemetry ingestion.
Requirements: input validation, safe file handling, prevent path traversal, include tests.
Constraints: must be streaming-friendly, must be memory-efficient.
Difficulty: expert. Support both Windows and POSIX paths correctly.
|
Deliverable: production-ready reference solution.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"security",
"validation"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
pygod_097900
|
bugfix
|
hard
|
Fix a subtle bug in a Python module used for caching layer.
Requirements: explain root cause briefly, provide corrected code, and add regression tests.
Constraints: must be memory-efficient, must be easy to extend, must include docstrings.
Difficulty: hard. Avoid quadratic behavior on large inputs.
|
Deliverable: API + reference implementation + tests.
```python
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
import json
class ValidationError(ValueError):
"""Raised when input validation fails."""
def safe_join(base: Path, *parts: str) -> Path:
"""Join paths while preventing traversal outside base."""
b = base.resolve()
p = (b / Path(*parts)).resolve()
if p != b and b not in p.parents:
raise ValidationError(f"unsafe path: {p}")
return p
@dataclass(frozen=True, slots=True)
class Record:
key: str
value: int
def parse_jsonl(lines: Iterable[str]) -> list[Record]:
out: list[Record] = []
for idx, line in enumerate(lines, 1):
s = line.strip()
if not s:
continue
try:
obj = json.loads(s)
except json.JSONDecodeError as e:
raise ValidationError(f"line {idx}: invalid json") from e
if not isinstance(obj, dict):
raise ValidationError(f"line {idx}: expected object")
key = obj.get("key")
val = obj.get("value")
if not isinstance(key, str) or not key:
raise ValidationError(f"line {idx}: key must be non-empty str")
if not isinstance(val, int):
raise ValidationError(f"line {idx}: value must be int")
out.append(Record(key, val))
return out
def write_jsonl(base: Path, rel: str, records: Iterable[Record]) -> Path:
base.mkdir(parents=True, exist_ok=True)
dst = safe_join(base, rel)
dst.parent.mkdir(parents=True, exist_ok=True)
with dst.open("w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps({"key": r.key, "value": r.value}, ensure_ascii=False) + "\n")
return dst
```
```python
# tests (pytest-style)
import json
from pathlib import Path
import pytest
from module_under_test import ValidationError, Record, parse_jsonl, write_jsonl
def test_parse_ok():
lines = [json.dumps({"key":"a","value":1}), json.dumps({"key":"b","value":2})]
assert parse_jsonl(lines) == [Record("a",1), Record("b",2)]
def test_parse_rejects_bad_json():
with pytest.raises(ValidationError):
parse_jsonl(["{not json}"])
def test_safe_join_blocks_traversal(tmp_path: Path):
with pytest.raises(ValidationError):
write_jsonl(tmp_path, "../x.jsonl", [Record("a",1)])
```
|
{
"tags": [
"python",
"debugging",
"tests"
],
"has_code": true,
"requires_thinking": true,
"seed": 1337
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.