version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | complete | Docs | Docs: Python310_46030_C | import select
def handle_read(fd):
print(f"Handling read for FD {fd}")
def handle_write(fd):
print(f"Handling write for FD {fd}")
def handle_exception(fd):
print(f"Handling exception for FD {fd}")
def monitor_file_descriptors(rlist, wlist, xlist, timeout=5.0) -> dict:
"""
Monitors multiple file ... | import select
def handle_read(fd):
print(f"Handling read for FD {fd}")
def handle_write(fd):
print(f"Handling write for FD {fd}")
def handle_exception(fd):
print(f"Handling exception for FD {fd}")
def monitor_file_descriptors(rlist, wlist, xlist, timeout=5.0) -> dict:
"""
Monitors multiple file ... | # To test this function, we need to mock the select function and file descriptors.
# Let's assume `select.select` is correctly implemented and returns a mock result.
# Note: We cannot actually test file descriptors without a proper I/O context.
# This is a limitation, but we can mock the behavior.
import select
import... | [
{
"docstring": null,
"function_declaration": "def handle_read(fd):",
"function_name": "handle_read",
"parameter_list": "(fd)"
},
{
"docstring": null,
"function_declaration": "def handle_write(fd):",
"function_name": "handle_write",
"parameter_list": "(fd)"
},
{
"docstring... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import select\n\ndef handle_read(fd):\n print(f\"Handling read for FD {fd}\")\n\ndef handle_write(fd):\n print(f\"Handling write for FD {fd}\")\n\ndef handle_exce... | trial_gpt4o_9 | {
"original_instruction": "### Advanced I/O Multiplexing with Python's `select` Module\n\n#### Objective\nImplement a function called `monitor_file_descriptors` that uses the `select` module to monitor multiple file descriptors (FDs) and handle different types of I/O events that occur on them.\n\n#### Requirements\n1... | 0.504353 | Docs: Python310_46030 | C | [
"handle_read",
"handle_write",
"handle_exception",
"monitor_file_descriptors"
] | 4 | [
[
"monitor_file_descriptors",
"handle_exception"
],
[
"monitor_file_descriptors",
"handle_read"
],
[
"monitor_file_descriptors",
"handle_write"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 9192b8dc19bec72ffb781a8fb0dbd5b4c0f9dec0 | ffca1c1944063c3d290f74a379d5f82a9bfcddf2 | |||
v1.0 | complete | Docs | Docs: Pytorch_46450_C | import torch
from typing import List
def async_computation(value: int) -> torch.futures.Future:
"""
Performs a simple asynchronous operation using the torch.futures.Future class.
Args:
value (int): A numerical value to be used in the computation.
Returns:
torch.futures.Future: A futur... | import torch
import asyncio
from typing import List
async def async_double(value: int) -> int:
"""
Asynchronously doubles the input value after a short delay.
Args:
value (int): A numerical value to double.
Returns:
int: The doubled value after a delay.
"""
await asyncio.sleep... | import pytest
import torch
from solution import async_computation, process_results
@pytest.mark.asyncio
async def test_async_computation():
future = async_computation(10)
result = await future # Await the result of the async computation
assert result == 20
@pytest.mark.asyncio
async def test_process_resu... | [
{
"docstring": "Initiates an asynchronous computation to double the input value and returns a Future.\n\nArgs:\nvalue (int): A numerical value to be used in the computation.\n\nReturns:\ntorch.futures.Future: A future object that will complete with value * 2 after a simulated delay.",
"function_declaration"... | [
1,
1,
0,
0,
1,
1,
0,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport torch\nfrom torch.futures import Future\nfrom typing import List\n\ndef async_computation(value: int) -> Future:\n \"\"\"\n Asynchronous co... | trial_gpt4o_9 | {
"original_instruction": "#### Problem Statement\n\nYou are required to demonstrate your understanding of the `torch.futures.Future` class and related utility functions by simulating a distributed computing scenario. In this exercise, you will:\n\n1. Create a function `async_computation` that performs a simple async... | 0.565645 | Docs: Pytorch_46450 | C | [
"async_double",
"async_computation",
"process_results"
] | 3 | [
[
"async_computation",
"async_double"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | db10fa5830f1a88b7a07694f5ccfae3126c89909 | 176ea2cdec656a865bc64bf0dd0905c3282c74ea | |||
v1.0 | complete | Docs | Docs: Python310_46579_C | import asyncio
import shlex
async def run_multiple_subprocesses(commands: list, timeout: int) -> dict:
"""
Execute a list of shell commands asynchronously and returns their results.
Arguments:
commands (list): A list of strings, where each string is a shell command to be executed.
timeout ... | import asyncio
import shlex
async def run_command(command: str, timeout: int):
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeo... | import pytest
from solution import run_multiple_subprocesses
@pytest.mark.asyncio
async def test_single_command_ls():
commands = ["ls /"]
timeout = 5
results = await run_multiple_subprocesses(commands, timeout)
assert "ls /" in results
assert results["ls /"][0] == 0
assert results["ls /"][1] is... | [] | [
1,
0,
0,
1,
0,
0,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport shlex\n\nasync def run_command(command: str, timeout: int):\n process = await asyncio.create_subprocess_shell(\n command,\n stdo... | trial_gpt4o_0 | {
"original_instruction": "### Advanced Python Coding Assessment: Asynchronous Subprocess Management\n\n**Objective**:\nAssess the understanding and ability to implement asynchronous subprocess handling in Python using `asyncio`.\n\n**Problem Statement**:\n\nYou are to implement a function `run_multiple_subprocesses(... | 0.712072 | Docs: Python310_46579 | C | [
"run_command",
"run_multiple_subprocesses"
] | 2 | [
[
"run_multiple_subprocesses",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4b82641d06a4095022307cf5b9761400c1132214 | 41c4e4efada29f6caba73bd0572ed0f8c7394019 | |||
v1.0 | complete | Docs | Docs: Pytorch_46459_C | import torch
import torch._dynamo as dynamo
@dynamo.optimize("eager", dynamic=True)
def dynamic_shape_operations(x):
""" Perform operations based on the dynamic shape of the input tensor x.
If the size of the first dimension is greater than 10, multiply by 2.
Otherwise, add 5 to each element.
"""
i... | import torch
import torch._dynamo as dynamo
@dynamo.optimize("eager", dynamic=True)
def dynamic_shape_operations(x):
"""
Perform operations based on the dynamic shape of the input tensor x.
If the size of the first dimension is greater than 10, multiply by 2.
Otherwise, add 5 to each element.
"""
... | from solution import dynamic_shape_operations
import torch
def test_dynamic_shape_operations_add():
x = torch.randn(8, 3)
result = dynamic_shape_operations(x)
expected = x + 5
assert torch.allclose(result, expected), "Test failed: Expected addition operation for x.size(0) <= 10."
def test_dynamic_shap... | [
{
"docstring": "Perform operations based on the dynamic shape of the input tensor x.\nIf the size of the first dimension is greater than 10, multiply by 2.\nOtherwise, add 5 to each element.",
"function_declaration": "def dynamic_shape_operations(x):",
"function_name": "dynamic_shape_operations",
"p... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torchdynamo as dynamo\nimport logging\n\n# Set logger to display debug messages\nlogging.basicConfig(level=logging.DEBUG)\n\n@dynamo.optimize(\"eag... | trial_gpt4o_1 | {
"original_instruction": "### Question: Dynamo Tracing and FX Graph Generation\n\n**Objective**: \nTo assess your understanding of TorchDynamo and its functionality in tracing Python functions and generating FX graphs.\n\n**Problem Statement**:\n\nCreate a Python function that demonstrates the use of dynamic shapes ... | 0.488376 | Docs: Pytorch_46459 | C | [
"dynamic_shape_operations",
"demonstrate_fx_graph_generation"
] | 2 | [
[
"demonstrate_fx_graph_generation",
"dynamic_shape_operations"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 499400afaaa074fbb2bd3eeead529e543ce04853 | a9124a9d44815b823c853635cb887fcae6f6a38f | |||
v1.0 | complete | Docs | Docs: Python310_46395_C | def create_set_from_iterable(iterable):
""" Create a set from the given iterable.
>>> create_set_from_iterable([1, 2, 3]) {1, 2, 3}
>>> create_set_from_iterable(None) set()
>>> create_set_from_iterable((1, 2, 2, 3)) {1, 2, 3}
>>> create_set_from_iterable(123) # Raises TypeError
"""
pass
de... | def create_set_from_iterable(iterable):
"""
Create a set from the given iterable. If the iterable is None, return an empty set.
Raise TypeError if the input is not iterable.
"""
if iterable is None:
return set()
try:
result_set = set(iterable)
except TypeError:
raise ... | from solution import create_set_from_iterable, custom_set_operations
def test_create_set_from_iterable_with_list():
assert create_set_from_iterable([1, 2, 3]) == {1, 2, 3}
def test_create_set_from_iterable_with_tuple():
assert create_set_from_iterable((1, 2, 2, 3)) == {1, 2, 3}
def test_create_set_from_itera... | [
{
"docstring": "Create a set from the given iterable. If the iterable is None, return an empty set.\nRaise TypeError if the input is not iterable.",
"function_declaration": "def create_set_from_iterable(iterable):",
"function_name": "create_set_from_iterable",
"parameter_list": "(iterable)"
},
{... | [
1,
1,
1,
1,
0,
1,
0,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def create_set_from_iterable(iterable):\n \"\"\"\n Takes an iterable and returns a new set containing objects from the iterable.\n If the iterable is None, ret... | trial_gpt4o_8 | {
"original_instruction": "#### Title: Custom Set Operations and Conversions\n\n#### Objective:\nImplement functions that demonstrate your ability to work with Python `set` and `frozenset` objects using the provided API methods.\n\n#### Problem Statement:\n\nYou need to implement two functions: `create_set_from_itera... | 0.499718 | Docs: Python310_46395 | C | [
"create_set_from_iterable",
"custom_set_operations"
] | 2 | [
[
"custom_set_operations",
"create_set_from_iterable"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2cfee214c3b9fed871eb7a8ec06529420066b6ac | 13d10b526c80dbd9f710be2a130c70bca46da7d3 | |||
v1.0 | complete | Docs | Docs: Python310_46556_C | import hmac
import hashlib
def generate_hmac(file_path: str, key: bytes, digestmod: str) -> str:
"""
Generates an HMAC tag for the given file using the specified key and hash algorithm.
Args:
- file_path (str): The path to the file.
- key (bytes): The secret key used for HMAC.
- digestmod ... | import hmac
import hashlib
def generate_hmac(file_path: str, key: bytes, digestmod: str) -> str:
"""
Generates an HMAC tag for the given file using the specified key and hash algorithm.
Args:
- file_path (str): The path to the file.
- key (bytes): The secret key used for HMAC.
- digestmod ... | import os
def test_generate_hmac():
# Create a temporary file for testing
test_file_path = 'test_file.txt'
test_content = b'This is a test file for HMAC generation.'
with open(test_file_path, 'wb') as f:
f.write(test_content)
try:
key = b'secret_key'
digestmod = 'sha256'
... | [
{
"docstring": "Generates an HMAC tag for the given file using the specified key and hash algorithm.\n\nArgs:\n- file_path (str): The path to the file.\n- key (bytes): The secret key used for HMAC.\n- digestmod (str): The hash algorithm to use (e.g., \"sha256\").\n\nReturns:\n- str: The hexadecimal HMAC tag for... | [
1,
1,
0,
1,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hmac\nimport hashlib\n\ndef generate_hmac(file_path: str, key: bytes, digestmod: str) -> str:\n \"\"\"\n Generates an HMAC tag for the provided file using ... | trial_gpt4o_9 | {
"original_instruction": "### Challenge: Implement Secure File Integrity Verification Using the `hmac` Module\n\n**Objective:**\nWrite a Python program to verify the integrity of files using the HMAC algorithm. You need to implement two functions: one to generate an HMAC tag for a given file and another to verify th... | 0.719268 | Docs: Python310_46556 | C | [
"generate_hmac",
"verify_file_integrity"
] | 2 | [
[
"verify_file_integrity",
"generate_hmac"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 79a3e172e26eb3946d7545993da706454d8a751d | 7c525290427370d08df4fde7b5dd5a6ae818734a | |||
v1.0 | complete | Docs | Docs: Python310_46739_C | import asyncio
import os
import sys
async def handle_client(reader, writer):
"""Receive file name and file content from client, and save it to the current directory."""
pass
async def start_server(ip, port):
"""Start an asynchronous file server that listens on a specified IP and port."""
pass
async d... | import asyncio
import os
import sys
async def handle_client(reader, writer):
try:
# Receive file name
data = await reader.read(100)
file_name = data.decode().strip()
# Receive file content
file_data = await reader.read(10485760) # Maximum file size is 10MB
... | import asyncio
import os
import tempfile
import pytest
from solution import start_server, send_file
@pytest.fixture
def temp_file():
with tempfile.NamedTemporaryFile(delete=False) as tmp:
tmp.write(b'This is a test file.')
yield tmp.name
os.remove(tmp.name)
@pytest.fixture
def async_server():
... | [] | [
1,
0,
0,
0,
1,
1,
0,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport os\nimport sys\n\nasync def handle_client(reader, writer):\n try:\n # Read filename size (first 4 bytes)\n size_data = await rea... | trial_gpt4o_5 | {
"original_instruction": "### Advanced Python Coding Assessment: Design a File Transfer Service Using asyncio Streams\n\n#### Objective\nCreate a simple file transfer service using asyncio streams. The service involves two parts:\n1. A **file server** that listens on a specified TCP port and waits for a file transfe... | 0.523774 | Docs: Python310_46739 | C | [
"handle_client",
"start_server",
"send_file"
] | 3 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c26480f0518b1611ce3d6330f65a0ce01a2bcaf3 | aca6fbafb5fb838d5f2a8f5acf2d98c5cef52a4e | |||
v1.0 | complete | Docs | Docs: Python310_46603_C | import asyncio
from typing import Dict, List, Tuple
async def download_file(file_id: int, size: int) -> int:
"""Simulates a file download by sleeping for 'size' seconds and returns the 'file_id'."""
await asyncio.sleep(size)
return file_id
async def download_manager(file_sizes: Dict[int, int], timeout: f... | import asyncio
from typing import Dict, List, Tuple
async def download_file(file_id: int, size: int) -> int:
"""Simulates a file download by sleeping for 'size' seconds and returns the 'file_id'."""
await asyncio.sleep(size)
return file_id
async def download_manager(file_sizes: Dict[int, int], timeout: fl... | import asyncio
from solution import download_file, download_manager
def test_download_file():
result = asyncio.run(download_file(1, 1))
assert result == 1
def test_download_manager():
file_sizes = {1: 2, 2: 4, 3: 1}
timeout = 3.0
completed, cancelled = asyncio.run(download_manager(file_sizes, time... | [] | [
1,
1,
1,
0,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import Dict, List, Tuple\n\nasync def download_file(file_id: int, size: int) -> int:\n \"\"\"\n Simulates a file download by sleeping ... | trial_gpt4o_9 | {
"original_instruction": "**Question: Asynchronous Download Manager**\n\nYou are to implement an asynchronous download manager using the `asyncio` module. The download manager will perform multiple \"download\" tasks concurrently, each task downloading a file whose size is specified. For simplicity, assume \"downloa... | 0.594553 | Docs: Python310_46603 | C | [
"download_file",
"download_manager"
] | 2 | [
[
"download_manager",
"download_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f6e4f8696cfbe62c01b87983fde469fc8bcc83fb | 62141573921f10473a32f560f55ce6c17c5e281d | |||
v1.0 | complete | Docs | Docs: Pytorch_46442_C | import torch
from typing import Tuple
def qr_decomposition(matrix: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Perform QR decomposition of a given square matrix.
Arguments:
matrix (torch.Tensor): A square matrix of shape (n, n).
Returns:
Tuple[torch.Tensor, torch.Tensor]: ... | import torch
from typing import Tuple
def qr_decomposition(matrix: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Perform QR decomposition of a given square matrix.
Arguments:
matrix (torch.Tensor): A square matrix of shape (n, n).
Returns:
Tuple[torch.Tensor, torch.Tensor]: ... | import torch
from solution import qr_decomposition, solve_linear_system_qr
def test_qr_decomposition():
A = torch.tensor([[12., -51., 4.], [6., 167., -68.], [-4., 24., -41.]])
Q, R = qr_decomposition(A)
assert torch.allclose(torch.matmul(Q, R), A, atol=1e-6)
assert torch.allclose(torch.matmul(Q.transpo... | [
{
"docstring": "Perform QR decomposition of a given square matrix.\n\nArguments:\nmatrix (torch.Tensor): A square matrix of shape (n, n).\n\nReturns:\nTuple[torch.Tensor, torch.Tensor]: A tuple containing Q and R matrices.",
"function_declaration": "def qr_decomposition(matrix):",
"function_name": "qr_d... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom typing import Tuple\n\ndef qr_decomposition(matrix: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Perform QR decomposition of ... | trial_gpt4o_4 | {
"original_instruction": "### PyTorch Linear Algebra - QR Decomposition and Linear System Solver\n\nIn this task, you will demonstrate your understanding of PyTorch's linear algebra operations by implementing two functions. \n\n1. **QR Decomposition using PyTorch**:\n Implement a function `qr_decomposition` that p... | 0.510485 | Docs: Pytorch_46442 | C | [
"qr_decomposition",
"solve_linear_system_qr"
] | 2 | [
[
"solve_linear_system_qr",
"qr_decomposition"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 27835ddee6b2182b319545ac890d801b8915a474 | 8c68c8942b4c413000ba24bf5033fe15c623caec | |||
v1.0 | complete | Docs | Docs: Python310_46530_C | from functools import lru_cache, wraps
@lru_cache(maxsize=None)
def compute_term(n: int) -> int:
""" Calculate the n-th term in the series using the relation:
T(n) = T(n-1) + 2*T(n-2) for n > 1, with base cases T(0) = 0 and T(1) = 1.
>>> compute_term(0) == 0
>>> compute_term(1) == 1
>>> compute_ter... | from functools import lru_cache, wraps
# Define the base computation function
@lru_cache(maxsize=None)
def compute_term(n):
if n == 0:
return 0
elif n == 1:
return 1
return compute_term(n-1) + 2 * compute_term(n-2)
# Define the transformation function
def apply_transformation(f):
@wrap... | from solution import compute_term, apply_transformation, transformed_series
def test_compute_term_base_cases():
assert compute_term(0) == 0
assert compute_term(1) == 1
def test_compute_term_recursive_cases():
assert compute_term(2) == 1 # T(2) = T(1) + 2 * T(0) = 1 + 2 * 0 = 1
assert compute_term(3) ... | [
{
"docstring": null,
"function_declaration": "def compute_term(n):",
"function_name": "compute_term",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def apply_transformation(f):",
"function_name": "apply_transformation",
"parameter_list": "(f)"
},
{
... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import lru_cache, wraps\n\n# Define the base computation function\n@lru_cache(maxsize=None)\ndef compute_term(n):\n if n == 0:\n return 0\n ... | trial_gpt4o_2 | {
"original_instruction": "#### Function Composability and Memoization\n\nYou need to implement a function that efficiently calculates the n-th term in a custom series defined by a certain recursive relation. Use `functools` to manage caching and function composition.\n\n### Specifications:\n\n1. **Function Compositi... | 0.616681 | Docs: Python310_46530 | C | [
"compute_term",
"apply_transformation",
"transformed_series"
] | 3 | [
[
"transformed_series",
"apply_transformation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dfc232e5b56770eb5dedc3ec97903468e37e7b26 | a36dacf60232e81d0e98e833038211b7e9918349 | |||
v1.0 | complete | Docs | Docs: Python310_46891_C | import signal
import time
import sys
def handle_sigusr1(signum, frame):
print("Received SIGUSR1")
def handle_sigalrm(signum, frame):
print("Terminating the task")
sys.exit(0)
def register_signal_handler():
"""
Register a signal handler for the SIGUSR1 signal.
The signal handler should print t... | import signal
import time
import sys
def handle_sigusr1(signum, frame):
print("Received SIGUSR1")
def handle_sigalrm(signum, frame):
print("Terminating the task")
sys.exit(0)
def register_signal_handler():
signal.signal(signal.SIGUSR1, handle_sigusr1)
def setup_interval_timer(interval):
signal.s... | import subprocess
import os
import signal
import time
# We need to run the script in a separate process to test signal handling effectively
def test_signal_handling():
p = subprocess.Popen(['python3', 'solution.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(1) # Allow some time for the proce... | [
{
"docstring": null,
"function_declaration": "def handle_sigusr1(signum, frame):",
"function_name": "handle_sigusr1",
"parameter_list": "(signum, frame)"
},
{
"docstring": null,
"function_declaration": "def handle_sigalrm(signum, frame):",
"function_name": "handle_sigalrm",
"para... | [
0,
1,
1,
0,
0,
0,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\nimport time\nimport sys\n\ndef signal_handler_usr1(signum, frame):\n print(\"Received SIGUSR1\")\n\ndef signal_handler_alrm(signum, frame):\n print... | trial_gpt4o_2 | {
"original_instruction": "### Problem Description\n\nYou are required to implement a Python program that uses the `signal` module to set up a signal handler for `SIGUSR1` and manage an interval timer using `signal.setitimer`. Your program should handle the `SIGUSR1` signal by printing a message indicating the signal... | 0.618239 | Docs: Python310_46891 | C | [
"handle_sigusr1",
"handle_sigalrm",
"register_signal_handler",
"setup_interval_timer",
"long_running_task",
"main"
] | 6 | [
[
"register_signal_handler",
"handle_sigusr1"
],
[
"setup_interval_timer",
"handle_sigalrm"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 3ba93b832a970ec8ad465f3dac51765171192213 | 57af892aa16f77b244f0c7f2cabcd97c2b88ae45 | |||
v1.0 | complete | Docs | Docs: Python310_47012_C | import asyncio
from typing import List, Dict, Any
import aiohttp
async def fetch(url: str, timeout: int) -> str:
"""
Fetches the content of a URL within the defined timeout.
Returns the content of the URL or an error message if failed.
"""
# Your code here
async def scrape_urls(urls: List[str], ti... | import asyncio
from typing import List, Dict, Any
import aiohttp
async def fetch(url: str, timeout: int) -> str:
"""
Fetches the content of a URL within the defined timeout.
Returns the content of the URL or an error message if failed.
"""
try:
async with aiohttp.ClientSession() as session:... | import pytest
import asyncio
from solution import scrape_urls
@pytest.mark.asyncio
async def test_scrape_urls_success():
urls = ["https://jsonplaceholder.typicode.com/posts/1",
"https://jsonplaceholder.typicode.com/posts/2"]
timeout = 2
result = await scrape_urls(urls, timeout)
assert isin... | [] | [
1,
1,
1,
0,
0,
1,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Dict, Any\nimport aiohttp\n\nasync def fetch(url: str, timeout: int) -> str:\n \"\"\"\n Fetches the content of a URL with... | trial_gpt4o_0 | {
"original_instruction": "### Problem Description\nIn this coding assessment, you will implement a Python function that utilizes the `asyncio` library to perform asynchronous web scraping tasks. The primary task is to scrape multiple web pages concurrently and return the combined results.\n\n### Task\n\nImplement th... | 0.659883 | Docs: Python310_47012 | C | [
"fetch",
"scrape_urls"
] | 2 | [
[
"scrape_urls",
"fetch"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 4a8a7eafc1268265e1570c24f9f3f95e8f1366d1 | c4d0d8f2914f7247001a2162a7ef565f720721d0 | |||
v1.0 | complete | Docs | Docs: Python310_47252_C | from typing import List
import concurrent.futures
import urllib.request
def fetch_url_content_size(url: str) -> int:
"""Fetch the size of the content from a given URL.
"""
pass
def fetch_urls_total_size(urls: List[str]) -> int:
""" Process a list of URLs concurrently to fetch the content and compute t... | from typing import List
import concurrent.futures
import urllib.request
def fetch_url_content_size(url: str) -> int:
try:
with urllib.request.urlopen(url) as response:
content = response.read()
return len(content)
except Exception as e:
# In case of an exception, conside... | import pytest
from unittest.mock import patch
from solution import fetch_urls_total_size, fetch_url_content_size
def fake_urlopen(url):
"""
This function simulates the behavior of urllib.request.urlopen for different URLs.
"""
class FakeResponse:
def __init__(self, content):
self.co... | [
{
"docstring": null,
"function_declaration": "def fetch_url_content_size(url):",
"function_name": "fetch_url_content_size",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def fetch_urls_total_size(urls):",
"function_name": "fetch_urls_total_size",
"par... | [
0,
1,
0,
0,
0,
1,
1,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from concurrent.futures import ThreadPoolExecutor\nfrom typing import List\nimport urllib.request\n\ndef fetch_url_content_length(url: str) -> int:\n try:\n w... | trial_gpt4o_9 | {
"original_instruction": "### Question: Parallel Task Execution Using ThreadPoolExecutor\n\n#### Objective:\nWrite a Python function that processes a list of URLs concurrently to fetch the content using the `concurrent.futures.ThreadPoolExecutor`. Use this function to compute the total size of the combined content o... | 0.53441 | Docs: Python310_47252 | C | [
"fetch_url_content_size",
"fetch_urls_total_size"
] | 2 | [
[
"fetch_urls_total_size",
"fetch_url_content_size"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 46ccb8c6f420c880543886501dd5a3ad958b3088 | fa9356c44c738cff55b73aeebdbb2bb2d325d0bf | |||
v1.0 | complete | Docs | Docs: Python310_47231_C | import pwd
from typing import List, Optional, Dict
def get_user_by_name(username: str) -> Optional[Dict[str, str]]:
""" Get user information by username.
>>> get_user_by_name('root') == {'pw_name': 'root', 'pw_passwd': 'x', 'pw_uid': 0, 'pw_gid': 0, 'pw_gecos': 'root', 'pw_dir': '/root', 'pw_shell': '/bin/bash... | import pwd
from typing import List, Optional, Dict
def get_user_by_name(username: str) -> Optional[Dict[str, str]]:
try:
pw_record = pwd.getpwnam(username)
user_info = {
"pw_name": pw_record.pw_name,
"pw_passwd": pw_record.pw_passwd,
"pw_uid": pw_record.pw_uid,
... | from solution import get_user_by_name, list_all_users, has_root_access
import pytest
import pwd
def test_get_user_by_name_existing_user():
user_info = get_user_by_name('root')
assert user_info is not None
assert user_info['pw_name'] == 'root'
assert user_info['pw_uid'] == 0
def test_get_user_by_name_n... | [
{
"docstring": null,
"function_declaration": "def get_user_by_name(username):",
"function_name": "get_user_by_name",
"parameter_list": "(username)"
},
{
"docstring": null,
"function_declaration": "def list_all_users():",
"function_name": "list_all_users",
"parameter_list": "()"
... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pwd\n\ndef get_user_by_name(username: str) -> dict:\n \"\"\"\n Returns user information for a given username.\n If the user is not found, returns None.\... | trial_gpt4o_9 | {
"original_instruction": "User Management with pwd Module\n\nGiven the Unix `pwd` module, you are required to write a Python script that performs the following tasks:\n\n1. **Get User Information by Username**: Implement a function `get_user_by_name(username: str) -> dict` that takes a username as input and returns ... | 0.441004 | Docs: Python310_47231 | C | [
"get_user_by_name",
"list_all_users",
"has_root_access"
] | 3 | [
[
"has_root_access",
"get_user_by_name"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 25877e38236d6ac6f8ca4a17f7d4de69575fe8fc | 7ce89563cc46821d46f17f73aee59a8d2938ecd7 | |||
v1.0 | complete | Docs | Docs: Python310_47070_C | def read_library_database(file_name='library_database.txt'):
"""
Reads the library records from a text file and returns them as a list of dictionaries.
Each dictionary represents a book's record with the following keys:
'title', 'author', 'year', 'genre', 'shelf'.
"""
# Implementation here
def... | import os
def read_library_database(file_name='library_database.txt'):
"""
Reads the library records from a text file and returns them as a list of dictionaries.
Each dictionary represents a book's record with the following keys:
'title', 'author', 'year', 'genre', 'shelf'.
"""
if not os.path.... | import os
import pytest
from solution import display_books_by_genre, search_book_by_title, add_new_record
# Mock data for testing
mock_data = """The Great Gatsby;F. Scott Fitzgerald;1925;Fiction;A1
To Kill a Mockingbird;Harper Lee;1960;Fiction;A2
A Brief History of Time;Stephen Hawking;1988;Science;B1
The Art of Compu... | [
{
"docstring": "Reads the library records from a text file and returns them as a list of dictionaries.\nEach dictionary represents a book's record with the following keys: \n'title', 'author', 'year', 'genre', 'shelf'.",
"function_declaration": "def read_library_database(file_name='library_database.txt'):",... | [
1,
1,
1,
0,
1,
0,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\n\ndef read_library_records(filepath='library_database.txt'):\n \"\"\"\n Reads library records from the given file and returns a list of dictionaries.\n... | trial_gpt4o_2 | {
"original_instruction": "**Objective:** Demonstrate your understanding of Python's high-level data types, file I/O, and modular programming by implementing a complex data processing task.\n\n#### Problem Statement\n\nYou are given a text file `library_database.txt` that contains library records. Each record is on a... | 0.389409 | Docs: Python310_47070 | C | [
"read_library_database",
"display_books_by_genre",
"search_book_by_title",
"add_new_record"
] | 4 | [
[
"display_books_by_genre",
"read_library_database"
],
[
"search_book_by_title",
"read_library_database"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 25ae41e5a4ace90cab0cdddc7eb25aed9b493a24 | 5ab690725758f70079318d0067e8681cecec909d | |||
v1.0 | complete | Docs | Docs: Pytorch_46721_C | import torch
import torch.distributed.rpc as rpc
def setup_workers():
"""
Initializes the RPC framework and sets up the workers.
"""
pass
def generate_matrices():
"""
Generates two random 1024x1024 matrices on worker0.
Returns:
Tuple[torch.Tensor, torch.Tensor]: Matrices A and B.
... | import torch
import torch.distributed.rpc as rpc
def setup_workers():
"""
Initializes the RPC framework and sets up the workers.
"""
options = rpc.TensorPipeRpcBackendOptions(init_method='tcp://127.0.0.1:29500')
rpc.init_rpc("worker0", rank=0, world_size=3, rpc_backend_options=options)
rpc.init... | import torch
from solution import generate_matrices, split_matrix, gather_results, result_storage
def test_generate_matrices():
A, B = generate_matrices()
assert A.shape == (1024, 1024)
assert B.shape == (1024, 1024)
def test_split_matrix():
matrix = torch.rand(1024, 1024)
sub_matrices = split_mat... | [
{
"docstring": "Initializes the RPC framework and sets up the workers.",
"function_declaration": "def setup_workers():",
"function_name": "setup_workers",
"parameter_list": "()"
},
{
"docstring": "Generates two random 1024x1024 matrices on worker0.\nReturns:\n Tuple[torch.Tensor, torch.Te... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.distributed.rpc as rpc\nfrom torch.distributed.rpc import RRef\n\ndef setup_workers():\n \"\"\"\n Initializes the RPC framework and set... | trial_gpt4o_9 | {
"original_instruction": "**Title: Distributed Matrix Multiplication using PyTorch RRef Protocol**\n\n**Objective:** \nThe goal of this exercise is to test the student's understanding of PyTorch's distributed RPC framework, specifically focusing on the creation, usage, and lifecycle management of Remote References (... | 0.470131 | Docs: Pytorch_46721 | C | [
"setup_workers",
"generate_matrices",
"split_matrix",
"create_and_share_rrefs",
"process_sub_matrix",
"collect_result",
"gather_results"
] | 7 | [
[
"create_and_share_rrefs",
"process_sub_matrix"
],
[
"process_sub_matrix",
"collect_result"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 0f70b95ba696aa18d3f0f0b3e761bb3d7822abc3 | 6f08af437d07f5004fa72418195a3801762e4d11 | |||
v1.0 | complete | Docs | Docs: Python310_47236_C | import asyncio
import aiohttp
from bs4 import BeautifulSoup
async def fetch_url(session, url):
"""
Fetch the HTML content of a given URL asynchronously.
Parameters:
session (aiohttp.ClientSession): The aiohttp session to use for the request.
url (str): The URL to fetch.
Returns:
... | import asyncio
import aiohttp
from bs4 import BeautifulSoup
async def fetch_url(session, url):
"""
Fetch the HTML content of a given URL asynchronously.
Parameters:
session (aiohttp.ClientSession): The aiohttp session to use for the request.
url (str): The URL to fetch.
Returns:
... | import pytest
import asyncio
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from aiohttp import web
from solution import fetch_url, extract_links, main
class TestWebScraper(AioHTTPTestCase):
async def get_application(self):
async def handler(request):
return web.Response(tex... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiohttp\nfrom bs4 import BeautifulSoup\n\nasync def fetch_url(session, url):\n \"\"\"\n Fetch the HTML content of a given URL asynchronousl... | trial_gpt4o_0 | {
"original_instruction": "### Asynchronous Web Scraper\n\nYou are tasked with building an asynchronous web scraper using the `asyncio` library in Python 3.10. The scraper should be able to fetch and parse a list of URLs concurrently and extract certain data from the fetched HTML content.\n\n#### Problem Statement\n\... | 0.765897 | Docs: Python310_47236 | C | [
"fetch_url",
"extract_links",
"worker",
"main"
] | 4 | [
[
"worker",
"extract_links"
],
[
"worker",
"fetch_url"
]
] | 2 | [] | false | [] | false | pytest | true | [
"aiohttp",
"bs4"
] | false | ca6c84632ccff96f7cda9f5f4d7a461a7c3d7d27 | 122798e4445e460a6d86fcdb293da7f0c9902bb3 | |||
v1.0 | complete | Docs | Docs: Python310_46861_C | from typing import List, Tuple
import concurrent.futures
import urllib.request
def fetch_url(url: str, timeout: int) -> bool:
""" Fetches a URL and checks if it returns a 200 status code within the given timeout.
Args:
url (str): The URL to fetch.
timeout (int): The timeout in seconds for the f... | from typing import List, Tuple
import concurrent.futures
import urllib.request
def fetch_url(url: str, timeout: int) -> bool:
try:
with urllib.request.urlopen(url, timeout=timeout) as response:
return response.status == 200
except Exception:
return False
def process_urls(ur... | from solution import process_urls
import urllib.error
from unittest import mock
def mock_urlopen(url, timeout):
""" Mock response for urllib.request.urlopen based on the URL. """
class MockResponse:
def __init__(self, url):
self.url = url
self.status = 200 if "example" in url el... | [
{
"docstring": null,
"function_declaration": "def fetch_url(url, timeout):",
"function_name": "fetch_url",
"parameter_list": "(url, timeout)"
},
{
"docstring": null,
"function_declaration": "def process_urls(urls, timeout):",
"function_name": "process_urls",
"parameter_list": "(u... | [
0,
0,
0,
1,
0,
0,
1,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport concurrent.futures\nimport urllib.request\n\ndef fetch_url(url: str, timeout: int) -> bool:\n try:\n with urllib.reques... | trial_gpt4o_3 | {
"original_instruction": "### Advanced Python Coding Assessment: Concurrent Task Management\n\nUsing the shared documentation on the \"concurrent.futures\" module, solve the following problem that assesses your understanding of concurrent task management in Python.\n\n#### Problem Statement:\nYou are required to imp... | 0.569338 | Docs: Python310_46861 | C | [
"fetch_url",
"process_urls"
] | 2 | [
[
"process_urls",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 564ac0b42a49706a1bbf19051e81b885aba932ec | 6da8bf689f452989c6df476b8c051a29092c18ab | |||
v1.0 | complete | Docs | Docs: Python310_47356_C | def init_custom_python(argc: int, argv: list):
""" Initialize Python with customized configurations using PyConfig and PyPreConfig structures.
Preinitialize Python using the isolated configuration, set specific command-line arguments, handle any exceptions, and clear configuration memory after initialization.
... | import sys
import ctypes
# Define placeholders for PyConfig and PyPreConfig analogous to what would be used in the C API.
class PyPreConfig(ctypes.Structure):
_fields_ = [('isolated', ctypes.c_int)]
class PyConfig(ctypes.Structure):
_fields_ = [('isolated', ctypes.c_int)]
# Define placeholder functions to si... | def test_init_custom_python_no_args():
init_custom_python(0, [])
# Possible checks:
# Since this should just initialize with no arguments,
# we could check the initialization status via a global flag if implemented in actual code.
def test_init_custom_python_simple_cmd():
init_custom_python(3, ["pr... | [] | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nfrom _testinternalcapi import _Py_PreInitializeFromPyPreConfig, _Py_InitializeFromPyConfig, PyPreConfig, PyConfig, PyStatus_Exception, Py_ExitStatusExceptio... | trial_gpt4o_7 | {
"original_instruction": "**Coding Assessment Question: Advanced Python Initialization**\n\nIn this task, you will implement a function that initializes Python with customized configurations using the `PyConfig` and `PyPreConfig` structures. This function will:\n\n1. Preinitialize Python using the isolated configura... | 0.52723 | Docs: Python310_47356 | C | [
"PyPreConfig_InitIsolated",
"PyConfig_InitIsolated",
"PyConfig_SetBytesArgv",
"Py_InitializeFromConfig",
"PyConfig_Clear",
"PyPreConfig_Clear",
"PyStatus_Exception",
"Py_ExitStatusException",
"init_custom_python"
] | 9 | [
[
"init_custom_python",
"PyConfig_Clear"
],
[
"init_custom_python",
"PyConfig_InitIsolated"
],
[
"init_custom_python",
"PyConfig_SetBytesArgv"
],
[
"init_custom_python",
"PyPreConfig_Clear"
],
[
"init_custom_python",
"PyPreConfig_InitIsolated"
],
[
"in... | 8 | [] | false | [
"PyPreConfig",
"PyConfig"
] | true | pytest | false | [] | true | 415a715e7199e4efb80679599860e0964b13f6b6 | 2e230bc698d46a3498fbff09b51408682a654043 | |||
v1.0 | complete | Docs | Docs: Pytorch_47251_C | import torch
from typing import List
def initialize_devices() -> List[int]:
"""
Initializes the XPU devices and checks if any devices are available.
Returns:
A list of available device IDs (integers).
"""
pass
def set_global_seed(seed: int) -> None:
"""
Sets the same random se... | import torch
def initialize_devices():
"""
Initializes the XPU devices and checks if any devices are available.
Returns:
A list of available device IDs (integers).
"""
if torch.xpu.is_available():
num_devices = torch.xpu.device_count()
return list(range(num_devices))
... | import pytest
import torch
from solution import initialize_devices, set_global_seed, parallel_computation, optimize_memory
def test_initialize_devices():
device_ids = initialize_devices()
if torch.xpu.is_available():
assert len(device_ids) > 0
assert all(isinstance(id, int) for id in device_ids... | [
{
"docstring": "Initializes the XPU devices and checks if any devices are available.\n\nReturns:\n A list of available device IDs (integers).",
"function_declaration": "def initialize_devices():",
"function_name": "initialize_devices",
"parameter_list": "()"
},
{
"docstring": "Sets the sa... | [
0,
0,
1,
1,
0,
1,
1,
1,
1
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom typing import List, Dict\n\ndef initialize_devices():\n \"\"\"\n Initializes the XPU devices and checks if any devices are available.\n \"\"... | trial_gpt4o_4 | {
"original_instruction": "In this assignment, you will demonstrate your proficiency in managing devices, streams, and the random number generator in PyTorch's `torch.xpu` module. You will write functions that:\n1. Initialize the XPU devices.\n2. Set a specific random seed for reproducibility across all devices.\n3. ... | 0.507143 | Docs: Pytorch_47251 | C | [
"initialize_devices",
"set_global_seed",
"parallel_computation",
"optimize_memory"
] | 4 | [
[
"set_global_seed",
"initialize_devices"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 45c5ec727ee018738230990eb3263e76b65b9e04 | 0128347eac40ab228a5af9c4477ce8e9e654fabf | |||
v1.0 | complete | Docs | Docs: Python310_46990_C | import asyncio
import json
tasks = []
async def schedule_task(delay: int, name: str):
"""
Schedule a task to be executed after a given delay.
The task should print the statement 'Task {name} executed'.
"""
# Your implementation here
async def handle_client(reader, writer):
"""
Handle cli... | import asyncio
import json
tasks = []
async def schedule_task(delay: int, name: str):
await asyncio.sleep(delay)
print(f'Task {name} executed')
for task in tasks:
if task["name"] == name:
task["status"] = "Completed"
async def handle_client(reader, writer):
data = json.dumps(tasks... | import asyncio
import json
import socket
import pytest
from solution import tasks, schedule_task, handle_client, tcp_server
@pytest.fixture
def setup_tasks():
tasks.clear()
tasks.append({"name": "Task1", "delay": 2, "status": "Scheduled"})
tasks.append({"name": "Task2", "delay": 5, "status": "Scheduled"})
... | [] | [
0,
1,
0,
0,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport json\n\ntasks = []\n\nasync def schedule_task(delay: int, name: str):\n await asyncio.sleep(delay)\n print(f'Task {name} executed')\n fo... | trial_gpt4o_1 | {
"original_instruction": "<|Analysis Begin|>\n\nThe provided documentation describes the event loop in Python's asyncio package in detail. It explains how to obtain the event loop, run and stop it, schedule callbacks, create Futures and Tasks, manage network connections, servers, and subprocesses, and work with sock... | 0.605561 | Docs: Python310_46990 | C | [
"schedule_task",
"handle_client",
"tcp_server",
"main"
] | 4 | [
[
"tcp_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 19982919dcb54ab627d3dd468414ed7e490cd41c | 6e9cb8e431f50455781e5ecddc20a2e3c0911648 | |||
v1.0 | complete | Docs | Docs: Python310_47493_C | import asyncio
import contextvars
# Create logging_level ContextVar
logging_level = contextvars.ContextVar('logging_level', default="INFO")
def set_logging_level(level: str) -> None:
"""Set the logging level for the current context using the provided level."""
...
def get_logging_level() -> str:
"""Retur... | import asyncio
import contextvars
# Create logging_level ContextVar
logging_level = contextvars.ContextVar('logging_level', default="INFO")
def set_logging_level(level: str) -> None:
logging_level.set(level)
def get_logging_level() -> str:
return logging_level.get()
async def process_request(request_id: int... | import asyncio
import pytest
from contextvars import ContextVar
import contextvars
# Import functions from the solution
from solution import set_logging_level, get_logging_level, process_request, logging_level
@pytest.mark.asyncio
async def test_set_get_logging_level():
set_logging_level("DEBUG")
assert get_l... | [
{
"docstring": null,
"function_declaration": "def set_logging_level(level):",
"function_name": "set_logging_level",
"parameter_list": "(level)"
},
{
"docstring": null,
"function_declaration": "def get_logging_level():",
"function_name": "get_logging_level",
"parameter_list": "()"... | [
0,
1,
0,
1,
0,
1,
1,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport contextvars\n\n# Create logging_level ContextVar\nlogging_level = contextvars.ContextVar('logging_level', default=\"INFO\")\n\ndef set_logging_le... | trial_gpt4o_6 | {
"original_instruction": "Context Management in Asynchronous Programming\n\n#### Objective\nIn this assessment, you are required to demonstrate your understanding of the `contextvars` module in Python. Specifically, you will write a function that makes use of `ContextVar` to manage context-local state in an asynchro... | 0.49514 | Docs: Python310_47493 | C | [
"set_logging_level",
"get_logging_level",
"process_request",
"main"
] | 4 | [
[
"process_request",
"get_logging_level"
],
[
"process_request",
"set_logging_level"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | bd45256e3ed7914cddb934fce3cc35b50f1f7b5e | 1334168fd4dad445a79ed92c68fe628303b14401 | |||
v1.0 | complete | Docs | Docs: Python310_47329_C | from typing import List
import asyncio
import aiohttp
async def fetch_data_concurrently(urls: List[str]) -> List[str]:
""" Fetches data from the given list of URLs concurrently and returns the corresponding content list.
If an error occurs while fetching data from a URL, capture it and store an empty string `'... | from typing import List
import asyncio
import aiohttp
async def fetch(url: str) -> str:
"""
Asynchronously fetches the content from the given URL. If an error occurs, returns an empty string.
"""
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp... | import asyncio
from solution import fetch_data_concurrently
def test_fetch_data_concurrently():
# Testing with some local test URLs
urls = [
'http://example.com', # Valid URL
'https://jsonplaceholder.typicode.com/posts/1', # Valid URL
'https://invalidurl.org' # Inva... | [] | [
1,
1,
1,
0,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport asyncio\nimport aiohttp\n\nasync def fetch(url: str) -> str:\n \"\"\"\n Fetches the content from the given URL asynchronously.\n ... | trial_gpt4o_4 | {
"original_instruction": "## Question: Implementing Asynchronous Tasks with asyncio\n\n### Objective\nThe goal of this question is to assess your understanding and ability to implement asynchronous tasks using asyncio’s concurrent programming capabilities.\n\n### Task\nYou need to implement a function `fetch_data_co... | 0.536353 | Docs: Python310_47329 | C | [
"fetch",
"fetch_data_concurrently"
] | 2 | [
[
"fetch_data_concurrently",
"fetch"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | c599811505e997a5a17d2ef78fe2a284622c42ab | af25ca2b4672b1474147adb4da652924e8d2424f | |||
v1.0 | complete | Docs | Docs: Python310_47399_C | import concurrent.futures
def sum_primes_threadpool(N: int, num_threads: int) -> int:
""" Compute the sum of all prime numbers up to a given number `N` by distributing the workload across multiple threads.
>>> sum_primes_threadpool(10, 2) == 17 # 2 + 3 + 5 + 7
>>> sum_primes_threadpool(100, 4) == 1060 # ... | import concurrent.futures
from math import isqrt
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return Tr... | import pytest
from solution import sum_primes_threadpool, sum_primes_processpool
def test_sum_primes_threadpool_small():
assert sum_primes_threadpool(10, 2) == 17 # 2 + 3 + 5 + 7
def test_sum_primes_processpool_small():
assert sum_primes_processpool(10, 2) == 17 # 2 + 3 + 5 + 7
def test_sum_primes_threadpo... | [
{
"docstring": null,
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def sum_primes_in_range(start, end):",
"function_name": "sum_primes_in_range",
"parameter_list": "(start, end)"
... | [
1,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nfrom math import isqrt\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n... | trial_gpt4o_0 | {
"original_instruction": "#### Objective:\nDemonstrate your understanding of concurrent execution in Python using the `concurrent.futures` module.\n\n#### Problem Statement:\nYou are tasked with designing a function that computes the sum of all prime numbers up to a given number `N` by distributing the workload acro... | 0.577855 | Docs: Python310_47399 | C | [
"is_prime",
"sum_primes_in_range",
"sum_primes_threadpool",
"sum_primes_processpool"
] | 4 | [
[
"sum_primes_in_range",
"is_prime"
],
[
"sum_primes_processpool",
"sum_primes_in_range"
],
[
"sum_primes_threadpool",
"sum_primes_in_range"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 20714c0b31be8efee7be3f173199c665d7f473ee | 1fb52d2961356a476e1243830d4e389927c29a2d | |||
v1.0 | complete | Docs | Docs: Python310_47307_C | import sys
import trace
def process_data(data):
"""Process a list of numerical data.
Args:
data (list): A list of integers to be processed.
Returns:
list: A list of processed integers where each number is either doubled if even, or incremented by one if odd.
Examples:
>>> pro... | import sys
import trace
def process_data(data):
processed_data = []
for num in data:
if num % 2 == 0:
processed_data.append(num * 2)
else:
processed_data.append(num + 1)
return processed_data
def trace_process_data(data):
# Create a Trace object
tracer = tra... | import os
from solution import process_data, trace_process_data
def test_process_data_even_numbers():
assert process_data([2, 4, 6]) == [4, 8, 12]
def test_process_data_odd_numbers():
assert process_data([1, 3, 5]) == [2, 4, 6]
def test_process_data_mixed_numbers():
assert process_data([1, 2, 3, 4, 5]) =... | [
{
"docstring": null,
"function_declaration": "def process_data(data):",
"function_name": "process_data",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def trace_process_data(data):",
"function_name": "trace_process_data",
"parameter_list": "(data)"
... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nimport trace\n\ndef process_data(data):\n processed_data = []\n for num in data:\n if num % 2 == 0:\n processed_data.append(num * 2)... | trial_gpt4o_2 | {
"original_instruction": "**Coding Assessment Question: Tracing Function Execution and Generating Coverage Report**\n\n### Objective\nDemonstrate your comprehension of the `trace` module by writing Python code that traces the execution of a given function, analyzes the coverage, and generates a detailed report.\n\n#... | 0.530584 | Docs: Python310_47307 | C | [
"process_data",
"trace_process_data"
] | 2 | [
[
"trace_process_data",
"process_data"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 0af3b3056d03cd87d9ae5ebfa145034de0387bdb | 8628669967d558706c5ab102144aec9e9f071136 | |||
v1.0 | complete | Docs | Docs: Pytorch_46970_C | import torch
from torch.autograd import Function
from torch.autograd import gradcheck
class MyExpFunction(Function):
@staticmethod
def forward(ctx, input):
""" Compute the exponential of the input tensor.
Args:
ctx: Context object to save information for backward pass.
i... | import torch
from torch.autograd import Function
from torch.autograd import gradcheck
class MyExpFunction(Function):
@staticmethod
def forward(ctx, input):
# Compute the exponential of the input tensor
exp_input = torch.exp(input)
# Save necessary tensors for the backward pass
c... | import torch
from torch.autograd import gradcheck
from solution import my_exp, validate_gradcheck
# Validate custom exported operations
def test_my_exp_forward():
input = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
output = my_exp(input)
expected_output = torch.exp(input)
assert torch.allclose(ou... | [] | [
1,
0,
0,
1,
1,
0,
1,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.autograd import Function\nfrom torch.autograd import gradcheck\n\nclass MyExpFunction(Function):\n @staticmethod\n def forward(ctx, input... | trial_gpt4o_6 | {
"original_instruction": "## Custom Pytorch Function Implementation and Verification\n\n### Objective\nImplement a custom PyTorch function using the `torch.autograd.Function` class to evaluate forward and backward passes for a simple operation. Verify the correctness of your implementation by comparing the gradients... | 0.568865 | Docs: Pytorch_46970 | C | [
"my_exp",
"validate_gradcheck"
] | 2 | [
[
"validate_gradcheck",
"my_exp"
]
] | 1 | [] | false | [
"MyExpFunction"
] | true | pytest | true | [
"torch"
] | false | b30840739061119c8f7ef67ef06a2726d650482d | a355b681b9f2d353376024f4cf801a963c6f7fab | |||
v1.0 | complete | Docs | Docs: Python310_47548_C | from typing import List
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def fibonacci(n: int) -> int:
""" Compute the nth Fibonacci number using an iterative approach.
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(10)
55
"""
def compute_fibonacci_concurrent... | from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from typing import List, Union
def fibonacci(n: int) -> int:
if n <= 1:
return n
a, b = 0, 1
for _ in range(2, n+1):
a, b = b, a + b
return b
def compute_fibonacci_concurrently(numbers: List[int], method: str) -> Li... | from solution import compute_fibonacci_concurrently
def test_fibonacci_thread():
numbers = [0, 1, 2, 3, 4, 5, 10]
expected = [0, 1, 1, 2, 3, 5, 55]
assert compute_fibonacci_concurrently(numbers, 'thread') == expected
def test_fibonacci_process():
numbers = [6, 7, 8, 9, 10]
expected = [8, 13, 2... | [] | [
0,
0,
0,
1,
1,
1,
0,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport concurrent.futures\n\ndef fibonacci(n: int) -> int:\n if n == 0: return 0\n elif n == 1: return 1\n a, b = 0, 1\n for _ in r... | trial_gpt4o_7 | {
"original_instruction": "### Concurrent Execution in Python Using `concurrent.futures`\n\n#### Objective:\nTo assess your understanding and ability to implement concurrent task execution in Python using the `concurrent.futures` module.\n\n#### Problem Statement:\n\nYou are required to write a Python function to sim... | 0.608369 | Docs: Python310_47548 | C | [
"fibonacci",
"compute_fibonacci_concurrently"
] | 2 | [
[
"compute_fibonacci_concurrently",
"fibonacci"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 99e533428dc44696c0d4d3b911f7b1587f3c27d6 | 50aa14225c1a14e5a5bc1191ddf14110b0594018 | |||
v1.0 | complete | Docs | Docs: Python310_47572_C | from typing import List, Dict
def fetch(url: str) -> str:
""" Fetch the HTML content of the given URL using the requests library.
>>> content = fetch("https://www.example.com")
>>> "<title>Example Domain</title>" in content
True
"""
def thread_scraper(urls: List[str]) -> Dict[str, str]:
""" Fe... | import requests
import threading
import multiprocessing
from queue import Queue
from typing import List, Dict
import time
# Fetch function to get the HTML content of a URL
def fetch(url: str) -> str:
try:
response = requests.get(url)
response.raise_for_status()
return response.text
exce... | from solution import fetch, thread_scraper, process_scraper
def test_fetch_valid_url():
content = fetch("https://www.example.com")
assert content is not None
assert "<title>Example Domain</title>" in content
def test_fetch_invalid_url():
content = fetch("https://www.nonexistentwebsite.com")
assert... | [
{
"docstring": null,
"function_declaration": "def fetch(url):",
"function_name": "fetch",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def thread_scraper(urls):",
"function_name": "thread_scraper",
"parameter_list": "(urls)"
},
{
"docstring":... | [
0,
1,
1,
1,
1,
0,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import requests\nfrom typing import List, Dict\nimport threading\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nimport time\n\ndef fetch(url: ... | trial_gpt4o_1 | {
"original_instruction": "You are tasked with building a simple yet efficient web scraping application that can concurrently fetch data from a list of URLs. Your goal is to evaluate the performance difference between using `threading` and `multiprocessing` for concurrent execution.\n\n#### Requirements\n\n1. **Fetch... | 0.664479 | Docs: Python310_47572 | C | [
"fetch",
"thread_scraper",
"process_worker",
"process_scraper"
] | 4 | [
[
"process_scraper",
"process_worker"
],
[
"process_worker",
"fetch"
],
[
"thread_scraper",
"fetch"
]
] | 3 | [] | false | [] | false | pytest | true | [
"requests"
] | false | 338800e97573414947d5faf514183b508c5244b3 | 9d589d98b04398fbb302c02498a0b20e949dbf23 | |||
v1.0 | complete | Docs | Docs: Python310_47481_C | import os
import sysconfig
import inspect
from dataclasses import dataclass
from contextlib import contextmanager
@dataclass
class PythonFileInfo:
filename: str
size: int
config_info: dict
@contextmanager
def open_file(file_path):
""" A context manager to ensure proper file handling.
"""
try:
... | import os
import sysconfig
import inspect
from dataclasses import dataclass
from contextlib import contextmanager
@dataclass
class PythonFileInfo:
filename: str
size: int
config_info: dict
@contextmanager
def open_file(file_path):
try:
file = open(file_path, 'r')
yield file
except ... | from solution import list_python_files, get_file_info, process_directory, open_file, PythonFileInfo
import os
def create_test_files(test_dir):
os.makedirs(test_dir, exist_ok=True)
file_paths = []
with open(os.path.join(test_dir, 'test1.py'), 'w') as f:
f.write("def test_func(): pass\n")
with o... | [] | [
0,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport sysconfig\nimport inspect\nfrom dataclasses import dataclass\nfrom contextlib import contextmanager\n\n@dataclass\nclass PythonFileInfo:\n filename... | trial_gpt4o_8 | {
"original_instruction": "Your task is to implement a Python function that takes a directory path as input and performs the following:\n\n1. Lists all the Python files (.py) in the directory and its subdirectories.\n2. For each identified Python file, retrieve and print its configuration information using the \"sysc... | 0.565333 | Docs: Python310_47481 | C | [
"open_file",
"list_python_files",
"get_file_info",
"process_directory"
] | 4 | [
[
"get_file_info",
"open_file"
],
[
"process_directory",
"get_file_info"
],
[
"process_directory",
"list_python_files"
]
] | 3 | [] | false | [
"PythonFileInfo"
] | true | pytest | true | [] | true | 555894b6394e9bc7a35f19faf6400aa1ad113208 | 59df6bead4f8456c8be0277eb8cfb62dc66297d4 | |||
v1.0 | complete | Docs | Docs: Python310_47436_C | from typing import List, Tuple
def perform_operations(numbers: List[int]) -> Tuple[List[int], int, int]:
""" Perform multiple operations on a list of integers.
1. Sort the list.
2. Calculate the sum of the elements.
3. Find the maximum value in the list.
Args:
numbers (List[int]): A list of in... | from typing import List, Tuple
def perform_operations(numbers: List[int]) -> Tuple[List[int], int, int]:
# Perform required operations
sorted_numbers = sorted(numbers)
total_sum = sum(numbers)
max_value = max(numbers)
return sorted_numbers, total_sum, max_value
# Profiling the function
import cPro... | from solution import perform_operations
def test_sorted_list():
assert perform_operations([3, 1, 2])[0] == [1, 2, 3]
def test_sum():
assert perform_operations([3, 1, 2])[1] == 6
def test_max_value():
assert perform_operations([3, 1, 2])[2] == 3
def test_large_list():
import random
numbers = ran... | [
{
"docstring": null,
"function_declaration": "def perform_operations(numbers):",
"function_name": "perform_operations",
"parameter_list": "(numbers)"
},
{
"docstring": null,
"function_declaration": "def profile_code():",
"function_name": "profile_code",
"parameter_list": "()"
}... | [
1,
1,
1,
0,
1,
1,
0,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef perform_operations(numbers: List[int]) -> Tuple[List[int], int, int]:\n sorted_numbers = sorted(numbers)\n total_sum = sum(n... | trial_gpt4o_5 | {
"original_instruction": "You are tasked with profiling a piece of Python code to identify performance bottlenecks and optimize its runtime. Given a list of integers, the code performs multiple operations, including sorting, calculating the sum, and finding the max value. Your job is to:\n\n1. Implement a function `... | 0.578033 | Docs: Python310_47436 | C | [
"perform_operations",
"profile_code"
] | 2 | [
[
"profile_code",
"perform_operations"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 255eb1a6d89c4a4d8ef1bb1e73cf68ae5f33057f | 53f2e75fd277861ced2d2c70defbfad91d45e797 | |||
v1.0 | complete | Docs | Docs: Python310_47716_C | import asyncio
from typing import List, Tuple
async def task_scheduler(tasks: List[Tuple[int, int, float]], num_workers: int) -> None:
""" Implement a task scheduler using asyncio.Queue that schedules tasks based on their priority and processes them concurrently with a given number of worker coroutines.
Args:... | import asyncio
from typing import List, Tuple
async def worker(name, queue):
while True:
priority, task_id, duration = await queue.get()
await asyncio.sleep(duration)
print(f"Task {task_id} completed after {duration:.2f} seconds")
queue.task_done()
async def task_scheduler(tasks: L... | import asyncio
import pytest
from solution import task_scheduler
@pytest.mark.asyncio
async def test_simple_case():
tasks = [
(1, 101, 2.5),
(2, 102, 1.0),
(0, 103, 3.0),
(1, 104, 1.5)
]
num_workers = 2
await task_scheduler(tasks, num_workers)
@pytest.mark.asyncio
async... | [] | [
0,
0,
1,
1,
1,
1,
1,
1,
0,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def worker(name, queue):\n while True:\n priority, task_id, duration = await queue.get()\n awai... | trial_gpt4o_6 | {
"original_instruction": "**Objective**: Implement a task scheduler using `asyncio.Queue` that schedules tasks based on their priority and processes them concurrently with a given number of worker coroutines.\n\n**Problem Statement**:\nYou are to design a task scheduler that manages tasks with varying priorities. Ta... | 0.6456 | Docs: Python310_47716 | C | [
"worker",
"task_scheduler"
] | 2 | [
[
"task_scheduler",
"worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4d79b8fe0a964a5db7a16577aafea41cb6979a27 | a2f183f02725b7fd57e7de37226a16454a81158b | |||
v1.0 | complete | Docs | Docs: Python310_47741_C | from multiprocessing import Pool
def is_prime(n):
"""Determine if a given integer n is prime.
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(5)
True
"""
# Implement this function
pass
def find_primes_in_range(start, end, process_count):
... | import math
from multiprocessing import Pool
def is_prime(n):
"""
Returns True if n is a prime number, otherwise False.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n... | from solution import is_prime, find_primes_in_range
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(5) == True
assert is_prime(29) == True
assert is_prime(30) == False
assert is_prime(1) == False
assert is_prime(0) =... | [
{
"docstring": "Returns True if n is a prime number, otherwise False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of prime numbers in the range [start, end] using the specified number of worker processes... | [
0,
1,
0,
1,
0,
0,
0,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import multiprocessing\nimport math\n\ndef is_prime(n):\n \"\"\"\n Check if the number n is a prime number.\n A prime number is a positive integer greater than... | trial_gpt4o_7 | {
"original_instruction": "### Question: Prime Number Computation using multiprocessing\n\nYou are to implement a Python program to find all prime numbers within a given range using process-based parallelism with the `multiprocessing` module.\n\n#### Requirements\n\n1. **Function `is_prime(n)`**:\n - **Input**: An... | 0.626622 | Docs: Python310_47741 | C | [
"is_prime",
"find_primes_in_range"
] | 2 | [
[
"find_primes_in_range",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4700fbb7f58ed1255136ac9ff9f901c855a0f2ab | 5deb7ed78ee3b2b68b3e6a2ab01c1c2efb69e826 | |||
v1.0 | complete | Docs | Docs: Python310_47702_C | from typing import List, Dict
def is_prime(n: int) -> bool:
"""
Returns True if n is a prime number, else False.
"""
pass
def analyze_numbers(numbers: List[int]) -> Dict[str, List[int]]:
"""
Analyzes a list of integers returning a dictionary with prime, even and odd numbers.
>>> analyze_n... | def is_prime(n: int) -> bool:
"""
Returns True if n is a prime number, else False.
"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def analyze_numbers(numbers):
"""
Analyzes a list of integers returning ... | from solution import analyze_numbers, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(20) == False
assert is_prime(1) == False
assert is_prime(0) == False
def test_analyze_numbers_wi... | [
{
"docstring": "Returns True if n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Analyzes a list of integers returning a dictionary with prime, even and odd numbers.",
"function_declarat... | [
0,
0,
0,
1,
1,
0,
1,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n \"\"\"\n Helper function to check if a number is prime.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return True\... | trial_gpt4o_9 | {
"original_instruction": "### Unique Coding Challenge for Python310 Understanding\n\n#### Task\n\nYou are required to implement a function called `analyze_numbers` that takes in a list of integers and performs the following tasks:\n\n1. Filters out the prime numbers from the list.\n2. Categorizes the remaining numbe... | 0.710215 | Docs: Python310_47702 | C | [
"is_prime",
"analyze_numbers"
] | 2 | [
[
"analyze_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 09439d7a60ee607bb1ea83af38346977ea85c1eb | 4fb65b83f56f3b6b700d6f255becaa9c8594cdb6 | |||
v1.0 | complete | Docs | Docs: Python310_47615_C | import asyncio
import random
from typing import List
async def fetch_data(index: int) -> str:
""" An asynchronous function that simulates fetching data from a data source, where `index` is the identifier for the data source.
>>> import asyncio
>>> result = asyncio.run(fetch_data(1))
>>> result
'dat... | import asyncio
import random
from typing import List
async def fetch_data(index: int) -> str:
# Simulate network latency
await asyncio.sleep(random.uniform(0.1, 1.0))
return f"data-{index}"
async def fetch_all_data(count: int) -> List[str]:
tasks = [fetch_data(i) for i in range(count)]
results = a... | import asyncio
from solution import fetch_data, fetch_all_data
def test_fetch_data_format():
# Since fetch_data is async, we need to run it in an event loop
async def run_test():
result = await fetch_data(1)
assert result == "data-1"
asyncio.run(run_test())
def test_fetch_all_data_cou... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\nfrom typing import List\n\nasync def fetch_data(index: int) -> str:\n # Simulate network latency\n await asyncio.sleep(random.unifo... | trial_gpt4o_0 | {
"original_instruction": "**Objective:** Demonstrate your understanding of Python's `asyncio` library by implementing asynchronous functions and handling concurrent tasks.\n\n**Problem Statement:**\n\nYou are tasked with implementing an asynchronous program that fetches data from multiple sources concurrently, proce... | 0.547105 | Docs: Python310_47615 | C | [
"fetch_data",
"fetch_all_data"
] | 2 | [
[
"fetch_all_data",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c90d1b6b6610e6c175fa9f6e1f89850572c8843d | d1aca3eab8f2c712f980b2e9098d69e00749bad1 | |||
v1.0 | complete | Docs | Docs: Python310_47560_C | import functools
@functools.lru_cache(maxsize=128)
def compute_factorial(n: int) -> int:
"""
Compute the factorial of a number using recursion.
Cache the results for efficiency.
:param n: Integer whose factorial is to be computed.
:return: Factorial of the input number.
"""
if n < 2:
... | import functools
@functools.lru_cache(maxsize=128)
def compute_factorial(n: int) -> int:
"""
Compute the factorial of a number using recursion.
Cache the results for efficiency.
:param n: Integer whose factorial is to be computed.
:return: Factorial of the input number.
"""
if n < 2:
... | from solution import process_data
def test_process_data_with_integer():
assert process_data(5) == 120 # 5! = 120
def test_process_data_with_list():
assert process_data([1, 2, 3, 4, 5]) == [1, 2, 6, 24, 120] # Factorials of 1, 2, 3, 4, 5
def test_process_data_with_dict():
assert process_data({'a': 3, 'b... | [
{
"docstring": "Compute the factorial of a number using recursion.\nCache the results for efficiency.\n\n:param n: Integer whose factorial is to be computed.\n:return: Factorial of the input number.",
"function_declaration": "def compute_factorial(n):",
"function_name": "compute_factorial",
"paramet... | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import functools\n\n@functools.lru_cache(maxsize=128)\ndef compute_factorial(n: int) -> int:\n \"\"\"\n Compute the factorial of a number using recursion.\n Ca... | trial_gpt4o_9 | {
"original_instruction": "### Problem: Efficient Data Processing with Caching and Function Dispatch\n\n#### Background\nIn this task, you are required to implement a function that processes data efficiently using caching for repetitive computations and single-dispatch for handling different types of data structures.... | 0.682557 | Docs: Python310_47560 | C | [
"compute_factorial",
"process_data",
"_",
"_",
"_"
] | 5 | [
[
"_",
"compute_factorial"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 806143b7877c115676a4297cb4ea3164ff7a543e | 066054489773cb4e096279b2c88c0290dbf55a2a | |||
v1.0 | complete | Docs | Docs: Python310_47914_C | import asyncio
import platform
import selectors
async def echo_client(message: str):
"""A simple TCP echo client that connects to a given server, sends a message, and receives a response."""
reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
writer.write(message.encode())
await writer.dr... | import asyncio
import platform
import selectors
async def echo_client(message):
reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
writer.write(message.encode())
await writer.drain()
data = await reader.read(100)
print(f'Received: {data.decode()}')
writer.close()
await writer... | import asyncio
import pytest
import platform
from unittest.mock import patch
from solution import platform_aware_network_operation
@pytest.mark.asyncio
async def test_platform_aware_network_operation_windows():
with patch('platform.system', return_value='Windows'), \
patch('asyncio.ProactorEventLoop') as... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport platform\nimport selectors\n\nasync def echo_client(message):\n try:\n reader, writer = await asyncio.open_connection('127.0.0.1', 8888... | trial_gpt4o_1 | {
"original_instruction": "### Asynchronous Task Management Across Platforms\n\nDue to the differences in how different platforms handle asynchronous I/O, particularly with Python's `asyncio` module, it is essential to write code that adapts to these variations. This task requires you to implement an asynchronous fun... | 0.648036 | Docs: Python310_47914 | C | [
"echo_client",
"platform_aware_network_operation"
] | 2 | [
[
"platform_aware_network_operation",
"echo_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a97202206ec57ea7fe0b2b63a39dfdb6a84e9386 | 55961c2f988727102e8a962391ebd3b262b27774 | |||
v1.0 | complete | Docs | Docs: Python310_47547_C | import bz2
from typing import List, Dict
def verify_and_compress_files(directory: str) -> Dict[str, bool]:
"""
Compresses text files in the given directory and verifies the decompressed content matches the original.
Args:
directory (str): The path to the directory containing the text files to process.... | import bz2
import os
from typing import List, Dict
def compress_file(input_file: str, output_file: str) -> None:
"""
Compress a text file using bz2.
"""
with open(input_file, 'rb') as f_in, bz2.open(output_file, 'wb', compresslevel=9) as f_out:
for line in f_in:
f_out.write(line)
d... | import os
import pytest
from solution import verify_and_compress_files
@pytest.fixture
def setup_test_files(tmp_path):
"""
Creates a temporary directory with text files for testing.
"""
filenames = ['file1.txt', 'file2.txt', 'file3.txt']
contents = ['Hello World!', 'Goodbye World!', 'Another file w... | [
{
"docstring": "Compress a text file using bz2.",
"function_declaration": "def compress_file(input_file, output_file):",
"function_name": "compress_file",
"parameter_list": "(input_file, output_file)"
},
{
"docstring": "Decompress a bz2 file to a text file.",
"function_declaration": "def... | [
1,
1,
0,
0,
1,
1,
1,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import bz2\nimport os\nfrom typing import Dict\n\ndef verify_and_compress_files(directory: str) -> Dict[str, bool]:\n result = {}\n \n def compress_file(file_p... | trial_gpt4o_8 | {
"original_instruction": "#### Background\n\nYou are a data scientist working with large text files. To save disk space and transfer files more efficiently, you need to compress these files using the `bz2` library provided in Python. You also need to ensure that the compressed files can be decompressed back to their... | 0.712331 | Docs: Python310_47547 | C | [
"compress_file",
"decompress_file",
"verify_and_compress_files"
] | 3 | [
[
"verify_and_compress_files",
"compress_file"
],
[
"verify_and_compress_files",
"decompress_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 84a029bc66f13887e06f38fee7fe241cc35b09ec | fa0bbe84a40c3c05297df9331a898532c8646a5a | |||
v1.0 | complete | Docs | Docs: Python310_46950_C | import urllib.request
import http.client
from concurrent.futures import ThreadPoolExecutor
from typing import List, Dict, Union
def fetch_and_parse_urls(urls: List[str]) -> Dict[str, Union[List[str], str]]:
"""
Using the `urllib` and `http.client` modules, implement a Python function that performs the followin... | import urllib.request
import http.client
from concurrent.futures import ThreadPoolExecutor
from typing import List, Dict, Union
from urllib.parse import urlparse
import re
def fetch_url(url: str) -> Union[str, str]:
"""
Fetch a URL and return the content or an error message.
"""
try:
with urlli... | from solution import fetch_and_parse_urls
def test_fetch_and_parse_urls_empty_list():
assert fetch_and_parse_urls([]) == {}
def test_fetch_and_parse_urls_valid_urls():
# Mock responses for testing
from unittest.mock import patch
html_example = """
<html>
<head><title>Example</title></head... | [
{
"docstring": "Fetch a URL and return the content or an error message.",
"function_declaration": "def fetch_url(url):",
"function_name": "fetch_url",
"parameter_list": "(url)"
},
{
"docstring": "Parse HTML content and extract all hyperlinks.",
"function_declaration": "def parse_links(ht... | [
0,
1,
1,
0,
1,
1,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import urllib.request\nfrom urllib.error import URLError, HTTPError\nimport re\nimport concurrent.futures\nfrom typing import List, Dict, Union\n\ndef fetch_url_content... | trial_gpt4o_2 | {
"original_instruction": "## Question: Web Scraper and Data Fetcher\n\nUsing the `urllib` and `http.client` modules, implement a Python function that performs the following tasks:\n\n1. **Fetch URLs**: Given a list of URLs, fetch the content of each URL.\n2. **Parse Links**: From the fetched content, extract all hyp... | 0.712293 | Docs: Python310_46950 | C | [
"fetch_url",
"parse_links",
"fetch_and_parse_urls"
] | 3 | [
[
"fetch_and_parse_urls",
"fetch_url"
],
[
"fetch_and_parse_urls",
"parse_links"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6ecfaeba58847df94bbc16867edc52c724cd785e | 16e1c0b2f34dbdd64fbdf39437492b8e27d14a96 | |||
v1.0 | complete | Docs | Docs: Pytorch_47566_C | import torch
import torch.nn as nn
import torch.nn.init as init
def custom_weight_init(model):
"""
Initializes the weights of the model's layers using specific initialization strategies:
- Xavier Uniform initialization for convolutional layers.
- Kaiming Normal initialization for fully connected layers... | import torch
import torch.nn as nn
import torch.nn.init as init
def custom_weight_init(model):
"""
Initializes the weights of the model's layers using specific initialization strategies:
- Xavier Uniform initialization for convolutional layers.
- Kaiming Normal initialization for fully connected layers... | import torch.nn as nn
from solution import custom_weight_init, define_cnn_model
def test_custom_weight_init():
model = define_cnn_model()
for layer in model.modules():
if isinstance(layer, nn.Conv2d):
assert layer.weight.data.mean().abs() < 0.1, "Xavier Uniform initialization may have ... | [] | [
1,
1,
1,
0,
0,
1,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.nn.init as init\n\ndef custom_weight_init(model):\n for layer in model.modules():\n if isinstance(layer, nn.... | trial_gpt4o_9 | {
"original_instruction": "**Objective:** \nThe goal of this coding assessment is to test your understanding of tensor initialization methods in PyTorch and their application in neural network models.\n\n**Problem Statement:**\nYou are tasked with designing a neural network for classifying images from the CIFAR-10 da... | 0.633245 | Docs: Pytorch_47566 | C | [
"custom_weight_init",
"define_cnn_model"
] | 2 | [
[
"define_cnn_model",
"custom_weight_init"
]
] | 1 | [] | false | [
"SimpleCNN"
] | true | pytest | true | [
"torch"
] | false | 31d50bf733c0355022e4af3f8de2c49e9eb49efe | 1fcb1bf267a59059d6fd612a5a8a7d71086e97a1 | |||
v1.0 | complete | Docs | Docs: Python310_48163_C | from multiprocessing import Pool
def calculate_factorials(nums):
""" Calculate the factorial of multiple numbers concurrently using multiprocessing.
Args:
nums : list of int
A list of non-negative integers.
Returns:
dict
A dictionary where the keys are the input integers and the v... | from multiprocessing import Pool
from math import factorial
def factorial_worker(n):
return n, factorial(n)
def calculate_factorials(nums):
with Pool() as pool:
results = pool.map(factorial_worker, nums)
return dict(results) | from solution import calculate_factorials
def test_single_element():
assert calculate_factorials([5]) == {5: 120}
def test_multiple_elements():
assert calculate_factorials([0, 1, 5, 7]) == {0: 1, 1: 1, 5: 120, 7: 5040}
def test_zero():
assert calculate_factorials([0]) == {0: 1}
def test_large_input(... | [
{
"docstring": null,
"function_declaration": "def factorial_worker(n):",
"function_name": "factorial_worker",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def calculate_factorials(nums):",
"function_name": "calculate_factorials",
"parameter_list": "(nu... | [
0,
1,
0,
1,
1,
1,
0,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import multiprocessing\nfrom math import factorial\n\ndef calculate_factorials(nums):\n \"\"\"\n Calculate the factorials of a list of non-negative integers concu... | trial_gpt4o_3 | {
"original_instruction": "### Assessing Multiprocessing in Python\n\n**Objective:** \nDesign a function that utilizes the `multiprocessing` package to calculate the factorial of multiple numbers concurrently. You need to demonstrate your understanding of creating and managing processes, handling shared resources, an... | 0.896286 | Docs: Python310_48163 | C | [
"factorial_worker",
"calculate_factorials"
] | 2 | [
[
"calculate_factorials",
"factorial_worker"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6a4dfa13a00c703704869b6f07687d809ef949dd | 9d94b75d848ebd21e08e86c75115c9b4337c58db | |||
v1.0 | complete | Docs | Docs: Python310_48152_C | import asyncio
from typing import List, Tuple
async def process_order(order: Tuple[int, int]) -> None:
"""Simulate processing an order.
Args:
order (Tuple[int, int]): A tuple containing priority and order ID.
Usage:
>>> await process_order((1, 'order1'))
"""
async def restaurant_system(order... | import asyncio
from typing import List, Tuple
async def process_order(order: Tuple[int, int]) -> None:
priority, order_id = order
await asyncio.sleep(priority * 0.1)
print(f"Order {order_id} with priority {priority} is being processed.")
async def worker(name: str, queue: asyncio.PriorityQueue) -> None:
... | from solution import process_order, restaurant_system
import asyncio
async def test_process_order():
order = (1, 'order1')
await process_order(order)
async def test_restaurant_system():
orders = [(1, 'order1'), (3, 'order3'), (2, 'order2'), (1, 'order4')]
await restaurant_system(orders)
async def... | [] | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def process_order(order: Tuple[int, int]) -> None:\n priority, order_id = order\n await asyncio.sleep(prio... | trial_gpt4o_7 | {
"original_instruction": "You are tasked with simulating a restaurant order processing system using `asyncio` queues. The system should handle orders with different priorities.\n\n#### Task:\n1. Implement an asynchronous function `process_order` that simulates processing an order.\n2. Implement an asynchronous funct... | 0.495834 | Docs: Python310_48152 | C | [
"process_order",
"worker",
"restaurant_system"
] | 3 | [
[
"restaurant_system",
"worker"
],
[
"worker",
"process_order"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 139a624e3b92225d5837b6e64b689e8b418b43c3 | ebe0137ed2c4c034527d1cef018cde9cf9363744 | |||
v1.0 | complete | Docs | Docs: Python310_48220_C | import asyncio
import ssl
async def handle_client(reader, writer):
""" Handles communication with a connected client. """
pass
async def start_server(ip: str, port: int, certfile: str, keyfile: str) -> None:
""" Starts a secure chat server with given IP address, port, and SSL certificate and key files.
... | import asyncio
import ssl
clients = []
async def handle_client(reader, writer):
global clients
addr = writer.get_extra_info('peername')
clients.append(writer)
print(f"New connection from {addr}")
try:
while True:
data = await reader.read(100)
if not data:
... | import asyncio
import ssl
import tempfile
from solution import start_server, start_client
async def run_test_server_and_client():
ip = '127.0.0.1'
port = 8888
# Generate a temporary SSL certificate and key for testing
certfile = tempfile.NamedTemporaryFile(delete=False)
keyfile = tempfile.NamedTe... | [] | [
1,
1,
1,
0,
0,
0,
1,
1,
1
] | 6 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport ssl\n\nclients = set()\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n clients.add(writer)\n pr... | trial_gpt4o_2 | {
"original_instruction": "You are required to implement a simple asynchronous chat server and client using the `asyncio` and `socket` modules. The communication between the server and clients should be secured using the `ssl` module.\n\n#### Server Requirements:\n1. The server should listen on a specified IP address... | 0.642073 | Docs: Python310_48220 | C | [
"handle_client",
"start_server",
"start_client"
] | 3 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e94456bceadf0b799749d8aba9a9269088ea1459 | 0d9e6fb9d98d981687c5a57e7d70710cf690f3e1 | |||
v1.0 | complete | Docs | Docs: Python310_47351_C | from dataclasses import dataclass
from contextlib import contextmanager
import time
@dataclass
class Task:
""" Data class to store metadata of a task. """
id: int
name: str
start_time: float
end_time: float
status: str
@contextmanager
def TaskManager(task: Task):
""" Context manager to tra... | from dataclasses import dataclass
from contextlib import contextmanager
import time
@dataclass
class Task:
id: int
name: str
start_time: float
end_time: float
status: str
@contextmanager
def TaskManager(task):
try:
task.start_time = time.time()
yield
task.status = 'Succ... | from solution import perform_task, Task
import time
def sample_task(duration):
time.sleep(duration)
def failing_task():
raise ValueError("This task failed")
def test_perform_task_success():
task = perform_task(1, "SleepTask", sample_task, 1)
assert task.id == 1
assert task.name == "SleepTask"
... | [] | [
1,
0,
0,
0,
0,
0,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from dataclasses import dataclass\nfrom contextlib import contextmanager\nimport time\n\n@dataclass\nclass Task:\n id: int\n name: str\n start_time: float\n ... | trial_gpt4o_8 | {
"original_instruction": "**Objective**: Demonstrate your understanding of Python's runtime services, specifically focusing on `dataclasses` and `contextlib`. You will need to create a robust context-driven data management system using these modules.\n\n**Problem Statement**:\nYou are tasked with implementing a data... | 0.548007 | Docs: Python310_47351 | C | [
"TaskManager",
"perform_task"
] | 2 | [
[
"perform_task",
"TaskManager"
]
] | 1 | [] | false | [
"Task"
] | true | pytest | true | [] | true | 432f0d638559b0203ddbb6fe234926653b410f09 | 08d52d8dcaa57c6f929953b00ab81a177314a8cf | |||
v1.0 | complete | Docs | Docs: Python310_47594_C | from typing import List
def calculate_primes(limit: int) -> List[int]:
"""
Calculate prime numbers up to a specified limit.
Args:
limit (int): The upper limit (inclusive) to calculate prime numbers.
Returns:
List[int]: A list of prime numbers up to the specified limit.
>>> calculate_prim... | def calculate_primes(limit):
"""
Original function to calculate prime numbers up to a specified limit.
"""
primes = []
for num in range(2, limit + 1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
... | from solution import calculate_primes, optimized_calculate_primes
def test_calculate_primes_small_limit():
assert calculate_primes(10) == [2, 3, 5, 7]
def test_optimized_calculate_primes_small_limit():
assert optimized_calculate_primes(10) == [2, 3, 5, 7]
def test_calculate_primes_larger_limit():
primes_... | [
{
"docstring": "Original function to calculate prime numbers up to a specified limit.",
"function_declaration": "def calculate_primes(limit):",
"function_name": "calculate_primes",
"parameter_list": "(limit)"
},
{
"docstring": "Profiles the original function to calculate primes up to 10000\n... | [
1,
1,
0,
0,
0,
0,
1,
1,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_primes(limit):\n \"\"\"\n Original function to calculate prime numbers up to a given limit.\n \"\"\"\n primes = []\n for num in range(2, li... | trial_gpt4o_1 | {
"original_instruction": "**Objective:** Utilize Python's `cProfile` and `pstats` modules to identify performance bottlenecks in code and optimize it.\n\n**Task:** You will be given a function `calculate_primes` which calculates prime numbers up to a given limit. Your tasks are:\n1. Profile the given function using ... | 0.551146 | Docs: Python310_47594 | C | [
"calculate_primes",
"run_profiling",
"analyze_profiling_results",
"optimized_calculate_primes",
"compare_performance"
] | 5 | [
[
"compare_performance",
"analyze_profiling_results"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 42d1eba29381e60a466e06a3cf0afa35a6a9c79e | 32fe3aef8fbf723d558d93fe21463cb6325e78d3 | |||
v1.0 | complete | Docs | Docs: Python310_47915_C | import asyncio
async def start_chat_server(host: str, port: int):
""" Start a chat server that handles multiple clients, broadcasts messages, and handles disconnections gracefully.
Args:
host (str): The host IP address.
port (int): The port number.
Example:
>>> asyncio.run(start_chat_server('1... | import asyncio
active_clients = []
async def broadcast_message(message, writer):
for client in active_clients:
if client != writer:
client.write(message)
await client.drain()
async def handle_client(reader, writer):
try:
active_clients.append(writer)
while True... | import asyncio
import pytest
import functools
from solution import start_chat_server, start_chat_client
HOST = '127.0.0.1'
PORT = 8888
@pytest.fixture
def event_loop():
loop = asyncio.new_event_loop()
yield loop
loop.close()
def run_server(loop):
loop.run_until_complete(start_chat_server(HOST, PORT))... | [] | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nactive_clients = []\n\nasync def broadcast_message(message, writer):\n for client in active_clients:\n if client != writer:\n cli... | trial_gpt4o_0 | {
"original_instruction": "You have been provided with documentation on how to use the `asyncio` package's streaming capabilities to handle network connections in Python. Using this knowledge, you are tasked with implementing a mini chat server and client using asyncio streams.\n\n### Part 1: Chat Server\n\nYour firs... | 0.581676 | Docs: Python310_47915 | C | [
"broadcast_message",
"handle_client",
"start_chat_server",
"send_message",
"receive_message",
"start_chat_client"
] | 6 | [
[
"handle_client",
"broadcast_message"
],
[
"start_chat_client",
"receive_message"
],
[
"start_chat_client",
"send_message"
],
[
"start_chat_server",
"handle_client"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 82d168f8e5308a16ba8ce52f71a1930a646cefbb | 64552e4fdf985e74fd9f8b8131adc26cc6d9a595 | |||
v1.0 | complete | Docs | Docs: Python310_47573_C | import importlib
import sys
from types import ModuleType
from typing import Optional
def import_module(module_name: str) -> ModuleType:
"""
Imports and returns the specified module. If the module is already imported,
returns the existing module from sys.modules.
>>> import_module('os') == importli... | import importlib
import sys
from types import ModuleType
from typing import Optional
def import_module(module_name: str) -> ModuleType:
"""
Imports and returns the specified module. If the module is already imported,
returns the existing module from sys.modules.
"""
if module_name in sys.modules:
... | import os
import importlib
import sys
from solution import import_module, reload_module, cache_bytecode, source_from_cache
def test_import_module_existing():
assert import_module('os') == os
def test_import_module_new():
module_name = 'math'
if module_name in sys.modules:
del sys.modules[module_na... | [
{
"docstring": "Imports and returns the specified module. If the module is already imported,\nreturns the existing module from sys.modules.",
"function_declaration": "def import_module(module_name):",
"function_name": "import_module",
"parameter_list": "(module_name)"
},
{
"docstring": "Relo... | [
0,
1,
0,
0,
1,
1,
1,
0,
1
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import importlib\nimport sys\nimport importlib.util\nfrom importlib import abc\nfrom types import ModuleType\n\ndef import_module(module_name: str) -> ModuleType:\n ... | trial_gpt4o_5 | {
"original_instruction": "#### Objective:\nDemonstrate the ability to handle Python module imports, loading, and reloading using the `importlib` module, which supersedes the deprecated `imp` module.\n\n#### Problem Statement:\n\nThe `imp` module is deprecated, and you are required to write a Python program that effe... | 0.620506 | Docs: Python310_47573 | C | [
"import_module",
"reload_module",
"cache_bytecode",
"source_from_cache"
] | 4 | [
[
"reload_module",
"import_module"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 85b39d11bc5be961bae4440745d2ea6da51dc3a4 | 730977641f6208a5d0d3d584db16412f00cfd29d | |||
v1.0 | complete | Docs | Docs: Python310_48212_C | from contextlib import contextmanager
# Mock functions for demonstration
def open_database_connection():
print("Database connection opened")
return "db_connection"
def close_database_connection(conn):
print(f"Database connection {conn} closed")
def log_exception(exc):
print(f"Exception Logged: {exc}"... | from contextlib import contextmanager
# Mock functions for demonstration
def open_database_connection():
print("Database connection opened")
return "db_connection"
def close_database_connection(conn):
print(f"Database connection {conn} closed")
def log_exception(exc):
print(f"Exception Logged: {exc}"... | from solution import manage_database_connection, open_database_connection, close_database_connection, log_exception
def test_normal_operation():
"""
Test that the context manager opens and closes the connection normally without exceptions.
"""
try:
with manage_database_connection() as conn:
... | [
{
"docstring": null,
"function_declaration": "def open_database_connection():",
"function_name": "open_database_connection",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def close_database_connection(conn):",
"function_name": "close_database_connection",
... | [
1,
0,
1,
0,
0,
1,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from contextlib import contextmanager\n\n# Mock functions for demonstration\ndef open_database_connection():\n print(\"Database connection opened\")\n return \"db... | trial_gpt4o_8 | {
"original_instruction": "### Advanced Context Manager with Contextlib\n\n#### Objective\nDesign a context manager that ensures resources are acquired and released correctly, even when exceptions occur, demonstrating your understanding of the `contextlib` module.\n\n#### Requirements\n1. **Function Implementation**:... | 0.388202 | Docs: Python310_48212 | C | [
"open_database_connection",
"close_database_connection",
"log_exception",
"manage_database_connection"
] | 4 | [
[
"manage_database_connection",
"close_database_connection"
],
[
"manage_database_connection",
"log_exception"
],
[
"manage_database_connection",
"open_database_connection"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 4c26389733aed7f5afedba934a7bb7c668756c14 | c154d9785dab0fa05fd4e97ed9209ce2ed136f05 | |||
v1.0 | complete | Docs | Docs: Python310_47888_C | from functools import cached_property, lru_cache, singledispatch, partial
class DataProcessor:
def __init__(self, data):
"""
Initialize the DataProcessor with a list of numeric data.
:param data: List of numeric values.
"""
self._data = data
@cached_property
def mea... | from functools import cached_property, lru_cache, singledispatch, partial
import time
import math
class DataProcessor:
def __init__(self, data):
self._data = data
@cached_property
def mean(self):
return sum(self._data) / len(self._data)
@cached_property
def stdev(self):
me... | from solution import DataProcessor, expensive_computation, quick_computation, partial_computation, process
import pytest
def test_data_processor_mean():
dp = DataProcessor([1, 2, 3, 4, 5])
assert dp.mean == 3.0
def test_data_processor_stdev():
dp = DataProcessor([1, 2, 3, 4, 5])
assert math.isclose(dp... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import cached_property, lru_cache, singledispatch, partial\nimport time\nimport math\n\nclass DataProcessor:\n def __init__(self, data):\n self... | trial_gpt4o_0 | {
"original_instruction": "### Question: Advanced Function Manipulation with functools\n\nYou are required to create a solution for a fictional data processing application. The problem involves implementing a class and a standalone function using the `functools` module to enhance performance and maintainability. Here... | 0.610228 | Docs: Python310_47888 | C | [
"expensive_computation",
"quick_computation",
"process",
"_",
"_",
"_"
] | 6 | [
[
"quick_computation",
"expensive_computation"
]
] | 1 | [] | false | [
"DataProcessor"
] | true | pytest | true | [] | true | 83d86d265d8b847e8b970573c3a1b0642f625a53 | eec45bc427177027f513a672415555eb276c6146 | |||
v1.0 | complete | Docs | Docs: Python310_48198_C | import asyncio
from typing import List, Tuple, Dict, Any
async def task_manager(task_specs: List[Tuple[int, str]]) -> Dict[str, Any]:
""" Task Manager Simulator: Schedule multiple asynchronous tasks, compute results concurrently, manage timeouts, and ensure the proper handling of cancellations.
Args:
... | import asyncio
from typing import List, Tuple, Dict, Any
async def simulated_task(delay: int, task_name: str) -> str:
await asyncio.sleep(delay)
return task_name
async def task_wrapper(delay: int, task_name: str):
try:
result = await asyncio.wait_for(simulated_task(delay, task_name), timeout=5)
... | import asyncio
import pytest
from solution import task_manager
@pytest.mark.asyncio
async def test_task_manager_all_success():
tasks = [(1, "task_1"), (2, "task_2"), (1, "task_3")]
expected_output = {
"results": ["task_1", "task_3", "task_2"],
"exceptions": [],
"order_of_completion": ["... | [] | [
0,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple, Dict, Any\n\nasync def task_function(delay: int, task_name: str) -> str:\n await asyncio.sleep(delay)\n return f\"... | trial_gpt4o_7 | {
"original_instruction": "**Problem Statement: Task Manager Simulator**\n\nYou are required to implement a task manager simulator using Python's `asyncio` library. The task manager should be able to schedule multiple asynchronous tasks, compute results concurrently, manage timeouts, and ensure the proper handling of... | 0.673397 | Docs: Python310_48198 | C | [
"simulated_task",
"task_wrapper",
"task_manager"
] | 3 | [
[
"task_manager",
"task_wrapper"
],
[
"task_wrapper",
"simulated_task"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 18d9801788372c3372d9d6d9308d40fcd30e8063 | 4a92817280f5a8de876e9b1aa47b139abfce87a2 | |||
v1.0 | complete | Docs | Docs: Python310_48470_C | from typing import List, Tuple
import asyncio
async def run_command(cmd: str) -> Tuple[str, str]:
"""
Executes a single shell command and captures its stdout and stderr outputs.
:param cmd: The shell command to execute.
:return: A tuple containing the stdout and stderr outputs of the command.
... | from typing import List, Tuple
import asyncio
async def run_command(cmd: str) -> Tuple[str, str]:
"""
Executes a single shell command and captures its stdout and stderr outputs.
:param cmd: The shell command to execute.
:return: A tuple containing the stdout and stderr outputs of the command.
... | import asyncio
from solution import run_commands
def test_single_command():
commands = ['echo Hello']
stdout_list, stderr_list = asyncio.run(run_commands(commands))
assert stdout_list == ['Hello\n']
assert stderr_list == ['']
def test_multiple_commands():
commands = ['echo Hello', 'echo World']
... | [] | [
0,
0,
1,
1,
0,
0,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\nimport asyncio\n\nasync def run_command(cmd: str) -> Tuple[str, str]:\n process = await asyncio.create_subprocess_shell(\n cmd... | trial_gpt4o_2 | {
"original_instruction": "**Objective:** Demonstrate your understanding of the asyncio subprocess API in Python 3.10.\n\n---\n\n**Question:** \n\nYou are tasked with creating a command-line utility that launches multiple shell commands in parallel, captures their outputs, and aggregates the results. Each command sho... | 0.680956 | Docs: Python310_48470 | C | [
"run_command",
"run_commands"
] | 2 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cd112b74b82143e26dc15b80027f6ca1e466d942 | 390c0ea6444f3bf9a4a52955b7210db499d98a16 | |||
v1.0 | complete | Docs | Docs: Python310_48609_C | #!/usr/bin/env python3
import cgi
import cgitb
import re
cgitb.enable()
def validate_form_data(username, email, password):
""" Validate the form data: username, email, and password.
>>> validate_form_data("user123", "user@example.com", "password123")
[]
>>> validate_form_data("", "user@example.com", ... | #!/usr/bin/env python3
import cgi
import cgitb
import re
cgitb.enable()
def validate_form_data(username, email, password):
errors = []
if not username:
errors.append("Username is required.")
if not email:
errors.append("Email is required.")
elif not re.match(r"[^@]+@[^@]+\.[^@]+", em... | import re
from solution import validate_form_data
def test_all_fields_valid():
errors = validate_form_data("user123", "user@example.com", "password123")
assert errors == []
def test_missing_username():
errors = validate_form_data("", "user@example.com", "password123")
assert "Username is required." in... | [
{
"docstring": null,
"function_declaration": "def validate_form_data(username, email, password):",
"function_name": "validate_form_data",
"parameter_list": "(username, email, password)"
},
{
"docstring": null,
"function_declaration": "def registration_form():",
"function_name": "regi... | [
1,
0
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl",
"solution_code": "#!/usr/bin/env python3\n\nimport cgi\nimport cgitb\nimport re\n\ncgitb.enable()\n\ndef validate_form_data(username, email, password):\n erro... | trial_gpt4o_1 | {
"original_instruction": "#### Objective\nCreate a CGI script using Python to process a user registration form. The form will collect a username, email address, and password from the user. Your CGI script should perform the following tasks:\n\n1. Validate the form data:\n - Ensure that all fields (username, email,... | 0.513563 | Docs: Python310_48609 | C | [
"validate_form_data",
"registration_form"
] | 2 | [
[
"registration_form",
"validate_form_data"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fbb09beb32f3e8b188e462eec9a087a94a72099e | 62c05ad897280614259adfe5d0e0e0c045bebff3 | |||
v1.0 | complete | Docs | Docs: Python310_48699_C | import turtle
from typing import Tuple
def hex_to_rgb(hex_color: str) -> Tuple[int, int, int]:
"""
Convert hex color to RGB.
"""
pass
def interpolate_color(color1: Tuple[int, int, int], color2: Tuple[int, int, int], fraction: float) -> Tuple[int, int, int]:
"""
Interpolate between two RGB colo... | import turtle
import math
from turtle import colormode
def hex_to_rgb(hex_color):
"""
Convert hex color to RGB.
"""
hex_color = hex_color.lstrip('#')
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
def interpolate_color(color1, color2, fraction):
"""
Interpolate between two RGB ... | from solution import hex_to_rgb, interpolate_color
def test_hex_to_rgb():
assert hex_to_rgb('#FF0000') == (255, 0, 0)
assert hex_to_rgb('#00FF00') == (0, 255, 0)
assert hex_to_rgb('#0000FF') == (0, 0, 255)
assert hex_to_rgb('#FFFFFF') == (255, 255, 255)
assert hex_to_rgb('#000000') == (0, 0, 0)
de... | [
{
"docstring": "Convert hex color to RGB.",
"function_declaration": "def hex_to_rgb(hex_color):",
"function_name": "hex_to_rgb",
"parameter_list": "(hex_color)"
},
{
"docstring": "Interpolate between two RGB colors.\nfraction is a float between 0 and 1.",
"function_declaration": "def int... | [
1,
0,
0,
1,
0,
0,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import turtle\nimport math\nfrom turtle import colormode\n\ndef hex_to_rgb(hex_color):\n \"\"\"\n Convert hex color to RGB.\n \"\"\"\n hex_color = hex_color... | trial_gpt4o_0 | {
"original_instruction": "**Turtle Graphics Challenge: Draw a Radial Pattern**\n\n### Objective\nWrite a Python function using the turtle module. This function should create a radial pattern where each spoke of the pattern is a concentric circle. The number of spokes and the number of circles within each spoke shoul... | 0.585639 | Docs: Python310_48699 | C | [
"hex_to_rgb",
"interpolate_color",
"draw_radial_pattern"
] | 3 | [
[
"draw_radial_pattern",
"hex_to_rgb"
],
[
"draw_radial_pattern",
"interpolate_color"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a143dc2309709e9a01aebc580aa1045ae0c5947e | c28db2c58908e17690fe1c35dd85ce7856d3bf34 | |||
v1.0 | complete | Docs | Docs: Python310_48575_C | from typing import List, Dict, Tuple, Iterator
from functools import reduce
def generate_values(events: List[Dict[str, Union[int, str, float]]]) -> Iterator[Union[int, float]]:
"""
Generator function that yields the value field from each event in the provided list of events.
"""
def filter_events(events: ... | from functools import reduce
def generate_values(events):
"""
Generator function that yields the value field from each event in the provided list of events.
"""
for event in events:
yield event['value']
def filter_events(events, event_type):
"""
Filters the events, only including those... | from solution import generate_values, filter_events, sum_values, enumerate_events, pipeline
def test_generate_values():
events = [{"id": 1, "type": "click", "value": 3.5}, {"id": 2, "type": "view", "value": 2.0}]
assert list(generate_values(events)) == [3.5, 2.0]
def test_filter_events():
events = [{"id":... | [
{
"docstring": "Generator function that yields the value field from each event in the provided list of events.",
"function_declaration": "def generate_values(events):",
"function_name": "generate_values",
"parameter_list": "(events)"
},
{
"docstring": "Filters the events, only including thos... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import reduce\n\ndef generate_values(events):\n \"\"\"\n Generator function that yields the value field from each event in events.\n \"\"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "**Problem Statement:**\n\nYou are working on a data processing pipeline that requires efficient handling and transformation of a stream of data using functional programming concepts in Python. Your task is to implement a series of functions that will process a list of events. Each event is ... | 0.536412 | Docs: Python310_48575 | C | [
"generate_values",
"filter_events",
"sum_values",
"enumerate_events",
"pipeline"
] | 5 | [
[
"pipeline",
"enumerate_events"
],
[
"pipeline",
"filter_events"
],
[
"pipeline",
"generate_values"
],
[
"pipeline",
"sum_values"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | b73de9a872a751b6da4bc9be16325a5fd0ac722d | de69888ef509e3e393084aef14e30178df1ac4b9 | |||
v1.0 | complete | Docs | Docs: Python310_48860_C | from contextlib import contextmanager, ExitStack
@contextmanager
def managed_file(file_name, mode):
"""
Context manager to open and close a file.
Args:
file_name (str): The name of the file to open.
mode (str): The mode to open the file in (e.g., 'r' for read, 'w' for write).
... | from contextlib import contextmanager, ExitStack
@contextmanager
def managed_file(file_name, mode):
"""
Context manager to open and close a file.
Args:
file_name (str): The name of the file to open.
mode (str): The mode to open the file in (e.g., 'r' for read, 'w' for write).
... | import os
from solution import managed_file, manage_multiple_files
# Helper function to create and populate a test file
def create_test_file(file_name, content):
with open(file_name, 'w') as f:
f.write(content)
def test_managed_file_read():
# Setup: Create a test file
test_file = 'test_read.txt'
... | [
{
"docstring": "Context manager to open and close a file.\n\nArgs:\n file_name (str): The name of the file to open.\n mode (str): The mode to open the file in (e.g., 'r' for read, 'w' for write).\n\nYields:\n file object: The opened file object.",
"function_declaration": "def managed_file(file_name... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from contextlib import contextmanager, ExitStack\n\n@contextmanager\ndef managed_file(file_name, mode):\n file = open(file_name, mode)\n try:\n yield file\... | trial_gpt4o_9 | {
"original_instruction": "### Custom Context Manager with ExitStack\n\n**Objective:**\n\nDesign and implement a custom context manager using the `contextmanager` decorator from the `contextlib` module. The context manager should handle resource acquisition and release, and you need to leverage `ExitStack` to manage ... | 0.509282 | Docs: Python310_48860 | C | [
"managed_file",
"manage_multiple_files"
] | 2 | [
[
"manage_multiple_files",
"managed_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d0eb30f9ea740d4da3fc99b9313cfb1062f037c3 | 375303f238067a928cfa321bc79cdf4ddb973fde | |||
v1.0 | complete | Docs | Docs: Python310_48838_C | from typing import List
async def matrix_operations(matrix: List[List[float]]) -> List[List[float]]:
""" Transforms the input matrix by squaring each element, computing the sum of each row asynchronously and replacing each element in the row by the computed sum.
>>> matrix = [
... [1.0, 2.0, 3.0],
... | from typing import List
import asyncio
async def async_row_sums(matrix: List[List[float]]) -> List[float]:
for row in matrix:
await asyncio.sleep(0) # Yield control, simulating an async operation
yield sum(row)
async def matrix_operations(matrix: List[List[float]]) -> List[List[float]]:
# Ste... | import asyncio
import pytest
from solution import matrix_operations
@pytest.mark.asyncio
async def test_matrix_operations_example():
matrix = [
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]
]
expected_result = [
[14.0, 14.0, 14.0],
[77.0, 77.0, 77.0],
[1... | [] | [
1,
1,
1,
1,
0,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport asyncio\n\nasync def matrix_operations(matrix: List[List[float]]) -> List[List[float]]:\n # Step 1: Squaring Elements\n squared_ma... | trial_gpt4o_9 | {
"original_instruction": "### Advanced Python Expression Evaluation\n\n#### Objective\nWrite a function `matrix_operations` that takes in a matrix (a list of lists of numbers) and performs various operations to transform it based on given functions. The transformations should include both synchronous and asynchronou... | 0.595657 | Docs: Python310_48838 | C | [
"async_row_sums",
"matrix_operations"
] | 2 | [
[
"matrix_operations",
"async_row_sums"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2bf56a617e07c0daedee8ce9756580d85257c1d0 | d0303f54363ba0c6a5c62f50108058373da7755f | |||
v1.0 | complete | Docs | Docs: Python310_48589_C | import functools
from functools import partial, singledispatch
# Part 1: Memoized Factorial
@functools.cache
def memoized_factorial(n):
""" Return the factorial of a non-negative integer n, using memoization to increase efficiency.
>>> memoized_factorial(5)
120
>>> memoized_factorial(6)
720
"""... | import functools
from functools import partial, singledispatch
# Part 1: Memoized Factorial
@functools.cache
def memoized_factorial(n):
if n < 2:
return 1
return n * memoized_factorial(n - 1)
# Part 2: Data Cleaner
def data_cleaner(data, strip_whitespace=True, to_lowercase=True, remove_chars=None):
... | from solution import memoized_factorial, default_data_cleaner, process_data, data_cleaner
def test_memoized_factorial():
assert memoized_factorial(0) == 1
assert memoized_factorial(1) == 1
assert memoized_factorial(5) == 120
assert memoized_factorial(6) == 720
def test_data_cleaner():
assert data_... | [
{
"docstring": null,
"function_declaration": "def memoized_factorial(n):",
"function_name": "memoized_factorial",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def data_cleaner(data, strip_whitespace=True, to_lowercase=True, remove_chars=None):",
"function_... | [
0,
0,
0,
0,
0,
1,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import functools\nfrom functools import partial, singledispatch\n\n# Part 1: Memoized Factorial\n@functools.cache\ndef memoized_factorial(n):\n if n == 0:\n r... | trial_gpt4o_8 | {
"original_instruction": "**Context & Objectives:**\nYou are tasked with improving the efficiency and flexibility of a hypothetical data processing system. Your solution should leverage the `functools` module’s features to optimize and enhance the system.\n\n**Problem Statement:**\nYou need to implement the followin... | 0.56822 | Docs: Python310_48589 | C | [
"memoized_factorial",
"data_cleaner",
"process_data",
"_",
"_",
"_"
] | 6 | [
[
"_",
"process_data"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 0dd8a39eed3ebc4de36ad2d2d9e984e6b68d6c1d | d2d57681a63e03ac1328ebcdbe61296662e31d9c | |||
v1.0 | complete | Docs | Docs: Python310_48311_C | import concurrent.futures
import urllib.request
import math
def fetch_url(url, timeout=60):
"""
Fetches the content from the given URL and returns its length.
Parameters:
- url (str): The URL to fetch.
- timeout (int): The timeout for the URL fetch operation.
Returns:
- int: The l... | import concurrent.futures
import urllib.request
import math
def fetch_url(url, timeout=60):
"""
Fetches the content from the given URL and returns its length.
Parameters:
- url (str): The URL to fetch.
- timeout (int): The timeout for the URL fetch operation.
Returns:
- int: The l... | import pytest
from solution import fetch_url, is_prime, execute_tasks
def test_fetch_url():
url = 'https://www.example.com'
length = fetch_url(url)
assert length > 0 # Assume example.com returns some content
def test_is_prime():
assert is_prime(2) is True
assert is_prime(3) is True
assert is_... | [
{
"docstring": "Fetches the content from the given URL and returns its length.\n\nParameters:\n- url (str): The URL to fetch.\n- timeout (int): The timeout for the URL fetch operation.\n\nReturns:\n- int: The length of the content fetched from the URL.",
"function_declaration": "def fetch_url(url, timeout=6... | [
0,
0,
0,
1,
1,
1,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nimport urllib.request\nimport math\n\ndef fetch_url(url, timeout=60):\n try:\n with urllib.request.urlopen(url, timeout=timeout) as... | trial_gpt4o_6 | {
"original_instruction": "#### Objective\nThe goal is to implement a solution that uses both `ThreadPoolExecutor` and `ProcessPoolExecutor` to manage heterogeneous tasks concurrently. You will need to ensure that the code handles exceptions gracefully and efficiently manages resources.\n\n#### Description\nYou are g... | 0.537046 | Docs: Python310_48311 | C | [
"fetch_url",
"is_prime",
"execute_tasks"
] | 3 | [
[
"execute_tasks",
"fetch_url"
],
[
"execute_tasks",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 47ff205dce5a3272e0b52a8bc1e0da6cbb74f654 | 9dc305107cd7d5311adb096c27f0954268731ce1 | |||
v1.0 | complete | Docs | Docs: Python310_48579_C | import os
import subprocess
def execute_command(command):
""" Execute the given shell command and handle errors gracefully. """
try:
subprocess.run(command, check=True, shell=True)
except subprocess.CalledProcessError as e:
print(f"An error occurred while executing: {command}\nError: {str(e... | import os
import subprocess
def execute_command(command):
try:
subprocess.run(command, check=True, shell=True)
except subprocess.CalledProcessError as e:
print(f"An error occurred while executing: {command}\nError: {str(e)}")
def create_virtual_environment(env_name='test-env'):
print(f"Cre... | from solution import create_virtual_environment, generate_requirements
def test_create_virtual_environment():
# Assuming the environment does not already exist
env_name = 'test-env-test'
create_virtual_environment(env_name)
assert os.path.isdir(env_name), f"Virtual environment '{env_name}' should have ... | [
{
"docstring": null,
"function_declaration": "def execute_command(command):",
"function_name": "execute_command",
"parameter_list": "(command)"
},
{
"docstring": null,
"function_declaration": "def create_virtual_environment(env_name='test-env'):",
"function_name": "create_virtual_env... | [
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport subprocess\n\ndef create_virtual_environment(env_name):\n \"\"\"\n Create a virtual environment with the given name.\n \"\"\"\n try:\n ... | trial_gpt4o_9 | {
"original_instruction": "Managing Virtual Environments and Packages\n\n**Objective**:\nCreate a script that demonstrates the creation, activation, and management of virtual environments and packages using Python.\n\n**Task**:\nWrite a Python script that performs the following tasks:\n\n1. **Create a Virtual Environ... | 0.549813 | Docs: Python310_48579 | C | [
"execute_command",
"create_virtual_environment",
"activate_virtual_environment",
"install_packages",
"generate_requirements",
"upgrade_package",
"list_installed_packages",
"main"
] | 8 | [
[
"create_virtual_environment",
"execute_command"
],
[
"generate_requirements",
"execute_command"
],
[
"install_packages",
"execute_command"
],
[
"upgrade_package",
"execute_command"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | e97343a35f7b44276a3be02babe3458d061e0181 | 6ca26a69174910dddc93e38a0da552497bd32447 | |||
v1.0 | complete | Docs | Docs: Python310_48954_C | import asyncio
async def run_workers(N: int, T: int) -> None:
"""
Write an asynchronous Python program using the `asyncio` library. The program should manage multiple coroutines that perform IO-bound tasks concurrently and synchronize their execution using `asyncio` synchronization primitives.
Paramet... | import asyncio
async def fetch_data(lock: asyncio.Lock, worker_id: int):
"""
Simulates fetching data from a server and processing it.
The lock ensures that only one worker fetches data at a time.
"""
async with lock:
await asyncio.sleep(1) # Simulates the fetch delay
data = f"data_... | import asyncio
from solution import run_workers
def test_run_workers_output():
async def test():
# Redirect stdout to capture print output
from io import StringIO
import sys
output = StringIO()
sys.stdout = output
await run_workers(3, 5)
... | [] | [
0,
0,
0,
0,
0,
1,
1,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List\n\nasync def fetch_data(lock: asyncio.Lock, worker_id: int) -> str:\n async with lock:\n await asyncio.sleep(1) # sim... | trial_gpt4o_8 | {
"original_instruction": "#### Objective\nWrite an asynchronous Python program using the `asyncio` library. The program should manage multiple coroutines that perform IO-bound tasks concurrently and synchronize their execution using `asyncio` synchronization primitives.\n\n#### Problem Statement\nDesign an asynchron... | 0.575199 | Docs: Python310_48954 | C | [
"fetch_data",
"worker",
"run_workers"
] | 3 | [
[
"run_workers",
"worker"
],
[
"worker",
"fetch_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ce03ffb7ac4cdf39ba83b3f455eca9677095bc8e | 0cc17b2e7b12314e71b3e31d04b10ca8c0573bc8 | |||
v1.0 | complete | Docs | Docs: Scikit_48769_C | from typing import List
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import string
def preprocess_text(text: str) -> str:
""" Preprocess the input text by removing pun... | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
import string
def preprocess_text(text):
"""
Preprocess the input text by removing punctuation and lowercasing.
""... | import pytest
from solution import preprocess_text, build_and_evaluate_pipeline
def test_preprocess_text():
assert preprocess_text("Hello, World!") == "hello world"
assert preprocess_text("It's simple.") == "its simple"
assert preprocess_text("Python-Programming!") == "pythonprogramming"
def test_build_an... | [
{
"docstring": "Preprocess the input text by removing punctuation and lowercasing.",
"function_declaration": "def preprocess_text(text):",
"function_name": "preprocess_text",
"parameter_list": "(text)"
},
{
"docstring": null,
"function_declaration": "def build_and_evaluate_pipeline(train... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.me... | trial_gpt4o_7 | {
"original_instruction": "**Title**: Implementing a Text Classification Pipeline with Scikit-learn\n\n**Objective**: Demonstrate the ability to preprocess text data, transform it into numerical features, and apply a machine learning model to classify the data using scikit-learn.\n\n**Problem Statement**:\n\nYou are ... | 0.624374 | Docs: Scikit_48769 | C | [
"preprocess_text",
"build_and_evaluate_pipeline"
] | 2 | [
[
"build_and_evaluate_pipeline",
"preprocess_text"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | 08dc4d285ff9837f67d8f93a63c4ec5a0be70e06 | 6cbd6f7285b0e8b261260862fc8a82aade06ee14 | |||
v1.0 | complete | Docs | Docs: Python310_48425_C | import hashlib
import hmac
import time
from typing import Union
def create_cookie(user_id: str, expires_at: int, secret_key: bytes, salt: bytes, personalization: bytes) -> str:
"""
Generates a hex-encoded cookie with BLAKE2b hash.
Parameters:
user_id (str): The user's unique identifier.
exp... | import hashlib
import hmac
import time
def create_cookie(user_id: str, expires_at: int, secret_key: bytes, salt: bytes, personalization: bytes) -> str:
"""
Generates a hex-encoded cookie with BLAKE2b hash.
"""
payload = f"{user_id}:{expires_at}".encode('utf-8')
h = hashlib.blake2b(key=secret_key, s... | import time
from solution import create_cookie, verify_cookie
# Define constant test data
USER_ID = "test_user"
SECRET_KEY = b'secret_key_for_testing'
SALT = b'salt_for_testing'
PERSONALIZATION = b'app_specific'
def test_create_and_verify_cookie():
expires_at = int(time.time()) + 60 # cookie valid for 60 seconds... | [
{
"docstring": "Generates a hex-encoded cookie with BLAKE2b hash.",
"function_declaration": "def create_cookie(user_id, expires_at, secret_key, salt, personalization):",
"function_name": "create_cookie",
"parameter_list": "(user_id, expires_at, secret_key, salt, personalization)"
},
{
"docst... | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nimport hmac\nimport time\n\ndef create_cookie(user_id: str, expires_at: int, secret_key: bytes, salt: bytes, personalization: bytes) -> str:\n \"\"\"... | trial_gpt4o_8 | {
"original_instruction": "### Question\n\nYou are tasked with securing the authentication process for an online service by implementing a function that creates hashed and salted cookies for users. The cookies should securely embed the user's ID and an expiration timestamp. Additionally, you should provide a function... | 0.65595 | Docs: Python310_48425 | C | [
"create_cookie",
"verify_cookie"
] | 2 | [
[
"verify_cookie",
"create_cookie"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e84647fe06837f79269077e676a3f11fa3f7abec | a1238198f346f09571bc1505e9a1c1bb15119e92 | |||
v1.0 | complete | Docs | Docs: Python310_48552_C | ### Python Profiling Assessment
You are given a large dataset processing function which takes a significant amount of time to execute. Your task is to profile this function using the `cProfile` and `pstats` modules to find performance bottlenecks.
#### Function to be Profiled
def process_data(data):
processed_da... | import cProfile
import pstats
def process_data(data):
processed_data = []
for record in data:
# Simulate some complex processing
for _ in range(1000):
processed_record = record ** 2
processed_data.append(processed_record)
return processed_data
def profile_processing(dat... | import os
import pytest
from solution import process_data, profile_processing
def test_process_data():
data = [1, 2, 3, 4, 5]
expected_output = [1, 4, 9, 16, 25]
output = process_data(data)
assert output == expected_output
def test_profile_processing():
data = list(range(1, 100))
profile_proce... | [
{
"docstring": null,
"function_declaration": "def process_data(data):",
"function_name": "process_data",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def profile_processing(data):",
"function_name": "profile_processing",
"parameter_list": "(data)"
... | [
0,
0,
0,
0,
0,
0,
1,
0,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import cProfile\nimport pstats\n\ndef process_data(data):\n processed_data = []\n for record in data:\n # Simulate some complex processing\n for _ i... | trial_gpt4o_9 | {
"original_instruction": "### Python Profiling Assessment\n\nYou are given a large dataset processing function which takes a significant amount of time to execute. Your task is to profile this function using the `cProfile` and `pstats` modules to find performance bottlenecks.\n\n#### Function to be Profiled\n\n```py... | 0.532249 | Docs: Python310_48552 | C | [
"process_data",
"profile_processing"
] | 2 | [
[
"profile_processing",
"process_data"
]
] | 1 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | fc9c3fd48c886d80134432ff75b3e62ebda3a0d4 | 3aefc1aa2e2b4cc02d481c94906cfc740cdcd175 | |||
v1.0 | complete | Docs | Docs: Python310_48439_C | def register_vowelnumber_codec():
"""
Register a custom codec for encoding and decoding strings where vowels are replaced by numbers.
"""
class VowelNumberEncoder:
def __init__(self):
self.vowel_map = {'a': '1', 'e': '2', 'i': '3', 'o': '4', 'u': '5'}
def encode(self... | import codecs
class VowelNumberEncoder:
def __init__(self):
self.vowel_map = {'a': '1', 'e': '2', 'i': '3', 'o': '4', 'u': '5'}
def encode(self, input, errors='strict'):
result = ''.join([self.vowel_map.get(char, char) for char in input])
return (result.encode(), len(input))
... | import pytest
from solution import (
register_vowelnumber_codec,
register_hex_replacement_error_handler,
encode_with_vowelnumber,
decode_with_vowelnumber,
hex_replacement_error_handler
)
def test_vowelnumber_codec_encoding():
register_vowelnumber_codec()
original_text = "hello world"
en... | [] | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import codecs\n\nclass VowelNumberEncoder:\n def __init__(self):\n self.vowel_map = {'a': '1', 'e': '2', 'i': '3', 'o': '4', 'u': '5'}\n\n def encode(self,... | trial_gpt4o_1 | {
"original_instruction": "### Codec Registration and Manipulation in Python\n\nIn this task, you are required to demonstrate your understanding of codec registration and encoding/decoding in Python by implementing a custom encoding and an error handling mechanism.\n\n#### Requirements\n\n1. **Register a Custom Codec... | 0.659885 | Docs: Python310_48439 | C | [
"register_vowelnumber_codec",
"encode_with_vowelnumber",
"decode_with_vowelnumber",
"hex_replacement_error_handler",
"register_hex_replacement_error_handler"
] | 5 | [
[
"register_hex_replacement_error_handler",
"hex_replacement_error_handler"
]
] | 1 | [] | false | [
"VowelNumberEncoder"
] | true | pytest | true | [] | true | 3590dca18055f4a31e5d6a3cb3534a2e551d43cb | 71797569cdecb1e4ac473dafac737782d9ee9641 | |||
v1.0 | complete | Docs | Docs: Python310_49141_C | import asyncio
async def process_logs(log_entries):
"""
Asynchronously process a list of log entries in various formats.
Each log entry can be:
1. A dictionary with a `type` key indicating the log type and a `content` key with the log message.
2. A tuple where the first element is the log typ... | import asyncio
class DummyAsyncContextManager:
async def __aenter__(self):
await asyncio.sleep(0) # Simulate some delay
return self
async def __aexit__(self, exc_type, exc, tb):
await asyncio.sleep(0) # Simulate some delay
async def process_log_entry(log_entry):
try:
mat... | import asyncio
from solution import process_logs
def test_process_logs():
log_entries = [
{'type': 'error', 'content': 'Failed to connect to server'},
('warning', 'Low disk space'),
'User logged in',
{'type': 'info', 'content': 'System rebooted'},
('debug', 'Variable x = 10'... | [] | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nclass DummyAsyncContextManager:\n async def __aenter__(self):\n await asyncio.sleep(0.1)\n return self\n\n async def __aexit__(sel... | trial_gpt4o_9 | {
"original_instruction": "**Background:**\n\nYou are tasked with creating a log processing system. The logs are provided in various formats, and your function needs to be able to handle these formats using Python's pattern matching features. Furthermore, some logs might contain errors, and your function should handl... | 0.615865 | Docs: Python310_49141 | C | [
"process_log_entry",
"process_logs"
] | 2 | [
[
"process_logs",
"process_log_entry"
]
] | 1 | [] | false | [
"DummyAsyncContextManager"
] | true | pytest | true | [] | true | b5e4c1034e3e52cf3fb0ba6a26bfddeab9c2b007 | 12ef5b50054601a8dbba8c6590393395a7e62419 | |||
v1.0 | complete | Docs | Docs: Python310_48443_C | #!/usr/bin/env python3
import cgi
import cgitb
import re
# Enable CGI traceback for debugging
cgitb.enable()
def validate_email(email):
"""
Validate the email format using regex.
>>> validate_email("test@example.com") True
>>> validate_email("bad-email") False
"""
# Implement the email valida... | #!/usr/bin/env python3
import cgi
import cgitb
import re
# Enable CGI traceback for debugging
cgitb.enable()
def validate_email(email):
"""
Validate the email format using regex.
"""
return re.match(r'^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$', email)
def handle_file_upload(fileitem):
"""... | import pytest
from solution import validate_email, handle_file_upload
from io import BytesIO
def test_validate_email():
assert validate_email("test@example.com")
assert not validate_email("bad-email")
assert not validate_email("missingAtsign.com")
assert not validate_email("@missingUsername.com")
def ... | [
{
"docstring": "Validate the email format using regex.",
"function_declaration": "def validate_email(email):",
"function_name": "validate_email",
"parameter_list": "(email)"
},
{
"docstring": "Check the file type and size for the uploaded profile picture.",
"function_declaration": "def h... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "#!/usr/bin/env python3\n\nimport cgi\nimport cgitb\nimport re\n\n# Enable CGI traceback for debugging\ncgitb.enable()\n\ndef validate_email(email):\n \"\"\"Validate ... | trial_gpt4o_9 | {
"original_instruction": "**Title: Implement a CGI Script to Process User Data and File Uploads**\n\n#### Objective:\nYou are tasked with creating a CGI script in Python that processes user-submitted form data and handles file uploads. Your script should validate the form data, ensure secure handling of file uploads... | 0.501504 | Docs: Python310_48443 | C | [
"validate_email",
"handle_file_upload",
"application"
] | 3 | [
[
"application",
"handle_file_upload"
],
[
"application",
"validate_email"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | a6742a6bdbbb75e964f57564e500a033705fca8c | ecafed35ac131e932fb1e33c5ad366bac3c7162e | |||
v1.0 | complete | Docs | Docs: Python310_48654_C | import asyncio
import aiohttp
async def fetch_data(session, url):
"""
Fetch data from a given URL using aiohttp session.
Args:
session (aiohttp.ClientSession): The aiohttp session to perform the request.
url (str): The URL to fetch data from.
Returns:
str: The text content of ... | import asyncio
import aiohttp
async def fetch_data(session, url):
"""
Fetch data from a given URL using aiohttp session.
Args:
session (aiohttp.ClientSession): The aiohttp session to perform the request.
url (str): The URL to fetch data from.
Returns:
str: The text content of ... | import pytest
import asyncio
from solution import fetch_data, aggregate_requests, process_aggregated_data
@pytest.mark.asyncio
async def test_fetch_data():
async with aiohttp.ClientSession() as session:
url = "https://jsonplaceholder.typicode.com/posts"
response = await fetch_data(session, url)
... | [] | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiohttp\n\nasync def fetch_data(session, url):\n \"\"\"\n Fetch data from a given URL using aiohttp session.\n\n Args:\n session ... | trial_gpt4o_6 | {
"original_instruction": "### Asynchronous Network Request Aggregator\n\n**Problem Statement:**\n\nYou are tasked with designing a asynchronous network request aggregator using the asyncio library. The aim is to fetch data concurrently from multiple URLs and process the collected data asynchronously.\n\n**Function t... | 0.608121 | Docs: Python310_48654 | C | [
"fetch_data",
"aggregate_requests",
"process_aggregated_data"
] | 3 | [
[
"aggregate_requests",
"fetch_data"
],
[
"process_aggregated_data",
"aggregate_requests"
]
] | 2 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 77aa2dbf2baf1419d86c8116b5e55608296b8a4f | dfab126119f17d7205cbad17a31cb9b41604f516 | |||
v1.0 | complete | Docs | Docs: Python310_49196_C | import asyncio
async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
"""
Handles client connections.
Reads a message from the client, processes it by appending " - processed",
and sends the processed message back to the client.
"""
async def start_server():
"""
... | import asyncio
async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
try:
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
response = f"{message} - pro... | import asyncio
from solution import handle_client, start_server, client
async def test_handle_client():
reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
writer.write(b'Hello Test!')
await writer.drain()
data = await reader.read(100)
assert data.decode() == "Hello Test! - ... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):\n try:\n data = await reader.read(100)\n message... | trial_gpt4o_5 | {
"original_instruction": "**Concurrency Challenge with asyncio**\n\n**Objective:**\nImplement an asynchronous system using the `asyncio` library to manage multiple clients connecting to a server. Each client will send a message, and the server will process these messages concurrently, then return a response to each ... | 0.632183 | Docs: Python310_49196 | C | [
"handle_client",
"start_server",
"client"
] | 3 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0a49c57e473968a3b6baf8e2750f819c2dc9a22d | b809f844800e25001a0cecb43fa440ff5b5b9571 | |||
v1.0 | complete | Docs | Docs: Python310_49315_C | import hashlib
def sign_message(message: str, secret_key: bytes, personalization: str = "") -> bytes:
"""
Returns a secure hash of the message using the secret key and optional personalization string.
"""
pass
def verify_message(message: str, secret_key: bytes, personalization: str, hashed_message: by... | import hashlib
def sign_message(message: str, secret_key: bytes, personalization: str = "") -> bytes:
"""
Returns a secure hash of the message using the secret key and optional personalization string.
"""
if len(secret_key) < 16:
raise ValueError("Secret key must be at least 16 bytes long.")
... | from solution import sign_message, verify_message
def test_sign_message_valid():
message = "Hello, World!"
key = b'secure_key_123456'
personalization = "test"
hashed = sign_message(message, key, personalization)
assert isinstance(hashed, bytes)
assert len(hashed) == 32
def test_sign_message_sh... | [
{
"docstring": "Returns a secure hash of the message using the secret key and optional personalization string.",
"function_declaration": "def sign_message(message, secret_key, personalization=''):",
"function_name": "sign_message",
"parameter_list": "(message, secret_key, personalization='')"
},
... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\n\ndef sign_message(message: str, secret_key: bytes, personalization: str = \"\") -> bytes:\n if len(secret_key) < 16:\n raise ValueError(\"The... | trial_gpt4o_9 | {
"original_instruction": "### Secure Communication System\n\n**Objective:**\n\nYour task is to implement a secure communication system using Python's `hashlib` module. This system involves creating, sending, and verifying messages that have been securely hashed and authenticated.\n\n### Requirements:\n\n1. **Functio... | 0.718365 | Docs: Python310_49315 | C | [
"sign_message",
"verify_message"
] | 2 | [
[
"verify_message",
"sign_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 38a3f5f9c21ae9586ef6e9fb3139c37abd5d393b | db9379756fa65f29cb97fba8c851c743d4237388 | |||
v1.0 | complete | Docs | Docs: Python310_49428_C | import asyncio
import logging
from typing import List
class NoSeatsAvailableException(Exception):
def __init__(self, user_id: int, message: str = "No seats available"):
self.user_id = user_id
super().__init__(message)
async def book_seat(user_id: int) -> None:
"""Simulates booking a seat, whic... | import asyncio
import logging
from typing import List
# Initialize logger
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
class NoSeatsAvailableException(Exception):
def __init__(self, user_id: int, message: str = "No seats available"):
self.user_id = user_id
super().... | import asyncio
import pytest
from solution import book_seat, booking_system, NoSeatsAvailableException
@pytest.mark.asyncio
async def test_booking_system_with_less_than_50_users():
booked_users = await booking_system(30)
assert len(booked_users) == 30
assert booked_users == list(range(30))
@pytest.mark.as... | [] | [
1,
1,
1,
0,
1,
1,
1,
0,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport logging\nfrom typing import List\n\nclass NoSeatsAvailableException(Exception):\n def __init__(self, user_id: int, message: str = \"No seats a... | trial_gpt4o_2 | {
"original_instruction": "#### Objective:\nTo assess your understanding of asynchronous programming with `asyncio` in Python 3.10, including handling concurrency, thread safety, dealing with blocking code, and implementing robust error handling.\n\n#### Problem Statement:\nYou are required to implement a small appli... | 0.441317 | Docs: Python310_49428 | C | [
"book_seat",
"booking_system"
] | 2 | [
[
"booking_system",
"book_seat"
]
] | 1 | [] | false | [
"NoSeatsAvailableException"
] | true | pytest | true | [] | true | 101e15d6ebc003c19cdcdc28d2c01ec481b7d448 | 985ee6b7ad0f0a90f7963ea4220443c5c379913a | |||
v1.0 | complete | Docs | Docs: Pytorch_49081_C | import torch.futures
from typing import List
import asyncio
async def simulate_complex_computation(value: int) -> int:
await asyncio.sleep(1) # Simulate delay
return value * value
def asynchronous_operations(n: int) -> List[int]:
"""
Create and manage multiple asynchronous tasks using torch.futures.... | import torch.futures
from typing import List
import asyncio
async def simulate_complex_computation(value: int) -> int:
await asyncio.sleep(1) # Simulate delay
return value * value
def asynchronous_operations(n: int) -> List[int]:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
a... | from solution import asynchronous_operations
def test_asynchronous_operations_single_task():
result = asynchronous_operations(1)
assert result == [0], f"Expected [0], but got {result}"
def test_asynchronous_operations_multiple_tasks():
result = asynchronous_operations(3)
assert result == [0, 1, 4], f"... | [
{
"docstring": null,
"function_declaration": "def asynchronous_operations(n):",
"function_name": "asynchronous_operations",
"parameter_list": "(n)"
}
] | [
0,
0,
1,
1,
0,
0,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch.futures\nfrom typing import List\nimport asyncio\n\ndef simulate_complex_computation(value: int) -> torch.futures.Future:\n loop = asyncio.get_event_loo... | trial_gpt4o_3 | {
"original_instruction": "#### Objective\nDemonstrate your understanding of the `torch.futures` package by implementing a function that creates and manages multiple asynchronous tasks using `Future` objects.\n\n#### Problem Statement\nYou are tasked with implementing a function `asynchronous_operations` that perform... | 0.506636 | Docs: Pytorch_49081 | C | [
"simulate_complex_computation",
"asynchronous_operations"
] | 2 | [
[
"asynchronous_operations",
"simulate_complex_computation"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 34610f5d3cd9472bc2764b62ae794f7d1f6ac1cf | bf02969d2f54b4b7b6667dcaffdd9af705f41cc5 | |||
v1.0 | complete | Docs | Docs: Python310_49275_C | import asyncio
import aiohttp
import logging
from typing import List, Tuple
logging.basicConfig(level=logging.DEBUG)
async def fetch_url(session: aiohttp.ClientSession, url: str) -> Tuple[str, str]:
"""
Fetch the content of the given URL.
Args:
- session: aiohttp ClientSession object for making H... | import asyncio
import aiohttp
import logging
from typing import List, Tuple
logging.basicConfig(level=logging.DEBUG)
async def fetch_url(session: aiohttp.ClientSession, url: str) -> Tuple[str, str]:
"""
Fetch the content of the given URL.
Args:
- session: aiohttp ClientSession object for making H... | import asyncio
from solution import fetch_url, fetch_urls, main
import pytest
import aiohttp
def test_fetch_url_success():
async def async_test():
async with aiohttp.ClientSession() as session:
url, response = await fetch_url(session, "https://www.example.com")
assert url == "https:... | [
{
"docstring": "Main function to set up asyncio environment and run the fetch tasks.\n\nArgs:\n- urls: A list of URLs to fetch.",
"function_declaration": "def main(urls):",
"function_name": "main",
"parameter_list": "(urls)"
}
] | [
1,
1,
0,
1,
1,
0,
1,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiohttp\nimport logging\nfrom typing import List, Tuple\n\n# Setup logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(... | trial_gpt4o_1 | {
"original_instruction": "**Question: Asynchronous URL Fetcher with Error Detection and Logging**\n\n**Objective**: Implement an asynchronous URL fetcher using Python's asyncio module that fetches a list of URLs concurrently, handles errors robustly, and logs the process efficiently.\n\n### Task\n\nYou are required ... | 0.598515 | Docs: Python310_49275 | C | [
"fetch_url",
"fetch_urls",
"main"
] | 3 | [
[
"fetch_urls",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 5991011f9a5aa5e615509c6c47a97c915e2ca121 | 2a20c55a910283ba9e1743c07fe51ec57cf3d16e | |||
v1.0 | complete | Docs | Docs: Pytorch_49184_C | import torch
def generate_tensor(shape):
"""
Generates a tensor of the specified shape with random values.
Args:
shape: A tuple specifying the shape of the tensor (e.g., (3, 4)).
Returns:
A tensor of the specified shape with random values.
"""
# Your implementation here
def c... | import torch
def generate_tensor(shape):
"""
Generates a tensor of the specified shape with random values.
"""
return torch.randn(shape)
def close_tensors(tensor_a, tensor_b, rtol=1e-05, atol=1e-08):
"""
Checks if two tensors are close within the specified tolerances.
Parameters:
... | from solution import generate_tensor, close_tensors, test_tensor_creation
import torch
def test_generate_tensor():
# Test if the generated tensor has the correct shape
shape = (3, 4)
tensor = generate_tensor(shape)
assert tensor.shape == shape, f"Tensor shape should be {shape}, but got {tensor.shape}"
... | [
{
"docstring": "Generates a tensor of the specified shape with random values.",
"function_declaration": "def generate_tensor(shape):",
"function_name": "generate_tensor",
"parameter_list": "(shape)"
},
{
"docstring": "Checks if two tensors are close within the specified tolerances.\n\nParame... | [
1,
1,
1,
1,
0,
1,
0,
0,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef generate_tensor(shape):\n \"\"\"\n Generates a tensor of the specified shape with random values.\n \"\"\"\n return torch.rand(shape)\n\n... | trial_gpt4o_5 | {
"original_instruction": "### PyTorch Coding Assessment Question\n\nYou are required to demonstrate your understanding of tensor creation, manipulation, and validation using PyTorch. Leverage the `torch.testing` module to create and validate tensors.\n\n#### Task:\n\n1. **Create a function `generate_tensor`**:\n -... | 0.524599 | Docs: Pytorch_49184 | C | [
"generate_tensor",
"close_tensors",
"test_tensor_creation"
] | 3 | [
[
"test_tensor_creation",
"close_tensors"
],
[
"test_tensor_creation",
"generate_tensor"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 7971ca01ac74a61156a581e7cd1a80acdb281d29 | 64ede71e1c410a7af9370e413ac6665225b0c6dd | |||
v1.0 | complete | Docs | Docs: Python310_49301_C | import queue
from threading import Thread
import random
import time
class Task:
def __init__(self, task_id, task_type, priority=0):
self.task_id = task_id
self.task_type = task_type
self.priority = priority
def __str__(self):
return f"Task({self.task_id}, {self.task_type}, {sel... | import queue
from threading import Thread, current_thread
import time
import random
class Task:
def __init__(self, task_id, task_type, priority=0):
self.task_id = task_id
self.task_type = task_type
self.priority = priority
def __str__(self):
return f"Task({self.task_id}, {self.... | import pytest
from threading import Thread
from solution import Task, add_task, producer, consumer, fifo_queue, lifo_queue, priority_queue
def test_task_creation():
task = Task(1, "FIFO")
assert task.task_id == 1
assert task.task_type == "FIFO"
assert task.priority == 0
assert str(task) == "Task(1,... | [] | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import queue\nfrom threading import Thread, Lock\nimport time\nimport random\n\nclass Task:\n def __init__(self, task_id, task_type, priority=0):\n self.task_... | trial_gpt4o_9 | {
"original_instruction": "Multi-threaded Task Manager\n\n### Objective:\nYou are required to implement a multi-threaded task manager utilizing the `queue` module. Your solution must demonstrate a comprehensive understanding of various queue types and threading mechanisms in Python.\n\n### Task Description:\nWrite a ... | 0.611328 | Docs: Python310_49301 | C | [
"add_task",
"producer",
"consumer",
"start_threads"
] | 4 | [
[
"producer",
"add_task"
]
] | 1 | [] | false | [
"Task"
] | true | pytest | true | [] | true | 81862e0d6fd836993b06f701a51cbb75aa09f724 | b4405a12bc8fe1943057c5155c9c7ebe5b7d961a | |||
v1.0 | complete | Docs | Docs: Python310_49316_C | from typing import List, Dict, Union
import concurrent.futures
import urllib.request
def download_pages(urls: List[str], max_workers: int) -> Dict[str, Union[bytes, str]]:
""" Concurrently download the content of given URLs using ThreadPoolExecutor from the concurrent.futures module.
Each download has a t... | from typing import List, Dict, Union
import concurrent.futures
import urllib.request
import urllib.error
def download_page(url: str) -> Union[bytes, str]:
try:
with urllib.request.urlopen(url, timeout=10) as response:
return response.read()
except Exception as e:
return f"Error: {st... | from solution import download_pages
def test_download_pages_success():
# Note: This URL should remain accessible for the test to pass.
urls = ["http://www.example.com/"]
results = download_pages(urls, max_workers=3)
assert "http://www.example.com/" in results
assert isinstance(results["http://www.e... | [
{
"docstring": null,
"function_declaration": "def download_page(url):",
"function_name": "download_page",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def download_pages(urls, max_workers):",
"function_name": "download_pages",
"parameter_list": "(url... | [
0,
1,
1,
1,
0,
0,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict, Union\nimport concurrent.futures\nimport urllib.request\nimport urllib.error\n\ndef download_pages(urls: List[str], max_workers: int) -> ... | trial_gpt4o_9 | {
"original_instruction": "**Objective**: Demonstrate your understanding of concurrent execution using the `concurrent.futures` module.\n\n**Problem Statement**:\n\nYou are given a list of URLs, and your task is to concurrently download the content of these URLs using both threading and future objects from the `concu... | 0.588334 | Docs: Python310_49316 | C | [
"download_page",
"download_pages"
] | 2 | [
[
"download_pages",
"download_page"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4e5d9c691d143012a21c088bbc70d8be7fbc9976 | 4d7255c9b1162afc79cee03db1b3b5b52420b1db | |||
v1.0 | complete | Docs | Docs: Scikit_49658_C | import pandas as pd
import numpy as np
from sklearn.mixture import GaussianMixture
import matplotlib.pyplot as plt
def gmm_clustering(file_path: str, n_components: int) -> None:
""" Perform GMM clustering on a 2D dataset and visualize the clustering results.
Parameters:
file_path (str): Path to the CS... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture
def gmm_clustering(file_path: str, n_components: int) -> None:
try:
# Load the dataset
data = pd.read_csv(file_path)
# Ensure the data has exactly 2 columns
as... | import os
import pandas as pd
from solution import gmm_clustering
# Helper function to create a temporary CSV file for testing
def create_test_csv(filepath, content):
df = pd.DataFrame(content, columns=["Feature1", "Feature2"])
df.to_csv(filepath, index=False)
return filepath
def test_gmm_clustering_basic... | [
{
"docstring": null,
"function_declaration": "def gmm_clustering(file_path, n_components):",
"function_name": "gmm_clustering",
"parameter_list": "(file_path, n_components)"
},
{
"docstring": "Helper function for plotting Gaussian contours",
"function_declaration": "def plot_gaussian_con... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.mixture import GaussianMixture\nfrom matplotlib.patches import Ellipse\nimport sy... | trial_gpt4o_9 | {
"original_instruction": "**Objective:**\nYou are given a dataset `data.csv` containing a 2D dataset with numerical attributes. Your task is to implement a function that performs clustering using Gaussian Mixture Models (GMM) and then visualizes the clustering results along with the cluster centers and contour plots... | 0.663914 | Docs: Scikit_49658 | C | [
"gmm_clustering",
"plot_gaussian_contour"
] | 2 | [
[
"gmm_clustering",
"plot_gaussian_contour"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"pandas",
"sklearn"
] | false | 00af7183ba2d692b37f2771da8574fc959482778 | 0f3176f58bfe51a5b784413fc682503617439161 | |||
v1.0 | complete | Docs | Docs: Scikit_49022_C | from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_digits
from joblib import Parallel, delayed
import time
def knn_classifier(X_train, y_train, X_test, y_test, n_neighbors=3):
""" Train a K-Nearest Neighbors (KNN) classifier usi... | import numpy as np
from sklearn.datasets import load_digits
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from joblib import Parallel, delayed
import time
import cProfile
import pstats
# Load dataset
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train,... | from solution import knn_classifier, profile_before_optimization, profile_after_optimization
def test_knn_classifier():
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
accuracy = knn_classifier(X_train, y_train, X_test, y_test, n... | [
{
"docstring": null,
"function_declaration": "def knn_classifier(X_train, y_train, X_test, y_test, n_neighbors=3):",
"function_name": "knn_classifier",
"parameter_list": "(X_train, y_train, X_test, y_test, n_neighbors=3)"
},
{
"docstring": null,
"function_declaration": "def profile(func)... | [
0,
1,
0,
0,
0,
0,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.datasets import load_digits\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\n... | trial_gpt4o_8 | {
"original_instruction": "#### Objective:\nTo assess your understanding of implementing, profiling, and optimizing machine learning models using scikit-learn.\n\n#### Task:\nYou are given a dataset and your task is to create a K-Nearest Neighbors (KNN) classifier. You need to implement the following steps:\n\n1. Loa... | 0.594277 | Docs: Scikit_49022 | C | [
"knn_classifier",
"profile",
"profile_before_optimization",
"profile_after_optimization"
] | 4 | [
[
"profile_before_optimization",
"knn_classifier"
]
] | 1 | [] | false | [] | false | pytest | true | [
"joblib",
"numpy",
"sklearn"
] | false | c832c2dae75434f7deeeb243647cafce0c4949c9 | c9694b7406a830d71a91bfb1f5301b355fa28b48 | |||
v1.0 | complete | Docs | Docs: Python310_49519_C | import asyncio
import platform
from typing import List
async def run_subprocess_command(command: str):
""" Run a subprocess command asynchronously and capture its output.
"""
def run_subprocess_tasks(commands: List[str]) -> None:
""" Execute a list of commands asynchronously as subprocesses.
>>> run_s... | import asyncio
import platform
from typing import List
async def run_subprocess_command(command: str):
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
... | import asyncio
from solution import run_subprocess_tasks
def test_run_single_command():
commands = ["echo Hello, World!"]
run_subprocess_tasks(commands)
def test_run_multiple_commands():
commands = ["echo Test 1", "echo Test 2", "echo Test 3"]
run_subprocess_tasks(commands)
def test_run_invalid_comma... | [
{
"docstring": null,
"function_declaration": "def run_subprocess_tasks(commands):",
"function_name": "run_subprocess_tasks",
"parameter_list": "(commands)"
}
] | [
1,
1,
1,
1,
0,
1,
0,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport platform\nfrom typing import List\n\nasync def run_subprocess_command(command: str):\n process = await asyncio.create_subprocess_shell(\n ... | trial_gpt4o_0 | {
"original_instruction": "### Task:\n\nYou are tasked with creating a script that spawns subprocesses and communicates with them asynchronously using the `asyncio` module. Your script should be compatible with both Windows and macOS platforms.\n\nImplement a function `run_subprocess_tasks(commands: List[str]) -> Non... | 0.739156 | Docs: Python310_49519 | C | [
"run_subprocess_command",
"run_subprocess_tasks"
] | 2 | [
[
"run_subprocess_tasks",
"run_subprocess_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d2688599f38268ced0a987ae9a12be3ebd1f19ff | 94a1280c031e20e386ffa60f5b07a3e7e936203d | |||
v1.0 | complete | Docs | Docs: Python310_49256_C | import hashlib
import hmac
def generate_file_hash(filepath: str, key: str) -> str:
"""
Generates an HMAC hash of the file's contents using SHA-256.
Args:
- filepath (str): The path to the file.
- key (str): The secret key for HMAC.
Returns:
- str: The hexadecimal HMAC hash of the file's c... | import hashlib
import hmac
def generate_file_hash(filepath: str, key: str) -> str:
"""
Generates an HMAC hash of the file's contents using SHA-256.
Args:
- filepath (str): The path to the file.
- key (str): The secret key for HMAC.
Returns:
- str: The hexadecimal HMAC hash of the file's c... | import pytest
from solution import generate_file_hash, verify_file_hash
def create_test_file(filepath, contents):
with open(filepath, 'w') as f:
f.write(contents)
def test_generate_file_hash():
filepath = 'test.txt'
key = 'supersecretkey'
create_test_file(filepath, 'Hello, World!')
ha... | [
{
"docstring": "Generates an HMAC hash of the file's contents using SHA-256.\n\nArgs:\n- filepath (str): The path to the file.\n- key (str): The secret key for HMAC.\n\nReturns:\n- str: The hexadecimal HMAC hash of the file's contents.",
"function_declaration": "def generate_file_hash(filepath, key):",
... | [
1,
1,
0,
0,
0,
1,
0,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\nimport hmac\n\ndef generate_file_hash(filepath: str, key: str) -> str:\n \"\"\"\n Generates an HMAC hash of the file's contents using SHA-256.\n\n... | trial_gpt4o_0 | {
"original_instruction": "### Objective\nDesign and implement a secure file integrity checker using Python's cryptographic services.\n\n### Problem Statement\nYou are tasked with creating a Python function that securely computes and verifies the hash of a file's content to detect any unauthorized modifications. Use ... | 0.703658 | Docs: Python310_49256 | C | [
"generate_file_hash",
"verify_file_hash"
] | 2 | [
[
"verify_file_hash",
"generate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d27960711f470207ff9dedc945d70ea37077a2ac | 3db1581c458abef802ff0bd419cd5e818daad850 | |||
v1.0 | complete | Docs | Docs: Pytorch_49388_C | import torch
def causal_lower_right(sequence_length):
""" Generates a lower triangular matrix mask for causal attention. """
mask = torch.tril(torch.ones(sequence_length, sequence_length))
return mask
def causal_upper_left(sequence_length):
""" Generates an upper triangular matrix mask for causal atte... | import torch
def causal_lower_right(sequence_length):
""" Generates a lower triangular matrix mask for causal attention. """
mask = torch.tril(torch.ones(sequence_length, sequence_length))
return mask
def causal_upper_left(sequence_length):
""" Generates an upper triangular matrix mask for causal atte... | import torch
import pytest
from solution import apply_causal_mask
def test_apply_causal_mask_lower_right():
attention_scores = torch.ones(4, 4)
masked_scores = apply_causal_mask(attention_scores, 'lower_right')
expected_masked_scores = torch.tensor([[1, -1e9, -1e9, -1e9],
... | [
{
"docstring": "Generates a lower triangular matrix mask for causal attention. ",
"function_declaration": "def causal_lower_right(sequence_length):",
"function_name": "causal_lower_right",
"parameter_list": "(sequence_length)"
},
{
"docstring": "Generates an upper triangular matrix mask for ... | [
0,
1,
0,
1,
1,
1,
0,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef causal_lower_right(sequence_length):\n \"\"\"\n Generates a lower-righthand causal mask.\n \"\"\"\n mask = torch.tril(torch.ones(sequenc... | trial_gpt4o_9 | {
"original_instruction": "### Advanced Coding Assessment Question:\n\nImplementing causal attention masking is crucial for sequence models, especially in tasks like language generation where future tokens should not influence current predictions. Using PyTorch, construct a function that integrates causal bias into a... | 0.467706 | Docs: Pytorch_49388 | C | [
"causal_lower_right",
"causal_upper_left",
"apply_causal_mask"
] | 3 | [
[
"apply_causal_mask",
"causal_lower_right"
],
[
"apply_causal_mask",
"causal_upper_left"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | ef7882f570652a362178cad1631f69db8ba51063 | d107478ef847c08b6940fda925183117a904742a | |||
v1.0 | complete | Docs | Docs: Python310_49328_C | import aiohttp
import asyncio
import platform
from typing import List
async def fetch_data(url: str) -> str:
"""
Fetch data from the given URL using asynchronous HTTP request.
Args:
url (str): The URL to fetch data from.
Returns:
str: The text content of the HTTP response.
"""
pass
a... | import aiohttp
import asyncio
import platform
async def fetch_data(url):
"""
Fetch data from the given URL using asynchronous HTTP request.
Args:
url (str): The URL to fetch data from.
Returns:
str: The text content of the HTTP response.
"""
async with aiohttp.ClientSession() as sessi... | import pytest
from solution import fetch_data, manage_tasks
import asyncio
@pytest.mark.asyncio
async def test_fetch_data():
url = "http://example.com"
response_text = await fetch_data(url)
assert response_text is not None
assert isinstance(response_text, str)
@pytest.mark.asyncio
async def test_manag... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import aiohttp\nimport asyncio\n\nasync def fetch_data(url: str) -> str:\n \"\"\"\n Asynchronously fetches data from the given URL using aiohttp.\n \"\"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "### Asynchronous Task Manager using asyncio\n\nYou are required to design an asynchronous task manager that can handle multiple tasks concurrently while considering platform-specific limitations discussed in the `asyncio` documentation provided.\n\n#### Task Description\n\n1. Implement an a... | 0.616366 | Docs: Python310_49328 | C | [
"fetch_data",
"manage_tasks"
] | 2 | [
[
"manage_tasks",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 532160d20bca539d4d629883035692ad34d045c9 | 94382114cbe81655af36051fc8da5babae024b9d | |||
v1.0 | complete | Docs | Docs: Python310_49298_C | import zlib
def compress_document(data: str, compression_level: int = -1) -> bytes:
"""
Compresses the input text document.
Parameters:
- data (str): The text document to be compressed.
- compression_level (int, optional): The level of compression (0-9). Defaults to -1.
Returns:
-... | import zlib
def compress_document(data, compression_level=-1):
"""
Compresses the input text document.
Parameters:
- data (str): The text document to be compressed.
- compression_level (int, optional): The level of compression (0-9). Defaults to -1.
Returns:
- bytes: Compressed da... | from solution import compress_document, decompress_document, compute_checksum, verify_checksum
def test_compress_decompress():
original_text = "This is a sample text document that needs to be compressed and decompressed."
compression_level = 6
compressed_data = compress_document(original_text, compres... | [
{
"docstring": "Compresses the input text document.\n\nParameters:\n- data (str): The text document to be compressed.\n- compression_level (int, optional): The level of compression (0-9). Defaults to -1.\n\nReturns:\n- bytes: Compressed data.",
"function_declaration": "def compress_document(data, compressio... | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import zlib\n\ndef compress_document(data, compression_level=-1):\n \"\"\"\n Compress the given text using zlib.\n Args:\n - data (str): The text document t... | trial_gpt4o_8 | {
"original_instruction": "### Compression and Decompression using zlib\n\nYou are tasked with designing a system that efficiently stores and retrieves large text documents. The system will compress the documents before storage and decompress them when retrieval is needed. To ensure the integrity of the documents, yo... | 0.598536 | Docs: Python310_49298 | C | [
"compress_document",
"decompress_document",
"compute_checksum",
"verify_checksum"
] | 4 | [
[
"verify_checksum",
"compute_checksum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e97e7e9c7777ced2d7322fca0eb0e932a917ba82 | 859c655897be9c715b04599fc64b398c491cf283 | |||
v1.0 | complete | Docs | Docs: Pytorch_49396_C | import torch
import torch.cuda.profiler as profiler
def pointwise_kernel(a, b):
"""Perform element-wise multiplication of two tensors a and b.
>>> a = torch.tensor([1, 2, 3], device='cuda')
>>> b = torch.tensor([4, 5, 6], device='cuda')
>>> result = pointwise_kernel(a, b)
>>> expected = torch.tenso... | import torch
import torch.cuda.profiler as profiler
def pointwise_kernel(a, b):
"""
Perform element-wise multiplication of two tensors a and b.
"""
return a * b
def benchmark_pointwise_kernel(a, b):
"""
Benchmark the pointwise kernel using torch.cuda.profiler and time measurement.
"""
... | from solution import pointwise_kernel, benchmark_pointwise_kernel
import torch
def test_pointwise_kernel_shape():
a = torch.randn(5, 5).cuda()
b = torch.randn(5, 5).cuda()
result = pointwise_kernel(a, b)
assert result.shape == (5, 5), "Shape mismatch."
def test_pointwise_kernel_values():
a = torch... | [
{
"docstring": "Perform element-wise multiplication of two tensors a and b.",
"function_declaration": "def pointwise_kernel(a, b):",
"function_name": "pointwise_kernel",
"parameter_list": "(a, b)"
},
{
"docstring": "Benchmark the pointwise kernel using torch.cuda.profiler and time measuremen... | [
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef pointwise_kernel(a, b):\n \"\"\"\n Element-wise multiplication of two tensors using GPU acceleration.\n \"\"\"\n if a.device.type != 'cu... | trial_gpt4o_5 | {
"original_instruction": "### Advanced PyTorch Assessment Task: Custom Kernel Performance Analysis\n\n#### Objective\nIn this assessment, you are required to create and analyze the performance of a custom GPU kernel using PyTorch and TorchInductor. This task will test your ability to implement backend optimizations ... | 0.471228 | Docs: Pytorch_49396 | C | [
"pointwise_kernel",
"benchmark_pointwise_kernel"
] | 2 | [
[
"benchmark_pointwise_kernel",
"pointwise_kernel"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 4cf98365e1785cf7cd782157e8d2a636cf4e0a17 | 650a8a78ca27169df82194963e038989bd29b795 | |||
v1.0 | complete | Docs | Docs: Scikit_49640_C | import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans, DBSCAN
from sklearn.metrics import silhouette_score
def generate_dataset() -> Tuple[np.ndarray, np.ndarray]:
"""Generates a synthetic dataset with 1000 samples and 4 centers.
Returns:
X (np.ndarray): The gene... | import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans, DBSCAN
from sklearn.metrics import silhouette_score
def generate_dataset():
"""
Generates a synthetic dataset with 1000 samples and 4 centers.
Returns:
X (np.ndarray): The generated samples.
... | from solution import generate_dataset, k_means_clustering, dbscan_clustering
def test_generate_dataset():
X, y = generate_dataset()
assert X.shape == (1000, 2)
assert len(y) == 1000
assert len(set(y)) == 4
def test_k_means_clustering():
X, _ = generate_dataset()
labels, inertia, silhouette = k... | [
{
"docstring": "Generates a synthetic dataset with 1000 samples and 4 centers.\n\nReturns:\n X (np.ndarray): The generated samples.\n y (np.ndarray): The true labels for the samples.",
"function_declaration": "def generate_dataset():",
"function_name": "generate_dataset",
"parameter_list": "()... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.datasets import make_blobs\nfrom sklearn.cluster import KMeans, DBSCAN\nfrom sklearn.metrics import silhouette_score\n\ndef generate_da... | trial_gpt4o_1 | {
"original_instruction": "### Clustering with K-Means and DBSCAN using Scikit-learn\n\nIn this assessment, you are required to perform clustering on a dataset using two different clustering algorithms provided by the Scikit-learn library: K-Means and DBSCAN. You will evaluate the performance of these algorithms base... | 0.759215 | Docs: Scikit_49640 | C | [
"generate_dataset",
"k_means_clustering",
"dbscan_clustering",
"evaluate_clustering"
] | 4 | [
[
"evaluate_clustering",
"dbscan_clustering"
],
[
"evaluate_clustering",
"generate_dataset"
],
[
"evaluate_clustering",
"k_means_clustering"
]
] | 3 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | e1dcf8aaa40e2e8923d3e80696aa9e033fd0feea | b676eb62b1b5c611b10bfee0e1336fef3f278374 | |||
v1.0 | complete | Docs | Docs: Scikit_49257_C | import numpy as np
from sklearn.isotonic import IsotonicRegression
from typing import Union, Dict
def train_isotonic_regression(X_train: np.ndarray, y_train: np.ndarray, increasing: Union[bool, str]) -> IsotonicRegression:
"""
Trains an Isotonic Regression model on the given data with the specified monotonic c... | import numpy as np
from sklearn.isotonic import IsotonicRegression
from typing import Union, Dict
def train_isotonic_regression(X_train: np.ndarray, y_train: np.ndarray, increasing: Union[bool, str]) -> IsotonicRegression:
"""
Trains an Isotonic Regression model on the given data with the specified monotonic c... | import pytest
import numpy as np
from solution import train_isotonic_regression, predict_isotonic_regression, evaluate_performance, experiment_with_constraints
def test_train_isotonic_regression():
X_train = np.array([1, 2, 3, 4, 5])
y_train = np.array([1, 4, 3, 8, 10])
model = train_isotonic_regression(X_... | [
{
"docstring": "Trains an Isotonic Regression model on the given data with the specified monotonic constraint.\n\nParameters:\nX_train (numpy.ndarray): 1D array of feature data.\ny_train (numpy.ndarray): 1D array of target values.\nincreasing (bool or str): Monotonic constraint ('True', 'False', or 'auto').\n\n... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nfrom sklearn.isotonic import IsotonicRegression\nfrom typing import Union, Dict\n\ndef train_isotonic_regression(X_train: np.ndarray, y_train: np.nd... | trial_gpt4o_8 | {
"original_instruction": "### Isotonic Regression with scikit-learn\n\nYou are given a dataset with 1-dimensional feature data `X` and corresponding target values `y`. Your task is to create an isotonic regression model using `scikit-learn`'s `IsotonicRegression` class and evaluate its performance on both the traini... | 0.662179 | Docs: Scikit_49257 | C | [
"train_isotonic_regression",
"predict_isotonic_regression",
"evaluate_performance",
"experiment_with_constraints"
] | 4 | [
[
"experiment_with_constraints",
"predict_isotonic_regression"
],
[
"experiment_with_constraints",
"train_isotonic_regression"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | ece9004df83730992a79ef902f85049dd4563434 | f1022ce2acd353a933986356f536a38cdd547722 | |||
v1.0 | complete | Docs | Docs: Python310_49828_C | import atexit
from datetime import datetime
LOG_FORMAT = "{event_type}: {timestamp} - {message}\n"
def log_event(filename: str, event_type: str, message: str) -> None:
"""
Log an event to the specified file with the given event type and message.
>>> log_event('test_event.log', 'Test', 'This is a test eve... | import atexit
from datetime import datetime
LOG_FORMAT = "{event_type}: {timestamp} - {message}\n"
def log_event(filename, event_type, message):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
try:
with open(filename, 'a') as file:
file.write(LOG_FORMAT.format(
eve... | import os
import pytest
from datetime import datetime
from solution import log_event, register_startup_log, register_shutdown_log, add_custom_shutdown, remove_custom_shutdown
def read_log_file(filename):
if not os.path.exists(filename):
return ""
with open(filename, 'r') as file:
return file.re... | [
{
"docstring": null,
"function_declaration": "def log_event(filename, event_type, message):",
"function_name": "log_event",
"parameter_list": "(filename, event_type, message)"
},
{
"docstring": null,
"function_declaration": "def register_startup_log():",
"function_name": "register_st... | [
1,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import atexit\nfrom datetime import datetime\n\nLOG_FORMAT = \"{event_type}: {timestamp} - {message}\\n\"\n\ndef log_event(filename, event_type, message):\n timestam... | trial_gpt4o_0 | {
"original_instruction": "**Objective:** \nImplement a module that keeps track of a startup sequence and a shutdown sequence of a program. Using the `atexit` module, ensure specific cleanup functions are executed at the program's normal termination.\n\n### Requirements:\n1. Create a Python module that maintains a lo... | 0.548582 | Docs: Python310_49828 | C | [
"log_event",
"register_startup_log",
"register_shutdown_log",
"add_custom_shutdown",
"remove_custom_shutdown",
"custom_goodbye"
] | 6 | [
[
"custom_goodbye",
"log_event"
],
[
"register_shutdown_log",
"log_event"
],
[
"register_startup_log",
"log_event"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 353db6b70002fcf08bc5d5c71edd48318b2daf28 | 540a2434ca10965ea7fe80df2c5f571c0c214ba4 | |||
v1.0 | complete | Docs | Docs: Scikit_49426_C | import numpy as np
def custom_manhattan_distance(X, Y):
"""
Compute the Manhattan distance matrix between two sets of vectors X and Y.
Parameters:
X (numpy.ndarray): A 2D array of shape (n_samples_X, n_features)
Y (numpy.ndarray): A 2D array of shape (n_samples_Y, n_features)
Returns:
num... | import numpy as np
def custom_manhattan_distance(X, Y):
"""
Compute the Manhattan distance matrix between two sets of vectors X and Y.
Parameters:
X (numpy.ndarray): A 2D array of shape (n_samples_X, n_features)
Y (numpy.ndarray): A 2D array of shape (n_samples_Y, n_features)
Returns:
num... | import pytest
import numpy as np
from solution import custom_manhattan_distance, custom_linear_kernel, validate_implementations
def test_custom_manhattan_distance():
X = np.array([[1, 2], [3, 4]])
Y = np.array([[5, 6], [7, 8]])
result = custom_manhattan_distance(X, Y)
expected = np.array([[8, 12],
... | [
{
"docstring": "Compute the Manhattan distance matrix between two sets of vectors X and Y.\n\nParameters:\nX (numpy.ndarray): A 2D array of shape (n_samples_X, n_features)\nY (numpy.ndarray): A 2D array of shape (n_samples_Y, n_features)\n\nReturns:\nnumpy.ndarray: A 2D array of shape (n_samples_X, n_samples_Y)... | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\n\ndef custom_manhattan_distance(X, Y):\n \"\"\"\n Compute the Manhattan distance matrix between two sets of vectors X and Y.\n\n Parameters... | trial_gpt4o_9 | {
"original_instruction": "### Objective\nImplement custom functions to compute specific distance metrics and kernel functions manually, then validate your implementations using `sklearn.metrics.pairwise` submodule.\n\n### Task\n1. Implement the following functions:\n - `custom_manhattan_distance(X, Y)`: Compute t... | 0.574004 | Docs: Scikit_49426 | C | [
"custom_manhattan_distance",
"custom_linear_kernel",
"validate_implementations"
] | 3 | [
[
"validate_implementations",
"custom_linear_kernel"
],
[
"validate_implementations",
"custom_manhattan_distance"
]
] | 2 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 7d217c054dddcb3a53b98dd98f219321fc210d28 | 5c5c47f03e7dc73c8de6734b4659a6691247b63c | |||
v1.0 | complete | Docs | Docs: Python310_49644_C | from typing import List, Dict, Tuple, Union
def process_files_concurrently(file_paths: List[str]) -> Dict[str, Union[Tuple[int, float], str]]:
""" Process a list of text files containing numerical data concurrently to compute statistics.
Args:
file_paths: A list of file paths.
Returns... | import concurrent.futures
from typing import List, Dict, Tuple, Union
def process_file(file_path: str) -> Union[Tuple[int, float], str]:
try:
with open(file_path, 'r') as file:
numbers = []
for line in file:
line = line.strip()
try:
... | import pytest
import os
from solution import process_files_concurrently
@pytest.fixture
def setup_files():
file_data = {
'file1.txt': "1\n2\n3\n",
'file2.txt': "4\n5\n",
'file3.txt': "invalid data"
}
for filename, content in file_data.items():
with open(filename, 'w') as f:
... | [
{
"docstring": null,
"function_declaration": "def process_file(file_path):",
"function_name": "process_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def process_files_concurrently(file_paths):",
"function_name": "process_files_concurrently",
... | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Dict, Tuple, Union\nfrom concurrent.futures import ThreadPoolExecutor\nimport os\n\ndef process_file(file_path: str) -> Union[Tuple[int, float]... | trial_gpt4o_2 | {
"original_instruction": "### Question: Concurrent File Processing with Reporting\n\nYou are given a set of text files containing numerical data (one number per line). You need to process these files concurrently to compute specific statistics (sum and average of numbers) for each file. Additionally, you want to han... | 0.562315 | Docs: Python310_49644 | C | [
"process_file",
"process_files_concurrently"
] | 2 | [
[
"process_files_concurrently",
"process_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d29fc1c063156682e47e21a4b5c3c3209ec645f6 | d9e20cf33200a78ac864869a7b830a18c124aef8 | |||
v1.0 | complete | Docs | Docs: Python310_49744_C | import codecs
def register_custom_codec():
""" Register a custom codec that swaps lowercase and uppercase letters. """
def custom_encode(input_str: str) -> str:
""" Encode the input string using the custom codec.
>>> custom_encode('HelloWorld') 'hELLOwORLD'
>>> custom_encode('HelloWorld123') 'hELLOwOR... | import codecs
class CustomCodec(codecs.Codec):
def encode(self, input, errors='strict'):
return self._transform(input), len(input)
def decode(self, input, errors='strict'):
return self._transform(input), len(input)
def _transform(self, s):
result = []
for char in s... | import pytest
from solution import register_custom_codec, custom_encode, custom_decode
def setup_module(module):
register_custom_codec()
def test_custom_encode_simple():
assert custom_encode('HelloWorld') == 'hELLOwORLD'
def test_custom_encode_with_numbers():
assert custom_encode('HelloWorld123') == 'hEL... | [] | [
0,
1
] | 1 | medium | 0.5 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import codecs\nimport string\n\n# Function to perform the custom encoding swap\ndef custom_encoder(input_str, errors='strict'):\n encoded = ... | trial_gpt4o_2 | {
"original_instruction": "**Coding Assessment Question**\n\n### Objective\nImplement a custom encoding-decoding system using the functions from the provided python310 codec registry and support functions. This task will assess your understanding of the codec registration, encoding, decoding, and error handling.\n\n#... | 0.632961 | Docs: Python310_49744 | C | [
"custom_codec_search",
"register_custom_codec",
"custom_encode",
"custom_decode"
] | 4 | [
[
"register_custom_codec",
"custom_codec_search"
]
] | 1 | [] | false | [
"CustomCodec",
"CustomCodecIncrementalEncoder",
"CustomCodecIncrementalDecoder",
"CustomCodecStreamReader",
"CustomCodecStreamWriter"
] | true | pytest | true | [] | true | 38ae8011818ff43f8ff14c3114ce4b4e0525c364 | 85ff9c501bc67e61cdd746fcf21a98c2901f5ec5 | |||
v1.0 | complete | Docs | Docs: Scikit_49718_C | import numpy as np
import pandas as pd
from sklearn.cross_decomposition import PLSRegression
from sklearn.metrics import mean_squared_error
def load_data(file_X, file_Y):
X = pd.read_csv(file_X, header=None).values
Y = pd.read_csv(file_Y, header=None).values
return X, Y
def pls_regression(file_X, file_Y, ... | import numpy as np
import pandas as pd
from sklearn.cross_decomposition import PLSRegression
from sklearn.metrics import mean_squared_error
def load_data(file_X, file_Y):
X = pd.read_csv(file_X, header=None).values
Y = pd.read_csv(file_Y, header=None).values
return X, Y
def pls_regression(file_X, file_Y, ... | import pytest
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
from solution import pls_regression
# Test data
X_test = np.array([
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]
])
Y_test = np.array([
[1.0, 2.0],
[2.0, 3.0],
[3.0, 4.0]
])
# Save test da... | [
{
"docstring": null,
"function_declaration": "def load_data(file_X, file_Y):",
"function_name": "load_data",
"parameter_list": "(file_X, file_Y)"
},
{
"docstring": "Loads the datasets, applies PLSRegression, and returns MSE and predicted responses.\n\nArgs:\n- file_X (str): Path to the CSV f... | [
0,
1,
1,
1,
0,
0,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport pandas as pd\nfrom sklearn.cross_decomposition import PLSRegression\nfrom sklearn.metrics import mean_squared_error\n\ndef load_data(file_X, ... | trial_gpt4o_9 | {
"original_instruction": "#### Objective\nImplement and apply the Partial Least Squares Regression (`PLSRegression`) method using scikit-learn to a given dataset. This will demonstrate your understanding of the method's principles, including the concepts of dimensionality reduction, projection, and regression.\n\n##... | 0.72677 | Docs: Scikit_49718 | C | [
"load_data",
"pls_regression"
] | 2 | [
[
"pls_regression",
"load_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | f83796caf4ac1bce1f2b33d9788a84ae2d51687b | 0f9ae1c8e940584a0971a92dd5ee88d64ea8309d | |||
v1.0 | complete | Docs | Docs: Python310_49831_C | import sys
import array
import os
audit_log = []
def audit_hook(event, args):
"""
Logs the audit event details to the audit log.
:param event: Name of the audit event
:param args: Arguments associated with the event
"""
audit_log.append((event, args))
def trigger_audit_events():
"""
... | import sys
import array
import os
audit_log = []
def audit_hook(event, args):
audit_log.append((event, args))
def trigger_audit_events():
# Add the audit hook
sys.addaudithook(audit_hook)
# Trigger array.__new__ audit event
arr = array.array('i', [1, 2, 3])
# Trigger compile audit event
... | from solution import trigger_audit_events, audit_log
def test_trigger_audit_events():
logged_events = trigger_audit_events()
# Check that we have logged all events
assert len(logged_events) >= 3
# Check that we have specific events logged
array_new_event = any(event[0] == 'array.__new__' for even... | [
{
"docstring": null,
"function_declaration": "def audit_hook(event, args):",
"function_name": "audit_hook",
"parameter_list": "(event, args)"
},
{
"docstring": null,
"function_declaration": "def trigger_audit_events():",
"function_name": "trigger_audit_events",
"parameter_list": ... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\n\n# Initialize the audit log list\naudit_log = []\n\ndef audit_hook(event, args):\n \"\"\"\n Logs the occurrence of audit events to audit_log.\n \"... | trial_gpt4o_8 | {
"original_instruction": "**Title:** Implement and Monitor Multiple Audit Events Using Python\n\n**Objective:**\nDesign a program that triggers multiple audit events and adds an audit hook to monitor these events.\n\n**Task Description:**\n1. Write a function named `trigger_audit_events` that performs the following:... | 0.470731 | Docs: Python310_49831 | C | [
"audit_hook",
"trigger_audit_events"
] | 2 | [
[
"trigger_audit_events",
"audit_hook"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d98b539b00b2708c100410152dd8cabfcd99f9f6 | 7c3309a8819fe717b965394173e6514be4179250 | |||
v1.0 | complete | Docs | Docs: Python310_49636_C | import atexit
tasks = []
def load_tasks(file_name: str) -> list:
""" Loads tasks from the given file and returns them as a list.
>>> load_tasks('todo.txt')
['Task 1', 'Task 2', 'Task 3']
"""
pass
def save_tasks(file_name: str, tasks: list):
""" Saves the given list of tasks to the specified f... | import atexit
tasks = []
def load_tasks(file_name: str) -> list:
try:
with open(file_name, 'r') as file:
return file.read().splitlines()
except FileNotFoundError:
return []
def save_tasks(file_name: str, tasks: list):
with open(file_name, 'w') as file:
file.write('\n'.... | import os
import pytest
from solution import load_tasks, save_tasks, add_task, complete_task, cancel_task, save_all_pending_tasks
@pytest.fixture(autouse=True)
def setup_and_teardown():
# Setup code: create an empty todo.txt before each test
with open('todo.txt', 'w') as file:
file.write('')
y... | [
{
"docstring": null,
"function_declaration": "def load_tasks(file_name):",
"function_name": "load_tasks",
"parameter_list": "(file_name)"
},
{
"docstring": null,
"function_declaration": "def save_tasks(file_name, tasks):",
"function_name": "save_tasks",
"parameter_list": "(file_n... | [
0,
1,
0,
0,
0,
1,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import atexit\n\ntasks = []\n\ndef load_tasks(file_name: str) -> list:\n \"\"\"\n Loads tasks from the given file and returns them as a list.\n \"\"\"\n try... | trial_gpt4o_8 | {
"original_instruction": "You are tasked with creating a Python program that manages a simple to-do list. Your program will read the current list of tasks from a file named `todo.txt` when it starts and automatically save any updates to the list when the program terminates. Additionally, you need to implement cleanu... | 0.505147 | Docs: Python310_49636 | C | [
"load_tasks",
"save_tasks",
"add_task",
"complete_task",
"cancel_task",
"save_all_pending_tasks"
] | 6 | [
[
"save_all_pending_tasks",
"save_tasks"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bc92cb72c06f263ebf5625985a18e5652f778a3f | c562628467896f7d3e0c5ed34890acbb44c984fd | |||
v1.0 | complete | Docs | Docs: Pytorch_49941_C | import torch
def are_broadcastable(x: torch.Tensor, y: torch.Tensor) -> bool:
"""
Checks if two tensors are broadcastable according to PyTorch's broadcasting rules.
>>> x = torch.empty(5, 1, 4, 1)
>>> y = torch.empty(3, 1, 1)
>>> are_broadcastable(x, y)
True
>>> x = torch.empty(5, 2)
>>... | import torch
def are_broadcastable(x: torch.Tensor, y: torch.Tensor) -> bool:
"""
Checks if two tensors are broadcastable according to PyTorch's broadcasting rules.
"""
x_shape = list(x.shape)
y_shape = list(y.shape)
# Reverse the shapes to compare from the last dimensions first
x_shap... | import torch
from solution import are_broadcastable, broadcast_tensors
def test_are_broadcastable_same_shape():
x = torch.empty(4, 3)
y = torch.empty(4, 3)
assert are_broadcastable(x, y) == True
def test_are_broadcastable_different_shapes():
x = torch.empty(5, 1, 4, 1)
y = torch.empty(3, 1, 1)
... | [
{
"docstring": "Checks if two tensors are broadcastable according to PyTorch's broadcasting rules.",
"function_declaration": "def are_broadcastable(x, y):",
"function_name": "are_broadcastable",
"parameter_list": "(x, y)"
},
{
"docstring": "Sums two tensors after broadcasting them if possibl... | [
1,
1,
1,
1,
0,
0,
0,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\n\ndef are_broadcastable(x: torch.Tensor, y: torch.Tensor) -> bool:\n \"\"\"\n Check if two tensors can be broadcasted according to PyTorch's broadca... | trial_gpt4o_9 | {
"original_instruction": "### PyTorch Broadcasting Challenge\n\nIn this coding challenge, you are required to implement two functions related to PyTorch's broadcasting semantics.\n\n#### Function 1: `are_broadcastable`\n\nImplement a function `are_broadcastable(x: torch.Tensor, y: torch.Tensor) -> bool`, which takes... | 0.515261 | Docs: Pytorch_49941 | C | [
"are_broadcastable",
"broadcast_tensors"
] | 2 | [
[
"broadcast_tensors",
"are_broadcastable"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | e2c8601aa51b22951a616ca8d2cbce28129ef30b | 4c991a6bd060eb7ae3f74670728fcff6a06b8d80 | |||
v1.0 | complete | Docs | Docs: Scikit_49815_C | import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import validation_curve, learning_curve
def generate_validation_curve(X, y):
"""
Generates validation curve data for SVM with linear kernel over a range of C values.
Parameters:
- X: Features
... | import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import validation_curve, learning_curve
def generate_validation_curve(X, y):
"""
Generates validation curve data for SVM with linear kernel over a range of C values.
Parameters:
- X: Features
... | from sklearn.datasets import load_iris
from sklearn.utils import shuffle
import numpy as np
# Assuming the functions are defined in a module named `solution`
from solution import generate_validation_curve, generate_learning_curve, plot_curves
def test_generate_validation_curve():
data = load_iris()
X, y = shu... | [
{
"docstring": "Generates validation curve data for SVM with linear kernel over a range of C values.\n\nParameters:\n- X: Features\n- y: Target\n\nReturns:\n- train_scores: Training scores for different C values.\n- valid_scores: Validation scores for different C values.",
"function_declaration": "def gener... | [
1,
0,
1,
0,
0,
0,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import validation_curve, learning_curve\nfrom ... | trial_gpt4o_6 | {
"original_instruction": "Analyzing Model Performance Using Validation and Learning Curves\n\n**Objective**:\nIn this task, you will leverage the scikit-learn library to analyze the performance of a Support Vector Machine (SVM) classifier using validation and learning curves. You will implement functions to generate... | 0.657521 | Docs: Scikit_49815 | C | [
"generate_validation_curve",
"generate_learning_curve",
"plot_curves"
] | 3 | [
[
"plot_curves",
"generate_learning_curve"
],
[
"plot_curves",
"generate_validation_curve"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"sklearn"
] | false | b77e59a793a93f08bd0508b2da8259d8b638a757 | eb3cf2157733205bc1f30a901c0dcae79887ecc7 | |||
v1.0 | complete | Docs | Docs: Scikit_49409_C | import numpy as np
import pandas as pd
from sklearn.datasets import load_digits
from sklearn.semi_supervised import LabelPropagation
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def prepare_data():
""" Load the digi... | import numpy as np
import pandas as pd
from sklearn.datasets import load_digits
from sklearn.semi_supervised import LabelPropagation
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def prepare_data():
digits = load_dig... | import pytest
from solution import prepare_data, preprocess_data, train_model, evaluate_model, semi_supervised_learning_pipeline
def test_prepare_data():
X, y = prepare_data()
# Check that the length of features matches the length of labels
assert len(X) == len(y)
# Check if some labels are set to -1
... | [
{
"docstring": null,
"function_declaration": "def prepare_data():",
"function_name": "prepare_data",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def preprocess_data(X, y):",
"function_name": "preprocess_data",
"parameter_list": "(X, y)"
},
{
"d... | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport pandas as pd\nfrom sklearn.datasets import load_digits\nfrom sklearn.semi_supervised import LabelPropagation\nfrom sklearn.metrics import acc... | trial_gpt4o_9 | {
"original_instruction": "### Semi-Supervised Learning with Scikit-Learn\n\nYou are tasked with implementing a semi-supervised learning pipeline to classify data using scikit-learn's `LabelPropagation` model. Your implementation must work with both numeric and categorical data and must be able to handle missing labe... | 0.710127 | Docs: Scikit_49409 | C | [
"prepare_data",
"preprocess_data",
"train_model",
"evaluate_model",
"semi_supervised_learning_pipeline"
] | 5 | [
[
"semi_supervised_learning_pipeline",
"evaluate_model"
],
[
"semi_supervised_learning_pipeline",
"prepare_data"
],
[
"semi_supervised_learning_pipeline",
"preprocess_data"
],
[
"semi_supervised_learning_pipeline",
"train_model"
]
] | 4 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 109e78dfc3ec10ddaf647aa9594434e16bdd6205 | 9feb73e67d2fe7748c571049ef50908f2b773ae2 | |||
v1.0 | complete | Docs | Docs: Python310_49732_C | import ossaudiodev
import struct
import numpy as np
def audio_echo(input_device: str, output_device: str, duration: int) -> None:
"""
Records audio from the input_device for a given duration, applies an echo effect,
and plays it back through the output_device.
Args:
input_device (str): The pa... | import ossaudiodev
import struct
import numpy as np
def audio_echo(input_device: str, output_device: str, duration: int) -> None:
"""
Records audio from the input_device for a given duration, applies an echo effect,
and plays it back through the output_device.
Args:
input_device (str): The pa... | import pytest
import numpy as np
from solution import add_echo
def test_add_echo():
sample_rate = 44100 # 44.1 kHz
duration = 1 # 1 second
delay = 0.5 # 0.5 second
attenuation = 0.6
# Generate a short sample of audio (1 second of a sine wave)
t = np.linspace(0, duration, int(sample_rate * d... | [
{
"docstring": "Records audio from the input_device for a given duration, applies an echo effect, \nand plays it back through the output_device.\n\nArgs:\n input_device (str): The path to the input audio device.\n output_device (str): The path to the output audio device.\n duration (int): The duration ... | [
1,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import ossaudiodev\nimport time\nimport struct\n\ndef audio_echo(input_device: str, output_device: str, duration: int) -> None:\n try:\n # Open input audio de... | trial_gpt4o_4 | {
"original_instruction": "**Task: Implementing an Audio Echo Program using `ossaudiodev`**\n\n### Description\n\nYou are required to implement a Python program that records audio from an input device, applies an echo effect, and plays the modified audio back through an output device using the `ossaudiodev` module.\n... | 0.60486 | Docs: Python310_49732 | C | [
"audio_echo",
"add_echo"
] | 2 | [
[
"audio_echo",
"add_echo"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy"
] | false | 1a1b149f85735065260b1efe42c3b86a6e635b2f | 3cb844d459a18e171b17981952596c434da711aa | |||
v1.0 | complete | Docs | Docs: Python310_49736_C | from itertools import compress, accumulate, tee
from typing import List, Tuple
def pairwise(iterable):
"""s -> (s0, s1), (s1, s2), (s2, s3), ..."""
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def complex_operations(data: List[int], selectors: List[bool]) -> List[Tuple[int, int]]:
"""
P... | from itertools import compress, accumulate, tee
def pairwise(iterable):
"s -> (s0, s1), (s1, s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def complex_operations(data, selectors):
"""
Perform complex operations using itertools functions.
Args:
data: List ... | from solution import complex_operations
def test_complex_operations_basic():
data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
selectors = [True, False, True, True, False, True, False, True, True, False, True]
expected = [(3, 7), (7, 8), (8, 17), (17, 23), (23, 28), (28, 33)]
assert complex_operations(data, sel... | [
{
"docstring": "s -> (s0, s1), (s1, s2), (s2, s3), ...",
"function_declaration": "def pairwise(iterable):",
"function_name": "pairwise",
"parameter_list": "(iterable)"
},
{
"docstring": "Perform complex operations using itertools functions.\n\nArgs:\ndata: List of integers.\nselectors: List ... | [
1,
1,
1,
0,
1,
0,
1,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import compress, accumulate, tee\nfrom typing import List, Tuple\n\ndef complex_operations(data: List[int], selectors: List[bool]) -> List[Tuple[int, int... | trial_gpt4o_8 | {
"original_instruction": "**Title:** Advanced Itertools Operations\n\n**Objective:**\nDesign a function that will process a dataset using various `itertools` functions to achieve a desired result. This will demonstrate your understanding and ability to leverage the power of the `itertools` module to perform efficien... | 0.591929 | Docs: Python310_49736 | C | [
"pairwise",
"complex_operations"
] | 2 | [
[
"complex_operations",
"pairwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2b1d378415e4f7b9281ca7af9963f039dd1e10bd | e927f577ecd07a72fa19e8dac13d3003c7bcf635 | |||
v1.0 | complete | Docs | Docs: Python310_6772_C | import concurrent.futures
import urllib.request
from typing import List, Dict
def concurrent_scrape(urls: List[str], max_workers: int = 5) -> Dict[str, str]:
""" Scrape the HTML content from a list of URLs concurrently using ThreadPoolExecutor.
Args:
urls (List[str]): A list of URLs to scrape. Each URL is... | import concurrent.futures
import urllib.request
from typing import List, Dict
def fetch_url(url: str) -> str:
try:
with urllib.request.urlopen(url, timeout=30) as response:
return response.read().decode('utf-8')
except Exception as e:
return "Error"
def concurrent_scrape(urls: List... | import pytest
from solution import concurrent_scrape
# Mocking urllib to avoid actual web requests during tests
from unittest.mock import patch
sample_html_content = "<html><body><h1>Sample Content</h1></body></html>"
def mocked_urlopen_success(url, timeout=30):
class MockResponse:
def read(self):
... | [
{
"docstring": null,
"function_declaration": "def fetch_url(url):",
"function_name": "fetch_url",
"parameter_list": "(url)"
},
{
"docstring": null,
"function_declaration": "def concurrent_scrape(urls, max_workers=5):",
"function_name": "concurrent_scrape",
"parameter_list": "(url... | [
1,
0,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nimport urllib.request\nfrom typing import List, Dict\n\ndef fetch_url(url: str) -> str:\n try:\n with urllib.request.urlopen(url, t... | trial_gpt4o_0 | {
"original_instruction": "### Asynchronous Web Scraping with concurrent.futures\n\nYou are required to implement a function that scrapes the HTML content from a list of URLs concurrently using the `concurrent.futures` module. The function should use the `ThreadPoolExecutor` for this purpose.\n\n#### Function Signatu... | 0.642901 | Docs: Python310_6772 | C | [
"fetch_url",
"concurrent_scrape"
] | 2 | [
[
"concurrent_scrape",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ab787b13d2d47b2e93500fc8fca8d99bfe99c84f | 1a9ab665e23483eded4894a6bd3a15140805dde2 | |||
v1.0 | complete | Docs | Docs: Python310_18246_C | class InsufficientFundsError(Exception):
""" Custom exception to be raised when an account does not have enough balance for a withdrawal. """
pass
class AccountNotFoundError(Exception):
""" Custom exception to be raised when an account is not found in the banking system. """
pass
def create_account(ac... | class InsufficientFundsError(Exception):
pass
class AccountNotFoundError(Exception):
pass
def create_account(account_data, account_id, initial_balance):
if initial_balance < 0:
raise ValueError("Initial balance cannot be negative!")
account_data[account_id] = initial_balance
def get_balance(a... | from solution import create_account, get_balance, deposit, withdraw, transfer, InsufficientFundsError, AccountNotFoundError
def test_create_account():
account_data = {}
create_account(account_data, 'acc1', 500)
assert account_data['acc1'] == 500
def test_create_account_negative_initial_balance():
acco... | [] | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class InsufficientFundsError(Exception):\n pass\n\nclass AccountNotFoundError(Exception):\n pass\n\ndef create_account(account_data, account_id, initial_balance):... | trial_gpt4o_2 | {
"original_instruction": "### Exception Handling and Custom Exception Creation in Python\n\nIn this exercise, you are required to demonstrate your understanding of Python's exception handling mechanisms and custom exception creation. You will create a set of functions that simulate a simple banking system, handle ex... | 0.576207 | Docs: Python310_18246 | C | [
"create_account",
"get_balance",
"deposit",
"withdraw",
"transfer"
] | 5 | [
[
"transfer",
"deposit"
],
[
"transfer",
"withdraw"
]
] | 2 | [] | false | [
"InsufficientFundsError",
"AccountNotFoundError"
] | true | pytest | true | [] | true | 3e0dab9bad6030fc89400d14cc92db6b52752950 | f6a9df5a7efd34c30f7fe772ed4dfadf053d0c16 | |||
v1.0 | complete | Docs | Docs: Python310_18501_C | from collections.abc import Iterable
class CustomObject:
def __init__(self, name="default_name", value=0):
self.name = name
self.value = value
def has_attribute(obj, attr_name):
""" Check if the object has a given attribute.
>>> obj = CustomObject(name="test")
>>> has_attribute(obj, "n... | from collections.abc import Iterable
class CustomObject:
def __init__(self, name="default_name", value=0):
self.name = name
self.value = value
def has_attribute(obj, attr_name):
return hasattr(obj, attr_name)
def get_attribute(obj, attr_name):
if has_attribute(obj, attr_name):
ret... | import pytest
from solution import (CustomObject, has_attribute, get_attribute,
set_attribute, del_attribute, compare_objects,
object_repr, object_str, get_iterator)
def test_initialization():
obj = CustomObject()
assert obj.name == "default_name"
assert obj.val... | [] | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from setuptools import setup, Extension\n\n# Define the extension module\ncustom_obj_module = Extension('custom_obj', sources=['custom_obj.c'])\n\n# Define the setup\ns... | trial_gpt4o_1 | {
"original_instruction": "#### Background\nIn Python, attributes of an object define various properties of that object. Python's C API offers a detailed set of functions to handle these attributes at a lower level. To demonstrate the understanding of these functionalities, let's create a Python C-extension module th... | 0.451021 | Docs: Python310_18501 | C | [
"has_attribute",
"get_attribute",
"set_attribute",
"del_attribute",
"compare_objects",
"object_repr",
"object_str",
"get_iterator"
] | 8 | [
[
"del_attribute",
"has_attribute"
],
[
"get_attribute",
"has_attribute"
]
] | 2 | [] | false | [
"CustomObject"
] | true | pytest | true | [] | true | bd86384acba407519a2c671e62cd7f55ac4b9c49 | a05e9140e0d50e7ebeaef530dabca551304954d6 | |||
v1.0 | complete | Docs | Docs: Python310_21020_C | import urllib.request
from urllib.parse import urlparse
from typing import List, Dict, Any
def fetch_html_content(url: str) -> str:
"""
Fetch the HTML content from the given URL.
Args:
- url (str): The URL to fetch HTML from.
Returns:
- str: The HTML content of the URL.
>>> c... | import urllib.request
from urllib.parse import urlparse, urljoin
from typing import List, Dict, Any
from bs4 import BeautifulSoup
import ipaddress
def fetch_html_content(url: str) -> str:
"""
Fetch the HTML content from the given URL.
Args:
- url (str): The URL to fetch HTML from.
Returns... | import pytest
from solution import fetch_html_content, extract_hyperlinks, validate_ip_addresses, url_fetch_and_parse
def test_fetch_html_content():
content = fetch_html_content("https://www.example.com")
assert "<html" in content
def test_extract_hyperlinks():
html = """
<html>
<body>
... | [
{
"docstring": "Fetch the HTML content from the given URL.\n\nArgs:\n- url (str): The URL to fetch HTML from.\n\nReturns:\n- str: The HTML content of the URL.",
"function_declaration": "def fetch_html_content(url):",
"function_name": "fetch_html_content",
"parameter_list": "(url)"
},
{
"docs... | [
0,
0,
1
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import urllib.request\nfrom urllib.parse import urlparse\nfrom bs4 import BeautifulSoup\nimport ipaddress\nfrom typing import List, Any, Dict\n\ndef fetch_html_content(... | trial_gpt4o_2 | {
"original_instruction": "**Question: Implement a Comprehensive URL Fetch and Parse Utility**\n\n*Objective:* Demonstrate your understanding of Python’s `urllib`, `http.client`, and `ipaddress` modules by implementing a utility function that fetches a URL, parses its content, and performs certain operations on the r... | 0.775769 | Docs: Python310_21020 | C | [
"fetch_html_content",
"extract_hyperlinks",
"validate_ip_addresses",
"url_fetch_and_parse"
] | 4 | [
[
"url_fetch_and_parse",
"extract_hyperlinks"
],
[
"url_fetch_and_parse",
"fetch_html_content"
],
[
"url_fetch_and_parse",
"validate_ip_addresses"
]
] | 3 | [] | false | [] | false | pytest | true | [
"bs4"
] | false | 3e934e8b25a23a7f567e07ec1d2bbaee54530f65 | 90f76086ac2a04fd11ffb4a37dcbff6b5678d49f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.