id stringclasses 50
values | testsource stringclasses 6
values | language stringclasses 6
values | prefix stringlengths 16 3.39k | golden_completion stringlengths 23 3.14k | suffix stringlengths 0 2.68k | assertions stringlengths 0 2.72k | category stringclasses 6
values |
|---|---|---|---|---|---|---|---|
1 | devbench-api-usage | python | import csv
import io
def write_strict_csv(rows, fieldnames):
| """Write rows with csv.DictWriter using strict fieldnames.
The output is built in an io.StringIO buffer with a header row and
no final line terminator. csv.DictWriter is configured with
extrasaction='raise', so a row containing a key outside fieldnames
raises ValueError instead of silently ignoring... | out = io.StringIO(newline='')
writer = csv.DictWriter(
out,
fieldnames=fieldnames,
extrasaction='raise',
lineterminator=''
)
writer.writeheader()
for row in rows:
writer.writerow(row)
return out.getvalue()
rows = [{'name': 'Alice', 'age': 30}, {'name': 'B... | doc = write_strict_csv.__doc__
assert doc is not None, 'Docstring is missing'
low = doc.lower()
assert 'dictwriter' in low, 'Must name csv.DictWriter'
assert 'extrasaction' in low and 'raise' in low, 'Must mention extrasaction=raise'
assert 'valueerror' in low, 'Must mention ValueError for extra keys'
assert 'fieldname... | api_usage |
2 | devbench-api-usage | python | from itertools import groupby
# Group these records by category
# IMPORTANT: groupby only groups CONSECUTIVE matching elements
records = [
('fruit', 'apple'), ('veggie', 'carrot'), ('fruit', 'banana'),
('veggie', 'pea'), ('fruit', 'cherry'), ('veggie', 'corn')
]
# To get all items per category, data must be s... | sorted_records = sorted(records, key=lambda x: x[0])
grouped = {k: [v for _, v in g] for k, g in groupby(sorted_records, key=lambda x: x[0])}
| assert grouped['fruit'] == ['apple', 'banana', 'cherry']
assert grouped['veggie'] == ['carrot', 'pea', 'corn']
print("Grouping successful:", grouped)
| from itertools import groupby
records = [
('fruit', 'apple'), ('veggie', 'carrot'), ('fruit', 'banana'),
('veggie', 'pea'), ('fruit', 'cherry'), ('veggie', 'corn')
]
sorted_records = sorted(records, key=lambda x: x[0])
grouped = {k: [v for _, v in g] for k, g in groupby(sorted_records, key=lambda x: x[0])}
asse... | api_usage |
3 | devbench-api-usage | python | import csv
import io
def default_csv_row(values):
out = io.StringIO(newline='')
writer = csv.writer(out, lineterminator='')
writer.writerow(values)
return out.getvalue()
# Implement a CSV row encoder for a non-default dialect. The function
# accepts delimiter, quotechar, and escapechar keyword argumen... | def csv_escape_row(values, delimiter=';', quotechar="'", escapechar='\\'):
out = io.StringIO(newline='')
writer = csv.writer(
out,
delimiter=delimiter,
quotechar=quotechar,
escapechar=escapechar,
doublequote=False,
lineterminator='\n',
quoting=csv.QUOTE_MI... |
assert default_csv_row(['a', 'b']) == 'a,b'
assert csv_escape_row(['a', 'b']) == 'a;b'
assert csv_escape_row(['semi;colon', "can't"]) == "'semi;colon';can\\'t"
assert csv_escape_row(['back\\slash', 'plain']) == 'back\\\\slash;plain'
assert csv_escape_row(['semi|colon', 'x'], delimiter='|') == "'semi|colon'|x"
assert c... | assert csv_escape_row([]) == ''
assert csv_escape_row(['he said \"hi\"', "it's ok"]) == 'he said "hi";it\\\'s ok'
assert csv_escape_row(['a;b', 'c;d']) == "'a;b';'c;d'"
assert csv_escape_row(['a|b', 'c'], delimiter='|') == "'a|b'|c"
assert not csv_escape_row(['tail']).endswith('\n')
| api_usage |
4 | devbench-api-usage | python | import csv
import io
def default_csv_row(values):
out = io.StringIO(newline='')
writer = csv.writer(out, lineterminator='')
writer.writerow(values)
return out.getvalue()
# Implement a CSV row encoder that never quotes fields. Use csv.QUOTE_NONE
# with backslash escaping. Delimiters, quote characters, ... | def csv_noquote_row(values, delimiter=',', escapechar='\\'):
out = io.StringIO(newline='')
writer = csv.writer(
out,
delimiter=delimiter,
escapechar=escapechar,
quotechar='"',
doublequote=False,
lineterminator='\n',
quoting=csv.QUOTE_NONE,
)
writer... |
assert default_csv_row(['a,b']) == '"a,b"'
assert csv_noquote_row(['a', 'b']) == 'a,b'
assert csv_noquote_row(['a,b', 'x"y', 'c\\d']) == 'a\\,b,x\\"y,c\\\\d'
assert csv_noquote_row(['line\nbreak', 'z']) == 'line\\\nbreak,z'
assert csv_noquote_row(['a|b', 'c'], delimiter='|') == 'a\\|b|c'
assert csv_noquote_row(['a,b']... | assert csv_noquote_row([]) == ''
assert csv_noquote_row(['semi;colon', 'x'], delimiter=';') == 'semi\\;colon;x'
assert csv_noquote_row(['back\\slash']) == 'back\\\\slash'
assert csv_noquote_row(['quote"only']) == 'quote\\"only'
assert not csv_noquote_row(['tail']).endswith('\n')
| api_usage |
5 | devbench-api-usage | python | import struct
# Pack a network protocol header: big-endian unsigned short (version),
# unsigned int (message_id), and a signed byte (flags)
# Then unpack it and verify round-trip
version = 3
message_id = 100000
flags = -1 # signed byte: will be 0xFF / 255 as unsigned
| packed = struct.pack('!HIb', version, message_id, flags)
unpacked_version, unpacked_id, unpacked_flags = struct.unpack('!HIb', packed)
| assert unpacked_version == version
assert unpacked_id == message_id
assert unpacked_flags == flags
assert len(packed) == struct.calcsize('!HIb')
print(f"Packed {len(packed)} bytes: {packed.hex()}")
print(f"Unpacked: version={unpacked_version}, id={unpacked_id}, flags={unpacked_flags}")
| import struct
version = 3
message_id = 100000
flags = -1
packed = struct.pack('!HIb', version, message_id, flags)
unpacked_version, unpacked_id, unpacked_flags = struct.unpack('!HIb', packed)
assert unpacked_version == version
assert unpacked_id == message_id
assert unpacked_flags == flags
assert len(packed) == 7 # 2 ... | api_usage |
6 | devbench-api-usage | python | import csv
import io
def default_tsv_row(values):
out = io.StringIO(newline='')
writer = csv.writer(out, delimiter='\t', lineterminator='')
writer.writerow(values)
return out.getvalue()
# Implement a TSV-style row encoder. Defaults are tab delimiter, double
# quote quotechar, backslash escapechar, and... | def tsv_escape_row(values, delimiter='\t', quotechar='"', escapechar='\\'):
out = io.StringIO(newline='')
writer = csv.writer(
out,
delimiter=delimiter,
quotechar=quotechar,
escapechar=escapechar,
doublequote=False,
lineterminator='\n',
quoting=csv.QUOTE_M... |
assert default_tsv_row(['a', 'b']) == 'a\tb'
assert tsv_escape_row(['a', 'b']) == 'a\tb'
assert tsv_escape_row(['a\tb', 'quote"']) == '"a\tb"\tquote\\"'
assert tsv_escape_row(['line\nbreak', 'z']) == '"line\nbreak"\tz'
assert tsv_escape_row(['path\\to', 'plain']) == 'path\\\\to\tplain'
assert tsv_escape_row(['a|b', 'c... | assert tsv_escape_row([]) == ''
assert tsv_escape_row(['x\ny', 'has\ttab']) == '"x\ny"\t"has\ttab"'
assert tsv_escape_row(['semi;colon', 'x'], delimiter=';') == '"semi;colon";x'
assert tsv_escape_row(['one', 'two']) == 'one\ttwo'
| api_usage |
7 | devbench-api-usage | python | import heapq
import operator
def newest_high_priority(records, n):
| """Return the n records with largest priority and newest timestamp.
Uses heapq.nlargest with an operator.itemgetter key over the
('priority', 'created_at') fields, so priority is compared first and
created_at breaks ties. The input list is not mutated; the returned
list is ordered from highest key ... | return heapq.nlargest(
n,
records,
key=operator.itemgetter('priority', 'created_at')
)
records = [
{'id': 'old-high', 'priority': 5, 'created_at': 10},
{'id': 'new-high', 'priority': 5, 'created_at': 20},
{'id': 'low-new', 'priority': 3, 'created_at': 99},
{'id': 'top', ... | doc = newest_high_priority.__doc__
assert doc is not None, 'Docstring is missing'
low = doc.lower()
assert 'heapq.nlargest' in low or 'nlargest' in low, 'Must mention heapq.nlargest'
assert 'operator.itemgetter' in low or 'itemgetter' in low, 'Must mention operator.itemgetter key'
assert 'priority' in low, 'Must mentio... | api_usage |
8 | devbench-api-usage | python | import bisect
import operator
def insert_by_score(records, record):
| """Insert record into records sorted by score and return its index.
Uses bisect.bisect_left with operator.itemgetter('score') as the key.
Python's bisect key is applied to existing records only, so x is the
raw score value, not the record dict. Equal scores are inserted on the
left, and the input l... | index = bisect.bisect_left(
records,
record['score'],
key=operator.itemgetter('score')
)
records.insert(index, record)
return index
records = [
{'name': 'a', 'score': 10},
{'name': 'b', 'score': 20},
{'name': 'c', 'score': 20},
{'name': 'd', 'score': 40},
]
idx =... | doc = insert_by_score.__doc__
assert doc is not None, 'Docstring is missing'
low = doc.lower()
assert 'bisect_left' in low or 'bisect.bisect_left' in low, 'Must mention bisect_left'
assert 'operator.itemgetter' in low or 'itemgetter' in low, 'Must mention operator.itemgetter key'
assert 'key' in low and ('existing' in ... | api_usage |
9 | devbench-api-usage | python | from datetime import datetime, timezone
def parse_log_timestamp(text):
| """Parse a timezone-offset log timestamp and return it in UTC.
datetime.strptime uses the '%Y-%m-%d %H:%M:%S %z' format, where %z
creates an aware datetime from a numeric UTC offset. The result is
normalized with astimezone(timezone.utc). Invalid text or a missing
offset propagates strptime's Value... | parsed = datetime.strptime(text, '%Y-%m-%d %H:%M:%S %z')
return parsed.astimezone(timezone.utc)
stamp = parse_log_timestamp('2026-05-01 09:30:00 -0700')
assert stamp.isoformat() == '2026-05-01T16:30:00+00:00'
assert stamp.tzinfo is timezone.utc
assert parse_log_timestamp.__doc__ is not None
print(stamp.isoform... | doc = parse_log_timestamp.__doc__
assert doc is not None, 'Docstring is missing'
low = doc.lower()
assert 'strptime' in low, 'Must mention datetime.strptime'
assert '%z' in doc, 'Must mention %z timezone offset parsing'
assert 'aware' in low or 'timezone' in low or 'tzinfo' in low, 'Must mention timezone-aware datetime... | api_usage |
10 | devbench-api-usage | python | import hashlib
import io
def sha256_stream_hex(stream, chunk_size=4):
| """Return the SHA-256 hex digest of a binary stream without consuming it.
The current stream position is saved with tell(), bytes are read in
chunk_size blocks and fed to hashlib.sha256().update(), then the stream
is seek()ed back to its original position. The return value is the
64-character hexdi... | start = stream.tell()
hasher = hashlib.sha256()
while True:
chunk = stream.read(chunk_size)
if not chunk:
break
hasher.update(chunk)
stream.seek(start)
return hasher.hexdigest()
buf = io.BytesIO(b'abcdef')
buf.seek(2)
expected = hashlib.sha256(b'cdef').hexdigest(... | doc = sha256_stream_hex.__doc__
assert doc is not None, 'Docstring is missing'
low = doc.lower()
assert 'hashlib.sha256' in low or 'sha256' in low, 'Must mention hashlib.sha256'
assert 'update' in low, 'Must mention update() streaming API'
assert 'hexdigest' in low, 'Must mention hexdigest return'
assert '64' in low, '... | api_usage |
11 | devbench-api-usage | python | import difflib
def word_diff(old, new):
"""Return a list of change tuples from a word-level diff.
Split on whitespace, use SequenceMatcher.get_opcodes().
Return list of tuples:
('replace', old_words, new_words)
('insert', new_words)
('delete', old_words)
Skip 'equal' opcodes. Words ar... | changes = []
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
if tag == 'replace':
changes.append(('replace', old_words[i1:i2], new_words[j1:j2]))
elif tag == 'insert':
changes.append(('insert', new_words[j1:j2]))
elif tag == 'delete':
changes.append(... |
result = word_diff('the quick brown fox', 'the slow brown cat')
print(result)
| r1 = word_diff('the quick brown fox', 'the slow brown cat')
assert ('replace', ['quick'], ['slow']) in r1
assert ('replace', ['fox'], ['cat']) in r1
assert len(r1) == 2
r2 = word_diff('a b c', 'a b x y c')
assert ('insert', ['x', 'y']) in r2
assert len(r2) == 1
r3 = word_diff('hello world', 'hello')
assert ('delete', [... | api_usage |
12 | devbench-api-usage | python | import textwrap
def reformat_code(text, new_indent=' '):
"""Remove common leading whitespace, then re-indent only non-empty
lines that don't start with '#' (after dedent). Return the result."""
dedented = textwrap.dedent(text)
| return textwrap.indent(
dedented, new_indent,
predicate=lambda line: line.strip() != '' and not line.lstrip().startswith('#')
) |
sample = '''\
def foo():
pass
# comment
x = 1
y = 2
'''
result = reformat_code(sample)
| import textwrap
sample = ' def foo():\n pass\n # comment\n x = 1\n\n y = 2\n'
result = reformat_code(sample)
lines = result.split('\n')
assert lines[0] == ' def foo():', f'Expected indented def line, got {lines[0]!r}'
assert any(line.startswith('#') for line in lines), 'Comment... | api_usage |
13 | devbench-api-usage | python | from urllib.parse import urlencode, parse_qs
def build_search_url(base, params):
"""Build a query string where params may have list values.
E.g. {'color': ['red','blue'], 'size': 'large'}
-> 'color=red&color=blue&size=large'
"""
| query = urlencode(params, doseq=True)
return f'{base}?{query}' |
url = build_search_url('https://shop.example.com/search',
{'color': ['red', 'blue'], 'size': 'large'})
| url = build_search_url('https://shop.example.com/search', {'color': ['red', 'blue'], 'size': 'large'})
assert 'color=red' in url
assert 'color=blue' in url
assert 'size=large' in url
assert url.startswith('https://shop.example.com/search?')
# Without doseq, list would be stringified
from urllib.parse import urlencode
b... | api_usage |
14 | devbench-api-usage | python | import json
from datetime import datetime, date
from decimal import Decimal
def custom_serializer(obj):
"""JSON serializer for objects not serializable by default.
- datetime/date -> .isoformat()
- Decimal -> float
- set/frozenset -> sorted list
- bytes -> decoded utf-8 string
Raises TypeError ... | if isinstance(obj, (datetime, date)):
return obj.isoformat()
if isinstance(obj, Decimal):
return float(obj)
if isinstance(obj, (set, frozenset)):
return sorted(obj)
if isinstance(obj, bytes):
return obj.decode('utf-8')
raise TypeError(f'Object of type {type(obj).__nam... |
data = {
'timestamp': datetime(2024, 1, 15, 10, 30),
'tags': {'beta', 'alpha', 'gamma'},
'price': Decimal('19.99'),
'raw': b'hello'
}
result = json.dumps(data, default=custom_serializer, sort_keys=True)
| import json
from datetime import datetime, date
from decimal import Decimal
data = {
'timestamp': datetime(2024, 1, 15, 10, 30),
'tags': {'beta', 'alpha', 'gamma'},
'price': Decimal('19.99'),
'raw': b'hello'
}
result = json.dumps(data, default=custom_serializer, sort_keys=True)
parsed = json.loads(resul... | api_usage |
15 | devbench-api-usage | python | import re
def reformat_dates(text):
"""Replace all YYYY-MM-DD dates in text with DD/MM/YYYY format.
Use re.sub with a function replacement and named groups.
Only transform valid-looking dates (4-digit year, 2-digit month/day)."""
pattern = r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'
| def replacer(match):
return f"{match.group('day')}/{match.group('month')}/{match.group('year')}"
return re.sub(pattern, replacer, text) |
original = 'Event on 2024-01-15 and deadline 2024-12-31.'
result = reformat_dates(original)
| assert reformat_dates('Date: 2024-01-15') == 'Date: 15/01/2024'
assert reformat_dates('From 2023-06-01 to 2023-12-25') == 'From 01/06/2023 to 25/12/2023'
assert reformat_dates('No dates here') == 'No dates here'
assert reformat_dates('2000-01-01') == '01/01/2000'
assert reformat_dates('mix 2024-03-15 text 2024-07-04 en... | api_usage |
16 | devbench-api-usage | python | import logging
import io
class RequestIdFilter(logging.Filter):
"""Filter that adds request_id to every LogRecord and prefixes the message.
Attaches self.request_id to the record.
Prepends '[<request_id>] ' to the record's msg.
filter() must return True (don't actually filter out records)."""
def _... | def filter(self, record):
record.request_id = self.request_id
record.msg = f'[{self.request_id}] {record.msg}'
return True |
# Set up logger with StringIO handler to capture output
def create_test_logger(request_id):
logger = logging.getLogger(f'test.{request_id}')
logger.setLevel(logging.DEBUG)
logger.handlers.clear()
stream = io.StringIO()
handler = logging.StreamHandler(stream)
handler.setFormatter(logging.Format... | logger, stream = create_test_logger('req-123')
logger.info('User logged in')
logger.warning('Slow query')
output = stream.getvalue()
assert '[req-123] User logged in' in output, f'Got: {output!r}'
assert '[req-123] Slow query' in output, f'Got: {output!r}'
# Verify request_id attribute was added
logger2, stream2 = crea... | api_usage |
17 | devbench-api-usage | python | from unittest.mock import patch, MagicMock
import os
def read_config_values(keys):
"""Read multiple config values from environment, returning a list.
Uses os.environ.get for each key."""
return [os.environ.get(k) for k in keys]
# Test: mock os.environ.get to return different values for successive calls
| with patch.object(os.environ, 'get', side_effect=['val1', 'val2', 'val3']) as mock_get:
result = read_config_values(['KEY1', 'KEY2', 'KEY3'])
assert result == ['val1', 'val2', 'val3']
assert mock_get.call_count == 3 |
print('Mock test passed')
| from unittest.mock import patch
import os
with patch.object(os.environ, 'get', side_effect=['a', 'b', 'c']) as m:
r = read_config_values(['X', 'Y', 'Z'])
assert r == ['a', 'b', 'c'], f'Got {r}'
assert m.call_count == 3
# Test with fewer calls than side_effect values
with patch.object(os.environ, 'get', side... | api_usage |
18 | devbench-api-usage | python | import inspect
import functools
def typecheck(func):
"""Decorator that enforces type annotations at call time.
For each parameter with an annotation, check isinstance.
Raise TypeError with the parameter name if check fails.
Unannotated parameters are not checked. Return type not checked."""
sig = i... | @functools.wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
bound.apply_defaults()
for name, value in bound.arguments.items():
param = sig.parameters[name]
if param.annotation is not inspect.Parameter.empty:
if not isinst... |
@typecheck
def greet(name: str, times: int = 1):
return (name + '! ') * times
| assert greet('hello', 3) == 'hello! hello! hello! '
assert greet('hi') == 'hi! '
assert greet(name='test', times=2) == 'test! test! '
try:
greet(123)
assert False, 'Should raise TypeError'
except TypeError as e:
assert 'name' in str(e)
try:
greet('ok', 'bad')
assert False, 'Should raise TypeError'
e... | api_usage |
19 | devbench-api-usage | python | from operator import attrgetter
class Address:
def __init__(self, city, zip_code):
self.city = city
self.zip_code = zip_code
class Company:
def __init__(self, name, address):
self.name = name
self.address = address
class Employee:
def __init__(self, name, company):
... | get_city = attrgetter('company.address.city')
get_zip = attrgetter('company.address.zip_code')
get_company_name = attrgetter('company.name')
city = get_city(emp)
zip_code = get_zip(emp)
company_name = get_company_name(emp) |
print(f'{emp.name} works at {company_name} in {city}, {zip_code}')
| from operator import attrgetter
assert attrgetter('company.address.city')(emp) == 'Springfield'
assert attrgetter('company.address.zip_code')(emp) == '62701'
assert attrgetter('company.name')(emp) == 'Acme'
assert attrgetter('name')(emp) == 'Alice'
# Multi-attribute getter
getter = attrgetter('name', 'company.name')
as... | api_usage |
20 | devbench-api-usage | python | import weakref
cleanup_log = []
class Resource:
"""Resource that registers a weakref.finalize callback on creation.
When the object is collected (or finalizer called), appends
'cleaned:<name>' to cleanup_log."""
def __init__(self, name):
self.name = name
| self._finalizer = weakref.finalize(
self, lambda n: cleanup_log.append(f'cleaned:{n}'), self.name
)
def close(self):
"""Explicitly trigger cleanup (idempotent)."""
self._finalizer() |
def is_alive(self):
return self._finalizer.alive
| cleanup_log.clear()
r = Resource('db')
assert r.is_alive()
assert cleanup_log == []
r.close()
assert cleanup_log == ['cleaned:db']
assert not r.is_alive()
# Calling close again should be a no-op (finalize is one-shot)
r.close()
assert cleanup_log == ['cleaned:db'], 'Finalize should only run once'
# Test with garbage co... | api_usage |
21 | devbench-api-usage | python | import functools
call_count = 0
| @functools.lru_cache(maxsize=128, typed=True)
def compute(x):
global call_count
call_count += 1
return x * 2
| # Reset
call_count = 0
compute.cache_clear()
r1 = compute(1)
r2 = compute(1.0)
r3 = compute(1)
assert r1 == 2
assert r2 == 2.0
# With typed=True, int(1) and float(1.0) are cached separately
assert call_count == 2, f'Expected 2 calls (int and float cached separately), got {call_count}'
# Third call to compute(1) shoul... | # Further verify typed behavior
compute.cache_clear()
call_count = 0
compute(2)
compute(2)
compute(2.0)
compute(2.0)
assert call_count == 2, f'Expected 2 calls, got {call_count}'
info = compute.cache_info()
assert info.hits == 2
assert info.misses == 2
# Verify True (bool, subclass of int) is also separate from 1
compu... | api_usage |
22 | devbench-api-usage | python | import itertools
def generate_chunks():
"""Yields chunks of numbers as lists."""
yield [1, 2, 3]
yield [4, 5]
yield [6, 7, 8, 9]
| def flatten_lazy(iterable_of_iterables):
"""Flatten an iterable of iterables lazily using chain.from_iterable."""
return itertools.chain.from_iterable(iterable_of_iterables)
| # Verify lazy flattening works with a generator (can only iterate once)
result = list(flatten_lazy(generate_chunks()))
assert result == [1, 2, 3, 4, 5, 6, 7, 8, 9], f'Got: {result}'
# Verify it works lazily - we can take partial results
gen = generate_chunks()
flattened = flatten_lazy(gen)
first_three = [next(flattene... | # Test with empty chunks
def gen_with_empty():
yield []
yield [1]
yield []
yield [2, 3]
yield []
result = list(flatten_lazy(gen_with_empty()))
assert result == [1, 2, 3], f'Got: {result}'
# Test with single chunk
result2 = list(flatten_lazy(iter([[10, 20]])))
assert result2 == [10, 20]
# Test wit... | api_usage |
23 | devbench-api-usage | python | from collections import ChainMap
defaults = {'color': 'red', 'size': 'medium', 'shape': 'circle'}
user_prefs = {'color': 'blue'}
| # Create a ChainMap where user_prefs overrides defaults
# Mutations only affect the first map (user_prefs)
config = ChainMap(user_prefs, defaults)
# Override a default value - this writes to user_prefs (first map)
config['size'] = 'large'
# Delete an overridden key - this deletes from user_prefs only
del config['colo... | # 'size' was set in user_prefs (first map)
assert config['size'] == 'large', f"Expected 'large', got {config['size']}"
assert user_prefs['size'] == 'large', 'Mutation should go to first map (user_prefs)'
assert defaults['size'] == 'medium', 'defaults should be unchanged'
# After deleting 'color' from user_prefs, it fa... | # Verify the maps attribute shows both dicts
assert len(config.maps) == 2
assert config.maps[0] is user_prefs
assert config.maps[1] is defaults
# Adding a new key goes to the first map
config['opacity'] = 0.5
assert user_prefs['opacity'] == 0.5
assert 'opacity' not in defaults
# new_child creates a new ChainMap with ... | api_usage |
24 | devbench-api-usage | python | import contextlib
results = []
| with contextlib.suppress(FileNotFoundError, PermissionError):
results.append('before')
raise FileNotFoundError('missing.txt')
results.append('unreachable')
results.append('after_suppress')
with contextlib.ExitStack() as stack:
stack.callback(results.append, 'cleanup_1')
stack.callback(results.appe... | # suppress skips everything after the exception
assert 'before' in results
assert 'unreachable' not in results, 'Code after raise should not execute'
assert 'after_suppress' in results, 'Code after with-block should execute'
# ExitStack callbacks fire in LIFO order
assert results[-3] == 'inside_stack'
assert results[-... | # Test suppress with an exception that is NOT suppressed
caught = False
try:
with contextlib.suppress(FileNotFoundError):
raise ValueError('not suppressed')
except ValueError:
caught = True
assert caught, 'ValueError should not be suppressed'
# Test suppress with no exception raised
flag = False
with c... | api_usage |
25 | devbench-api-usage | python | from dataclasses import dataclass, field, fields
| @dataclass
class Config:
name: str
tags: list = field(default_factory=list, metadata={'searchable': True, 'max_length': 10})
scores: dict = field(default_factory=dict, metadata={'searchable': False})
version: int = field(default=1, repr=False)
| # Each instance gets its OWN list/dict (not shared)
c1 = Config(name='alpha')
c2 = Config(name='beta')
c1.tags.append('fast')
c1.scores['accuracy'] = 0.95
assert c1.tags == ['fast']
assert c2.tags == [], f'c2.tags should be empty, got {c2.tags}'
assert c1.scores == {'accuracy': 0.95}
assert c2.scores == {}, f'c2.score... | # version has repr=False
c3 = Config(name='gamma')
r = repr(c3)
assert 'version' not in r, f'version should not be in repr, got {r}'
assert 'gamma' in r
# Default version
assert c3.version == 1
# Verify field count
assert len(fields(Config)) == 4
# Metadata is a mappingproxy (immutable)
tag_field = [f for f in field... | api_usage |
26 | devbench-api-usage | python | from enum import Flag, auto
| class Permission(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
DELETE = auto()
# Combined convenience flags
READ_WRITE = READ | WRITE
FULL_ACCESS = READ | WRITE | EXECUTE | DELETE
| # Basic flag operations
p = Permission.READ | Permission.WRITE
assert Permission.READ in p
assert Permission.WRITE in p
assert Permission.EXECUTE not in p
# Test combined flag
assert Permission.READ_WRITE == Permission.READ | Permission.WRITE
assert Permission.READ in Permission.READ_WRITE
assert Permission.WRITE in P... | # Bitwise AND to check specific permission
user_perms = Permission.READ | Permission.EXECUTE
assert bool(user_perms & Permission.READ)
assert not bool(user_perms & Permission.WRITE)
assert bool(user_perms & Permission.EXECUTE)
# XOR to toggle permissions
toggled = user_perms ^ Permission.READ # remove READ
assert Per... | api_usage |
27 | devbench-api-usage | python | from fractions import Fraction
| # Use string constructor for exact decimal representation
pi_approx = Fraction('3.14159265358979')
# limit_denominator finds the closest rational with denominator <= max
approx_7 = pi_approx.limit_denominator(7)
approx_100 = pi_approx.limit_denominator(100)
approx_1000 = pi_approx.limit_denominator(1000)
| # 22/7 is the best approximation with denominator <= 7
assert approx_7 == Fraction(22, 7), f'Got {approx_7}'
# 311/99 is the best approximation with denominator <= 100
assert approx_100 == Fraction(311, 99), f'Got {approx_100}'
# 355/113 is the best approximation with denominator <= 1000
assert approx_1000 == Fractio... | # Verify string constructor vs float constructor difference
from_string = Fraction('0.1')
from_float = Fraction(0.1)
# String gives exact decimal; float gives the IEEE 754 representation
assert from_string == Fraction(1, 10)
assert from_float != Fraction(1, 10) # float 0.1 is not exactly 1/10
# limit_denominator with... | api_usage |
28 | devbench-api-usage | python | import statistics
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
| # quantiles with n=4 gives quartile boundaries (3 cut points)
exclusive_q = statistics.quantiles(data, n=4, method='exclusive')
inclusive_q = statistics.quantiles(data, n=4, method='inclusive')
# quantiles with n=10 gives decile boundaries
deciles_excl = statistics.quantiles(data, n=10, method='exclusive')
deciles_inc... | # exclusive method (default): for data NOT including population extremes
# inclusive method: for data that includes the min/max of the population
assert len(exclusive_q) == 3, f'Expected 3 quartile points, got {len(exclusive_q)}'
assert len(inclusive_q) == 3
# For this dataset, the methods give different Q1 and Q3
ass... | # Verify specific quartile values
# Exclusive Q1=2.75, Q2=5.5, Q3=8.25 (for this data)
assert exclusive_q[0] == 2.75, f'Got {exclusive_q[0]}'
assert exclusive_q[2] == 8.25, f'Got {exclusive_q[2]}'
# Inclusive Q1=3.25, Q2=5.5, Q3=7.75 (for this data)
assert inclusive_q[0] == 3.25, f'Got {inclusive_q[0]}'
assert inclusi... | api_usage |
29 | devbench-api-usage | python | import copy
class TrackedObject:
"""Object that tracks copies and skips 'cache' during deep copy."""
_copy_count = 0
def __init__(self, name, data, cache=None):
self.name = name
self.data = data
self.cache = cache or {}
self._id = id(self)
| def __deepcopy__(self, memo):
TrackedObject._copy_count += 1
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
result.name = copy.deepcopy(self.name, memo)
result.data = copy.deepcopy(self.data, memo)
result.cache = {} # intentionally not... | # Create an object with nested mutable data and a populated cache
original = TrackedObject('root', {'values': [1, 2, 3], 'nested': {'a': 1}})
original.cache['key1'] = 'expensive_result'
original.cache['key2'] = 'another_result'
# Deep copy
TrackedObject._copy_count = 0
cloned = copy.deepcopy(original)
# Verify deep c... | # Verify nested data is deep copied
cloned2 = copy.deepcopy(original)
cloned2.data['nested']['a'] = 999
assert original.data['nested']['a'] == 1, 'Nested data should be independently copied'
# Verify _id is unique
assert cloned2._id != original._id
# Verify circular reference handling via memo
class Container:
de... | api_usage |
30 | devbench-api-usage | python | from abc import ABCMeta, abstractmethod
class Drawable(metaclass=ABCMeta):
@abstractmethod
def draw(self):
pass
| @classmethod
def __subclasshook__(cls, C):
if cls is Drawable:
if any('draw' in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
| class Circle:
def draw(self):
return 'drawing circle'
class Square(Drawable):
def draw(self):
return 'drawing square'
class Empty:
pass
# Circle is a "virtual subclass" via __subclasshook__ (structural typing)
assert isinstance(Circle(), Drawable), 'Circle should be considered Drawable'
a... | # Dynamic class with draw method should also match
class Triangle:
def draw(self):
return 'drawing triangle'
assert issubclass(Triangle, Drawable)
assert isinstance(Triangle(), Drawable)
# Class with draw as a non-callable attribute should match __subclasshook__
# because we only check 'draw' in __dict__,... | api_usage |
31 | devbench-api-usage | python | import string
# Create a Template subclass that uses '#' as delimiter instead of '$'
| class HashTemplate(string.Template):
delimiter = '#'
tmpl = HashTemplate('#name is #age years old')
result = tmpl.substitute(name='Alice', age=30)
|
print(result)
| assert result == 'Alice is 30 years old', f'Got: {result!r}'
tmpl2 = HashTemplate('##escaped and #val')
result2 = tmpl2.substitute(val='ok')
assert result2 == '#escaped and ok', f'Got: {result2!r}'
| api_usage |
32 | devbench-api-usage | python | import csv
import io
# Write CSV with DictWriter using strict extra key handling
output = io.StringIO()
fieldnames = ['name', 'age']
| writer = csv.DictWriter(output, fieldnames=fieldnames, extrasaction='raise')
writer.writeheader()
writer.writerow({'name': 'Alice', 'age': 25})
|
# Verify output
csv_output = output.getvalue()
print(csv_output)
| assert 'name,age' in csv_output
assert 'Alice,25' in csv_output
# Now test that extra keys raise ValueError
output2 = io.StringIO()
writer2 = csv.DictWriter(output2, fieldnames=['name', 'age'], extrasaction='raise')
try:
writer2.writerow({'name': 'Bob', 'age': 30, 'city': 'NYC'})
assert False, 'Should have rais... | api_usage |
33 | devbench-api-usage | python | import html
# Unescape HTML entities including numeric character references
| result1 = html.unescape('& < >')
result2 = html.unescape('& < >')
result3 = html.unescape('& < >')
|
print(result1, result2, result3)
| assert result1 == '& < >', f'Named entities failed: {result1!r}'
assert result2 == '& < >', f'Decimal refs failed: {result2!r}'
assert result3 == '& < >', f'Hex refs failed: {result3!r}'
assert html.unescape('no entities here') == 'no entities here'
assert html.unescape('&unknown;') == '&unknown;'
| api_usage |
34 | devbench-api-usage | python | import base64
# Demonstrate the difference between standard and URL-safe base64
# Use data that produces + and / in standard base64
data = b'\xfb\xff\xfe'
| standard = base64.b64encode(data)
urlsafe = base64.urlsafe_b64encode(data)
both_decode_same = base64.b64decode(standard) == base64.urlsafe_b64decode(urlsafe)
|
print(f'Standard: {standard}')
print(f'URL-safe: {urlsafe}')
print(f'Both decode same: {both_decode_same}')
| assert isinstance(standard, bytes)
assert isinstance(urlsafe, bytes)
# Standard encoding may contain + and /
# URL-safe replaces + with - and / with _
std_str = standard.decode()
url_str = urlsafe.decode()
assert '+' not in url_str and '/' not in url_str, f'URL-safe should not contain + or /: {url_str}'
# Verify they d... | api_usage |
35 | devbench-api-usage | python | import tempfile
import os
# Create a named temporary file that persists after closing
| tmp = tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False)
tmp_path = tmp.name
tmp.write('hello world')
tmp.close()
|
# File should still exist after close since delete=False
print(f'File exists: {os.path.exists(tmp_path)}')
| assert os.path.exists(tmp_path), 'File should persist after close with delete=False'
with open(tmp_path, 'r') as f:
content = f.read()
assert content == 'hello world', f'Content mismatch: {content!r}'
# Manual cleanup
os.unlink(tmp_path)
assert not os.path.exists(tmp_path), 'File should be deleted after unlink'
| api_usage |
36 | devbench-api-usage | python | import sqlite3
# Create a custom aggregate function for geometric mean
# Must define a class with step() and finalize() methods
class GeomMean:
def __init__(self):
self.product = 1.0
self.count = 0
| def step(self, value):
if value is not None:
self.product *= value
self.count += 1
def finalize(self):
if self.count == 0:
return None
return self.product ** (1.0 / self.count)
|
# Register and use the aggregate
conn = sqlite3.connect(':memory:')
conn.create_aggregate('geom_mean', 1, GeomMean)
conn.execute('CREATE TABLE nums (val REAL)')
conn.executemany('INSERT INTO nums VALUES (?)', [(2,), (8,)])
result = conn.execute('SELECT geom_mean(val) FROM nums').fetchone()[0]
print(f'Geometric mean: {... | conn = sqlite3.connect(':memory:')
conn.create_aggregate('geom_mean', 1, GeomMean)
conn.execute('CREATE TABLE nums (val REAL)')
conn.executemany('INSERT INTO nums VALUES (?)', [(2,), (8,)])
result = conn.execute('SELECT geom_mean(val) FROM nums').fetchone()[0]
assert abs(result - 4.0) < 0.0001, f'Geometric mean of 2,8 ... | api_usage |
37 | devbench-api-usage | python | import copy
import threading
class SafeCounter:
"""Thread-safe counter that supports deepcopy.
The lock cannot be deep-copied, so __deepcopy__ must
create a new lock while copying the value."""
def __init__(self, value=0):
self.value = value
self._lock = threading.Lock()
def increm... |
def __copy__(self):
new = SafeCounter(self.value)
return new
def __deepcopy__(self, memo):
new = SafeCounter(copy.deepcopy(self.value, memo))
memo[id(self)] = new
return new
|
# Test deep copying
counter = SafeCounter(42)
counter_copy = copy.deepcopy(counter)
print(f'Original: {counter.value}, Copy: {counter_copy.value}')
| c = SafeCounter(10)
c.increment()
c.increment()
assert c.value == 12
c2 = copy.deepcopy(c)
assert c2.value == 12, f'Expected 12, got {c2.value}'
assert hasattr(c2, '_lock'), 'Copied object should have _lock'
assert isinstance(c2._lock, type(threading.Lock())), 'Lock should be a new Lock'
assert c2._lock is not c._lock,... | api_usage |
38 | devbench-api-usage | python | import array
# Create typed arrays with different typecodes and inspect them
| int_arr = array.array('i', [1, 2, 3, 4, 5])
float_arr = array.array('d', [1.5, 2.5, 3.5])
addr, length = int_arr.buffer_info()
|
print(f'Int array: {int_arr}, buffer address: {addr}, length: {length}')
print(f'Float array: {float_arr}')
| assert int_arr.typecode == 'i'
assert float_arr.typecode == 'd'
assert len(int_arr) == 5
assert len(float_arr) == 3
assert length == 5, f'buffer_info length should be 5, got {length}'
assert isinstance(addr, int), 'Buffer address should be an integer'
assert list(int_arr) == [1, 2, 3, 4, 5]
assert list(float_arr) == [1... | api_usage |
39 | devbench-api-usage | python | import io
# Demonstrate proper use of BytesIO and StringIO
# and show that mixing types raises TypeError
| # BytesIO for binary data
bio = io.BytesIO()
bio.write(b'hello bytes')
bio.seek(0)
bytes_result = bio.read()
# StringIO for text data
sio = io.StringIO()
sio.write('hello string')
sio.seek(0)
str_result = sio.read()
|
print(f'BytesIO: {bytes_result!r}')
print(f'StringIO: {str_result!r}')
| assert bytes_result == b'hello bytes'
assert str_result == 'hello string'
assert isinstance(bytes_result, bytes)
assert isinstance(str_result, str)
# Verify that writing wrong type raises TypeError
bio2 = io.BytesIO()
try:
bio2.write('string to bytesio')
assert False, 'Should raise TypeError'
except TypeError:
... | api_usage |
40 | devbench-api-usage | python | from pathlib import PurePosixPath, PureWindowsPath
# Demonstrate differences between POSIX and Windows path handling
| posix = PurePosixPath('/usr/local/bin/python')
win = PureWindowsPath('C:/Users/Admin/file.txt')
posix_parts = posix.parts
win_parts = win.parts
posix_name = posix.name
win_suffix = win.suffix
win_drive = win.drive
|
print(f'POSIX parts: {posix_parts}')
print(f'Windows parts: {win_parts}')
| assert posix_parts == ('/', 'usr', 'local', 'bin', 'python')
assert win_parts == ('C:\\', 'Users', 'Admin', 'file.txt')
assert posix_name == 'python'
assert win_suffix == '.txt'
assert win_drive == 'C:'
assert posix.parent == PurePosixPath('/usr/local/bin')
# PurePosixPath doesn't understand drive letters
posix_c = Pur... | api_usage |
41 | devbench-api-usage | python | import math
# Compare floating point values with custom tolerances
| # Default tolerance comparison
close1 = math.isclose(1.0, 1.0000000001)
# Near zero: need abs_tol since rel_tol fails near zero
close2 = math.isclose(0.0, 0.0001, abs_tol=0.001)
not_close = math.isclose(0.0, 0.0001) # False with default abs_tol=0.0
# Custom rel_tol for looser comparison
close3 = math.isclose(1.0, 1.... |
print(f'close1={close1}, close2={close2}, not_close={not_close}, close3={close3}')
| assert close1 is True, 'Values within default rel_tol should be close'
assert close2 is True, 'Should be close with abs_tol=0.001'
assert not_close is False, 'Near-zero comparison fails with default abs_tol=0.0'
assert close3 is True, 'Should be close with rel_tol=0.2'
# Verify the near-zero trap
assert math.isclose(0.... | api_usage |
42 | devbench-api-usage | python | import secrets
# Generate various types of secure random data
| token_bytes = secrets.token_bytes(16)
token_hex = secrets.token_hex(16)
token_url = secrets.token_urlsafe(16)
random_int = secrets.randbelow(100)
|
print(f'Bytes: {token_bytes}')
print(f'Hex: {token_hex}')
print(f'URL-safe: {token_url}')
print(f'Random int: {random_int}')
| assert isinstance(token_bytes, bytes)
assert len(token_bytes) == 16
assert isinstance(token_hex, str)
assert len(token_hex) == 32, f'hex token should be 32 chars for 16 bytes, got {len(token_hex)}'
assert isinstance(token_url, str)
assert isinstance(random_int, int)
assert 0 <= random_int < 100
# Verify randomness (two... | api_usage |
43 | devbench-api-usage | python | import threading
import time
results = []
action_called = []
# Create a barrier for 3 threads with an action callback
# The action runs once when all threads reach the barrier
| def barrier_action():
action_called.append('action')
barrier = threading.Barrier(3, action=barrier_action)
def worker(name):
results.append(f'{name}_before')
barrier.wait()
results.append(f'{name}_after')
|
# Run the threads
threads = [threading.Thread(target=worker, args=(f't{i}',)) for i in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
| assert len(action_called) == 1, f'Action should be called once, got {len(action_called)}'
assert action_called[0] == 'action'
# All threads should have completed both phases
before_count = sum(1 for r in results if '_before' in r)
after_count = sum(1 for r in results if '_after' in r)
assert before_count == 3, f'All 3 ... | api_usage |
44 | devbench-api-usage | python | import xml.etree.ElementTree as ET
# Parse XML with namespaces
xml_data = '''<?xml version="1.0"?>
<root xmlns:ns="http://example.com/ns">
<ns:item id="1">First</ns:item>
<ns:item id="2">Second</ns:item>
<plain>No namespace</plain>
</root>'''
| root = ET.fromstring(xml_data)
ns = {'ns': 'http://example.com/ns'}
items = root.findall('ns:item', ns)
plain = root.find('plain')
item_texts = [item.text for item in items]
item_ids = [item.get('id') for item in items]
|
print(f'Items: {item_texts}')
print(f'IDs: {item_ids}')
print(f'Plain: {plain.text}')
| assert len(items) == 2, f'Should find 2 namespaced items, found {len(items)}'
assert item_texts == ['First', 'Second']
assert item_ids == ['1', '2']
assert plain.text == 'No namespace'
# Verify that searching without namespace map finds nothing
no_ns_items = root.findall('ns:item')
# Without namespace mapping, this sho... | api_usage |
45 | devbench-api-usage | python | import functools
# Create a class that orders by absolute value using total_ordering
@functools.total_ordering
class AbsVal:
def __init__(self, value):
self.value = value
| def __eq__(self, other):
if not isinstance(other, AbsVal):
return NotImplemented
return abs(self.value) == abs(other.value)
def __lt__(self, other):
if not isinstance(other, AbsVal):
return NotImplemented
return abs(self.value) < abs(other.value)
|
# Test the ordering
print(AbsVal(-3) < AbsVal(5))
print(AbsVal(-3) == AbsVal(3))
| assert AbsVal(-3) == AbsVal(3), 'Abs values should be equal'
assert AbsVal(-3) < AbsVal(5), '-3 < 5 by absolute value'
assert AbsVal(5) > AbsVal(-3), '5 > -3 by absolute value'
assert AbsVal(-3) <= AbsVal(3), 'Equal means also <='
assert AbsVal(-3) >= AbsVal(3), 'Equal means also >='
assert AbsVal(1) <= AbsVal(2), '1 <... | api_usage |
46 | devbench-api-usage | python | import typing
# Demonstrate get_type_hints resolving string (forward) annotations
# When classes are defined dynamically, you need to pass localns
| class Node:
value: int
children: typing.List['Node']
label: typing.Optional[str] = None
# Must pass localns={'Node': Node} to resolve forward reference 'Node'
hints = typing.get_type_hints(Node, localns={'Node': Node})
|
print(f'Type hints: {hints}')
| assert 'value' in hints
assert 'children' in hints
assert 'label' in hints
assert hints['value'] is int
# get_type_hints resolves the string 'Node' to the actual Node class
assert hints['children'] == typing.List[Node], f'Expected List[Node], got {hints["children"]}'
# Verify that Optional[str] is resolved properly
ass... | api_usage |
47 | devbench-api-usage | python | import dataclasses
from collections import OrderedDict
@dataclasses.dataclass
class Point:
x: float
y: float
z: float = 0.0
@dataclasses.dataclass
class Line:
start: Point
end: Point
# Convert nested dataclass to OrderedDict using dict_factory parameter
| line = Line(Point(1.0, 2.0), Point(3.0, 4.0, 5.0))
result = dataclasses.asdict(line, dict_factory=OrderedDict)
nested_types = [type(v) for v in result.values()]
|
print(f'Result: {result}')
print(f'Type: {type(result)}')
print(f'Nested types: {nested_types}')
| assert isinstance(result, OrderedDict), f'Expected OrderedDict, got {type(result)}'
assert isinstance(result['start'], OrderedDict), 'Nested should also be OrderedDict'
assert isinstance(result['end'], OrderedDict), 'Nested should also be OrderedDict'
assert result['start']['x'] == 1.0
assert result['start']['y'] == 2.... | api_usage |
48 | devbench-api-usage | python | import enum
# Create an enum where auto() generates lowercase member names as values
| class LowerEnum(enum.Enum):
@staticmethod
def _generate_next_value_(name, start, count, last_values):
return name.lower()
RED = enum.auto()
GREEN = enum.auto()
BLUE = enum.auto()
|
print(f'RED={LowerEnum.RED.value}, GREEN={LowerEnum.GREEN.value}, BLUE={LowerEnum.BLUE.value}')
| assert LowerEnum.RED.value == 'red', f'Expected red, got {LowerEnum.RED.value!r}'
assert LowerEnum.GREEN.value == 'green', f'Expected green, got {LowerEnum.GREEN.value!r}'
assert LowerEnum.BLUE.value == 'blue', f'Expected blue, got {LowerEnum.BLUE.value!r}'
assert LowerEnum('red') is LowerEnum.RED, 'Should be able to l... | api_usage |
49 | devbench-api-usage | python | import hmac
import hashlib
# Use hmac for message authentication and timing-safe comparison
| secret = b'my-secret-key'
message = b'important data'
digest = hmac.new(secret, message, hashlib.sha256).hexdigest()
# Timing-safe comparison
expected = hmac.new(secret, message, hashlib.sha256).hexdigest()
is_valid = hmac.compare_digest(digest, expected)
|
print(f'Digest: {digest}')
print(f'Valid: {is_valid}')
| assert is_valid is True, 'Same message should produce matching digest'
assert isinstance(digest, str), 'hexdigest should return str'
assert len(digest) == 64, f'SHA-256 hexdigest should be 64 chars, got {len(digest)}'
# Test with wrong message
wrong_digest = hmac.new(secret, b'wrong data', hashlib.sha256).hexdigest()
a... | api_usage |
50 | devbench-api-usage | python | import inspect
class MyClass:
class_var = 42
_private = 'hidden'
def method(self):
pass
def _private_method(self):
pass
@staticmethod
def static_method():
pass
@property
def prop(self):
return self.class_var
# Get only the public methods (not private... | public_methods = inspect.getmembers(
MyClass,
predicate=lambda m: (inspect.isfunction(m) or inspect.ismethod(m))
)
public_methods = [(name, m) for name, m in public_methods if not name.startswith('_')]
|
print(f'Public methods: {[name for name, _ in public_methods]}')
| names = [name for name, _ in public_methods]
assert 'method' in names, f'Should include method, got {names}'
assert 'static_method' in names, f'Should include static_method, got {names}'
assert '_private_method' not in names, 'Should exclude private methods'
assert '_private' not in names, 'Should exclude private attri... | api_usage |
1 | devbench-code-purpose-understanding | python | class ClaimAccumulator:
"""Adjudicates simple outpatient visits against member accumulators.
post_visit must be idempotent by visit_id. For a new visit it validates
the code and billed amount before mutating state. Patient responsibility is
applied in this order: optional facility fee, deductible, then ... | def post_visit(self, visit_id, code, billed_amount, facility=False):
if visit_id in self.visits:
return dict(self.visits[visit_id])
if code not in self.allowed_by_code:
raise ValueError("unknown service code")
billed_amount = float(billed_amount)
if billed_amo... |
acc = ClaimAccumulator({'PT': 200, 'XRAY': 150}, deductible_remaining=120, oop_remaining=160)
first = acc.post_visit('v1', 'PT', 180, facility=True)
assert first == {
'visit_id': 'v1', 'code': 'PT', 'allowed': 180.0,
'patient': 152.0, 'plan': 28.0, 'facility_fee': 25.0,
'deductible': 120.0, 'coinsurance': ... |
# Allowed amount is the lower of billed amount and contracted allowed amount.
acc2 = ClaimAccumulator({'LAB': 80}, deductible_remaining=30, oop_remaining=100, coinsurance=0.25)
res = acc2.post_visit('l1', 'LAB', 50)
assert res['allowed'] == 50.0
assert res['deductible'] == 30.0
assert res['coinsurance'] == 5.0
assert ... | code_purpose_understanding |
2 | devbench-code-purpose-understanding | python | class PayrollLedger:
"""Posts approved hourly timesheets into payroll.
post_timesheet is idempotent by sheet_id. For a new sheet it must validate
the employee and hours before mutating anything. Gross pay uses 40 regular
hours then 1.5x overtime. Benefit deductions are pre-tax and capped by gross.
T... | def post_timesheet(self, sheet_id, emp_id, hours, period):
if sheet_id in self.timesheets:
return dict(self.timesheets[sheet_id])
if emp_id not in self.employees:
raise ValueError("unknown employee")
emp = self.employees[emp_id]
if not emp['active']:
... |
ledger = PayrollLedger()
ledger.add_employee('e1', hourly_rate=20, tax_rate=0.10, benefit=50, garnishment_balance=100)
check = ledger.post_timesheet('ts1', 'e1', 45, '2026-04')
assert check == {
'sheet_id': 'ts1', 'emp_id': 'e1', 'period': '2026-04',
'regular_hours': 40.0, 'overtime_hours': 5.0,
'gross': 9... |
# Garnishment is capped at 25% of disposable pay when the balance is large.
ledger2 = PayrollLedger()
ledger2.add_employee('g1', hourly_rate=40, tax_rate=0.25, benefit=0, garnishment_balance=10000)
res = ledger2.post_timesheet('g-ts', 'g1', 40, '2026-05')
assert res['gross'] == 1600.0
assert res['tax'] == 400.0
assert... | code_purpose_understanding |
3 | devbench-code-purpose-understanding | python | class Subscription:
VALID_TRANSITIONS = {
'pending': ['active'],
'active': ['paused', 'cancelled'],
'paused': ['active', 'cancelled'],
'cancelled': []
}
def __init__(self, user_id, plan, cooldown=0):
self.user_id = user_id
self.plan = plan
self.state ... | def resume(self, timestamp):
if self.state != 'paused':
raise ValueError(f"Cannot resume from {self.state}")
if self.paused_at is not None and (timestamp - self.paused_at) < self.cooldown:
raise ValueError("Cooldown period has not elapsed")
self._transition('active', ... |
sub = Subscription('u1', 'pro', cooldown=100)
sub.activate(1000)
sub.pause(2000)
# Too soon to resume
try:
sub.resume(2050)
assert False, "Should fail due to cooldown"
except ValueError:
pass
# After cooldown
sub.resume(2100)
assert sub.state == 'active'
|
# Zero cooldown allows immediate resume
sub2 = Subscription('u2', 'basic', cooldown=0)
sub2.activate(100)
sub2.pause(200)
sub2.resume(200)
assert sub2.state == 'active'
# Exact cooldown boundary is allowed
sub3 = Subscription('u3', 'pro', cooldown=50)
sub3.activate(100)
sub3.pause(200)
sub3.resume(250)
assert sub3.st... | code_purpose_understanding |
4 | devbench-code-purpose-understanding | python | class PurchaseOrderBook:
"""Receives purchase-order shipments into inventory.
receive() is idempotent by receipt_id. It validates the purchase order,
receipt lines, and over-receipt limits before mutating anything. Accepted
units increase on-hand stock and weighted average cost. Defective units go
t... | def receive(self, po_id, receipt_id, lines, timestamp):
if receipt_id in self.receipts:
return dict(self.receipts[receipt_id])
if po_id not in self.orders:
raise ValueError("unknown purchase order")
order = self.orders[po_id]
if order['status'] == 'closed':
... |
book = PurchaseOrderBook()
book.create_order('PO1', 'Acme', [
{'sku': 'A', 'qty': 10, 'unit_cost': 5.00},
{'sku': 'B', 'qty': 4, 'unit_cost': 2.00},
])
first = book.receive('PO1', 'R1', [
{'sku': 'A', 'accepted': 6, 'defective': 1},
{'sku': 'B', 'accepted': 4, 'defective': 0},
], timestamp=100)
assert ... |
# Duplicate receipt lines for the same SKU are aggregated before over-receipt validation.
book2 = PurchaseOrderBook()
book2.create_order('PO2', 'Bravo', [{'sku': 'X', 'qty': 5, 'unit_cost': 10.0}])
try:
book2.receive('PO2', 'RX', [
{'sku': 'X', 'accepted': 3},
{'sku': 'X', 'accepted': 3},
], ti... | code_purpose_understanding |
5 | devbench-code-purpose-understanding | python | class Subscription:
VALID_TRANSITIONS = {
'pending': ['active'],
'active': ['paused', 'cancelled', 'active'],
'paused': ['active', 'cancelled'],
'cancelled': []
}
def __init__(self, user_id, plan, plan_price, total_days):
self.user_id = user_id
self.plan = pl... | def upgrade(self, new_plan, new_price, timestamp):
if self.state not in ('active', 'paused'):
raise ValueError("Can only upgrade active or paused subscriptions")
credit = self._compute_proration(self.plan_price)
cost = self._compute_proration(new_price)
self.balance_due =... |
sub = Subscription('u1', 'basic', 100.0, 30)
sub.activate(1)
sub.use_days(10)
sub.upgrade('pro', 150.0, 2)
assert sub.plan == 'pro'
assert sub.state == 'active'
remaining_frac = 20/30
expected_due = round(remaining_frac * 150.0 - remaining_frac * 100.0, 2)
assert sub.balance_due == expected_due
assert any(e.get('actio... |
# Upgrade from paused goes to active
sub2 = Subscription('u2', 'basic', 100.0, 30)
sub2.activate(1)
sub2.use_days(15)
sub2.pause(2)
sub2.upgrade('pro', 200.0, 3)
assert sub2.state == 'active'
assert sub2.plan == 'pro'
remaining_frac2 = 15/30
expected2 = round(remaining_frac2 * 200.0 - remaining_frac2 * 100.0, 2)
asser... | code_purpose_understanding |
6 | devbench-code-purpose-understanding | python | class CardStatement:
"""Credit-card statement ledger with a nonstandard payment waterfall.
apply_payment is idempotent by payment_id and validates amount before any
mutation. Payments allocate in this exact order: fees, interest, cash advance,
then purchases. Applied payment releases available credit up... | def apply_payment(self, payment_id, amount, timestamp):
if payment_id in self.payments:
return dict(self.payments[payment_id])
amount = float(amount)
if amount <= 0:
raise ValueError("payment amount must be positive")
remaining = amount
allocations = ... |
stmt = CardStatement(1000)
stmt.add_balance('purchases', 300)
stmt.add_balance('cash_advance', 100)
stmt.add_balance('interest', 20)
stmt.add_balance('fees', 30)
stmt.mark_delinquent()
res = stmt.apply_payment('p1', 175, timestamp=10)
assert res['allocations'] == {'fees': 30.0, 'interest': 20.0, 'cash_advance': 100.0,... |
# Fees and interest are paid before principal balances, and failed ids can be reused.
stmt2 = CardStatement(500)
stmt2.add_balance('purchases', 100)
stmt2.add_balance('interest', 50)
try:
stmt2.apply_payment('reuse', -5, timestamp=1)
assert False
except ValueError:
pass
assert 'reuse' not in stmt2.payments... | code_purpose_understanding |
7 | devbench-code-purpose-understanding | python | class TaxCalculator:
def __init__(self, brackets, std_deduction, phase_out_start):
self.brackets = brackets # [(upper_limit, rate), ...], last has None
self.std_deduction = std_deduction
self.phase_out_start = phase_out_start
def compute_tax(self, income):
tax = 0.0
pre... | def adjusted_deduction(self, gross_income):
if gross_income <= self.phase_out_start:
return self.std_deduction
excess = gross_income - self.phase_out_start
reduction = (excess // 1000) * 100
return max(self.std_deduction - reduction, 0)
def tax_owed(self, gross_incom... |
calc = TaxCalculator([(50000, 0.10), (None, 0.20)], std_deduction=12000, phase_out_start=80000)
# Below phase-out: full deduction
assert calc.adjusted_deduction(50000) == 12000
assert calc.tax_owed(50000) == calc.compute_tax(38000)
# At phase-out start: full deduction
assert calc.adjusted_deduction(80000) == 12000
... |
calc2 = TaxCalculator([(50000, 0.10), (None, 0.20)], std_deduction=12000, phase_out_start=80000)
# Exactly at full phase-out
assert calc2.adjusted_deduction(200000) == 0
assert calc2.tax_owed(200000) == calc2.compute_tax(200000)
# Just over phase-out by $500 (less than $1000, so no reduction yet)
assert calc2.adjuste... | code_purpose_understanding |
8 | devbench-code-purpose-understanding | python | class MarketplaceSettlement:
"""Settles captured marketplace orders to sellers.
settle_order is idempotent by settlement_id. It validates the order exists,
is captured, is not disputed, and has a delivery timestamp on or after the
capture timestamp before mutating anything. Commission is charged on item... | def settle_order(self, settlement_id, order_id, delivered_at):
if settlement_id in self.settlements:
return dict(self.settlements[settlement_id])
if order_id not in self.orders:
raise ValueError("unknown order")
order = self.orders[order_id]
if order['seller_i... |
ms = MarketplaceSettlement(commission_rate=0.10, reserve_rate=0.05)
ms.add_seller('s1', adjustment_balance=20)
ms.capture_order('o1', 's1', subtotal=100, shipping=10, captured_at=50)
res = ms.settle_order('st1', 'o1', delivered_at=60)
assert res == {
'settlement_id': 'st1', 'order_id': 'o1', 'gross': 110.0,
'c... |
# Adjustment larger than payout leaves a remaining adjustment and zero payout.
ms2 = MarketplaceSettlement(commission_rate=0.20, reserve_rate=0.10)
ms2.add_seller('s2', adjustment_balance=500)
ms2.capture_order('o2', 's2', subtotal=100, shipping=20, captured_at=10)
r2 = ms2.settle_order('st2', 'o2', delivered_at=10)
a... | code_purpose_understanding |
9 | devbench-code-purpose-understanding | python | class WarrantyClaimLedger:
"""Approves appliance warranty repair claims.
approve_repair is idempotent by approval_id. It validates the claim, labor,
and all requested parts before mutating anything. Covered parts plus labor
form the eligible amount. Uncovered parts and expedited fees are customer
re... | def approve_repair(self, approval_id, claim_id, part_lines, labor_hours, vendor, expedited=False):
if approval_id in self.approvals:
return dict(self.approvals[approval_id])
if claim_id not in self.claims:
raise ValueError("unknown claim")
claim = self.claims[claim_id... |
ledger = WarrantyClaimLedger(coverage_remaining=500, deductible_remaining=100, labor_rate=80)
ledger.add_part('PUMP', 50, covered=True)
ledger.add_part('KNOB', 30, covered=False)
ledger.open_claim('c1', 'SN1')
res = ledger.approve_repair('a1', 'c1', [
{'part_no': 'PUMP', 'qty': 2},
{'part_no': 'KNOB', 'qty': 1... |
# Coverage cap creates customer excess after deductible.
ledger2 = WarrantyClaimLedger(coverage_remaining=50, deductible_remaining=20, labor_rate=100)
ledger2.add_part('MOTOR', 100, covered=True)
ledger2.open_claim('c2', 'SN2')
r2 = ledger2.approve_repair('a2', 'c2', [{'part_no': 'MOTOR', 'qty': 1}], labor_hours=1, ve... | code_purpose_understanding |
10 | devbench-code-purpose-understanding | python | class Amortizer:
"""Generates an amortization schedule. Each month:
- interest = balance * monthly_rate (rounded to 2 decimals)
- For months 1..N-1: payment is fixed, principal = payment - interest
- For month N (last): principal = remaining balance, payment = principal + interest
This ensures final... | def schedule(self):
payment = self.monthly_payment()
balance = self.principal
result = []
for i in range(1, self.num_payments + 1):
interest = round(balance * self.monthly_rate, 2)
is_last = (i == self.num_payments)
princ = balance if is_last else ... |
am = Amortizer(10000, 0.06, 12)
sched = am.schedule()
assert len(sched) == 12
assert sched[0]['month'] == 1
assert sched[-1]['balance'] == 0.0
assert sched[-1]['month'] == 12
# All non-last payments should be the same
payments = [s['payment'] for s in sched[:-1]]
assert len(set(payments)) == 1
# Each row: payment =... |
# Zero interest rate
am2 = Amortizer(1200, 0.0, 12)
sched2 = am2.schedule()
assert sched2[-1]['balance'] == 0.0
for row in sched2:
assert row['interest'] == 0.0
assert row['payment'] == 100.0
# Large loan
am3 = Amortizer(500000, 0.05, 360)
sched3 = am3.schedule()
assert sched3[-1]['balance'] == 0.0
assert len... | code_purpose_understanding |
11 | devbench-code-purpose-understanding | python | class Inventory:
"""Batch-tracked inventory system.
Each stock addition creates a new batch with a unique sequential ID
(format B0001, B0002, ...), quantity, and expiry date.
Items are stored as name -> list of batch dicts.
add_stock must return the generated batch_id."""
def __init__(self):
... | def add_stock(self, name, qty, expiry):
batch_id = self._next_batch_id()
batch = {'qty': qty, 'expiry': expiry, 'batch_id': batch_id}
if name not in self.items:
self.items[name] = []
self.items[name].append(batch)
return batch_id
|
inv = Inventory()
b1 = inv.add_stock('aspirin', 100, 20251231)
b2 = inv.add_stock('aspirin', 50, 20260630)
b3 = inv.add_stock('ibuprofen', 200, 20251130)
assert inv.total_quantity('aspirin') == 150
assert inv.total_quantity('ibuprofen') == 200
assert b1 == 'B0001'
assert b2 == 'B0002'
assert b3 == 'B0003'
assert len(... |
inv2 = Inventory()
bid = inv2.add_stock('bandage', 10, 20301231)
assert bid == 'B0001'
assert inv2.total_quantity('bandage') == 10
assert inv2.items['bandage'][0]['expiry'] == 20301231
# Adding to same item
inv2.add_stock('bandage', 5, 20290101)
assert inv2.total_quantity('bandage') == 15
assert len(inv2.items['banda... | code_purpose_understanding |
12 | devbench-code-purpose-understanding | python | class Inventory:
def __init__(self):
self.items = {} # name -> list of {'qty': int, 'expiry': int, 'batch_id': str}
self._batch_counter = 0
def _next_batch_id(self):
self._batch_counter += 1
return f"B{self._batch_counter:04d}"
def add_stock(self, name, qty, expiry):
... | def remove_stock_fifo(self, name, qty):
if self.total_quantity(name) < qty:
raise ValueError("Insufficient stock")
rem = qty
while rem > 0:
take = min(self.items[name][0]['qty'], rem)
self.items[name][0]['qty'] -= take
rem -= take
i... |
inv = Inventory()
inv.add_stock('widget', 10, 20250101)
inv.add_stock('widget', 20, 20260101)
inv.add_stock('widget', 5, 20270101)
inv.remove_stock_fifo('widget', 15)
assert inv.total_quantity('widget') == 20
# First batch fully consumed, second partially
assert inv.items['widget'][0]['qty'] == 15
assert inv.items['w... |
inv2 = Inventory()
inv2.add_stock('nail', 5, 20250101)
inv2.add_stock('nail', 5, 20260101)
# Exact removal of first batch
inv2.remove_stock_fifo('nail', 5)
assert inv2.total_quantity('nail') == 5
assert len(inv2.items['nail']) == 1
# Remove all remaining
inv2.remove_stock_fifo('nail', 5)
assert inv2.total_quantity('... | code_purpose_understanding |
13 | devbench-code-purpose-understanding | python | class Inventory:
def __init__(self):
self.items = {}
def add_stock(self, name, qty, expiry, unit_cost):
if name not in self.items:
self.items[name] = []
self.items[name].append({
'qty': qty, 'expiry': expiry, 'unit_cost': unit_cost
})
def total_quant... | def remove_expired(self, current_date):
report = {'removed_items': [], 'total_waste_cost': 0.0}
for name in list(self.items.keys()):
expired = [b for b in self.items[name] if b['expiry'] < current_date]
for b in expired:
report['removed_items'].append(self._bu... |
inv = Inventory()
inv.add_stock('milk', 10, 20250101, 2.50)
inv.add_stock('milk', 5, 20250601, 2.50)
inv.add_stock('bread', 20, 20250115, 1.00)
inv.add_stock('cheese', 15, 20260101, 5.00)
report = inv.remove_expired(20250301)
assert inv.total_quantity('milk') == 5 # only the June batch remains
assert inv.total_quan... |
inv2 = Inventory()
inv2.add_stock('yogurt', 8, 20250101, 3.00)
inv2.add_stock('yogurt', 12, 20250201, 3.00)
# Remove with date between the two batches
report2 = inv2.remove_expired(20250115)
assert inv2.total_quantity('yogurt') == 12
assert report2['total_waste_cost'] == 24.0
# Remove all
report3 = inv2.remove_expir... | code_purpose_understanding |
14 | devbench-code-purpose-understanding | python | class Inventory:
"""Inventory with reorder-point tracking.
check_reorder returns a list of dicts for items below their
reorder point. Each dict has: name, current, reorder_point, shortfall.
Items AT their reorder point do NOT need reorder (strictly less than).
Items with reorder points but no stock ... | def check_reorder(self):
needs_reorder = []
for name, minimum in self.reorder_points.items():
current = self.total_quantity(name)
if current < minimum:
needs_reorder.append({
'name': name, 'current': current,
'reorder_po... |
inv = Inventory()
inv.add_stock('nails', 50)
inv.add_stock('screws', 10)
inv.set_reorder_point('nails', 100)
inv.set_reorder_point('screws', 5)
inv.set_reorder_point('bolts', 20)
reorder = inv.check_reorder()
names = [r['name'] for r in reorder]
assert 'nails' in names # 50 < 100
assert 'bolts' in names # 0 < 20
as... |
inv2 = Inventory()
inv2.set_reorder_point('x', 10)
reorder2 = inv2.check_reorder()
assert len(reorder2) == 1
assert reorder2[0]['current'] == 0
assert reorder2[0]['shortfall'] == 10
# All above reorder point
inv3 = Inventory()
inv3.add_stock('a', 100)
inv3.set_reorder_point('a', 50)
assert inv3.check_reorder() == []
... | code_purpose_understanding |
15 | devbench-code-purpose-understanding | python | class Inventory:
"""Inventory system with batch merging capability.
merge_batches(name) consolidates batches that share the same expiry date.
Merged batch qty = sum of quantities.
Merged batch unit_cost = weighted average (total_cost / total_qty),
rounded to 2 decimal places.
Batches with differ... | def merge_batches(self, name):
if name not in self.items or len(self.items[name]) <= 1:
return
groups = {}
for b in self.items[name]:
groups.setdefault(b['expiry'], {'qty': 0, 'cost': 0.0})
groups[b['expiry']]['qty'] += b['qty']
groups[b['expir... |
inv = Inventory()
inv.add_stock('aspirin', 100, 20251231, 0.50)
inv.add_stock('aspirin', 50, 20251231, 0.60)
inv.add_stock('aspirin', 30, 20260630, 0.55)
inv.merge_batches('aspirin')
assert len(inv.items['aspirin']) == 2 # two distinct expiry dates
assert inv.total_quantity('aspirin') == 180
# Find the merged batch... |
# Single batch - no change
inv2 = Inventory()
inv2.add_stock('x', 10, 20250101, 1.00)
inv2.merge_batches('x')
assert len(inv2.items['x']) == 1
assert inv2.items['x'][0]['unit_cost'] == 1.00
# Non-existent item - no error
inv2.merge_batches('nonexistent')
# All same expiry
inv3 = Inventory()
inv3.add_stock('y', 10, 2... | code_purpose_understanding |
16 | devbench-code-purpose-understanding | python | class PermissionSystem:
"""Role-based permission system with explicit deny support.
Roles have hierarchy levels (higher = more permissions).
Permissions have required levels.
A user has a role, and can also have explicitly denied permissions.
has_permission checks:
1. If user doesn't exist -> Fa... | def has_permission(self, user_id, permission):
if user_id not in self.users:
return False
user = self.users[user_id]
if permission in user['denied']:
return False
role_level = self.ROLE_HIERARCHY[user['role']]
perm_level = self.PERMISSION_LEVEL.get(per... |
ps = PermissionSystem()
ps.add_user('alice', 'admin')
ps.add_user('bob', 'manager')
ps.add_user('charlie', 'viewer')
assert ps.has_permission('alice', 'delete') == True
assert ps.has_permission('bob', 'write') == True
assert ps.has_permission('bob', 'delete') == False
assert ps.has_permission('charlie', 'read') == Tr... |
ps2 = PermissionSystem()
ps2.add_user('dave', 'admin')
ps2.deny_permission('dave', 'delete')
# Explicit deny overrides role
assert ps2.has_permission('dave', 'delete') == False
assert ps2.has_permission('dave', 'write') == True
# Unknown user
assert ps2.has_permission('unknown', 'read') == False
# Unknown permissio... | code_purpose_understanding |
17 | devbench-code-purpose-understanding | python | class LoanAccount:
"""Loan servicer with a non-standard payment waterfall.
apply_payment(amount, timestamp) must allocate cash in this exact order:
1. late_fees
2. principal
3. accrued_interest
4. unapplied_cash
This intentionally differs from the usual interest-before-principal order.
C... | def apply_payment(self, amount, timestamp):
if amount <= 0:
raise ValueError("payment amount must be positive")
remaining = round(float(amount), 2)
if self.status == 'charged_off':
self.recovery_cash = round(self.recovery_cash + remaining, 2)
allocation = ... |
loan = LoanAccount(100)
loan.accrue_interest(30)
loan.add_late_fee(10)
allocation = loan.apply_payment(50, timestamp=1)
assert allocation == {
'late_fees': 10.0,
'principal': 40.0,
'accrued_interest': 0.0,
'unapplied_cash': 0.0,
'recovery_cash': 0.0,
}
assert loan.principal == 60.0
assert loan.acc... |
loan2 = LoanAccount(25)
loan2.accrue_interest(7)
loan2.add_late_fee(3)
alloc = loan2.apply_payment(3, timestamp=10)
assert alloc['late_fees'] == 3.0
assert alloc['principal'] == 0.0
assert loan2.principal == 25.0
assert loan2.accrued_interest == 7.0
assert loan2.status == 'current'
alloc2 = loan2.apply_payment(32, ti... | code_purpose_understanding |
18 | devbench-code-purpose-understanding | python | class TemporalPermissions:
"""Time-bounded permission system.
Grants and denials have valid_from (inclusive) and valid_until (exclusive, or None=forever).
_is_active checks if an entry is active at a given time.
has_permission: deny-overrides-grant.
- If any active denial matches -> False
- If a... | def has_permission(self, user, perm, current_time):
for d in self.denials:
if d['user'] == user and d['perm'] == perm and self._is_active(d, current_time):
return False
for g in self.grants:
if g['user'] == user and g['perm'] == perm and self._is_active(g, cur... |
tp = TemporalPermissions()
tp.grant('alice', 'read', 100, 200)
tp.grant('alice', 'write', 100, None) # no expiry
tp.deny('alice', 'write', 150, 180)
# At time 120: read=yes, write=yes
assert tp.has_permission('alice', 'read', 120) == True
assert tp.has_permission('alice', 'write', 120) == True
# At time 160: read=y... |
tp2 = TemporalPermissions()
# Grant and deny at same time range - deny wins
tp2.grant('bob', 'delete', 0, 100)
tp2.deny('bob', 'delete', 0, 100)
assert tp2.has_permission('bob', 'delete', 50) == False
# Before valid_from
tp2.grant('charlie', 'read', 100, None)
assert tp2.has_permission('charlie', 'read', 50) == False... | code_purpose_understanding |
19 | devbench-code-purpose-understanding | python | class ClaimAdjudicator:
"""Medical claim adjudication with plan accumulators.
adjudicate_line(code, billed_amount, prior_auth=False) must:
- Denied codes return status 'denied' and do not change accumulators.
- Codes requiring prior auth return status 'auth_required' unless prior_auth=True.
- allowe... | def adjudicate_line(self, code, billed_amount, prior_auth=False):
billed_amount = float(billed_amount)
if code in self.denied_codes:
report = {'code': code, 'status': 'denied', 'allowed': 0.0, 'patient': 0.0, 'plan': 0.0}
self.audit_log.append(report)
return repor... |
claim = ClaimAdjudicator(deductible_remaining=100, oop_remaining=500, coinsurance=0.2, copay=25)
claim.set_allowed_rate('OV', 120)
claim.set_allowed_rate('MRI', 600)
claim.set_copay_code('OV')
claim.require_prior_auth('MRI')
claim.deny_code('X999')
denied = claim.adjudicate_line('X999', 1000)
assert denied == {'code'... |
claim2 = ClaimAdjudicator(deductible_remaining=0, oop_remaining=50, coinsurance=0.5, copay=25)
claim2.set_allowed_rate('THER', 200)
claim2.set_copay_code('THER')
ther = claim2.adjudicate_line('THER', 500)
# raw patient = copay 25 + 50% of 175 = 112.5, capped by oop_remaining 50
assert ther == {'code': 'THER', 'status'... | code_purpose_understanding |
20 | devbench-code-purpose-understanding | python | class PaymentLedger:
"""Authorization/capture ledger.
capture(auth_id, capture_id, amount, timestamp) must:
- Treat capture_id as idempotency key: repeated capture_id returns the
original report and does not append another audit entry.
- Validate before mutating: auth must exist, amount must be po... | def capture(self, auth_id, capture_id, amount, timestamp):
if capture_id in self.captures:
return self.captures[capture_id]
if auth_id not in self.authorizations:
raise ValueError("unknown authorization")
amount = self._money(float(amount))
if amount <= 0:
... |
ledger = PaymentLedger(fee_rate=0.029)
ledger.authorize('auth-1', 100.00)
cap1 = ledger.capture('auth-1', 'cap-1', 40.00, timestamp=10)
assert cap1 == {
'auth_id': 'auth-1', 'capture_id': 'cap-1', 'amount': 40.0,
'fee': 1.16, 'net': 38.84, 'remaining_auth': 60.0,
'status': 'partially_captured', 'ts': 10,
... |
ledger2 = PaymentLedger(fee_rate=0.10)
ledger2.authorize('a', 10)
try:
ledger2.capture('missing', 'c0', 1, timestamp=1)
assert False, "unknown auth should fail"
except ValueError:
pass
try:
ledger2.capture('a', 'c0', 0, timestamp=1)
assert False, "zero capture should fail"
except ValueError:
pa... | code_purpose_understanding |
21 | devbench-code-purpose-understanding | python | class TransferPicker:
"""Warehouse transfer picking.
pick(sku, qty, pick_id, ship_date) must:
- Treat pick_id as idempotency key: replay returns the original report and
does not reserve more stock or append another audit entry.
- Ignore expired batches where expiry <= ship_date.
- Allocate by ... | def pick(self, sku, qty, pick_id, ship_date):
if pick_id in self.picks:
return self.picks[pick_id]
if qty <= 0:
raise ValueError("pick quantity must be positive")
candidates = []
for batch in self.stock.get(sku, []):
available = batch['qty'] - batc... |
picker = TransferPicker()
picker.add_batch('A', 'late', 5, 20250601)
picker.add_batch('A', 'early', 4, 20250501)
picker.add_batch('A', 'expired', 99, 20250401)
report = picker.pick('A', 7, 'pick-1', 20250415)
assert report == {
'pick_id': 'pick-1',
'sku': 'A',
'qty': 7,
'ship_date': 20250415,
'all... |
picker2 = TransferPicker()
picker2.add_batch('B', 'b1', 1, 20250102)
picker2.add_batch('B', 'b2', 2, 20250103)
try:
picker2.pick('B', 0, 'bad', 20250101)
assert False, "zero qty should fail"
except ValueError:
pass
assert picker2._snapshot('B') == [
{'batch_id': 'b1', 'qty': 1, 'reserved': 0, 'expiry':... | code_purpose_understanding |
22 | devbench-code-purpose-understanding | python | class UsageBilling:
"""Usage invoice closing.
close_period(period_id) must:
- Be idempotent: if the period was already invoiced, return the same
invoice object and do not append audit entries again.
- Sum only events for period_id whose billed flag is False.
- subtotal = base_fee + max(units -... | def close_period(self, period_id):
if period_id in self.invoices:
return self.invoices[period_id]
period_events = [event for event in self.events if event['period_id'] == period_id and not event['billed']]
units = sum(event['units'] for event in period_events)
overage_uni... |
billing = UsageBilling(base_fee=100, included_units=1000, overage_rate=0.10, minimum_commit=150)
billing.record_usage('e1', '2026-01', 800)
billing.record_usage('e2', '2026-01', 500)
billing.record_usage('e3', '2026-02', 999)
billing.add_credit('c1', 30)
billing.add_credit('c2', 200)
invoice = billing.close_period('2... |
billing2 = UsageBilling(base_fee=50, included_units=10, overage_rate=2, minimum_commit=0)
billing2.record_usage('a', 'p1', 5)
billing2.record_usage('b', 'p1', 20)
billing2.add_credit('credit', 15)
invoice2 = billing2.close_period('p1')
assert invoice2 == {
'period_id': 'p1',
'units': 25,
'overage_units': 1... | code_purpose_understanding |
23 | devbench-code-purpose-understanding | python | class LeaveLedger:
"""Employee leave request ledger.
request_leave(employee, request_id, dates, leave_type, half_days=()) must:
- Be idempotent by request_id: replay returns the original report object
without changing balances or audit log.
- Validate before mutating: employee exists, dates are no... | def request_leave(self, employee, request_id, dates, leave_type, half_days=()):
if request_id in self.requests:
return self.requests[request_id]
if employee not in self.employees:
raise ValueError("unknown employee")
if not dates:
raise ValueError("leave d... |
ledger = LeaveLedger()
ledger.add_employee('alice', vacation=5, sick=1)
ledger.add_blackout('2026-12-25')
vac = ledger.request_leave('alice', 'r1', ['2026-05-01', '2026-05-02'], 'vacation', half_days=['2026-05-02'])
assert vac == {
'employee': 'alice', 'request_id': 'r1',
'dates': ['2026-05-01', '2026-05-02']... |
ledger2 = LeaveLedger()
ledger2.add_employee('bob', vacation=1, sick=0)
for args in [
('missing', 'x', ['2026-01-01'], 'vacation'),
('bob', 'x', [], 'vacation'),
('bob', 'x', ['2026-01-01'], 'jury'),
]:
try:
ledger2.request_leave(*args)
assert False, "invalid request should fail"
ex... | code_purpose_understanding |
24 | devbench-code-purpose-understanding | python | class EntitlementLedger:
"""Feature entitlement consumption.
consume(user, feature, units, request_id, timestamp) must:
- Be idempotent by request_id: replay returns the original result object and
does not consume more units or append another audit entry.
- Active denials override grants. Denials ... | def consume(self, user, feature, units, request_id, timestamp):
if request_id in self.consumptions:
return self.consumptions[request_id]
if units <= 0:
raise ValueError("units must be positive")
for denial in self.denials:
if denial['user'] == user and den... |
ledger = EntitlementLedger()
ledger.grant('g-late', 'u1', 'api', 10, valid_from=0, valid_until=None)
ledger.grant('g-soon', 'u1', 'api', 4, valid_from=0, valid_until=50)
ledger.grant('g-expired', 'u1', 'api', 99, valid_from=0, valid_until=10)
ledger.grant('g-other', 'u2', 'api', 100, valid_from=0, valid_until=50)
res... |
ledger2 = EntitlementLedger()
ledger2.grant('a', 'u', 'f', 1, 10, 20)
try:
ledger2.consume('u', 'f', 1, 'early', timestamp=9)
assert False, "grant not active yet"
except ValueError:
pass
assert ledger2._snapshot()[0]['remaining'] == 1
try:
ledger2.consume('u', 'f', 0, 'zero', timestamp=10)
assert ... | code_purpose_understanding |
25 | devbench-code-purpose-understanding | python | class LWWProjection:
"""Last-Writer-Wins projection. Each key tracks the timestamp
of the last write. A write with an older timestamp is ignored.
Deletes are tracked as tombstones with timestamps.
apply_event handles 'set' and 'delete' actions with timestamp 'ts'.
For 'set': ignore if tombstone >= t... | def apply_event(self, event):
key, ts, action = event['key'], event['ts'], event['action']
if action == 'set':
if self._is_stale_set(key, ts):
return
self.data[key], self.timestamps[key] = event['value'], ts
elif action == 'delete':
if self... |
proj = LWWProjection()
events = [
{'key': 'x', 'action': 'set', 'value': 1, 'ts': 100},
{'key': 'x', 'action': 'set', 'value': 2, 'ts': 200},
{'key': 'x', 'action': 'set', 'value': 0, 'ts': 50}, # old, ignored
]
proj.project(events)
assert proj.data == {'x': 2}
# Delete then set with older timestamp
proj... |
# Set after delete with newer timestamp
proj3 = LWWProjection()
proj3.project([
{'key': 'z', 'action': 'set', 'value': 1, 'ts': 100},
{'key': 'z', 'action': 'delete', 'ts': 200},
{'key': 'z', 'action': 'set', 'value': 2, 'ts': 300}, # newer than delete
])
assert proj3.data == {'z': 2}
# Equal timestamps:... | code_purpose_understanding |
26 | devbench-code-purpose-understanding | python | class MilestoneEscrow:
"""Construction milestone escrow.
record_progress(milestone_id, release_id, percent_complete, defects_open, timestamp)
must:
- Be idempotent by release_id.
- Validate before mutating: milestone exists and percent_complete is between
the current percent and 100 inclusive.... | def record_progress(self, milestone_id, release_id, percent_complete, defects_open, timestamp):
if release_id in self.releases:
return self.releases[release_id]
if milestone_id not in self.milestones:
raise ValueError("unknown milestone")
milestone = self.milestones[m... |
escrow = MilestoneEscrow()
escrow.add_milestone('foundation', amount=1000, holdback_rate=0.10)
r1 = escrow.record_progress('foundation', 'rel-1', 40, defects_open=False, timestamp=1)
assert r1 == {
'milestone_id': 'foundation', 'release_id': 'rel-1',
'delta_percent': 40.0, 'gross_earned': 400.0, 'holdback': 4... |
escrow2 = MilestoneEscrow()
escrow2.add_milestone('roof', amount=333.33, holdback_rate=0.15)
try:
escrow2.record_progress('missing', 'x', 10, False, 1)
assert False, "unknown milestone"
except ValueError:
pass
try:
escrow2.record_progress('roof', 'x', 101, False, 1)
assert False, "over 100 percent"... | code_purpose_understanding |
27 | devbench-code-purpose-understanding | python | class PharmacyRefill:
"""Prescription refill policy using integer service days.
fill(rx_id, fill_id, requested_days, service_day, expedited=False) must:
- Be idempotent by fill_id.
- Validate before mutating: rx exists, requested_days > 0, prescription is active.
- First fill does not consume a refi... | def fill(self, rx_id, fill_id, requested_days, service_day, expedited=False):
if fill_id in self.fills:
return self.fills[fill_id]
if rx_id not in self.prescriptions:
raise ValueError("unknown prescription")
rx = self.prescriptions[rx_id]
if not rx['active']:
... |
pharm = PharmacyRefill(plan_max_days=30, refill_threshold=0.8)
pharm.add_prescription('rx1', daily_qty=2, refills=1, tier='preferred')
first = pharm.fill('rx1', 'fill-1', 30, service_day=100)
assert first == {
'rx_id': 'rx1', 'fill_id': 'fill-1', 'days_supply': 30,
'quantity': 60, 'copay': 20.0, 'refills_rema... |
pharm2 = PharmacyRefill(plan_max_days=30, refill_threshold=0.75)
pharm2.add_prescription('ctrl', daily_qty=1, refills=1, controlled=True)
for args in [
('missing', 'x', 1, 1, False),
('ctrl', 'x', 0, 1, False),
('ctrl', 'x', 31, 1, False),
('ctrl', 'x', 31, 1, True),
]:
try:
pharm2.fill(*ar... | code_purpose_understanding |
28 | devbench-code-purpose-understanding | python | class IncidentSLA:
"""Incident SLA state machine using integer minute timestamps.
transition(event_id, new_state, timestamp, reason='') must:
- Be idempotent by event_id.
- Enforce transitions:
open -> acknowledged
acknowledged -> paused or mitigated
paused -> acknowledged
mitiga... | def transition(self, event_id, new_state, timestamp, reason=''):
if event_id in self.events:
return self.events[event_id]
if new_state not in self.ALLOWED[self.state]:
raise ValueError(f"Cannot transition from {self.state} to {new_state}")
old_state = self.state
... |
inc = IncidentSLA('inc1', created_at=100, ack_target=10, resolve_target=60)
ack = inc.transition('e1', 'acknowledged', 108, reason='paged')
assert ack == {
'event_id': 'e1', 'from': 'open', 'to': 'acknowledged', 'ts': 108,
'reason': 'paged', 'elapsed': 8, 'paused_total': 0,
'ack_breached': False, 'resolve_... |
inc2 = IncidentSLA('inc2', created_at=0, ack_target=5, resolve_target=20)
before = inc2._snapshot()
try:
inc2.transition('bad', 'resolved', 1)
assert False, "invalid transition"
except ValueError:
pass
assert inc2._snapshot() == before
assert inc2.audit_log == []
late_ack = inc2.transition('a', 'acknowled... | code_purpose_understanding |
29 | devbench-code-purpose-understanding | python | class LRUCache:
def __init__(self, max_size):
self.max_size = max_size
self.cache = {}
self.access_order = [] # most-recently-used at the END
def _touch(self, key):
if key in self.access_order:
self.access_order.remove(key)
self.access_order.append(key)
... | def set(self, key, value):
if key in self.cache:
self.cache[key] = value
self._touch(key)
return
if len(self.cache) >= self.max_size:
evicted = self.access_order.pop(0)
del self.cache[evicted]
self.cache[key] = value
self._t... | lru = LRUCache(3)
lru.set('a', 1)
lru.set('b', 2)
lru.set('c', 3)
lru.get('a')
# Adding 'd' should evict 'b' (LRU), not 'a'
lru.set('d', 4)
assert lru.get('b') is None, 'b should have been evicted (LRU)'
assert lru.get('a') == 1
assert lru.get('c') == 3
assert lru.get('d') == 4
| lru2 = LRUCache(2)
lru2.set('x', 1)
lru2.set('y', 2)
lru2.set('x', 10)
assert lru2.get('x') == 10
assert lru2.get('y') == 2
lru3 = LRUCache(3)
lru3.set('a', 1)
lru3.set('b', 2)
lru3.set('c', 3)
lru3.get('a')
lru3.get('b')
lru3.set('d', 4) # evict 'c'
assert lru3.get('c') is None
assert lru3.get('a') == 1
assert lru3.... | code_purpose_understanding |
30 | devbench-code-purpose-understanding | python | class TwoLevelCache:
def __init__(self, l1_max_size):
self.l1 = {}
self.l1_order = []
self.l1_max = l1_max_size
self.l2 = {}
def _l1_evict(self):
if len(self.l1) > self.l1_max:
oldest = self.l1_order.pop(0)
del self.l1[oldest]
# Inclus... | def get(self, key):
if key in self.l1:
self._l1_touch(key); return self.l1[key]
if key in self.l2:
self.l1[key] = self.l2[key]
self._l1_touch(key); self._l1_evict()
return self.l2[key]
return None
def set(self, key, value):
self.l1... | tc = TwoLevelCache(2)
tc.set('a', 1)
tc.set('b', 2)
tc.set('c', 3) # evicts 'a' from L1
assert tc.l1.get('a') is None
assert tc.l2.get('a') == 1 # inclusive: L2 keeps it
assert tc.get('a') == 1 # promotes from L2
assert 'a' in tc.l1
| tc2 = TwoLevelCache(2)
tc2.set('x', 10)
assert tc2.l1['x'] == 10
assert tc2.l2['x'] == 10
tc2.set('y', 20)
tc2.set('z', 30)
assert 'x' not in tc2.l1
assert tc2.get('x') == 10
tc3 = TwoLevelCache(1)
tc3.set('a', 1)
tc3.set('b', 2)
tc3.set('c', 3)
assert tc3.l2 == {'a': 1, 'b': 2, 'c': 3}
assert tc3.get('a') == 1
| code_purpose_understanding |
31 | devbench-code-purpose-understanding | python | class FixedWindowRateLimiter:
"""Allows N requests per fixed time window.
Window resets at fixed intervals from epoch, not rolling."""
def __init__(self, max_requests, window_seconds, clock=None):
self.max_requests = max_requests
self.window_seconds = window_seconds
self.clock = clo... | def allow(self, key='default'):
now = self.clock()
wid = self._window_id(now)
bucket = (key, wid)
current = self.counts.get(bucket, 0)
if current >= self.max_requests:
return False
self.counts[bucket] = current + 1
return True
| class FakeClock:
def __init__(self, start=0):
self.now = start
def __call__(self):
return self.now
def advance(self, s):
self.now += s
clock = FakeClock(100)
rl = FixedWindowRateLimiter(3, 10, clock=clock)
assert rl.allow('u1') == True
assert rl.allow('u1') == True
assert rl.allow('... | clock2 = FakeClock(19)
rl2 = FixedWindowRateLimiter(2, 10, clock=clock2)
assert rl2.allow() == True
assert rl2.allow() == True
assert rl2.allow() == False
clock2.advance(1)
assert rl2.allow() == True
rl3 = FixedWindowRateLimiter(1, 10, clock=FakeClock(0))
assert rl3.allow('a') == True
assert rl3.allow('a') == False
as... | code_purpose_understanding |
32 | devbench-code-purpose-understanding | python | class TokenBucketLimiter:
"""Tokens refill at 'rate' per second up to 'max_burst'.
Each allow() consumes one token. New keys start with max_burst tokens."""
def __init__(self, rate, max_burst, clock=None):
self.rate = rate
self.max_burst = max_burst
self.clock = clock or (lambda: __... | def allow(self, key='default'):
now = self.clock()
if key not in self.tokens:
self.tokens[key] = self.max_burst
self.last_refill[key] = now
elapsed = now - self.last_refill[key]
self.tokens[key] = min(self.max_burst, self.tokens[key] + elapsed * self.rate)
... | class FakeClock:
def __init__(self, start=0):
self.now = start
def __call__(self):
return self.now
def advance(self, s):
self.now += s
clock = FakeClock(0)
tb = TokenBucketLimiter(rate=1, max_burst=5, clock=clock)
for i in range(5):
assert tb.allow() == True, f'Burst {i} should... | clock2 = FakeClock(0)
tb2 = TokenBucketLimiter(rate=2, max_burst=3, clock=clock2)
for _ in range(3): tb2.allow()
assert tb2.allow() == False
clock2.advance(0.5)
assert tb2.allow() == True
assert tb2.allow() == False
clock3 = FakeClock(0)
tb3 = TokenBucketLimiter(rate=1, max_burst=1, clock=clock3)
assert tb3.allow('a')... | code_purpose_understanding |
33 | devbench-code-purpose-understanding | python | class QuotaManager:
"""Daily and monthly quotas reset at calendar boundaries.
Daily resets at midnight (day change). Monthly resets on 1st.
Both must have capacity for a request to be allowed."""
def __init__(self, daily_limit, monthly_limit, clock=None):
self.daily_limit = daily_limit
... | def check_and_consume(self, user):
year, month, day = self.clock()
d_key = (user, year, month, day)
m_key = (user, year, month)
d_used = self.daily_usage.get(d_key, 0)
m_used = self.monthly_usage.get(m_key, 0)
if d_used >= self.daily_limit or m_used >= self.monthly_li... | current_date = [2024, 1, 15]
def fake_clock():
return tuple(current_date)
qm = QuotaManager(daily_limit=3, monthly_limit=5, clock=fake_clock)
assert qm.check_and_consume('alice') == True
assert qm.check_and_consume('alice') == True
assert qm.check_and_consume('alice') == True
assert qm.check_and_consume('alice') ... | current_date[:] = [2024, 2, 1]
assert qm.check_and_consume('alice') == True # new month resets
assert qm.check_and_consume('bob') == True
current_date[:] = [2024, 2, 2]
assert qm.check_and_consume('bob') == True
| code_purpose_understanding |
34 | devbench-code-purpose-understanding | python | class EndpointRateLimiter:
def __init__(self, clock=None):
self.clock = clock or (lambda: __import__('time').monotonic())
self.limits = {} # endpoint -> (max_req, window_sec)
self.requests = {} # (endpoint, user, window_id) -> count
def configure(self, endpoint, max_requests, wi... | def allow(self, endpoint, user=None):
if endpoint not in self.limits:
return True
max_req, window_sec = self.limits[endpoint]
now = self.clock()
wid = int(now // window_sec)
key = (endpoint, user, wid)
current = self.requests.get(key, 0)
if current... | class FakeClock:
def __init__(self, start=0):
self.now = start
def __call__(self):
return self.now
def advance(self, s):
self.now += s
clock = FakeClock(0)
erl = EndpointRateLimiter(clock=clock)
erl.configure('/api/search', 2, 60)
erl.configure('/api/upload', 1, 60)
assert erl.allo... | clock2 = FakeClock(0)
erl2 = EndpointRateLimiter(clock=clock2)
erl2.configure('/api/data', 1, 60)
assert erl2.allow('/api/data', 'alice') == True
assert erl2.allow('/api/data', 'alice') == False
assert erl2.allow('/api/data', 'bob') == True
clock2.advance(60)
assert erl2.allow('/api/data', 'alice') == True
| code_purpose_understanding |
35 | devbench-code-purpose-understanding | python | class TieredRateLimiter:
def __init__(self, clock=None):
self.clock = clock or (lambda: __import__('time').monotonic())
self.tiers = {}
self.user_tiers = {}
self.counts = {}
self.default_tier = 'basic'
def define_tier(self, name, max_requests, window_seconds):
se... | def allow(self, user):
tier = self.user_tiers.get(user, self.default_tier)
if tier not in self.tiers:
return True
max_req, window_sec = self.tiers[tier]
now = self.clock()
key = (user, int(now // window_sec))
current = self.counts.get(key, 0)
if cu... | class FakeClock:
def __init__(self, start=0):
self.now = start
def __call__(self):
return self.now
clock = FakeClock(0)
trl = TieredRateLimiter(clock=clock)
trl.define_tier('basic', 2, 60)
trl.define_tier('premium', 10, 60)
trl.assign_user('alice', 'premium')
assert trl.allow('alice') == True
... | clock2 = FakeClock(0)
trl2 = TieredRateLimiter(clock=clock2)
trl2.define_tier('basic', 2, 60)
trl2.define_tier('premium', 5, 60)
trl2.assign_user('vip', 'premium')
for _ in range(5):
assert trl2.allow('vip') == True
assert trl2.allow('vip') == False
for _ in range(2):
assert trl2.allow('stranger') == True
ass... | code_purpose_understanding |
36 | devbench-code-purpose-understanding | python | class ValidationResult:
def __init__(self, is_valid, errors=None):
self.is_valid = is_valid
self.errors = errors or []
class FailFastValidator:
"""Runs validators in order. Stops at the FIRST failure.
Each validator returns (bool, error_message)."""
def __init__(self):
self.val... | def validate(self, data):
for name, fn in self.validators:
ok, msg = fn(data)
if not ok:
return ValidationResult(False, [f'{name}: {msg}'])
return ValidationResult(True)
| v = FailFastValidator()
v.add('not_empty', lambda d: (bool(d.get('name')), 'name is required'))
v.add('name_length', lambda d: (len(d.get('name', '')) >= 2, 'name too short'))
v.add('has_email', lambda d: (bool(d.get('email')), 'email is required'))
result = v.validate({'name': 'Alice', 'email': 'a@b.com'})
assert res... | v2 = FailFastValidator()
r = v2.validate({})
assert r.is_valid == True
v3 = FailFastValidator()
v3.add('a', lambda d: (False, 'err_a'))
v3.add('b', lambda d: (False, 'err_b'))
v3.add('c', lambda d: (False, 'err_c'))
r3 = v3.validate({})
assert len(r3.errors) == 1
assert 'a' in r3.errors[0]
| code_purpose_understanding |
37 | devbench-code-purpose-understanding | python | class ValidationError:
def __init__(self, field, message):
self.field = field
self.message = message
class CollectAllValidator:
"""Runs ALL validators regardless of failures. Collects every error."""
def __init__(self):
self.validators = []
def add(self, field, validator_fn):
... | def validate(self, data):
errors = []
for field, fn in self.validators:
ok, msg = fn(data)
if not ok:
errors.append(ValidationError(field, msg))
return errors
| v = CollectAllValidator()
v.add('name', lambda d: (bool(d.get('name')), 'required'))
v.add('email', lambda d: ('@' in d.get('email', ''), 'invalid'))
v.add('age', lambda d: (isinstance(d.get('age'), int) and d['age'] >= 0, 'bad age'))
errors = v.validate({})
assert len(errors) == 3, f'Expected 3 errors, got {len(error... | v2 = CollectAllValidator()
assert v2.validate({}) == []
v3 = CollectAllValidator()
v3.add('x', lambda d: (False, 'x wrong'))
v3.add('y', lambda d: (False, 'y wrong'))
errs = v3.validate({})
assert errs[0].message == 'x wrong'
assert errs[1].message == 'y wrong'
| code_purpose_understanding |
38 | devbench-code-purpose-understanding | python | class DependentValidator:
"""Validators can depend on others. Only runs if all deps passed.
Skipped validators do not appear in errors."""
def __init__(self):
self.validators = {}
self.order = []
def add(self, name, fn, depends_on=None):
self.validators[name] = {'fn': fn, 'deps... | def validate(self, data):
errors, passed = {}, set()
for name in self.order:
v = self.validators[name]
if not all(d in passed for d in v['deps']):
continue
ok, msg = v['fn'](data)
if ok:
passed.add(name)
else... | dv = DependentValidator()
dv.add('has_email', lambda d: ('@' in d.get('email', ''), 'invalid email'))
dv.add('email_domain', lambda d: (d.get('email', '').endswith('.com'), 'must be .com'), depends_on=['has_email'])
dv.add('has_name', lambda d: (bool(d.get('name')), 'name required'))
errors, passed = dv.validate({'ema... | dv2 = DependentValidator()
dv2.add('a', lambda d: (False, 'a failed'))
dv2.add('b', lambda d: (False, 'b failed'), depends_on=['a'])
dv2.add('c', lambda d: (False, 'c failed'), depends_on=['b'])
errs, p = dv2.validate({})
assert errs == {'a': 'a failed'}
assert p == set()
dv3 = DependentValidator()
dv3.add('x', lambda... | code_purpose_understanding |
39 | devbench-code-purpose-understanding | python | class SanitizationPipeline:
"""Runs sanitizers in sequence. Tracks which ones actually modified
the data (output differs from input)."""
def __init__(self):
self.sanitizers = []
def add(self, name, sanitizer_fn):
self.sanitizers.append((name, sanitizer_fn))
| def run(self, data):
applied = []
current = data
for name, fn in self.sanitizers:
result = fn(current)
if result != current:
applied.append(name)
current = result
return current, applied
| sp = SanitizationPipeline()
sp.add('strip', lambda s: s.strip())
sp.add('lower', lambda s: s.lower())
sp.add('remove_dots', lambda s: s.replace('.', ''))
result, applied = sp.run(' Hello.World ')
assert result == 'helloworld'
assert applied == ['strip', 'lower', 'remove_dots']
result2, applied2 = sp.run('helloworld... | sp2 = SanitizationPipeline()
sp2.add('strip', lambda s: s.strip())
sp2.add('lower', lambda s: s.lower())
r, a = sp2.run(' hello ')
assert r == 'hello'
assert a == ['strip']
sp3 = SanitizationPipeline()
r3, a3 = sp3.run('test')
assert r3 == 'test'
assert a3 == []
sp4 = SanitizationPipeline()
sp4.add('a_to_b', lambda... | code_purpose_understanding |
40 | devbench-code-purpose-understanding | python | class NormalizeAndValidate:
"""Normalizes data, then validates the NORMALIZED version.
Preserves original data for auditing."""
def __init__(self):
self.normalizers = {}
self.validators = []
def add_normalizer(self, field, fn):
self.normalizers[field] = fn
def add_validato... | def process(self, data):
original = dict(data)
normalized = dict(data)
for field, fn in self.normalizers.items():
if field in normalized:
normalized[field] = fn(normalized[field])
errors = []
for field, fn, msg in self.validators:
if no... | nv = NormalizeAndValidate()
nv.add_normalizer('email', lambda e: e.strip().lower())
nv.add_normalizer('name', lambda n: n.strip())
nv.add_validator('email', lambda e: e and '@' in e, 'invalid email')
nv.add_validator('name', lambda n: n and len(n) >= 2, 'name too short')
r = nv.process({'email': ' ALICE@X.COM ', 'na... | nv2 = NormalizeAndValidate()
nv2.add_normalizer('x', lambda v: v.upper())
nv2.add_validator('x', lambda v: v is not None, 'x required')
r = nv2.process({})
assert r['valid'] == False
assert 'x' not in r['normalized']
r2 = nv2.process({'x': 'hello', 'extra': 42})
assert r2['valid'] == True
assert r2['normalized']['x'] ... | code_purpose_understanding |
41 | devbench-code-purpose-understanding | python | class ApprovalChain:
def __init__(self, required_approvals):
self.required = required_approvals
self.decisions = []
self.status = 'pending'
def _record(self, approver, decision, reason=''):
self.decisions.append((approver, decision, reason))
| def decide(self, approver, decision, reason=''):
if self.status != 'pending':
return self.status
self._record(approver, decision, reason)
if decision == 'reject':
self.status = 'rejected'
elif decision == 'approve':
approvals = sum(1 for _, d, _ in... | chain = ApprovalChain(required_approvals=2)
chain.decide('mgr', 'approve', 'ok')
assert chain.status == 'pending'
chain.decide('dir', 'approve', 'agreed')
assert chain.status == 'approved'
chain.decide('vp', 'reject', 'too late')
assert chain.status == 'approved' # unchanged
chain2 = ApprovalChain(required_approval... | c = ApprovalChain(required_approvals=1)
c.decide('boss', 'approve')
assert c.status == 'approved'
c2 = ApprovalChain(required_approvals=1)
c2.decide('a', 'skip')
c2.decide('b', 'skip')
c2.decide('c', 'reject')
assert c2.status == 'rejected'
c3 = ApprovalChain(required_approvals=1)
c3.decide('a', 'reject')
result = c3... | code_purpose_understanding |
42 | devbench-code-purpose-understanding | python | class EscalatingWorkflow:
def __init__(self, approver_chain, clock=None):
self.chain = list(approver_chain)
self.idx = 0
self.status = 'pending'
self.history = []
self.clock = clock or (lambda: 0)
def current_approver(self):
return self.chain[self.idx] if self.id... | def escalate(self):
if self.status != 'pending':
return self.status
cur = self.current_approver()
self.history.append((cur, 'escalated', self.clock()))
self.idx += 1
if self.idx >= len(self.chain):
self.status = 'rejected'
return self.status
| wf = EscalatingWorkflow(['mgr', 'dir', 'vp'])
assert wf.current_approver() == 'mgr'
assert wf.decide('dir', 'approve') == 'wrong_approver'
assert wf.status == 'pending'
wf.escalate()
assert wf.current_approver() == 'dir'
assert wf.history[-1][1] == 'escalated'
wf.decide('dir', 'approve')
assert wf.status == 'approved... | wf3 = EscalatingWorkflow(['boss'])
wf3.decide('boss', 'approve')
assert wf3.status == 'approved'
wf4 = EscalatingWorkflow(['a', 'b', 'c'])
wf4.decide('a', 'reject')
assert wf4.status == 'rejected'
result = wf4.escalate()
assert wf4.status == 'rejected'
wf5 = EscalatingWorkflow(['a', 'b'])
wf5.escalate()
wf5.decide('b... | code_purpose_understanding |
43 | devbench-code-purpose-understanding | python | class TransactionalWorkflow:
def __init__(self):
self.steps = []
self.completed = []
self.rolled_back = []
self.status = 'idle'
def add_step(self, name, do_fn, undo_fn):
self.steps.append((name, do_fn, undo_fn))
| def execute(self):
self.status, self.completed, self.rolled_back, done = 'running', [], [], []
for name, do_fn, undo_fn in self.steps:
if not do_fn():
for n, u in reversed(done):
u(); self.rolled_back.append(n)
self.status = 'rolled_bac... | log = []
wf = TransactionalWorkflow()
wf.add_step('s1', lambda: (log.append('do1'), True)[1], lambda: log.append('undo1'))
wf.add_step('s2', lambda: (log.append('do2'), True)[1], lambda: log.append('undo2'))
wf.add_step('s3', lambda: (log.append('do3'), False)[1], lambda: log.append('undo3'))
assert wf.execute() == Fa... | log2 = []
wf3 = TransactionalWorkflow()
wf3.add_step('x', lambda: False, lambda: log2.append('undo_x'))
assert wf3.execute() == False
assert wf3.completed == []
assert wf3.rolled_back == []
assert log2 == []
wf4 = TransactionalWorkflow()
wf4.add_step('only', lambda: True, lambda: None)
assert wf4.execute() == True
ass... | code_purpose_understanding |
44 | devbench-code-purpose-understanding | python | class WorkflowStateMachine:
def __init__(self, initial_state):
self.state = initial_state
self.transitions = {}
self.history = [initial_state]
def allow_transition(self, from_state, to_state):
if from_state not in self.transitions:
self.transitions[from_state] = set(... | def advance(self, to_state):
allowed = self.transitions.get(self.state, set())
if to_state not in allowed:
return False
self.state = to_state
self.history.append(to_state)
return True
def can_advance(self, to_state):
return to_state in self.transition... | wf = WorkflowStateMachine('draft')
wf.allow_transition('draft', 'review')
wf.allow_transition('review', 'approved')
wf.allow_transition('review', 'rejected')
wf.allow_transition('rejected', 'draft')
assert wf.advance('review') == True
assert wf.advance('draft') == False # review->draft not allowed
assert wf.state == ... | wf3 = WorkflowStateMachine('draft')
wf3.allow_transition('draft', 'review')
wf3.allow_transition('review', 'rejected')
wf3.allow_transition('rejected', 'draft')
wf3.advance('review')
wf3.advance('rejected')
wf3.advance('draft')
assert wf3.history == ['draft', 'review', 'rejected', 'draft']
wf4 = WorkflowStateMachine('... | code_purpose_understanding |
45 | devbench-code-purpose-understanding | python | class QuorumApproval:
"""Requires N approvals from M approvers.
Auto-approved when threshold met.
Auto-rejected when impossible to reach threshold."""
def __init__(self, approvers, threshold):
self.approvers = set(approvers)
self.threshold = threshold
self.votes = {}
sel... | def vote(self, approver, decision):
if self.status != 'pending': return self.status
if approver not in self.approvers: return 'invalid_approver'
if approver in self.votes: return 'already_voted'
self.votes[approver] = decision
approvals = sum(1 for v in self.votes.values() if... | qa = QuorumApproval({'alice', 'bob', 'charlie', 'dave'}, threshold=2)
qa.vote('alice', 'reject')
assert qa.status == 'pending' # still possible
qa.vote('bob', 'approve')
assert qa.status == 'pending'
qa.vote('charlie', 'approve')
assert qa.status == 'approved'
qa2 = QuorumApproval({'a', 'b', 'c'}, threshold=2)
qa2... | qa3 = QuorumApproval({'x', 'y', 'z'}, threshold=1)
qa3.vote('x', 'reject')
qa3.vote('y', 'reject')
assert qa3.status == 'pending'
qa3.vote('z', 'reject')
assert qa3.status == 'rejected'
qa4 = QuorumApproval({'a', 'b'}, threshold=1)
qa4.vote('a', 'approve')
assert qa4.status == 'approved'
qa5 = QuorumApproval({'a'}, t... | code_purpose_understanding |
46 | devbench-code-purpose-understanding | python | import math
class PercentileCalculator:
"""Nearest-rank method. For percentile P and N values:
rank = ceil(P / 100 * N), 1-indexed.
P=0 returns minimum. P=100 returns maximum."""
def __init__(self, values):
self.sorted_values = sorted(values)
self.n = len(self.sorted_values)
| def percentile(self, p):
if self.n == 0:
return None
if p <= 0:
return self.sorted_values[0]
if p >= 100:
return self.sorted_values[-1]
rank = math.ceil(p / 100 * self.n)
return self.sorted_values[rank - 1]
def median(self):
re... | pc = PercentileCalculator([15, 20, 35, 40, 50])
assert pc.percentile(50) == 35 # ceil(2.5)=3, idx 2
assert pc.percentile(25) == 20 # ceil(1.25)=2, idx 1
assert pc.percentile(75) == 40 # ceil(3.75)=4, idx 3
assert pc.percentile(0) == 15
assert pc.percentile(100) == 50
assert pc.median() == 35
| pc2 = PercentileCalculator([42])
assert pc2.percentile(50) == 42
assert pc2.percentile(1) == 42
pc3 = PercentileCalculator([10, 20])
assert pc3.percentile(50) == 10 # ceil(1)=1, idx 0
assert pc3.percentile(51) == 20 # ceil(1.02)=2, idx 1
pc4 = PercentileCalculator([5, 1, 3, 2, 4])
assert pc4.percentile(20) == 1
ass... | code_purpose_understanding |
47 | devbench-code-purpose-understanding | python | class Histogram:
"""Fixed-width histogram. Buckets cover [lower, lower+width).
Values below start -> underflow. Values >= end -> overflow."""
def __init__(self, start, width, num_buckets):
self.start = start
self.width = width
self.num_buckets = num_buckets
self.buckets = [0... | def add(self, value):
if value < self.start:
self.underflow += 1
elif value >= self.start + self.width * self.num_buckets:
self.overflow += 1
else:
idx = int((value - self.start) / self.width)
self.buckets[idx] += 1
def get_buckets(self):
... | h = Histogram(start=0, width=10, num_buckets=5)
h.add(5)
h.add(15)
h.add(25)
h.add(25)
h.add(-1)
h.add(50)
h.add(0)
h.add(9.99)
assert h.underflow == 1
assert h.overflow == 1
assert h.get_buckets()[0] == (0, 3) # 5, 0, 9.99
assert h.get_buckets()[1] == (10, 1) # 15
assert h.get_buckets()[2] == (20, 2) # 25, 25
| h2 = Histogram(0, 10, 3)
h2.add(10)
h2.add(20)
h2.add(30)
assert h2.get_buckets()[0] == (0, 0)
assert h2.get_buckets()[1] == (10, 1)
assert h2.get_buckets()[2] == (20, 1)
assert h2.overflow == 1
h3 = Histogram(100, 5, 2)
h3.add(99)
h3.add(100)
h3.add(105)
h3.add(110)
assert h3.underflow == 1
assert h3.overflow == 1
as... | code_purpose_understanding |
48 | devbench-code-purpose-understanding | python | class ExponentialMovingStats:
"""EMA mean and variance with custom alpha.
mean = alpha * value + (1-alpha) * mean
var = alpha * (value - OLD_mean)^2 + (1-alpha) * var
Note: variance uses PREVIOUS mean (before update).
First value initializes mean; variance starts at 0."""
def __init__(self, alp... | def update(self, value):
self.count += 1
if self.mean is None:
self.mean = float(value)
self.variance = 0.0
return
old_mean = self.mean
self.mean = self.alpha * value + (1 - self.alpha) * old_mean
diff = value - old_mean
self.varian... | ema = ExponentialMovingStats(alpha=0.5)
ema.update(10)
assert ema.mean == 10.0
assert ema.variance == 0.0
ema.update(20)
assert ema.mean == 15.0
# var = 0.5 * (20-10)^2 + 0.5*0 = 50.0 (uses OLD mean=10)
assert ema.variance == 50.0
ema.update(15)
assert ema.mean == 15.0
# var = 0.5 * (15-15)^2 + 0.5*50 = 25.0
assert e... | ema2 = ExponentialMovingStats(alpha=1.0)
ema2.update(100)
ema2.update(200)
assert ema2.mean == 200.0
assert ema2.variance == 10000.0
ema2.update(200)
assert ema2.variance == 0.0
ema3 = ExponentialMovingStats(alpha=0.1)
ema3.update(0)
ema3.update(100)
assert abs(ema3.mean - 10.0) < 0.001
assert abs(ema3.variance - 1000... | code_purpose_understanding |
49 | devbench-code-purpose-understanding | python | class DecayingCounter:
"""Counter decays exponentially: count *= decay_factor^elapsed.
increment() adds to the current decayed count."""
def __init__(self, decay_factor, clock=None):
self.decay_factor = decay_factor
self.clock = clock or (lambda: __import__('time').monotonic())
self... | def _decay(self, key):
if key not in self.counters: return 0.0
count, last = self.counters[key]
now = self.clock()
decayed = count * (self.decay_factor ** (now - last))
self.counters[key] = (decayed, now)
return decayed
def increment(self, key, amount=1):
... | class FakeClock:
def __init__(self, start=0):
self.now = start
def __call__(self):
return self.now
def advance(self, s):
self.now += s
clock = FakeClock(0)
dc = DecayingCounter(0.5, clock=clock)
dc.increment('hits', 100)
assert dc.get_count('hits') == 100.0
clock.advance(1)
assert... | clock2 = FakeClock(0)
dc2 = DecayingCounter(1.0, clock=clock2)
dc2.increment('x', 100)
clock2.advance(1000)
assert dc2.get_count('x') == 100.0 # no decay
clock3 = FakeClock(0)
dc3 = DecayingCounter(0.0, clock=clock3)
dc3.increment('x', 100)
clock3.advance(1)
assert dc3.get_count('x') == 0.0
clock4 = FakeClock(0)
dc4... | code_purpose_understanding |
50 | devbench-code-purpose-understanding | python | class TimeWindowStats:
"""Statistics over a time-based sliding window.
Values older than window_seconds are evicted."""
def __init__(self, window_seconds, clock=None):
self.window = window_seconds
self.clock = clock or (lambda: __import__('time').monotonic())
self.values = [] # (ti... | def add(self, value):
self._evict()
self.values.append((self.clock(), value))
def mean(self):
self._evict()
if not self.values:
return None
return sum(v for _, v in self.values) / len(self.values)
def count(self):
self._evict()
return len... | class FakeClock:
def __init__(self, start=0):
self.now = start
def __call__(self):
return self.now
def advance(self, s):
self.now += s
clock = FakeClock(0)
tw = TimeWindowStats(10, clock=clock)
tw.add(10)
clock.advance(3)
tw.add(20)
clock.advance(3)
tw.add(30)
assert tw.count() ==... | clock2 = FakeClock(0)
tw2 = TimeWindowStats(100, clock=clock2)
tw2.add(10)
tw2.add(20)
tw2.add(30)
assert tw2.mean() == 20.0
clock3 = FakeClock(0)
tw3 = TimeWindowStats(10, clock=clock3)
tw3.add(42)
assert tw3.mean() == 42.0
# Time-based not count-based: many values, no time passed
clock4 = FakeClock(0)
tw4 = TimeWin... | code_purpose_understanding |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.