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_21684_C
import asyncio from typing import Union async def async_file_read(file_path: str) -> bytes: """ Simulates asynchronous file read operation. """ await asyncio.sleep(1) # Simulate I/O operation with open(file_path, 'rb') as f: return f.read() async def read_file_async_with_timeout(file_path...
import asyncio from typing import Union from asyncio import IncompleteReadError, LimitOverrunError async def async_file_read(file_path: str) -> bytes: """ Simulates asynchronous file read operation. """ await asyncio.sleep(1) # Simulate I/O operation with open(file_path, 'rb') as f: return...
import pytest import asyncio from solution import read_file_async_with_timeout @pytest.fixture def create_test_file(tmp_path): file_path = tmp_path / "test_file.txt" with open(file_path, "w") as f: f.write("Hello, World!") return file_path @pytest.mark.asyncio async def test_read_file_async_with_t...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import Union\nfrom asyncio import IncompleteReadError, LimitOverrunError\n\nasync def async_file_read(file_path: str) -> bytes:\n \"\"\"\...
trial_gpt4o_0
{ "original_instruction": "### Asynchronous File Reader with Timeout and Exception Handling\n\n#### Background\nYou are given the task of implementing a function to read data from a file asynchronously, handle various asyncio-related exceptions, and ensure a timeout for the read operation.\n\n#### Objective\nImplemen...
0.467175
Docs: Python310_21684
C
[ "async_file_read", "read_file_async_with_timeout" ]
2
[ [ "read_file_async_with_timeout", "async_file_read" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8e1b653a02b77c06ae588eae8396971138d117b1
11f20032b6bb10e113977ccda47a958af46be2a6
v1.0
complete
Docs
Docs: Python310_21585_C
import os import tarfile def create_and_extract_tar(input_dir: str, output_tar: str, extract_dir: str, allowed_extensions: list[str]) -> None: """ Create a tar archive from a given directory including only files with specific extensions, and extract it to a specified directory ensuring security measures. ...
import os import tarfile def is_within_directory(directory, target): """ Check if a file is within a given directory. """ abs_directory = os.path.abspath(directory) abs_target = os.path.abspath(target) prefix = os.path.commonprefix([abs_directory, abs_target]) return prefix == abs_directory...
import os import pytest import tarfile import shutil from solution import create_and_extract_tar @pytest.fixture def setup_dirs(tmp_path): # Setup temporary directories input_dir = tmp_path / "input_dir" extract_dir = tmp_path / "extract_dir" input_dir.mkdir() extract_dir.mkdir() # Create ...
[ { "docstring": "Check if a file is within a given directory.", "function_declaration": "def is_within_directory(directory, target):", "function_name": "is_within_directory", "parameter_list": "(directory, target)" }, { "docstring": null, "function_declaration": "def create_and_extract_ta...
[ 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 os\nimport tarfile\n\ndef is_within_directory(directory, target):\n \"\"\"\n Check if a file is within a given directory.\n \"\"\"\n abs_directory = ...
trial_gpt4o_0
{ "original_instruction": "**Question:**\n\nYou are tasked with implementing a Python function using the `tarfile` module to create a tar archive from a given directory, including only specific file types, and to extract that archive to a specified destination directory, ensuring certain security measures.\n\n### Fun...
0.655275
Docs: Python310_21585
C
[ "is_within_directory", "create_and_extract_tar" ]
2
[ [ "create_and_extract_tar", "is_within_directory" ] ]
1
[]
false
[]
false
pytest
true
[]
true
15ac109d827872746c1ce65ffece9bbcb4e750a6
6b041600f5f1ed7c8db9062526e22a906bc7483a
v1.0
complete
Docs
Docs: Python310_21702_C
import signal import time import os LOG_FILE = 'signal_log.txt' def log_signal(signum, frame): """ Logs the signal number and stack frame information to a file. """ with open(LOG_FILE, 'a') as f: f.write(f"Signal received: {signum}, Frame: {repr(frame)}\n") if signum == signal.SIGALRM:...
import signal import time import os import traceback LOG_FILE = 'signal_log.txt' def log_signal(signum, frame): """ Logs the signal number and stack frame information to a file. """ with open(LOG_FILE, 'a') as f: f.write(f"Signal received: {signum}, Frame: {repr(frame)}\n") if signum =...
import os import signal from time import sleep # Duplicate part of the solution for the testing scope def log_signal(signum, frame): with open(LOG_FILE, 'a') as f: f.write(f"Signal received: {signum}, Frame: {repr(frame)}\n") if signum == signal.SIGALRM: f.write("SIGALRM received, termi...
[ { "docstring": "Logs the signal number and stack frame information to a file.", "function_declaration": "def log_signal(signum, frame):", "function_name": "log_signal", "parameter_list": "(signum, frame)" }, { "docstring": null, "function_declaration": "def handler(signum, frame):", ...
[ 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 signal\nimport time\nimport os\nimport traceback\n\nLOG_FILE = 'signal_log.txt'\n\ndef log_signal(signum, frame):\n \"\"\"\n Logs the signal number and sta...
trial_gpt4o_0
{ "original_instruction": "**Objective:** Write a Python program using the `signal` module that handles multiple types of signals and implements a timer-based execution mechanism for a critical section of code.\n\n**Task:**\n\n1. Create a custom signal handler that logs the signal number and the stack frame informati...
0.546086
Docs: Python310_21702
C
[ "log_signal", "handler", "sigusr1_handler", "critical_section", "main" ]
5
[ [ "handler", "log_signal" ], [ "sigusr1_handler", "log_signal" ] ]
2
[]
false
[]
false
pytest
false
[]
true
0915c8f5c126fd6a3f66349b2645b134c5d5520c
a672b7228966745612c841999757df9b776ab82a
v1.0
complete
Docs
Docs: Python310_21725_C
import os import signal import ctypes import locale # Using ctypes to bind necessary C functions libc = ctypes.CDLL(None) libc.isatty.argtypes = [ctypes.c_int] libc.isatty.restype = ctypes.c_int def is_interactive_file(filepath: str) -> bool: """ Check if a given file is interactive. >>> is_interactive_file("...
import os import signal import ctypes # Using ctypes to bind necessary C functions libc = ctypes.CDLL(None) libc.isatty.argtypes = [ctypes.c_int] libc.isatty.restype = ctypes.c_int libc.fdopen.argtypes = [ctypes.c_int, ctypes.c_char_p] libc.fdopen.restype = ctypes.c_void_p # Interactive file check function def is_int...
from solution import is_interactive_file, get_and_set_signal_handler, decode_locale_string, encode_locale_string import os import signal def test_is_interactive_file(): assert is_interactive_file("/dev/tty") == True # Interactive if terminal tmp_filename = 'tmp_regular_file.txt' with open(tmp_filename, ...
[ { "docstring": null, "function_declaration": "def is_interactive_file(filepath):", "function_name": "is_interactive_file", "parameter_list": "(filepath)" }, { "docstring": null, "function_declaration": "def PyOS_getsig(n):", "function_name": "PyOS_getsig", "parameter_list": "(n)"...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import ctypes\nimport locale\nimport signal\n\n# Attempting to create Python bindings using ctypes for the specified C functions.\n# Normally, these are not available d...
trial_gpt4o_1
{ "original_instruction": "**System-Level Interaction Challenge**\n\nPython provides various utility functions to interact with the underlying system's internal states and capabilities considered part of stable ABI. Your task is to implement a Python program that simulates a practical scenario using these utility fun...
0.479732
Docs: Python310_21725
C
[ "is_interactive_file", "PyOS_getsig", "PyOS_setsig", "get_and_set_signal_handler", "decode_locale_string", "encode_locale_string" ]
6
[ [ "get_and_set_signal_handler", "PyOS_getsig" ], [ "get_and_set_signal_handler", "PyOS_setsig" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2a0eb2b852bfe23291374262c02ac97410940e0a
f94a58bd95c6e9872b29ea93bcdd8d8472597552
v1.0
complete
Docs
Docs: Pytorch_21866_C
import torch from torch.autograd import Function class FReal(Function): @staticmethod def forward(ctx, x): """ Forward pass for f_real function. Computes y = sin(x) * x^2. """ # Implementation here @staticmethod def backward(ctx, grad_output): """ Backward pass for ...
import torch from torch.autograd import Function class FReal(Function): @staticmethod def forward(ctx, x): ctx.save_for_backward(x) return torch.sin(x) * x ** 2 @staticmethod def backward(ctx, grad_output): x, = ctx.saved_tensors grad_x = grad_output * (2 * x * torch.si...
import torch from solution import verify_gradients, f_real, f_complex def test_gradcheck_real(): real_ok, _ = verify_gradients() assert real_ok, "Gradcheck for f_real did not pass." def test_gradcheck_complex(): _, complex_ok = verify_gradients() assert complex_ok, "Gradcheck for f_complex did not pas...
[]
[ 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.autograd import Function\n\nclass FReal(Function):\n @staticmethod\n def forward(ctx, x):\n ctx.save_for_backward(x)\n retu...
trial_gpt4o_7
{ "original_instruction": "### Custom Function Implementation and Gradient Check\n\n#### Objective:\nImplement a custom function in PyTorch and verify its gradient using `torch.autograd.gradcheck`. This exercise will test your understanding of automatic differentiation, both in the real and complex domains, and the u...
0.470905
Docs: Pytorch_21866
C
[ "f_real", "f_complex", "verify_gradients" ]
3
[ [ "verify_gradients", "f_complex" ], [ "verify_gradients", "f_real" ] ]
2
[]
false
[ "FReal", "FComplex" ]
true
pytest
true
[ "torch" ]
false
7fc8d3eb70fd5f605d5c7408d663b04ad9a6e320
e6309d24a7e7c89bb7c945f3c57714b212d64455
v1.0
complete
Docs
Docs: Python310_21826_C
import asyncio class CustomServerProtocol(asyncio.Protocol): def connection_made(self, transport): """Called when a connection is made.""" self.transport = transport def data_received(self, data): """Called when some data is received.""" message = data.decode() response...
import asyncio class CustomServerProtocol(asyncio.Protocol): def __init__(self): super().__init__() self.transport = None def connection_made(self, transport): self.transport = transport peername = transport.get_extra_info('peername') print(f'Connection made from {peer...
import asyncio from solution import start_server, start_client async def test_server_response(): server_task = asyncio.create_task(run_server()) await asyncio.sleep(1) # allow server time to start response = await tcp_client('Hello, server!') assert response == 'Server Response: Hello, server!' ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nclass EchoServerProtocol(asyncio.Protocol):\n def connection_made(self, transport):\n self.transport = transport\n print('Connection ...
trial_gpt4o_1
{ "original_instruction": "### asyncio Server-Client Communication\n\n#### Objective:\nYour task is to implement a simple server-client architecture using the asyncio package in Python 3.10. The server should handle multiple client connections, and the client should be able to send messages to the server and receive ...
0.61911
Docs: Python310_21826
C
[ "run_server", "tcp_client", "start_server", "start_client" ]
4
[ [ "start_client", "tcp_client" ], [ "start_server", "run_server" ] ]
2
[]
false
[ "CustomServerProtocol" ]
true
pytest
true
[]
true
906019f5ef564928cebd064f65e26be07a9cb6eb
8b16b828514345d27ebcb192b6fb841cf719f40d
v1.0
complete
Docs
Docs: Python310_22039_C
import asyncio async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): """Handle individual client connections. Args: reader (asyncio.StreamReader): Stream reader to read data from client. writer (asyncio.StreamWriter): Stream writer to send data to client. ...
import asyncio async def handle_client(reader, writer): try: request = (await reader.read(1024)).decode('utf-8') if request.startswith('GET'): response = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<html><body><h1>Hello, World!</h1></body></html>\r\n' else: re...
import asyncio import socket import pytest from solution import start_http_server @pytest.fixture(scope="module") def event_loop(): loop = asyncio.get_event_loop() yield loop loop.close() @pytest.fixture(scope="module") def server(event_loop): task = event_loop.create_task(start_http_server('127.0.0.1...
[]
[ 1, 1, 1 ]
3
easy
1
{ "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, writer):\n try:\n request = (await reader.read(1024)).decode('utf-8')\n if request.startswith('GET'):...
trial_gpt4o_0
{ "original_instruction": "### Asynchronous HTTP Server Assessment\n\nImplement an Asynchronous HTTP Server using `asyncio` streams that can handle multiple client connections simultaneously. The server should be capable of accepting HTTP GET requests and responding with a simple HTML page. Clients can connect, reque...
0.60495
Docs: Python310_22039
C
[ "handle_client", "start_http_server" ]
2
[ [ "start_http_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
88d5594c4e928360087aec072ea94e4b285c3338
a7df682257609687b37e559882c57224bd3f60db
v1.0
complete
Docs
Docs: Python310_21710_C
import argparse import sys def process_file(file: str) -> list: """ Read numeric data from a file and return as a list of floats. """ pass def process_arguments(argv=None): """ Parse command-line arguments to sum or average numeric values in input files. Example usage: >>> process_arguments([...
import argparse import sys def process_file(file): with open(file, 'r') as f: data = f.read().split() return list(map(float, data)) def process_arguments(argv=None): parser = argparse.ArgumentParser(description='Process some numeric data.') group = parser.add_mutually_exclusive_group(...
from solution import process_arguments import pytest import tempfile import os # Utility function to create a temporary file with given content def create_temp_file(content): temp_file = tempfile.NamedTemporaryFile(delete=False) with open(temp_file.name, 'w') as f: f.write(content) return temp_file...
[ { "docstring": null, "function_declaration": "def process_file(file):", "function_name": "process_file", "parameter_list": "(file)" }, { "docstring": null, "function_declaration": "def process_arguments(argv=None):", "function_name": "process_arguments", "parameter_list": "(argv=...
[ 0, 0, 0, 1, 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 argparse\nimport sys\n\ndef read_file_data(filepaths):\n data = []\n for filepath in filepaths:\n with open(filepath, 'r') as file:\n for...
trial_gpt4o_3
{ "original_instruction": "**Question: Parsing Command-Line Arguments for a Data Processing Script**\n\nYou are tasked with writing a Python script that processes data from a list of input files and performs various operations (such as summing or averaging numeric values) based on command-line arguments. You need to ...
0.601442
Docs: Python310_21710
C
[ "process_file", "process_arguments" ]
2
[ [ "process_arguments", "process_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
48aabb1f0254748afc15d3923bb18cfc65c125d5
ecab51ccfefb0e11736e290eab7ab9080b865f27
v1.0
complete
Docs
Docs: Pytorch_21899_C
import torch from torch.ao.ns.fx.utils import compute_sqnr, compute_normalized_l2_error, compute_cosine_similarity from typing import Dict def compute_sqnr_metric(tensor1: torch.Tensor, tensor2: torch.Tensor) -> float: """ Compute the signal-to-quantization-noise ratio (SQNR) between two input tensors. >>> com...
import torch from torch.ao.ns.fx.utils import compute_sqnr, compute_normalized_l2_error, compute_cosine_similarity from typing import Dict def compute_sqnr_metric(tensor1: torch.Tensor, tensor2: torch.Tensor) -> float: if tensor1.shape != tensor2.shape: raise ValueError("The shapes of tensor1 and tensor2 m...
import torch import pytest from solution import compute_sqnr_metric, compute_normalized_l2_metric, compute_cosine_similarity_metric, compute_all_metrics @pytest.fixture def sample_tensors(): tensor1 = torch.tensor([1.0, 2.0, 3.0]) tensor2 = torch.tensor([1.0, 2.1, 2.9]) return tensor1, tensor2 def test_co...
[ { "docstring": null, "function_declaration": "def compute_sqnr_metric(tensor1, tensor2):", "function_name": "compute_sqnr_metric", "parameter_list": "(tensor1, tensor2)" }, { "docstring": null, "function_declaration": "def compute_normalized_l2_metric(tensor1, tensor2):", "function_n...
[ 0, 0, 0, 0, 0, 0, 1, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.ao.ns.fx.utils import compute_sqnr, compute_normalized_l2_error, compute_cosine_similarity\nfrom typing import Dict\n\ndef compute_sqnr_metric(...
trial_gpt4o_7
{ "original_instruction": "### PyTorch FX Numeric Suite: Compute Tensor Metrics\n\n**Objective:**\n\nIn this assessment, you'll demonstrate your understanding of the PyTorch FX numeric suite utilities by implementing functions that utilize core metrics to compare two input tensors. You will be required to:\n1. Use th...
0.584236
Docs: Pytorch_21899
C
[ "compute_sqnr_metric", "compute_normalized_l2_metric", "compute_cosine_similarity_metric", "compute_all_metrics" ]
4
[ [ "compute_all_metrics", "compute_cosine_similarity_metric" ], [ "compute_all_metrics", "compute_normalized_l2_metric" ], [ "compute_all_metrics", "compute_sqnr_metric" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
c943c10d4983982d9882a6a38291bd7bdf3344a2
1bf2c7abca0c66ddd4f477d346a802ec91702e29
v1.0
complete
Docs
Docs: Python310_21984_C
import asyncio import contextvars var1 = contextvars.ContextVar('var1', default=0) var2 = contextvars.ContextVar('var2', default=None) async def task1(): """ Task 1 sets the context variables var1 and var2 and runs task2 within its context. """ token1 = var1.set(10) var2.set(20) print(f"Values...
import asyncio import contextvars var1 = contextvars.ContextVar('var1', default=0) var2 = contextvars.ContextVar('var2', default=None) async def task1(): """ Task 1 sets the context variables var1 and var2 and runs task2 within its context. """ token1 = var1.set(10) var2.set(20) print(f"Values...
import pytest import asyncio from contextvars import ContextVar from solution import manage_context_data, var1, var2 @pytest.mark.asyncio async def test_manage_context_data_initial_values(): # Test initial values assert var1.get() == 0 assert var2.get() is None @pytest.mark.asyncio async def test_manage_c...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\n\nvar1 = contextvars.ContextVar('var1', default=0)\nvar2 = contextvars.ContextVar('var2', default=None)\n\nasync def task1():\n \...
trial_gpt4o_0
{ "original_instruction": "### Contextual Data Management in Concurrent Tasks\n\nAs an exercise, you will implement a function `manage_context_data` to demonstrate the use of the contextvars module for handling contextual data within asynchronous tasks. This function will be composed of a nested structure of asynchro...
0.426917
Docs: Python310_21984
C
[ "task1", "task2", "manage_context_data" ]
3
[ [ "manage_context_data", "task1" ], [ "task1", "task2" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6f2c9818e85ecd203f892128e8c6f10ccaa877ef
639c40765ad9af7203d7868a508b842aaa07be70
v1.0
complete
Docs
Docs: Python310_22012_C
import asyncio from typing import NoReturn async def producer_consumer_system() -> NoReturn: """ Launches three producer coroutines that generate integers from 1 to 10 with an interval of 0.1 seconds between each number. Launches two consumer coroutines that process the received integers by printing them ...
import asyncio from typing import NoReturn async def producer(queue: asyncio.Queue, id: int) -> None: for i in range(1, 11): await asyncio.sleep(0.1) # Simulate time taken to produce an item await queue.put(f'Producer {id}: {i}') async def consumer(queue: asyncio.Queue, id: int) -> None: ...
import asyncio import io import pytest from solution import producer_consumer_system @pytest.mark.asyncio async def test_producer_consumer_system(monkeypatch, capsys): # Capture print statements from consumer coroutine monkeypatch.setattr('sys.stdout', io.StringIO()) await producer_consumer_system()...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import NoReturn\n\nasync def producer(queue: asyncio.Queue, producer_id: int) -> None:\n for i in range(1, 11):\n await asyncio.sl...
trial_gpt4o_1
{ "original_instruction": "#### Background:\n\nYou are tasked with building a simple producer-consumer system where multiple producers are generating data, and multiple consumers are processing that data. You will use the `asyncio` library to implement this system asynchronously.\n\n#### Task:\n\nWrite a Python funct...
0.499734
Docs: Python310_22012
C
[ "producer", "consumer", "producer_consumer_system" ]
3
[ [ "producer_consumer_system", "consumer" ], [ "producer_consumer_system", "producer" ] ]
2
[]
false
[]
false
pytest
true
[]
true
0f1592393eff99e474fca0d4274d09632c34d3f3
d5976b6c297e196ce0907a5036679b42956aae07
v1.0
complete
Docs
Docs: Python310_22101_C
import ensurepip import subprocess def is_version_less(current_version, min_version): current_parts = list(map(int, current_version.split('.'))) min_parts = list(map(int, min_version.split('.'))) return current_parts < min_parts def bootstrap_pip_if_needed(upgrade=False, user_install=False, verbosity_leve...
import ensurepip import subprocess def is_version_less(current_version, min_version): current_parts = list(map(int, current_version.split('.'))) min_parts = list(map(int, min_version.split('.'))) return current_parts < min_parts def bootstrap_pip_if_needed(upgrade=False, user_install=False, verbosity_leve...
from unittest.mock import patch, MagicMock import subprocess import ensurepip from solution import bootstrap_pip_if_needed, is_version_less def test_is_version_less(): assert is_version_less("20.3", "21.0") == True assert is_version_less("21.0", "21.0") == False assert is_version_less("21.1", "21.0") == Fa...
[ { "docstring": null, "function_declaration": "def is_version_less(current_version, min_version):", "function_name": "is_version_less", "parameter_list": "(current_version, min_version)" }, { "docstring": null, "function_declaration": "def bootstrap_pip_if_needed(upgrade=False, user_insta...
[ 0, 1 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import ensurepip\nimport subprocess\n\ndef is_version_less(current_version, min_version):\n current_parts = list(map(int, current_version.split('.')))\n min_parts...
trial_gpt4o_2
{ "original_instruction": "**Question:**\n\nAs a Pythonista, you may sometimes need to ensure the 'pip' package installer is available in your Python environment programmatically. To assess your understanding of the `ensurepip` package, you are required to write a function that uses this package to check the current ...
0.56801
Docs: Python310_22101
C
[ "is_version_less", "bootstrap_pip_if_needed" ]
2
[ [ "bootstrap_pip_if_needed", "is_version_less" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d2421d6d92988e32a4741b810fdd7d91fd21fa8a
34566d3d851c0f170f3ee5de6d54cbb5850f1fbd
v1.0
complete
Docs
Docs: Pytorch_22150_C
import torch @torch.jit.script def matrix_multiplication(A: torch.Tensor, B: torch.Tensor, C: torch.Tensor) -> torch.Tensor: """ Perform asynchronous matrix multiplication and add the result to another matrix. >>> A = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) >>> B = torch.tensor([[2.0, 0.0], [1.0, 2.0]]) ...
import torch import timeit @torch.jit.script def matrix_multiplication(A: torch.Tensor, B: torch.Tensor, C: torch.Tensor) -> torch.Tensor: # Perform asynchronous matrix multiplication result = torch.jit._fork(torch.mm, A, B) out = torch.jit._wait(result) return out + C def optimize_and_benchmark(N: in...
from solution import matrix_multiplication, optimize_and_benchmark def test_matrix_multiplication(): N = 4 A = torch.tensor([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]) B = torch.tensor([[1...
[ { "docstring": null, "function_declaration": "def matrix_multiplication(A, B, C):", "function_name": "matrix_multiplication", "parameter_list": "(A, B, C)" }, { "docstring": null, "function_declaration": "def optimize_and_benchmark(N):", "function_name": "optimize_and_benchmark", ...
[ 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 timeit\n\n@torch.jit.script\ndef matrix_multiplication(A: torch.Tensor, B: torch.Tensor, C: torch.Tensor) -> torch.Tensor:\n result = torch.mm(A...
trial_gpt4o_9
{ "original_instruction": "### PyTorch Threading and Parallelism Challenge\n\n#### Objective\nDesign a function utilizing PyTorch's TorchScript to perform parallel computations and adjust thread settings to optimize performance for matrix multiplication operations.\n\n#### Problem Statement\nYou are given two matrice...
0.485491
Docs: Pytorch_22150
C
[ "matrix_multiplication", "optimize_and_benchmark" ]
2
[ [ "optimize_and_benchmark", "matrix_multiplication" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
21427c7d09ccb2f12caa16766a8723f7ae41d889
1c1ef0513071eaa35139eb803b41771668fa8578
v1.0
complete
Docs
Docs: Python310_21693_C
import secrets import string def generate_token(token_type: str, length: int = None) -> str: """Generates a secure token. Args: token_type (str): The type of token ('hex', 'bytes', 'urlsafe'). length (int): The number of bytes for the token. If None, default length is used. Returns: s...
import secrets import string def generate_token(token_type: str, length: int = None) -> str: """ Generates a secure token. Args: token_type (str): The type of token ('hex', 'bytes', 'urlsafe'). length (int): The number of bytes for the token. If None, default length is used. Returns: ...
from solution import generate_token, generate_password, generate_secure_url def test_generate_token_hex_default_length(): token = generate_token('hex') assert len(token) == 64 # 32 bytes * 2 hex chars per byte def test_generate_token_hex_specific_length(): token = generate_token('hex', 16) assert len...
[ { "docstring": "Generates a secure token.\n\nArgs:\ntoken_type (str): The type of token ('hex', 'bytes', 'urlsafe').\nlength (int): The number of bytes for the token. If None, default length is used.\n\nReturns:\nstr: The generated token.", "function_declaration": "def generate_token(token_type, length=None...
[ 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 secrets\nimport string\n\ndef generate_token(token_type: str, length: int = None) -> str:\n \"\"\"\n Generates a secure token based on the provided type an...
trial_gpt4o_2
{ "original_instruction": "**Secure Token Management System**\n\nGiven the necessity to secure sensitive information and manage secure communication, you are tasked to implement a token management system using Python's `secrets` module. Your implementation should include the following functionalities:\n\n1. **Generat...
0.617944
Docs: Python310_21693
C
[ "generate_token", "generate_password", "generate_secure_url" ]
3
[ [ "generate_secure_url", "generate_token" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4874d17575e114e885c0839ff1245e85655c576f
1fae98d5eb7a2915d182824e8673274c22e195c5
v1.0
complete
Docs
Docs: Python310_22044_C
import pdb def process_numbers(numbers): """ Process a list of integers to return the sum of squares of even numbers. Set a breakpoint at the start of the `process_numbers` function. Step through the code to identify the cause of exception, inspect variables, evaluate expressions, handle post-mort...
import pdb def process_numbers(numbers): pdb.set_trace() # Part 1: Setting a breakpoint at the start of the function result = 0 for num in numbers: if num % 2 == 0: result += num ** 2 else: result -= 'NaN' # Intentional bug: cannot subtract string from int ret...
from solution import process_numbers_fixed def test_process_numbers_fixed_with_even_and_odd_numbers(): assert process_numbers_fixed([1, 2, 3, 4, 5, 6]) == 56 def test_process_numbers_fixed_with_even_numbers_only(): assert process_numbers_fixed([2, 4, 6, 8]) == 120 def test_process_numbers_fixed_with_odd_numb...
[ { "docstring": null, "function_declaration": "def process_numbers(numbers):", "function_name": "process_numbers", "parameter_list": "(numbers)" }, { "docstring": null, "function_declaration": "def main():", "function_name": "main", "parameter_list": "()" }, { "docstring":...
[ 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": "# Fixed faulty program with pdb debugging\n\nimport pdb\n\ndef process_numbers(numbers):\n result = 0\n \n # Part 1: Use set_trace method to set a breakpoint\n...
trial_gpt4o_9
{ "original_instruction": "Advanced Python Debugging\n\n#### Objective:\nDemonstrate your understanding of the Python Debugger (`pdb` module) by creating and debugging a Python script. The task will evaluate your ability to use breakpoints, inspect stack frames, evaluate expressions, and handle post-mortem debugging....
0.63188
Docs: Python310_22044
C
[ "process_numbers", "main", "process_numbers_fixed", "main_fixed" ]
4
[ [ "main_fixed", "process_numbers_fixed" ] ]
1
[]
false
[]
false
pytest
true
[]
true
27675bf4f60cc7e0e7b3dac9e9ea98ae726fa223
6f1028dcdb734348706c6b3162b2147fa9073b10
v1.0
complete
Docs
Docs: Python310_22162_C
import asyncio from typing import List import random async def run_task_manager(num_tasks: int, timeout: float) -> List[str]: """ Implement a command-line asynchronous task manager using asyncio. The manager should: 1. Create `num_tasks` asynchronous tasks which each pick up a string from an asyncio queue,...
import asyncio from typing import List import random async def worker(task_id: int, queue: asyncio.Queue, result: List[str]): while True: try: input_string = await queue.get() await asyncio.sleep(random.randint(1, 5)) # Simulate processing time result.append(f"Task {tas...
import asyncio from solution import run_task_manager async def test_run_task_manager_all_tasks_complete(): result = await run_task_manager(5, 10) assert len(result) == 10 assert all("Task " in r and "completed: data_" in r for r in result) async def test_run_task_manager_timeout(): result = await run_...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List\nimport random\n\nasync def worker(task_id: int, queue: asyncio.Queue, result: List[str]):\n while True:\n try:\n ...
trial_gpt4o_0
{ "original_instruction": "### Python Asyncio Coding Assessment\n\n#### Objective\nImplement a command-line asynchronous task manager using asyncio. The manager should be able to:\n1. Spawn a number of asynchronous tasks to complete a particular job.\n2. Use an asyncio queue to distribute work among these tasks.\n3. ...
0.65344
Docs: Python310_22162
C
[ "worker", "run_task_manager" ]
2
[ [ "run_task_manager", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
58d260835226e23aeeaddde759939d108043207c
eee58efbe8e6f6152e60680d93141f8600accf07
v1.0
complete
Docs
Docs: Pytorch_21975_C
import torch import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP import torch.distributed.elastic.multiprocessing as mp from torch.utils.data import DataLoader, DistributedSampler import torch.optim as optim import torch.nn as nn def initialize_distributed_process_group(rank, ...
import torch import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP import torch.distributed.elastic.multiprocessing as mp from torch.utils.data import DataLoader, DistributedSampler import torch.optim as optim import torch.nn as nn import os def initialize_distributed_process_gr...
import os from solution import SimpleModel, save_model, load_model def test_model_save_and_load(): model = SimpleModel() save_path = "test_checkpoint.pth" # Initial epoch to save save_model(model, 3, path=save_path) assert os.path.exists(save_path), "Checkpoint file not created." new_model = ...
[]
[ 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 os\nimport torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch....
trial_gpt4o_4
{ "original_instruction": "### Distributed Training with PyTorch\n\n**Objective:**\n\nYour task is to implement a fault-tolerant distributed training script using PyTorch and Torch Distributed Elastic. This will assess your understanding of setting up distributed training, handling node synchronization, and ensuring ...
0.530658
Docs: Pytorch_21975
C
[ "initialize_distributed_process_group", "load_data", "save_model", "load_model", "train" ]
5
[ [ "train", "initialize_distributed_process_group" ], [ "train", "load_data" ], [ "train", "load_model" ], [ "train", "save_model" ] ]
4
[]
false
[ "SimpleModel" ]
true
pytest
true
[ "torch" ]
false
0b020c8f05b7cc7d7fb457101cd25eda56f80e1e
897e48c0601f88941b77c60fae06460ec91afda1
v1.0
complete
Docs
Docs: Python310_22420_C
import sys import os import shutil import socket from datetime import datetime import threading def audit_event_handler(event, args): """ Handles audit events and logs them to a file. """ pass def monitor_audit_events(): """ Registers the audit_event_handler function as an audit hook and demonstrates ...
import sys import os import shutil import socket from datetime import datetime import threading # Lock for thread-safe file operations log_lock = threading.Lock() def audit_event_handler(event, args): events_to_monitor = ['os.system', 'socket.connect', 'shutil.copyfile'] if event in events_to_monitor: ...
import sys import os import shutil import socket import threading from datetime import datetime # Ensure the solution module is imported correctly from solution import monitor_audit_events, audit_event_handler def setup_module(module): # Cleanup the previous log file if it exists if os.path.exists('audit.log'...
[ { "docstring": null, "function_declaration": "def audit_event_handler(event, args):", "function_name": "audit_event_handler", "parameter_list": "(event, args)" }, { "docstring": null, "function_declaration": "def monitor_audit_events():", "function_name": "monitor_audit_events", ...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\nimport os\nimport shutil\nimport socket\nfrom datetime import datetime\nimport threading\n\nlog_file_lock = threading.Lock()\n\ndef audit_event_handler(even...
trial_gpt4o_1
{ "original_instruction": "### Custom Audit Hook Implementation\n\n**Objective**: Implement a custom audit hook handler that monitors specific audit events and logs them to a specified log file.\n\n**Description**:\nPython's `sys.audit()` and `PySys_AddAuditHook()` functions allow the monitoring of various events rai...
0.600997
Docs: Python310_22420
C
[ "audit_event_handler", "monitor_audit_events" ]
2
[ [ "monitor_audit_events", "audit_event_handler" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1c54a0e923a293de108206d377cb78a5e8ed5d97
5b237632bd73e4bdfe1925b04970f72ce02f8616
v1.0
complete
Docs
Docs: Python310_22182_C
import threading import multiprocessing from multiprocessing import Process, Queue from typing import List def is_prime(num): """ Return True if num is a prime number. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 ...
import threading import multiprocessing import queue from multiprocessing import Process, Queue def is_prime(num): """ Return True if num is a prime number. """ if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i...
import pytest import tempfile import os from solution import is_prime, cpu_bound_task, io_bound_task def test_is_prime(): assert is_prime(2) assert is_prime(3) assert not is_prime(4) assert is_prime(5) assert not is_prime(1) assert not is_prime(0) assert is_prime(23) def test_cpu_bound_tas...
[ { "docstring": "Return True if num is a prime number. ", "function_declaration": "def is_prime(num):", "function_name": "is_prime", "parameter_list": "(num)" }, { "docstring": "Calculate the sum of the first n prime numbers. ", "function_declaration": "def cpu_bound_task(n, output_queue)...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\nimport multiprocessing\nfrom multiprocessing import Queue\nimport queue\n\n\ndef cpu_bound_task(n):\n \"\"\"\n Calculates the sum of the first n...
trial_gpt4o_2
{ "original_instruction": "### Objective\nThe task is to implement a Python program that utilizes both the `threading` and `multiprocessing` modules to perform concurrent execution of CPU-bound and I/O-bound tasks. This will assess your understanding of how to effectively use threads and processes for different types...
0.627641
Docs: Python310_22182
C
[ "is_prime", "cpu_bound_task", "io_bound_task", "main" ]
4
[ [ "cpu_bound_task", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
52794fdad9461d709327400548e682a3747c4951
9c11efd8ae0f848682c94f92d721ea5d3e7b075e
v1.0
complete
Docs
Docs: Python310_21982_C
import tokenize def check_indentation(file_path: str) -> None: """Checks the file for mixed or inconsistent indentation and prints issues found. Args: file_path: The path to the Python (.py) file to be checked. Output: Prints the filename and the line number for each detected issue. ...
import tokenize import os def check_indentation(file_path): """ Checks the file for mixed or inconsistent indentation and prints issues found. """ with open(file_path, 'r') as f: tokens = list(tokenize.generate_tokens(f.readline)) last_indent = None spaces = 0 tabs = 0 for token...
import os import pytest from solution import check_indentation, check_directory def test_check_indentation_mixed(): with open("mixed_indentation.py", "w") as f: f.write("def function():\n\t print('hello')\n") expected_output = [ "File: mixed_indentation.py, Line: 2 - Mixed indentation" ] ...
[ { "docstring": "Checks the file for mixed or inconsistent indentation and prints issues found.", "function_declaration": "def check_indentation(file_path):", "function_name": "check_indentation", "parameter_list": "(file_path)" }, { "docstring": "Recursively checks all .py files in the direc...
[ 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 tokenize\nimport os\n\ndef check_indentation(file_path: str) -> None:\n with open(file_path, 'r') as f:\n tokens = tokenize.generate_tokens(f.readline)...
trial_gpt4o_8
{ "original_instruction": "The `tabnanny` module is used to detect ambiguous indentation in Python files. It includes functions to check files and directories for such issues and provides diagnostic messages.\n\nYour task is to implement a simplified version of a tool similar to `tabnanny` that checks Python files fo...
0.558475
Docs: Python310_21982
C
[ "check_indentation", "check_directory" ]
2
[ [ "check_directory", "check_indentation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f61902b71620bc568519506ccc655f4090ffe1c4
16468cba4d6fc73ac38e5f62f64e0eca89a1ce9a
v1.0
complete
Docs
Docs: Python310_21853_C
def get_caps_from_string(mailcap_string): """ Parses a string containing mailcap entries and returns a dictionary mapping MIME types to lists of action dictionaries. Args: - mailcap_string (str): A string where each line is a mailcap entry, in the format 'MIMEtype; action' Return...
import re def get_caps_from_string(mailcap_string): """ Parses a string containing mailcap entries and returns a dictionary mapping MIME types to lists of action dictionaries. Args: - mailcap_string (str): A string where each line is a mailcap entry, in the format 'MIMEtype; action' ...
from solution import get_caps_from_string, find_match def test_get_caps_from_string(): mailcap_string = """ video/mpeg; xmpeg %s text/html; browser %s text/plain; cat %s application/pdf; pdfreader %s """ expected_output = { 'video/mpeg': [{'view': 'xmpeg %s'}], 'text/html': ...
[ { "docstring": "Parses a string containing mailcap entries and returns a dictionary mapping\nMIME types to lists of action dictionaries.\n\nArgs:\n- mailcap_string (str): A string where each line is a mailcap entry, in the format\n 'MIMEtype; action'\n\nReturns:\n- dict: A dictionary where each key is a MIME t...
[ 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\n\ndef get_caps_from_string(mailcap_string):\n \"\"\"\n Parses a string containing mailcap entries and returns a dictionary mapping\n MIME types to l...
trial_gpt4o_5
{ "original_instruction": "### Mailcap File Handler Implementation\n\nMailcap files are essential for configuring how MIME-aware applications handle files with different MIME types. Python's `mailcap` module provides tools to interact with these files. In this task, you are required to work with a subset of this modu...
0.503158
Docs: Python310_21853
C
[ "get_caps_from_string", "valid_filename", "find_match" ]
3
[ [ "find_match", "valid_filename" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ab368fefa72ad2e659a5396c18e5c43b248da7b6
bada5eadf6edd133544d0be5c29819e4e589174d
v1.0
complete
Docs
Docs: Python310_22105_C
def create_set(iterable): """ Create a new set from the given iterable. Parameters: iterable: An iterable from which to create the set. Can be None. Returns: set: A new set containing the elements from the iterable. """ pass def contains_element(s, key): """ Check if a...
def create_set(iterable): """ Create a new set from the given iterable. Parameters: iterable: An iterable from which to create the set. Can be None. Returns: set: A new set containing the elements from the iterable. """ return set() if iterable is None else set(iterable) def c...
from solution import create_set, contains_element, add_element, remove_element, clear_set def test_create_set(): assert create_set([1, 2, 3]) == {1, 2, 3} assert create_set(None) == set() assert create_set("abc") == {'a', 'c', 'b'} def test_contains_element(): s = {1, 2, 3} assert contains_element...
[ { "docstring": "Create a new set from the given iterable.\n\nParameters:\niterable: An iterable from which to create the set. Can be None.\n\nReturns:\nset: A new set containing the elements from the iterable.", "function_declaration": "def create_set(iterable):", "function_name": "create_set", "par...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def create_set(iterable):\n \"\"\"\n Create a new set from the given iterable.\n \n Parameters:\n iterable: An iterable from which to create the set. Can...
trial_gpt4o_2
{ "original_instruction": "### Advanced Coding Assessment: Custom Set Manipulations in Python\n\nYou are required to implement advanced functionalities for set manipulations in Python. This will involve creating and operating on `set` and `frozenset` types. You should demonstrate your understanding of these operation...
0.429816
Docs: Python310_22105
C
[ "create_set", "contains_element", "add_element", "remove_element", "clear_set" ]
5
[ [ "add_element", "contains_element" ] ]
1
[]
false
[]
false
pytest
true
[]
true
844451979f5ac9d06e4163ea59b6336e6246eae1
5024ede6b72013f64c0d9dac573fa16955bffa75
v1.0
complete
Docs
Docs: Python310_22466_C
import asyncio from typing import List, Any async def fetch_data_source_1() -> Any: # Simulate fetching data from source 1 await asyncio.sleep(random.random()) return "data from source 1" async def fetch_data_source_2() -> Any: # Simulate fetching data from source 2 await asyncio.sleep(random.rand...
import asyncio import random from typing import List, Any async def fetch_data_source_1() -> Any: # Simulate fetching data from source 1 await asyncio.sleep(random.uniform(0, 2)) return "data from source 1" async def fetch_data_source_2() -> Any: # Simulate fetching data from source 2 await asynci...
import pytest import asyncio from solution import aggregate_data @pytest.mark.asyncio async def test_aggregate_data(): result = await aggregate_data() assert len(result) == 3 assert "data from source 1" in result assert "data from source 2" in result assert "data from source 3" in result @pytest.m...
[]
[ 1, 1, 1 ]
3
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, Any\n\nasync def fetch_data_source_1() -> Any:\n # Simulate fetching data from source 1\n await asyncio.sl...
trial_gpt4o_0
{ "original_instruction": "### Advanced Python Coding Question: Coroutines\n\n#### Objective\nDesign a coroutine-based function in Python that reads data from multiple asynchronous data sources concurrently and returns the aggregated results as a list. This problem will test your understanding of coroutines and their...
0.427618
Docs: Python310_22466
C
[ "fetch_data_source_1", "fetch_data_source_2", "fetch_data_source_3", "aggregate_data" ]
4
[ [ "aggregate_data", "fetch_data_source_1" ], [ "aggregate_data", "fetch_data_source_2" ], [ "aggregate_data", "fetch_data_source_3" ] ]
3
[]
false
[]
false
pytest
true
[]
true
f3d9e5ea2e409b0fc51161037b67790175867836
95773d743d32d9886af0d86166d865d5245d2bf5
v1.0
complete
Docs
Docs: Seaborn_22578_C
import seaborn as sns import matplotlib.pyplot as plt def create_light_palette(color, n_colors=6): """ Generate a light color palette from light gray to the specified color. Args: - color (str or tuple): The target color as a named color, hex code, or HUSL coordinates. - n_colors (int): Number...
import seaborn as sns import matplotlib.pyplot as plt def create_light_palette(color, n_colors=6): """ Generate a light color palette from light gray to the specified color. Args: - color (str or tuple): The target color as a named color, hex code, or HUSL coordinates. - n_colors (int): Number...
from solution import create_light_palette, create_continuous_cmap, test_palette_inputs def test_create_light_palette_named_color(): palette = create_light_palette("seagreen", 8) assert len(palette) == 8 assert isinstance(palette[0], tuple) def test_create_light_palette_hex_color(): palette = create_li...
[ { "docstring": "Generate a light color palette from light gray to the specified color.\n\nArgs:\n- color (str or tuple): The target color as a named color, hex code, or HUSL coordinates.\n- n_colors (int): Number of colors in the palette (default is 6).\n\nReturns:\n- palette (list): List of colors in the gener...
[ 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 seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef create_light_palette(color, n_colors=6):\n \"\"\"\n Generate a light color palet...
trial_gpt4o_9
{ "original_instruction": "### Question\nYou are a data analyst working on visualizing data for a marketing team. They have specifically requested that all visualizations contain color schemes with specific characteristics for brand consistency. You have decided to use the `seaborn` library to create these color pale...
0.715534
Docs: Seaborn_22578
C
[ "create_light_palette", "create_continuous_cmap", "test_palette_inputs" ]
3
[ [ "test_palette_inputs", "create_light_palette" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn" ]
false
95b9d32955ee950ed823c9a908c5a14bd38dc9bb
185df6a3c5a07906d0057c8f3d16b7318b4d4705
v1.0
complete
Docs
Docs: Python310_22356_C
import asyncio import aiohttp from bs4 import BeautifulSoup async def scrape_pages(urls: list[str], timeout: int) -> dict[str, str]: """ Asynchronous web scraper that fetches content from a list of URLs and processes the fetched HTML to extract the title of each page within the specified timeout. >>> results =...
import asyncio import aiohttp from bs4 import BeautifulSoup async def fetch_page(session, url): """ Fetches the HTML content of a page given a URL using the provided aiohttp session. """ try: async with session.get(url) as response: if response.status == 200: return ...
import asyncio import pytest from solution import scrape_pages @pytest.mark.asyncio async def test_scrape_pages_valid_urls(): urls = [ "https://www.example.com", "https://www.python.org", ] timeout = 10 results = await scrape_pages(urls, timeout) assert "https://www.example.com...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "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_page(session, url, timeout):\n try:\n async with session.get(url, timeout=tim...
trial_gpt4o_1
{ "original_instruction": "### Coding Assessment: Asynchronous Web Scraper\n\n#### Objective:\nDesign and implement an asynchronous web scraper using Python's `asyncio` library. The scraper should be able to fetch and process multiple web pages concurrently while managing potential timeouts and cancellations effectiv...
0.770543
Docs: Python310_22356
C
[ "fetch_page", "process_page", "scrape_page", "scrape_pages" ]
4
[ [ "scrape_page", "fetch_page" ], [ "scrape_page", "process_page" ], [ "scrape_pages", "scrape_page" ] ]
3
[]
false
[]
false
pytest
true
[ "aiohttp", "bs4" ]
false
97e3d4ed11f6714c5ed4e2ad8dcba4f94f57be5f
4470acef24727e5a1936727e509f477e2cff3486
v1.0
complete
Docs
Docs: Python310_22241_C
import asyncio from typing import List, Tuple, Optional, Coroutine async def task(name: str, duration: float) -> float: """ Simulate an asynchronous task that does some work for `duration` seconds. """ await asyncio.sleep(duration) return duration async def wait_task_with_timeout(task_coro: Corout...
import asyncio from typing import List, Tuple, Optional, Coroutine async def task(name: str, duration: float) -> float: """ Simulate an asynchronous task that does some work for `duration` seconds. """ await asyncio.sleep(duration) return duration async def wait_task_with_timeout(task_coro: Corout...
import asyncio import pytest from solution import task, wait_task_with_timeout, perform_tasks_concurrently @pytest.mark.asyncio async def test_task(): assert await task('test_task', 1.0) == 1.0 @pytest.mark.asyncio async def test_wait_task_with_timeout_success(): assert await wait_task_with_timeout(task('test...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple, Optional, Coroutine\n\nasync def task(name: str, duration: float) -> float:\n \"\"\"\n Simulates an asynchronous t...
trial_gpt4o_1
{ "original_instruction": "### Asyncio Task Management\n\nYou have been asked to develop a Python program that performs multiple asynchronous tasks concurrently, handles task timeouts, and ensures that resources are cleaned up properly even if some tasks fail or are cancelled.\n\n#### Requirements and Constraints:\n\...
0.632666
Docs: Python310_22241
C
[ "task", "wait_task_with_timeout", "perform_tasks_concurrently" ]
3
[ [ "perform_tasks_concurrently", "task" ], [ "perform_tasks_concurrently", "wait_task_with_timeout" ] ]
2
[]
false
[]
false
pytest
true
[]
true
444022584724c645128064e6c2818fb131e24ac8
576b02efce7b6228fb2f4c35a56a6e17eff05953
v1.0
complete
Docs
Docs: Python310_22690_C
import warnings import json from dataclasses import dataclass from contextlib import contextmanager @dataclass class AppConfig: """ Data class to hold the application configuration. """ host: str port: int use_ssl: bool timeout: int # Deprecated field def check_deprecations(config: AppCon...
import warnings import json from dataclasses import dataclass from contextlib import contextmanager @dataclass class AppConfig: host: str port: int use_ssl: bool timeout: int # Deprecated field def check_deprecations(config: AppConfig): if hasattr(config, 'timeout'): warnings.warn("The 't...
import pytest import warnings import os import json from contextlib import contextmanager from solution import AppConfig, check_deprecations, configuration_loader def test_app_config_initialization(): config = AppConfig(host="localhost", port=8080, use_ssl=True, timeout=30) assert config.host == "localhost" ...
[]
[ 0, 0, 0, 1, 0, 0, 1, 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 warnings\nimport json\nfrom dataclasses import dataclass\nfrom contextlib import contextmanager\n\n# Step 1: Define the configuration data class\n@dataclass\ncla...
trial_gpt4o_9
{ "original_instruction": "**Python Coding Assessment: Custom Configuration Loader**\n\n### Objective:\nCreate a custom configuration loader for a Python application by leveraging the functionalities of `warnings`, `dataclasses`, and `contextlib`. This loader should provide the ability to define configuration data st...
0.672374
Docs: Python310_22690
C
[ "check_deprecations", "configuration_loader" ]
2
[ [ "configuration_loader", "check_deprecations" ] ]
1
[]
false
[ "AppConfig" ]
true
pytest
true
[]
true
6e3a0535c9e196e847aa232386563cd30d367a43
5547ad12fd75f204917cf20f98b68ec6325e092b
v1.0
complete
Docs
Docs: Python310_22350_C
import hmac import hashlib def generate_token(user_id: str, secret_key: bytes, digestmod: str) -> str: """ Generate an HMAC session token for the given user ID. Parameters: - user_id (str): Unique identifier for the user. - secret_key (bytes): Secret key used for HMAC. - digestmod (str): H...
import hmac import hashlib def generate_token(user_id: str, secret_key: bytes, digestmod: str) -> str: """ Generate an HMAC session token for the given user ID. Parameters: - user_id (str): Unique identifier for the user. - secret_key (bytes): Secret key used for HMAC. - digestmod (str): H...
from solution import generate_token, verify_token def test_generate_token(): user_id = "user123" secret_key = b'supersecretkey' digestmod = 'sha256' token = generate_token(user_id, secret_key, digestmod) assert isinstance(token, str) assert len(token) == 64 # Length of sha256 hash in hexadecim...
[ { "docstring": "Generate an HMAC session token for the given user ID.\n\nParameters:\n- user_id (str): Unique identifier for the user.\n- secret_key (bytes): Secret key used for HMAC.\n- digestmod (str): Hashing algorithm to use (e.g., 'sha256').\n\nReturns:\n- str: The generated HMAC session token in hexadecim...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hmac\nimport hashlib\n\ndef generate_token(user_id: str, secret_key: bytes, digestmod: str) -> str:\n \"\"\"\n Generate an HMAC session token for the given...
trial_gpt4o_2
{ "original_instruction": "### HMAC Authentication System\n\nYou are tasked to develop an HMAC-based session authentication system for a secure web application. This system will allow you to authenticate user sessions by verifying message integrity and authenticity using the HMAC algorithm.\n\n#### Requirements\n\n1....
0.726778
Docs: Python310_22350
C
[ "generate_token", "verify_token" ]
2
[ [ "verify_token", "generate_token" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4e2d7b3316a1312f927d19d30f5d7b9928a56db9
c69b83213cbd6bdf66c67fdfff6aaebd37651448
v1.0
complete
Docs
Docs: Python310_22661_C
import asyncio async def handle_client(reader, writer): """ Handle client connections by reading messages, printing them, and sending them back to the clients. """ pass async def start_server(): """ Start an asynchronous TCP server that listens on localhost:8888 and handles multiple clients concurrent...
import asyncio async def handle_client(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message!r} from {addr!r}") print(f"Send: {message!r}") writer.write(data) await writer.drain() print("C...
import asyncio import pytest import subprocess import time from solution import start_server, tcp_client @pytest.fixture def run_event_loop(): loop = asyncio.get_event_loop() yield loop loop.close() @pytest.fixture def server_process(): # Start the server process process = subprocess.Popen(['pyth...
[]
[ 1, 1, 1 ]
3
easy
1
{ "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, writer):\n data = await reader.read(100)\n message = data.decode()\n addr = writer.get_extra_info('peername')...
trial_gpt4o_0
{ "original_instruction": "### Question: Implement an Asynchronous Echo Server and Client\n\n**Objective:**\nCreate an asynchronous echo server and client using Python's asyncio streams. The server should be able to handle multiple clients concurrently, receive messages from them, and echo the messages back to the re...
0.619892
Docs: Python310_22661
C
[ "handle_client", "start_server", "tcp_client" ]
3
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
12824a12650a9c5f38618a36480ee0fff82ae960
fba7371f989623e5dabbb8c24dc325a46e1768fc
v1.0
complete
Docs
Docs: Python310_22965_C
import gzip import bz2 import lzma from zipfile import ZipFile from typing import List def compress_and_archive(files: List[str], archive_name: str) -> None: """ Compress a given set of files using multiple compression algorithms and archive all compressed files into a single ZIP file. :param files: ...
import gzip import bz2 import lzma import os import shutil from zipfile import ZipFile def compress_file(file_path: str, algorithm: str) -> str: """ Compress a file using the specified algorithm and return the path to the compressed file. """ extension = { 'gzip': '.gz', 'bz2': '.bz2', ...
import os import pytest from zipfile import ZipFile from solution import compress_and_archive TEST_FILE_CONTENT = "This is a test file content." @pytest.fixture def setup_files(tmp_path): file1 = tmp_path / "file1.txt" file2 = tmp_path / "file2.txt" file1.write_text(TEST_FILE_CONTENT) file2.write_text...
[ { "docstring": "Compress a file using the specified algorithm and return the path to the compressed file.", "function_declaration": "def compress_file(file_path, algorithm):", "function_name": "compress_file", "parameter_list": "(file_path, algorithm)" }, { "docstring": null, "function_d...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import gzip\nimport bz2\nimport lzma\nimport os\nimport shutil\nfrom zipfile import ZipFile\n\ndef compress_file(file_path: str, algorithm: str) -> str:\n \"\"\"\n ...
trial_gpt4o_0
{ "original_instruction": "**Coding Question: Data Compression and Archiving**\n\n### Objective:\nImplement a Python function that can compress a given set of files using multiple compression algorithms and then archive all compressed files into a single ZIP file.\n\n### Function Signature:\n```python\ndef compress_a...
0.697508
Docs: Python310_22965
C
[ "compress_file", "compress_and_archive" ]
2
[ [ "compress_and_archive", "compress_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8bc31d989dcdf89bccf5955a36464e95781027ff
06e168fc67041007e167d1ad24db202de8528b01
v1.0
complete
Docs
Docs: Python310_22570_C
import threading import multiprocessing from typing import List, Tuple def is_prime(n: int) -> bool: """ Returns True if n is a prime number, otherwise False. >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(4) False >>> is_prime(5) True >>> is_prime(1) False >>> i...
import threading import multiprocessing import math def is_prime(n: int) -> bool: """ 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: ...
from solution import is_prime, count_primes_in_range, count_primes_with_threads, count_primes_with_processes 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(1) == False assert is_prime(0) == False ...
[ { "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 the count of prime numbers in the given range [start, end).", "function_declaration": "def c...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\nimport multiprocessing\nfrom math import isqrt\nfrom time import time \n\ndef is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is a prime ...
trial_gpt4o_2
{ "original_instruction": "### Part 1: Concurrent Execution with Threading and Multiprocessing\n\n**Objective:** Implement a program demonstrating both thread-based and process-based parallelism to count prime numbers in a given range.\n\n#### Task\nWrite a Python program that does the following:\n1. **Define a funct...
0.648766
Docs: Python310_22570
C
[ "is_prime", "count_primes_in_range", "count_primes_with_threads", "count_primes_with_processes" ]
4
[ [ "count_primes_in_range", "is_prime" ], [ "count_primes_with_processes", "count_primes_in_range" ], [ "count_primes_with_threads", "count_primes_in_range" ] ]
3
[]
false
[]
false
pytest
true
[]
true
8984b628aa5bf7b35e6c4b01b4fcc3dbf74063d2
fa047dfb6ef42fe64705e4d65c7ab55a25090112
v1.0
complete
Docs
Docs: Python310_22848_C
import asyncio async def handle_client(reader, writer): """ Handle a client connection, reading the data from the client and echoing it back. """ pass async def start_echo_server(host, port): """ Start an asynchronous echo server that listens on the specified host and port, handles multiple client...
import asyncio async def handle_client(reader, writer): try: while True: data = await reader.read(100) if not data: break writer.write(data) await writer.drain() except Exception as e: print(f'Error: {e}') finally: writ...
import asyncio import pytest @pytest.fixture(scope="module") def event_loop(): loop = asyncio.get_event_loop() yield loop loop.close() @pytest.mark.asyncio async def test_echo_server(event_loop): host = 'localhost' port = 8889 server_task = event_loop.create_task(start_echo_server(host, port)...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "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, writer):\n try:\n while True:\n data = await reader.read(100)\n if not data:\n ...
trial_gpt4o_1
{ "original_instruction": "#### Objective\nDesign and implement an asynchronous network echo server using asyncio's event loop that handles multiple simultaneous client connections.\n\n#### Description\nYou are required to implement an echo server that listens on a specified host and port, handles multiple concurrent...
0.647412
Docs: Python310_22848
C
[ "handle_client", "start_echo_server" ]
2
[ [ "start_echo_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
false
[]
true
b9865e8895f4fd7d8384f7a3fe94682a5efcdbb1
40fbe34161d5c847e9f8c667d2388bcbe3a57f96
v1.0
complete
Docs
Docs: Python310_22139_C
import hashlib def hash_file(file_path: str, algorithm: str, salt: bytes = None, key: bytes = None, digest_size: int = None) -> str: """ Hash the contents of a file using the specified algorithm. Args: file_path (str): The path to the file. algorithm (str): The hashing algorithm to use (e....
import hashlib def hash_file(file_path: str, algorithm: str, salt: bytes = None, key: bytes = None, digest_size: int = None) -> str: try: with open(file_path, 'rb') as f: file_content = f.read() except FileNotFoundError: raise FileNotFoundError(f"No such file: {file_path}") ...
from solution import hash_file, verify_file_integrity import tempfile import os def create_temp_file(content): temp_file = tempfile.NamedTemporaryFile(delete=False) temp_file.write(content) temp_file.close() return temp_file.name def remove_temp_file(file_path): os.remove(file_path) def test_hash...
[ { "docstring": null, "function_declaration": "def hash_file(file_path, algorithm, salt=None, key=None, digest_size=None):", "function_name": "hash_file", "parameter_list": "(file_path, algorithm, salt=None, key=None, digest_size=None)" }, { "docstring": null, "function_declaration": "def...
[ 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 hashlib\n\ndef hash_file(file_path: str, algorithm: str, salt: bytes = None, key: bytes = None, digest_size: int = None) -> str:\n h = None\n if algorithm....
trial_gpt4o_2
{ "original_instruction": "### Secure File Hashing and Integrity Verification\n\nIn this programming assessment, you will implement a Python script that securely hashes the contents of a file and verifies its integrity. The solution will make use of the `hashlib` module for hashing and must be capable of handling dif...
0.666461
Docs: Python310_22139
C
[ "hash_file", "verify_file_integrity" ]
2
[ [ "verify_file_integrity", "hash_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
92cfcd1455d970a4cd819c17309e36c9e6bc5480
65c01514eaf359d870507b39410c0f27d689d4b2
v1.0
complete
Docs
Docs: Python310_22741_C
import uuid def generate_uuids() -> dict: """ Generates and returns a dictionary with UUIDs of versions 1, 3, 4, and 5. """ def is_valid_uuid(uuid_string: str) -> bool: """ Takes a string and returns True if the string is a valid UUID, otherwise returns False. """ def parse_uuid(uuid_string: ...
import uuid def generate_uuids() -> dict: """ Generates and returns a dictionary with UUIDs of versions 1, 3, 4, and 5. """ return { 1: uuid.uuid1(), 3: uuid.uuid3(uuid.NAMESPACE_DNS, 'example.com'), 4: uuid.uuid4(), 5: uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com') }...
from solution import generate_uuids, is_valid_uuid, parse_uuid import uuid def test_generate_uuids(): uuids = generate_uuids() assert isinstance(uuids, dict) assert len(uuids) == 4 assert 1 in uuids and uuids[1].version == 1 assert 3 in uuids and uuids[3].version == 3 assert 4 in uuids and uuid...
[ { "docstring": "Generates and returns a dictionary with UUIDs of versions 1, 3, 4, and 5.", "function_declaration": "def generate_uuids():", "function_name": "generate_uuids", "parameter_list": "()" }, { "docstring": "Takes a string and returns True if the string is a valid UUID, otherwise r...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import uuid\n\ndef generate_uuids() -> dict:\n \"\"\"\n Generates and returns a dictionary with UUIDs of versions 1, 3, 4, and 5.\n For versions 3 and 5, use t...
trial_gpt4o_1
{ "original_instruction": "### UUID Generation and Validation\n\n#### Problem Statement\n\nYou are tasked with creating a utility function that generates and validates various UUIDs using Python's `uuid` module. Specifically, you need to implement a function that:\n\n1. Generates a UUID of each specified version (1, ...
0.482841
Docs: Python310_22741
C
[ "generate_uuids", "is_valid_uuid", "parse_uuid" ]
3
[ [ "parse_uuid", "is_valid_uuid" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cd21c24ea39ea903b9404909ef4e1ffc9e30126b
a4e6eb393729f2045775828956b3876b954d7eac
v1.0
complete
Docs
Docs: Python310_22780_C
import warnings class MyCustomWarning(Warning): pass def sensitive_operation(): """ Issue a custom warning class 'MyCustomWarning'. """ # Your code to issue MyCustomWarning goes here def manage_warnings(): """ Manage warnings: - Ignore MyCustomWarning. - Convert RuntimeWarning to an error...
import warnings class MyCustomWarning(Warning): pass def sensitive_operation(): warnings.warn("This is a custom warning", MyCustomWarning) def manage_warnings(): with warnings.catch_warnings(record=True) as w: # Ignore MyCustomWarning warnings.filterwarnings("ignore", category=MyCustomWar...
import warnings from solution import MyCustomWarning, sensitive_operation, manage_warnings def test_sensitive_operation_warning_issued(): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("ignore", category=RuntimeWarning) # Ignore other warnings to focus on custom warning sens...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import warnings\n\nclass MyCustomWarning(Warning):\n pass\n\ndef sensitive_operation():\n warnings.warn(\"This is a custom warning\", MyCustomWarning)\n\ndef mana...
trial_gpt4o_0
{ "original_instruction": "### Warning Management and Custom Filters\n\nIn this exercise, you will demonstrate your understanding of Python's warnings module. Your task is to create a custom warning, issue that warning appropriately in a function, and manipulate how this warning is handled by using warning filters. S...
0.510782
Docs: Python310_22780
C
[ "sensitive_operation", "manage_warnings" ]
2
[ [ "manage_warnings", "sensitive_operation" ] ]
1
[]
false
[ "MyCustomWarning" ]
true
pytest
true
[]
true
eca1f5eb2376c214d4177a4ae81c97c6b40b4f6d
2f43dce568763f45ceabe9d938060de2b1a7f746
v1.0
complete
Docs
Docs: Python310_22674_C
import asyncio async def delayed_addition(fut: asyncio.Future, delay: int, a: int, b: int) -> None: """ Waits for `delay` seconds and sets the result of `fut` to be the sum of `a` and `b`. Args: fut (asyncio.Future): The future to set the result on. delay (int): The number of seconds to wait befor...
import asyncio async def delayed_addition(fut: asyncio.Future, delay: int, a: int, b: int) -> None: """ Waits for `delay` seconds and sets the result of `fut` to be the sum of `a` and `b`. """ await asyncio.sleep(delay) fut.set_result(a + b) async def delayed_multiplication(fut: asyncio.Future, de...
import asyncio import pytest from solution import delayed_addition, delayed_multiplication, async_pipeline @pytest.mark.asyncio async def test_delayed_addition(): fut = asyncio.Future() await delayed_addition(fut, 1, 2, 3) assert fut.result() == 5 @pytest.mark.asyncio async def test_delayed_multiplication...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def delayed_addition(fut: asyncio.Future, delay: int, a: int, b: int) -> None:\n \"\"\"\n Waits for `delay` seconds and sets the result of...
trial_gpt4o_0
{ "original_instruction": "**Question**: Implement and manage an asynchronous operation using `asyncio.Future`\n\n**Objective**:\nYou are required to implement an asynchronous function that performs a sequence of operations using `asyncio.Future`. This will test your understanding of futures, awaiting results, and sc...
0.524655
Docs: Python310_22674
C
[ "delayed_addition", "delayed_multiplication", "async_pipeline" ]
3
[ [ "async_pipeline", "delayed_addition" ], [ "async_pipeline", "delayed_multiplication" ] ]
2
[]
false
[]
false
pytest
true
[]
true
287defd43d7b41336028c8a0ab3d82664c8da67f
9c02b4930afb1809fab15aedde3a1c47281f26c5
v1.0
complete
Docs
Docs: Pytorch_23046_C
import torch from torch import autograd def custom_square(tensor: torch.Tensor) -> torch.Tensor: """ Implements the custom square operation.""" pass def register_custom_op(): """ Registers the custom operator with PyTorch.""" pass def test_custom_op() -> (torch.Tensor, bool): """ Tests the custom...
import torch from torch import autograd # Step 1: Define the custom operator def custom_square(tensor): return tensor * tensor # Step 2: Register the custom operator def register_custom_op(): my_lib = torch.library.Library("my_custom_lib", "DEF") # Register our custom_square operator my_lib.define("cu...
from solution import custom_square, register_custom_op, test_custom_op import pytest import torch from torch import autograd def test_custom_square_values(): # Test custom_square on a known tensor tensor = torch.tensor([1.0, 2.0, -3.0], requires_grad=True) result = custom_square(tensor) expected_result...
[ { "docstring": null, "function_declaration": "def custom_square(tensor):", "function_name": "custom_square", "parameter_list": "(tensor)" }, { "docstring": null, "function_declaration": "def register_custom_op():", "function_name": "register_custom_op", "parameter_list": "()" }...
[ 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 torch\nfrom torch import autograd\n\n# Step 1: Define the custom operator\ndef custom_square(tensor):\n return tensor * tensor\n\n# Step 2: Register the custo...
trial_gpt4o_0
{ "original_instruction": "### PyTorch Custom Operator Implementation and Testing\n\nIn this problem, you are required to implement a custom PyTorch operator and test its functionality, including gradient checking. We'll guide you through the steps to ensure that your implementation covers the required aspects.\n\n##...
0.510376
Docs: Pytorch_23046
C
[ "custom_square", "register_custom_op", "test_custom_op" ]
3
[ [ "register_custom_op", "custom_square" ], [ "test_custom_op", "custom_square" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
b8d69313e3b7962fc8c980ed143b8ea531ab5bec
5c5e67341b6d03f70ad1a8580f469e6f21815e4f
v1.0
complete
Docs
Docs: Python310_22765_C
from typing import List, Dict import ipaddress def categorize_ip_addresses(ip_addresses: List[str], subnet_mask: str) -> Dict[str, List[str]]: """ Categorize the given IP addresses into 'private' or 'public' based on the subnet mask. Args: ip_addresses (List[str]): A list of IP addresses (strings...
from typing import List, Dict import ipaddress def is_private_ip(ip: str) -> bool: """ Determine if the given IP address is private. """ ip_addr = ipaddress.ip_address(ip) return ip_addr.is_private def categorize_ip_addresses(ip_addresses: List[str], subnet_mask: str) -> Dict[str, List[str]]: ...
from solution import categorize_ip_addresses def test_basic_categorization(): ip_addresses = [ "192.168.1.10", "192.168.1.20", "10.0.0.1", "8.8.8.8", "2001:db8::1", "fc00::1" ] subnet_mask = "192.168.1.0/24" result = categorize_ip_addresses(ip_addresses, subnet_mask) assert result =...
[ { "docstring": "Determine if the given IP address is private.", "function_declaration": "def is_private_ip(ip):", "function_name": "is_private_ip", "parameter_list": "(ip)" }, { "docstring": "Categorize IP addresses into 'private' or 'public' based on the subnet mask.", "function_declara...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Dict\nimport ipaddress\n\ndef categorize_ip_addresses(ip_addresses: List[str], subnet_mask: str) -> Dict[str, List[str]]:\n categorized_ips ...
trial_gpt4o_2
{ "original_instruction": "#### Objective\nImplement a function that takes a list of IP addresses and a subnet mask, then returns a new list categorizing the IP addresses into 'private' or 'public' based on the subnet mask.\n\n#### Description\nWrite a function `categorize_ip_addresses(ip_addresses: List[str], subnet...
0.649632
Docs: Python310_22765
C
[ "is_private_ip", "categorize_ip_addresses" ]
2
[ [ "categorize_ip_addresses", "is_private_ip" ] ]
1
[]
false
[]
false
pytest
true
[]
true
136adf8675bfe0d2e743aa9027cc5a47ad0341a8
95c9f1b1f1a330a64b31110894fe7e3b0fe4385a
v1.0
complete
Docs
Docs: Python310_22552_C
import asyncio async def handle_echo(reader, writer): """Handle incoming data and echo it back to the sender.""" data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message} from {addr}") print(f"Send: {message}") writer.wri...
import asyncio import platform async def handle_echo(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message} from {addr}") print(f"Send: {message}") writer.write(data) await writer.drain() print("C...
import asyncio import socket import pytest from solution import run_echo_server @pytest.fixture async def start_server(): server_host = '127.0.0.1' server_port = 8888 server_task = asyncio.create_task(run_echo_server(server_host, server_port)) # Give a moment to ensure the server starts await...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\n\nasync def handle_echo(reader, writer):\n data = await reader.read(100)\n message = data.decode()\n addr = writer.get_extra_i...
trial_gpt4o_0
{ "original_instruction": "### Question: Cross-Platform AsyncIO Event Loop Management\n\nThe `asyncio` module in Python provides a framework for writing applications that incorporate asynchronous I/O operations. However, the functionality and support for different methods in `asyncio` can vary significantly across di...
0.646822
Docs: Python310_22552
C
[ "handle_echo", "run_echo_server" ]
2
[ [ "run_echo_server", "handle_echo" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0b20fcaa9308dd94e34f5f3295f2e3cd27520042
0f3601099193fcc4306fbfe8995061075b864cb7
v1.0
complete
Docs
Docs: Python310_22617_C
import contextvars import asyncio # Define a ContextVar to hold the context identifier context_id_var = contextvars.ContextVar('context_id', default='default') def log_message(message): """ Logs the message along with the current context identifier. If no context identifier is set, it uses 'default'. ...
import contextvars import asyncio # Define a ContextVar to hold the context identifier context_id_var = contextvars.ContextVar('context_id', default='default') def log_message(message): """ Logs the message along with the current context identifier. If no context identifier is set, it uses 'default'. ...
from solution import log_message, set_context_identifier, get_context_identifier, reset_context_identifier, async_log_simulation import asyncio def test_log_message(capfd): log_message("Hello, World!") captured = capfd.readouterr() assert captured.out.strip() == "Context[default]: Hello, World!" def test_...
[ { "docstring": "Logs the message along with the current context identifier.\nIf no context identifier is set, it uses 'default'.", "function_declaration": "def log_message(message):", "function_name": "log_message", "parameter_list": "(message)" }, { "docstring": "Sets the context identifier...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextvars\nimport asyncio\n\n# Define a ContextVar to hold the context identifier\ncontext_id_var = contextvars.ContextVar('context_id', default='default')\n\n...
trial_gpt4o_0
{ "original_instruction": "#### Problem Statement\n\nYou have been tasked with implementing a context-aware logging system that uses the `contextvars` package to manage context-local state.\n\nYou need to implement the following functions:\n\n1. `log_message`:\n - **Input**: A string `message`.\n - **Output**: No...
0.460327
Docs: Python310_22617
C
[ "log_message", "set_context_identifier", "get_context_identifier", "reset_context_identifier", "async_log_simulation", "log_with_context" ]
6
[ [ "async_log_simulation", "log_with_context" ], [ "log_with_context", "log_message" ], [ "log_with_context", "set_context_identifier" ] ]
3
[]
false
[]
false
pytest
true
[]
true
6d08f62ade3176a6d012f9d861b5b57e13b47e96
b6c5a97b2cc795e03a9d528fa73ef77c2f22b111
v1.0
complete
Docs
Docs: Pytorch_22636_C
import os def set_mps_environment_variable(env_vars): """ Sets environment variables for the MPS backend in PyTorch. Args: env_vars (dict): Dictionary where keys are environment variable names and values are the corresponding settings. >>> test_env_vars = { ... ...
import os def set_mps_environment_variable(env_vars): """ Sets environment variables for the MPS backend in PyTorch. Args: env_vars (dict): Dictionary where keys are environment variable names and values are the corresponding settings. Returns: None """ f...
import os import pytest from solution import set_mps_environment_variable def test_set_mps_environment_variable(): test_env_vars = { "PYTORCH_MPS_FAST_MATH": "1", "PYTORCH_MPS_DEBUG": "2" } # Setting the environment variables set_mps_environment_variable(test_env_vars) # A...
[ { "docstring": "Sets environment variables for the MPS backend in PyTorch.\n\nArgs:\nenv_vars (dict): Dictionary where keys are environment variable names \n and values are the corresponding settings.\n\nReturns:\nNone", "function_declaration": "def set_mps_environment_variable(env_vars):", ...
[ 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 os\nimport torch\nimport time\n\ndef set_mps_environment_variable(env_vars):\n \"\"\"\n Sets the given environment variables for the PyTorch MPS backend.\n...
trial_gpt4o_9
{ "original_instruction": "**Objective:** Implement a utility function to manage MPS-related PyTorch environment variables and demonstrate its effect on a PyTorch computation using the MPS backend.\n\n#### Background\n\nPyTorch supports running models on Apple devices using Metal Performance Shaders (MPS). Various en...
0.460811
Docs: Pytorch_22636
C
[ "set_mps_environment_variable", "mps_matrix_multiplication_demo" ]
2
[ [ "mps_matrix_multiplication_demo", "set_mps_environment_variable" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
64ca69c4cdc1166a672e15a2f5c2bbe0da9ed96b
c75ea917a58895315d4647ed1cf975ce54c3de7e
v1.0
complete
Docs
Docs: Python310_22768_C
import asyncio from typing import Tuple # In-memory key-value store kv_store = {} async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): """Handle incoming client connections and process commands. Args: reader (asyncio.StreamReader): The stream reader to read data from t...
import asyncio # In-memory key-value store kv_store = {} async def handle_client(reader, writer): while True: data = await reader.read(100) if not data: break message = data.decode().strip() response = process_command(message) writer.write(response.encode()) ...
import pytest import asyncio from asyncio import StreamReader, StreamWriter async def mock_client(server, command): reader, writer = await asyncio.open_connection('127.0.0.1', 9999) writer.write(command.encode()) await writer.drain() data = await reader.read(100) writer.close() await writer.wai...
[ { "docstring": null, "function_declaration": "def process_command(command):", "function_name": "process_command", "parameter_list": "(command)" } ]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "# server.py\n\nimport asyncio\n\nclass KeyValueStore:\n def __init__(self):\n self.store = {}\n\n def process_command(self, command):\n parts = comm...
trial_gpt4o_2
{ "original_instruction": "### Asyncio Streams: Create a Key-Value Store\n\nCreate an asynchronous TCP server and client using the `asyncio` streams module in Python. The server will act as a simple in-memory key-value store that supports basic commands (SET, GET, DELETE). The client will communicate with the server ...
0.506536
Docs: Python310_22768
C
[ "handle_client", "process_command", "main" ]
3
[ [ "handle_client", "process_command" ] ]
1
[]
false
[]
false
pytest
false
[]
true
4986df7dc9bdb3c381568546b064fff20e881a25
141ca10f75c7ccb0ae2f03b829832613d7b2a14a
v1.0
complete
Docs
Docs: Python310_23227_C
import contextlib @contextlib.contextmanager def open_file(file_path, mode): """ Context manager to safely open and close a file. Args: - file_path: Path to the file. - mode: Mode in which to open the file. Yields: - file object """ file = None try: file = open...
import contextlib @contextlib.contextmanager def open_file(file_path, mode): """ Context manager to safely open and close a file. Args: - file_path: Path to the file. - mode: Mode in which to open the file. Yields: - file object """ file = None try: file = open...
import os import pytest from solution import safe_file_operation def test_safe_file_operation_write(tmpdir): test_file = os.path.join(tmpdir, "test.txt") content = "Hello, world!" result = safe_file_operation(test_file, "write", content) assert result == f"Content written to {test_file}" ...
[ { "docstring": "Context manager to safely open and close a file.\n\nArgs:\n- file_path: Path to the file.\n- mode: Mode in which to open the file.\n\nYields:\n- file object", "function_declaration": "def open_file(file_path, mode):", "function_name": "open_file", "parameter_list": "(file_path, mode)...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from contextlib import contextmanager\n\n@contextmanager\ndef open_file_safe(file_path, mode):\n file = None\n try:\n file = open(file_path, mode)\n ...
trial_gpt4o_2
{ "original_instruction": "Create a function `safe_file_operation` that safely performs reading from or writing to a file based on given parameters, ensuring that the file is properly closed after the operation, even if an error occurs. To implement this function, you must utilize the `contextlib` module's `contextma...
0.517039
Docs: Python310_23227
C
[ "open_file", "safe_file_operation" ]
2
[ [ "safe_file_operation", "open_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
31c9bdff0e2027f2be365e70ae23165ecabbde57
c1103daba2b7e9a0388f9dd28b65e1a4d2cfce24
v1.0
complete
Docs
Docs: Python310_23134_C
import os def create_directory(directory_name): """Creates a new directory with the given name.""" pass def write_process_info(file_path): """Writes current process ID, parent process ID, and environment variables to the specified file.""" pass def append_new_var_to_file(file_path, new_var_value): ...
import os import sys def create_directory(directory_name): try: os.mkdir(directory_name) except FileExistsError: pass def write_process_info(file_path): with open(file_path, 'w') as file: pid = os.getpid() ppid = os.getppid() env_vars = os.environ file.writ...
import os import pytest from solution import main, create_directory, write_process_info, append_new_var_to_file, child_process def test_create_directory(): dir_name = "test_dir" create_directory(dir_name) assert os.path.isdir(dir_name) == True os.rmdir(dir_name) def test_write_process_info(tmp_pat...
[ { "docstring": null, "function_declaration": "def create_directory(directory_name):", "function_name": "create_directory", "parameter_list": "(directory_name)" }, { "docstring": null, "function_declaration": "def write_process_info(file_path):", "function_name": "write_process_info",...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport sys\n\ndef create_directory(directory_name):\n if not os.path.exists(directory_name):\n os.mkdir(directory_name)\n\ndef write_process_info(f...
trial_gpt4o_2
{ "original_instruction": "#### **File System and Process Management in Python**\n\n**Objective**: Implement a Python script that performs the following tasks leveraging the `os` module.\n\n1. **File Creation and Writing**:\n - Create a new directory named `test_dir`.\n - Inside `test_dir`, create a file named ...
0.568403
Docs: Python310_23134
C
[ "create_directory", "write_process_info", "append_new_var_to_file", "child_process", "main" ]
5
[ [ "child_process", "append_new_var_to_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
381e8d547b680786000c5c139431bd482b13e448
efe3d5956722d2209fb7d4250274c2f5aa9ceca2
v1.0
complete
Docs
Docs: Seaborn_23596_C
def visualize_health_expenditure(year_start: int, year_end: int) -> None: """Visualizes health expenditure and life expectancy from healthexp dataset within given years. Parameters: - year_start (int): the starting year for filtering the healthexp dataset. - year_end (int): the ending year for filterin...
import seaborn as sns import matplotlib.pyplot as plt def load_healthexp_dataset(): """ Loads the healthexp dataset from seaborn. """ healthexp = sns.load_dataset('healthexp') return healthexp def visualize_health_expenditure(year_start: int, year_end: int) -> None: """ Visualizes health e...
import pytest def test_load_healthexp_dataset(): data = load_healthexp_dataset() assert not data.empty, "Dataset should not be empty" assert 'Year' in data.columns, "Dataset should contain 'Year' column" assert 'Spending_USD' in data.columns, "Dataset should contain 'Spending_USD' column" assert 'L...
[ { "docstring": "Loads the healthexp dataset from seaborn.", "function_declaration": "def load_healthexp_dataset():", "function_name": "load_healthexp_dataset", "parameter_list": "()" }, { "docstring": "Visualizes health expenditure and life expectancy from healthexp dataset within given year...
[ 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 seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef load_healthexp_dataset():\n \"\"\"\n Loads the healthexp dataset from seaborn.\n \"\"\"\n heal...
trial_gpt4o_0
{ "original_instruction": "### Seaborn Coding Assessment\n\n#### Objective\nDemonstrate your understanding and proficiency in using the seaborn library for data visualization by implementing and customizing a plot based on given specifications.\n\n#### Problem Statement\nImplement a Python function using seaborn that...
0.498791
Docs: Seaborn_23596
C
[ "load_healthexp_dataset", "visualize_health_expenditure" ]
2
[ [ "visualize_health_expenditure", "load_healthexp_dataset" ] ]
1
[]
false
[]
false
pytest
false
[ "matplotlib", "seaborn" ]
false
48fc6bcad113b73330978bce9692f83347a4c32f
7904ab1020c0132229c33bd6a20e258e113ea3e7
v1.0
complete
Docs
Docs: Python310_23279_C
import gc def function_1(): """ function_1 calls function_2 and function_3. """ # marker for function entry (DTrace/SystemTap) function_2() function_3() # marker for function return (DTrace/SystemTap) def function_2(): """ function_2 performs a basic arithmetic operation and incl...
import gc def function_1(): function_2() function_3() def function_2(): result = 1 + 1 print(f"function_2 result: {result}") def function_3(): try: raise ValueError("An error occurred in function_3") except ValueError as e: print(e) if __name__ == "__main__": function_1()...
from solution import function_1, function_2, function_3 def test_function_1_calls_functions(): try: function_1() assert True # If no exception, test passes except Exception: assert False # If an exception occurs, test fails def test_function_2_arithmetic_operation(): result = fun...
[ { "docstring": null, "function_declaration": "def function_1():", "function_name": "function_1", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def function_2():", "function_name": "function_2", "parameter_list": "()" }, { "docstring": null, "...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import gc\n\ndef function_1():\n function_2()\n function_3()\n\ndef function_2():\n result = 42 / 2 # Perform a basic arithmetic operation\n print(f\"The r...
trial_gpt4o_1
{ "original_instruction": "### Advanced Python Tracing with SystemTap\n\n#### Objective\nCreate a Python script that can be monitored using SystemTap. You will utilize the pre-defined static markers available in CPython to trace function calls and garbage collection cycles in your script.\n\n#### Task\n1. Write a Pyt...
0.570014
Docs: Python310_23279
C
[ "function_1", "function_2", "function_3" ]
3
[ [ "function_1", "function_2" ], [ "function_1", "function_3" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c4028a4e4490cd343517025b1f4ea8c23547a4a5
20d16785fdedff583156c752b45c2660ea862104
v1.0
complete
Docs
Docs: Python310_23531_C
import asyncio import aiohttp from bs4 import BeautifulSoup from typing import List, Dict async def fetch_urls(urls: List[str]) -> Dict[str, List[str]]: """ Fetch and process multiple URLs concurrently to get hyperlinks from each. This should handle errors gracefully and not disrupt the entire process for a si...
import asyncio import aiohttp from bs4 import BeautifulSoup from typing import List, Dict async def fetch_content(session: aiohttp.ClientSession, url: str) -> str: """ Fetches the content of a URL. """ try: async with session.get(url) as response: return await response.text() ex...
import pytest import asyncio from solution import fetch_urls @pytest.mark.asyncio async def test_fetch_urls_single_page(): urls = ["https://example.com"] result = await fetch_urls(urls) assert "https://example.com" in result assert isinstance(result["https://example.com"], list) @pytest.mark.asyncio a...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom aiohttp import ClientSession\nfrom typing import List, Dict\nfrom bs4 import BeautifulSoup\n\nasync def fetch_content(url: str, session: ClientSess...
trial_gpt4o_2
{ "original_instruction": "## Coding Assessment Question\n\n### Background:\nThe `asyncio` library in Python allows for writing concurrent programs using the `async/await` syntax. This capability is particularly useful for IO-bound operations where you can avoid blocking the main thread while awaiting results (such a...
0.740832
Docs: Python310_23531
C
[ "fetch_content", "parse_links", "fetch_and_parse", "fetch_urls" ]
4
[ [ "fetch_and_parse", "fetch_content" ], [ "fetch_and_parse", "parse_links" ], [ "fetch_urls", "fetch_and_parse" ] ]
3
[]
false
[]
false
pytest
true
[ "aiohttp", "bs4" ]
false
bcfd54141b96589cf1d03c34d0857bf7da15991c
4e00538eddfbd18cb14f66c4fc2dbf0c0ba9f94a
v1.0
complete
Docs
Docs: Python310_23397_C
import pickle import sqlite3 from typing import List class Book: def __init__(self, title: str, author: str, isbn: str, year: int, genre: str): """Initialize the Book object with title, author, isbn, year, and genre attributes""" self.title = title self.author = author self.isbn = i...
import pickle import sqlite3 from typing import List # Define the Book class with necessary attributes class Book: def __init__(self, title: str, author: str, isbn: str, year: int, genre: str): self.title = title self.author = author self.isbn = isbn self.year = year self.ge...
from solution import Book, serialize_book, deserialize_book, store_book, retrieve_books def test_book_serialization(): book = Book(title="Test Book", author="John Doe", isbn="1234567890", year=2023, genre="Test") serialized = serialize_book(book) deserialized = deserialize_book(serialized) assert ...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sqlite3\nimport pickle\nfrom typing import List\n\nclass Book:\n def __init__(self, title: str, author: str, isbn: str, year: int, genre: str):\n self....
trial_gpt4o_1
{ "original_instruction": "#### Objective:\nYour task is to create a Python program that demonstrates the ability to serialize complex data structures, store them persistently in a database, and retrieve and deserialize them efficiently.\n\n#### Problem Statement:\nYou are required to implement a library management s...
0.532758
Docs: Python310_23397
C
[ "serialize_book", "deserialize_book", "store_book", "retrieve_books" ]
4
[ [ "retrieve_books", "deserialize_book" ], [ "store_book", "serialize_book" ] ]
2
[]
false
[ "Book" ]
true
pytest
true
[]
true
11d9ffd0407785523a79d1b082f6d7066b809bd9
d1877ada2d00f3cca171546748939cb0104111de
v1.0
complete
Docs
Docs: Seaborn_23511_C
import seaborn as sns import pandas as pd import matplotlib.pyplot as plt sns.set_theme(style="ticks") def create_facetgrid_histogram(df): """ Create a FacetGrid to show the distribution of purchase_amount faceted by age_group. Use histograms to visualize the distributions. Customize the grid to have each sub...
import seaborn as sns import pandas as pd import matplotlib.pyplot as plt import numpy as np sns.set_theme(style="ticks") def create_facetgrid_histogram(df): g = sns.FacetGrid(df, col="age_group", height=4, aspect=1.5) g.map(sns.histplot, "purchase_amount", kde=False) g.add_legend() plt.show() def cr...
from solution import create_facetgrid_histogram, create_pairgrid_relationship, create_custom_facetgrid import pandas as pd def test_create_facetgrid_histogram(): data = { "customer_id": [1, 2, 3, 4], "purchase_amount": [100, 150, 200, 250], "satisfaction_level": [2, 3, 4, 5], "age_g...
[ { "docstring": null, "function_declaration": "def create_facetgrid_histogram(df):", "function_name": "create_facetgrid_histogram", "parameter_list": "(df)" }, { "docstring": null, "function_declaration": "def create_pairgrid_relationship(df):", "function_name": "create_pairgrid_relat...
[ 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 pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Set the theme for seaborn\nsns.set_theme(style=\"ticks\")\n\ndef cr...
trial_gpt4o_2
{ "original_instruction": "Advanced Data Visualization with Seaborn\n\n#### Problem Statement\n\nYou are provided with a dataset containing information about customers' purchases and their satisfaction levels at a retail store. You need to use the seaborn library to create several visualizations that will help in und...
0.748393
Docs: Seaborn_23511
C
[ "create_facetgrid_histogram", "create_pairgrid_relationship", "custom_plot", "create_custom_facetgrid" ]
4
[ [ "create_custom_facetgrid", "custom_plot" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "pandas", "seaborn" ]
false
f78c14c31d89bc81c02eb34885334a80562e975c
ec600f99fffc6da4b9eaa6f9c338f506a3df00fa
v1.0
complete
Docs
Docs: Pandas_23520_C
def next_ten_business_days(start_date: str, region: str) -> list: """ Given a start date and a region, return the next 10 business days for the given region. Parameters: start_date (str): The starting date in the format 'YYYY-MM-DD'. region (str): The region for which to compute the business da...
import pandas as pd from pandas.tseries.holiday import USFederalHolidayCalendar from pandas.tseries.offsets import CustomBusinessDay from datetime import datetime # Function to get specific holidays for regions def get_region_holidays(region): if region == 'US': holidays = [ pd.Timestamp('2023-...
from solution import next_ten_business_days def test_next_ten_business_days_us_case(): result = next_ten_business_days('2023-11-22', 'US') expected = ['2023-11-22', '2023-11-24', '2023-11-27', '2023-11-28', '2023-11-29', '2023-11-30', '2023-12-01', '2023-12-04', '2023-12-05', '2023-12-06'] assert result ==...
[ { "docstring": null, "function_declaration": "def get_region_holidays(region):", "function_name": "get_region_holidays", "parameter_list": "(region)" }, { "docstring": null, "function_declaration": "def next_ten_business_days(start_date, region):", "function_name": "next_ten_business...
[ 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\nfrom pandas.tseries.holiday import (\n AbstractHolidayCalendar, Holiday,\n USFederalHolidayCalendar, nearest_workday,\n)\nfrom pandas.tseries...
trial_gpt4o_9
{ "original_instruction": "You are tasked with analyzing business date offsets for a company that operates on a global scale. The company has different working calendars for different regions, which include varying business days and holidays. Your task is to implement a function that computes the next 10 business day...
0.709593
Docs: Pandas_23520
C
[ "get_region_holidays", "next_ten_business_days" ]
2
[ [ "next_ten_business_days", "get_region_holidays" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas" ]
false
f8e06f6065e28805310807d5b58c4b20f05f0199
ea2d9c7088426529631b70db90229b2a4d970fc9
v1.0
complete
Docs
Docs: Python310_23605_C
import _thread import time class BankAccount: def __init__(self, balance: int): """Initializes the bank account with a given balance.""" def deposit(self, amount: int): """Deposits the specified amount into the bank account.""" def withdraw(self, amount: int): """Withdraws...
import _thread import time class BankAccount: def __init__(self, balance: int): self.balance = balance self.lock = _thread.allocate_lock() def deposit(self, amount: int): with self.lock: self.balance += amount def withdraw(self, amount: int): ...
from solution import BankAccount, process_transactions, simulate_bank_tellers def test_bank_account_operations(): account = BankAccount(1000) # Test deposit account.deposit(200) assert account.get_balance() == 1200 # Test withdraw with sufficient balance account.withdraw(600) asse...
[]
[ 0, 0, 0, 1, 1, 1, 1, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import _thread\nimport time\n\nclass BankAccount:\n def __init__(self, balance: int):\n self.balance = balance\n self.lock = _thread.allocate_lock()\n ...
trial_gpt4o_8
{ "original_instruction": "You are tasked with creating a multi-threaded Python program using the `_thread` module. Your program will simulate a banking system where multiple threads represent different bank tellers handling transactions simultaneously. Each teller will process a list of transactions that include dep...
0.505751
Docs: Python310_23605
C
[ "process_transactions", "simulate_bank_tellers" ]
2
[ [ "simulate_bank_tellers", "process_transactions" ] ]
1
[]
false
[ "BankAccount" ]
true
pytest
true
[]
true
bbf808d8ff06301340ccd0955730fae455ad56af
27282c1193a7bb27f484bfa745e4e8bcbc44a11d
v1.0
complete
Docs
Docs: Pytorch_23841_C
import torch import timeit from torch import Tensor from typing import List, Tuple @torch.jit.script def compute_y(x: Tensor) -> Tensor: """ Compute matrix multiplication with a random matrix. >>> y = compute_y(torch.randn(512, 512)) """ w_y = torch.randn(x.size(1), x.size(1)) return torch.mm(x, w_...
import torch import timeit from torch import Tensor from typing import List, Tuple @torch.jit.script def compute_y(x: Tensor) -> Tensor: w_y = torch.randn(x.size(1), x.size(1)) return torch.mm(x, w_y) @torch.jit.script def compute_z(x: Tensor) -> Tensor: w_z = torch.randn(x.size(1), x.size(1)) ret...
import torch import pytest from solution import optimized_matrix_multiplication def test_optimized_matrix_multiplication(): x = torch.randn(512, 512) max_threads = 4 results = optimized_matrix_multiplication(x, max_threads) # Verify the structure of results assert isinstance(results, list) ass...
[ { "docstring": null, "function_declaration": "def compute_y(x):", "function_name": "compute_y", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def compute_z(x):", "function_name": "compute_z", "parameter_list": "(x)" }, { "docstring": null, "...
[ 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 torch\nimport timeit\nfrom torch import Tensor\nfrom typing import List, Tuple\n\n@torch.jit.script\ndef compute_y(x: Tensor) -> Tensor:\n # assuming x is a s...
trial_gpt4o_7
{ "original_instruction": "### Question\n\nYou are given a PyTorch model that performs matrix multiplication with large tensors. To optimize performance, you need to implement a function that:\n1. Performs matrix multiplication in parallel using TorchScript.\n2. Tunes the number of intra-op threads to find the optima...
0.557519
Docs: Pytorch_23841
C
[ "compute_y", "compute_z", "optimized_matrix_multiplication" ]
3
[ [ "optimized_matrix_multiplication", "compute_y" ], [ "optimized_matrix_multiplication", "compute_z" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
bf8f3a78a5a5980e186a28aa4e0e3c349e153a4b
3c27465503b4d227d597c1440d74033cefe34d7d
v1.0
complete
Docs
Docs: Seaborn_23751_C
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd def load_sample_data(): """ Load the built-in mpg dataset from seaborn. Returns: DataFrame: The mpg dataset. """ pass def generate_palette(num_colors, start=0, rot=0.5, gamma=1.0, hue=1.0, dark=0, light=1.0, reverse=Fals...
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd def load_sample_data(): """ Load the built-in mpg dataset from seaborn. Returns: DataFrame: The mpg dataset. """ return sns.load_dataset("mpg") def generate_palette(num_colors, start=0, rot=0.5, gamma=1.0, hue=1...
import pytest from solution import load_sample_data, generate_palette, visualize_data, main_visualization def test_load_sample_data(): data = load_sample_data() assert isinstance(data, pd.DataFrame) assert not data.empty expected_columns = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'a...
[ { "docstring": "Load the built-in mpg dataset from seaborn.\n\nReturns:\n DataFrame: The mpg dataset.", "function_declaration": "def load_sample_data():", "function_name": "load_sample_data", "parameter_list": "()" }, { "docstring": "Generate a cubehelix palette based on the provided para...
[ 0, 0, 0, 0, 1, 1, 0, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef load_sample_data():\n \"\"\"\n Load the built-in 'mpg' dataset from seaborn.\n \n Returns:\n ...
trial_gpt4o_7
{ "original_instruction": "#### Objective\nAssess students' proficiency in using seaborn's `cubehelix_palette` function to generate and customize color palettes for data visualization.\n\n#### Problem Statement\nYou are given a dataset of car specifications, and you need to visualize various aspects of this data usin...
0.650528
Docs: Seaborn_23751
C
[ "load_sample_data", "generate_palette", "visualize_data", "main_visualization" ]
4
[ [ "main_visualization", "generate_palette" ], [ "main_visualization", "load_sample_data" ], [ "main_visualization", "visualize_data" ] ]
3
[]
false
[]
false
pytest
true
[ "matplotlib", "pandas", "seaborn" ]
false
1c40611b6fa16f56676b5b69b69f8f1ec5743a55
59a37158a49ee9a1e4021eb9d8086aececd47b23
v1.0
complete
Docs
Docs: Python310_23922_C
import _thread import time def thread_worker(counter_lock, increments, counter_list, index): """ Worker function for each thread. Increments the value in the counter_list by 1 for the specified number of increments in a thread-safe manner using the provided lock. """ pass def main_threaded_counte...
import _thread import time def thread_worker(counter_lock, increments, counter_list, index): """ Worker function for each thread. Increments the value in the counter_list by 1 for the specified number of increments in a thread-safe manner using the provided lock. """ for _ in range(increments): ...
from solution import main_threaded_counter def test_main_threaded_counter_single_thread(): assert main_threaded_counter(1, 500) == 500 def test_main_threaded_counter_multiple_threads(): assert main_threaded_counter(5, 1000) == 5000 def test_main_threaded_counter_large_number_threads(): assert main_thread...
[ { "docstring": "Worker function for each thread. Increments the value in the counter_list by 1 for \nthe specified number of increments in a thread-safe manner using the provided lock.", "function_declaration": "def thread_worker(counter_lock, increments, counter_list, index):", "function_name": "thread...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import _thread\nfrom time import sleep\n\ndef thread_worker(counter_lock, increments, counter_list, index):\n \"\"\"\n Increments the value in counter_list[index]...
trial_gpt4o_2
{ "original_instruction": "#### Title: Implementing a Multi-threaded Counter with Synchronization\n\n#### Objective:\nDemonstrate your understanding of creating, managing, and synchronizing multiple threads using the `_thread` module in Python.\n\n#### Problem Statement:\n\nYou are required to implement a multi-threa...
0.590402
Docs: Python310_23922
C
[ "thread_worker", "main_threaded_counter" ]
2
[ [ "main_threaded_counter", "thread_worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7821f4c58690cf931e71d8592a6a23a93481ba1c
01e3136d6ca353350053854aa7bb9ac1dcd3720f
v1.0
complete
Docs
Docs: Python310_23743_C
import asyncio from typing import List, Tuple async def delayed_result(value: int, delay_time: int) -> int: """ Asynchronously waits for delay_time seconds and then returns the given value. :param value: The value to return after the delay. :param delay_time: The time (in seconds) to wait before ...
import asyncio from typing import List, Tuple async def delayed_result(value: int, delay_time: int) -> int: """ Asynchronously waits for delay_time seconds and then returns the given value. :param value: The value to return after the delay. :param delay_time: The time (in seconds) to wait before r...
import asyncio from solution import delayed_result, run_tasks async def test_delayed_result(): result = await delayed_result(5, 1) assert result == 5 result = await delayed_result(10, 2) assert result == 10 async def test_run_tasks(): input_tasks = [(10, 2), (20, 1), (30, 3)] results = await ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "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 delayed_result(value: int, delay_time: int) -> int:\n \"\"\"\n Asynchronously wait for delay_time seco...
trial_gpt4o_1
{ "original_instruction": "### Question: Implement an Asynchronous Task Scheduler\n\n#### Objective:\nYour task is to implement a simple asynchronous task scheduler in Python that can run multiple async tasks and gather their results once they are completed.\n\n#### Task Details:\n1. Implement an `async` function nam...
0.723423
Docs: Python310_23743
C
[ "delayed_result", "run_tasks" ]
2
[ [ "run_tasks", "delayed_result" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0c62aaf2966f1999abb4adf06a5856399e85ccfa
1eb279736890bc1844c80568fef2fafc5fc58520
v1.0
complete
Docs
Docs: Python310_23843_C
import warnings import threading # Custom warning definition class CustomWarning(Warning): pass # Function to process data and issue warnings def process_data(data): """Processes a list of integers and issues a CustomWarning for each negative integer. Args: data (list): List of integers. >>> ...
import warnings import threading # Custom warning definition class CustomWarning(Warning): pass # Function to process data and issue warnings def process_data(data): for value in data: if value < 0: warnings.warn(f"Negative value found: {value} in data: {data}", CustomWarning) # Function ...
from solution import CustomWarning, process_data, handle_warnings, ThreadSafeProcessor def test_process_data_no_warnings(): data = [1, 2, 3] with warnings.catch_warnings(record=True) as caught_warnings: warnings.simplefilter("always", CustomWarning) process_data(data) assert len(caught_...
[]
[ 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 warnings\nimport threading\n\n# Custom warning definition\nclass CustomWarning(Warning):\n pass\n\n# Function to process data and issue warnings\ndef process_...
trial_gpt4o_0
{ "original_instruction": "#### Objective:\nThis question aims to assess your understanding of the Python `warnings` module and your ability to manage and control warnings in a specific scenario while ensuring thread safety.\n\n#### Problem Statement:\nYou are required to create a Python program that simulates a util...
0.537168
Docs: Python310_23843
C
[ "process_data", "handle_warnings" ]
2
[ [ "handle_warnings", "process_data" ] ]
1
[ "process_data" ]
false
[ "CustomWarning", "ThreadSafeProcessor" ]
true
pytest
true
[]
true
825d7ff187d3137ceccaa180b37d494bc0600a43
2b97c5e255be48eb476c3a2ec18538c3eff973c4
v1.0
complete
Docs
Docs: Python310_23425_C
import os def read_from_fd(fd: int, n: int) -> str: """Read up to n characters (or bytes) from the file descriptor fd. If n is -1, read an entire line. If n is 0, return an empty string. Handle file reading errors gracefully by raising an appropriate exception. """ def write_to_fd(fd: int, data: str) ...
import os def read_from_fd(fd: int, n: int) -> str: try: if n == 0: return "" elif n == -1: return os.read(fd, os.fstat(fd).st_size).decode() else: return os.read(fd, n).decode() except Exception as e: raise IOError(f"Error reading from file d...
import os import tempfile import pytest from solution import read_from_fd, write_to_fd, dup_fd, close_fd, process_file def test_read_from_fd(): temp_file = tempfile.TemporaryFile() fd = temp_file.fileno() os.write(fd, b"Hello, World!") os.lseek(fd, 0, os.SEEK_SET) assert read_from_fd(fd, 5) == "He...
[ { "docstring": null, "function_declaration": "def read_from_fd(fd, n):", "function_name": "read_from_fd", "parameter_list": "(fd, n)" }, { "docstring": null, "function_declaration": "def write_to_fd(fd, data):", "function_name": "write_to_fd", "parameter_list": "(fd, data)" }, ...
[ 0, 0, 0, 1, 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 os\n\ndef read_from_fd(fd: int, n: int) -> str:\n \"\"\"\n Reads up to n characters or bytes from the file descriptor fd.\n \n If n is -1, reads an e...
trial_gpt4o_3
{ "original_instruction": "As a file operations specialist, you need to process several file descriptors provided to you. Your task is to create a Python module encapsulating the following functionality:\n\n1. **Read from a File Descriptor**:\n - Implement a function `read_from_fd(fd: int, n: int) -> str` that rea...
0.541849
Docs: Python310_23425
C
[ "read_from_fd", "write_to_fd", "dup_fd", "close_fd", "process_file" ]
5
[ [ "process_file", "close_fd" ], [ "process_file", "read_from_fd" ], [ "process_file", "write_to_fd" ] ]
3
[]
false
[]
false
pytest
true
[]
true
fda67018b6cc04e902a1c432c9b75b0dab383674
f279dff3695b7c2d2be5c49debb358876f879818
v1.0
complete
Docs
Docs: Python310_23953_C
import linecache def retrieve_line(filename: str, lineno: int) -> str: """ Retrieve a specific line from a file. Parameters: - filename: The path to the source file. - lineno: The line number to retrieve. Returns: - The content of the line including newline character, or an empty ...
import linecache def retrieve_line(filename: str, lineno: int) -> str: """ Retrieve a specific line from a file. Parameters: - filename: The path to the source file. - lineno: The line number to retrieve. Returns: - The content of the line including newline character, or an empty ...
import os import pytest from solution import retrieve_line, retrieve_multiple_lines, reset_cache, validate_cache test_filename = "test_file.py" def setup_module(module): # Create a test file lines = [ "import os\n", "import sys\n", "\n", "def foo():\n", " return 'foo...
[ { "docstring": "Retrieve a specific line from a file.\n\nParameters:\n- filename: The path to the source file.\n- lineno: The line number to retrieve.\n\nReturns:\n- The content of the line including newline character, or an empty string if the line or file doesn't exist.", "function_declaration": "def retr...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import linecache\n\ndef retrieve_line(filename: str, lineno: int) -> str:\n \"\"\"\n Retrieves the specific line from the file.\n\n Parameters:\n filename (...
trial_gpt4o_1
{ "original_instruction": "**Question: Implement a Debugging Tool Using `linecache`**\n\nYou are asked to implement a lightweight debugging tool in Python that inspects source files and retrieves specific lines of code. The tool should use the `linecache` module for efficient line retrieval and should provide the fol...
0.537428
Docs: Python310_23953
C
[ "retrieve_line", "retrieve_multiple_lines", "reset_cache", "validate_cache" ]
4
[ [ "retrieve_multiple_lines", "retrieve_line" ] ]
1
[]
false
[]
false
pytest
true
[]
true
163accf3b3041600addbeb7c591edf095e192436
927db632da6ed8c4e88446cfcdcde68464558e42
v1.0
complete
Docs
Docs: Scikit_23894_C
def optimize_nmf(): """ Profile and optimize NMF fitting on the sklearn's digits dataset. The function should: - Profile the performance of NMF fitting on the digits dataset to identify bottlenecks. - Optimize the code by either converting critical sections to Cython or implementing multi-core...
from sklearn.decomposition import NMF from sklearn.datasets import load_digits from joblib import Parallel, delayed import timeit # Original function to be optimized def original_nmf(): X, _ = load_digits(return_X_y=True) model = NMF(n_components=16, tol=1e-2) model.fit(X) # Function to perform NMF fittin...
from solution import optimize_nmf def test_optimize_nmf(): # Testing this function involves checking the printed output # Asserting the print output for verification # We might mock the print statement and timeit to capture the output for verification import io import sys # Capture the output ...
[ { "docstring": null, "function_declaration": "def original_nmf():", "function_name": "original_nmf", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def parallel_nmf(X, n_components, tol, n_jobs=-1):", "function_name": "parallel_nmf", "parameter_list": "(X...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def optimize_nmf():\n # Import necessary libraries\n from sklearn.decomposition import NMF\n from sklearn.datasets import load_digits\n import timeit\n f...
trial_gpt4o_2
{ "original_instruction": "Profiling and Optimization with scikit-learn\n\n#### Objective\nDemonstrate your understanding of profiling Python code, identifying performance bottlenecks, and optimizing code using Cython or multi-core parallelism.\n\n#### Problem Statement\nYou are given a dataset and a scikit-learn mod...
0.47198
Docs: Scikit_23894
C
[ "original_nmf", "parallel_nmf", "optimize_nmf" ]
3
[ [ "optimize_nmf", "parallel_nmf" ] ]
1
[]
false
[]
false
pytest
true
[ "joblib", "sklearn" ]
false
4d1fa52d5070476070e4a7d7cf8926946e402273
867015156549f20a53353fc6c3a229f7f7c0d4c4
v1.0
complete
Docs
Docs: Python310_23846_C
from xmlrpc.server import SimpleXMLRPCServer import xmlrpc.client import threading def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def run_server(): """ Create an XML-RPC server that provides basic arithmetic operations. - It should listen on `localh...
from xmlrpc.server import SimpleXMLRPCServer import threading def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def run_server(): server = SimpleXMLRPCServer(('localhost', 9000)) server.register_function(add, 'add') server.register_function(subtrac...
import xmlrpc.client import pytest from solution import add, subtract, multiply, client_interaction, server_thread def test_add(): assert add(5, 3) == 8 def test_subtract(): assert subtract(5, 3) == 2 def test_multiply(): assert multiply(5, 3) == 15 def test_client_interaction(): # Ensure the server...
[ { "docstring": null, "function_declaration": "def add(x, y):", "function_name": "add", "parameter_list": "(x, y)" }, { "docstring": null, "function_declaration": "def subtract(x, y):", "function_name": "subtract", "parameter_list": "(x, y)" }, { "docstring": null, "fu...
[ 0, 0, 0, 1, 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": "# xmlrpc_server.py\n\nfrom xmlrpc.server import SimpleXMLRPCServer\nimport threading\n\ndef add(x, y):\n return x + y\n\ndef subtract(x, y):\n return x - y\n\ndef...
trial_gpt4o_3
{ "original_instruction": "### XML-RPC Server and Client Setup\n\nIn this exercise, you'll create a simple XML-RPC server that performs basic arithmetic operations and a client to interact with the server.\n\n#### Objectives:\n1. Create an XML-RPC server that provides three arithmetic operations: addition, subtractio...
0.424773
Docs: Python310_23846
C
[ "add", "subtract", "multiply", "run_server", "client_interaction" ]
5
[ [ "run_server", "add" ], [ "run_server", "multiply" ], [ "run_server", "subtract" ] ]
3
[]
false
[]
false
pytest
true
[]
true
e42a73315f12c79f83a4c9fd5146eedb468e8564
f206ec5e9b43c614b630a3f9944aaed977db3cd8
v1.0
complete
Docs
Docs: Python310_23910_C
import dis from types import FunctionType def analyze_bytecode(func): """ Analyze the bytecode of the given function. Args: func (function): The function to disassemble. Returns: list: A list of dis.Instruction named tuples representing the bytecode instructions. """ instructions = di...
import dis import types def square_and_add(x, y): """ Squares the first number and adds it to the second number. """ result = (x * x) + y return result def analyze_bytecode(func): """ Analyze the bytecode of the given function. Args: func (function): The function to disassemble. ...
from solution import analyze_bytecode, modify_bytecode, square_and_add def test_analyze_bytecode(): bytecode = analyze_bytecode(square_and_add) assert len(bytecode) > 0 assert isinstance(bytecode, list) assert isinstance(bytecode[0], dis.Instruction) def test_modify_bytecode(): modified_func = mod...
[ { "docstring": "Squares the first number and adds it to the second number.", "function_declaration": "def square_and_add(x, y):", "function_name": "square_and_add", "parameter_list": "(x, y)" }, { "docstring": "Analyze the bytecode of the given function.\n\nArgs:\nfunc (function): The functi...
[ 0, 1 ]
1
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import dis\nimport types\n\ndef analyze_bytecode(func):\n \"\"\"\n Analyze the bytecode of the given function.\n\n Args:\n func (function): The function to ...
trial_gpt4o_2
{ "original_instruction": "### Bytecode Analysis and Modification Task\n\nIn this task, you will explore Python bytecode using the \"dis\" module. You will be given a function, and you will need to analyze its bytecode, modify the bytecode to change the function's behavior, and then verify the changes. This will test...
0.577946
Docs: Python310_23910
C
[ "square_and_add", "analyze_bytecode", "modify_bytecode", "verify_modification" ]
4
[ [ "verify_modification", "modify_bytecode" ], [ "verify_modification", "square_and_add" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d2f775ad70f785a886dcc5955344a73c250336b3
5f63dfa8d8902608990536560a6f46d391c71321
v1.0
complete
Docs
Docs: Python310_23451_C
class MockWideStringList: """Simulate PyWideStringList which maintains a list of wide strings.""" def __init__(self): self.items = [] def append(self, item): """Append an item to the list.""" self.items.append(item) def __repr__(self): return f"MockWideStringList({self...
class MockWideStringList: def __init__(self): self.items = [] def append(self, item): self.items.append(item) def __repr__(self): return f"MockWideStringList({self.items})" class MockStatus: def __init__(self, status, message=''): self.status = status self.mes...
import pytest from solution import MockWideStringList, MockStatus, initialize_mock_config, apply_command_line_args, preinitialize, initialize, run_mock_environment def test_initialize_mock_config(): config = initialize_mock_config() assert config == {'home': '', 'utf8_mode': True, 'log_to_file': False} def te...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class MockWideStringList:\n def __init__(self):\n self.items = []\n\n def append(self, item):\n self.items.append(item)\n\n def __repr__(self):\n...
trial_gpt4o_0
{ "original_instruction": "#### Objective\nCreate a Python script that simulates some of the initialization and configuration behavior of an embedded Python interpreter. Specifically, you will write a series of functions that will manage the configuration, preinitialization, and initialization of a mock Python enviro...
0.544561
Docs: Python310_23451
C
[ "initialize_mock_config", "apply_command_line_args", "preinitialize", "initialize", "run_mock_environment" ]
5
[ [ "initialize", "preinitialize" ], [ "run_mock_environment", "apply_command_line_args" ], [ "run_mock_environment", "initialize" ], [ "run_mock_environment", "initialize_mock_config" ] ]
4
[]
false
[ "MockWideStringList", "MockStatus" ]
true
pytest
true
[]
true
815755c030c3fad2aac8a38d4193dcd9c8a064ab
c5d489b93395479160dbae8c7a055eff384520bd
v1.0
complete
Docs
Docs: Python310_23688_C
import asyncio from typing import List # Task 1 - Coroutine using async and await async def fetch_data(n: int) -> int: """ Coroutine that simulates data fetching operation which takes n seconds to complete and then returns n. Args: - n (int): The number of seconds to wait before returning the numb...
import asyncio from typing import List # Task 1 - Coroutine using async and await async def fetch_data(n: int) -> int: """ Coroutine that simulates data fetching operation which takes n seconds to complete and then returns n. """ await asyncio.sleep(n) return n # Task 2 - Coroutine using PyCor...
import pytest import asyncio from solution import fetch_data, process_data, is_coroutine @pytest.mark.asyncio async def test_fetch_data(): result = await fetch_data(1) assert result == 1 @pytest.mark.asyncio async def test_process_data(): result = await process_data([1, 2, 3]) assert result == 6 def ...
[ { "docstring": "Function that would use PyCoro_New to create a new coroutine object.\nPlaceholder for actual implementation.", "function_declaration": "def fetch_data_new(frame, name, qualname):", "function_name": "fetch_data_new", "parameter_list": "(frame, name, qualname)" }, { "docstring"...
[ 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\nfrom typing import List\n\n# Task 1 - Coroutine using async and await\nasync def fetch_data(n: int) -> int:\n \"\"\"\n Coroutine that simulates da...
trial_gpt4o_0
{ "original_instruction": "### Understanding and Implementing Coroutines in Python\n\n#### Objective:\nTo assess the understanding and implementation of coroutines in Python using both high-level `async` and `await` syntax and the lower-level functions provided in the Python C API for creating and managing coroutine ...
0.577752
Docs: Python310_23688
C
[ "fetch_data", "fetch_data_new", "process_data", "is_coroutine" ]
4
[ [ "process_data", "fetch_data" ] ]
1
[ "process_data" ]
false
[]
false
pytest
true
[]
true
5262a54701a8bf7a00724265640a21d68144174f
f21df01f284681cc9052eddeab95e9edcb7d542d
v1.0
complete
Docs
Docs: Pytorch_23666_C
import torch from torch.func import vmap def squared_difference(x, y): """ Compute the squared difference between two vectors and sum it. >>> squared_difference(torch.tensor([1.0, 2.0]), torch.tensor([1.0, 2.1])) 0.01 """ return ((x - y) ** 2).sum() def vectorized_squared_difference(a, b): """ Com...
import torch from torch.func import vmap def squared_difference(x, y): return ((x - y) ** 2).sum() def vectorized_squared_difference(a, b): return vmap(squared_difference)(a, b) # Example usage a = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) b = torch.tensor([[1.0, 2.1], [2.9, 4.0], [5.1, 6.1]]) resul...
import torch from solution import vectorized_squared_difference def test_vectorized_squared_difference_same_tensors(): a = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) b = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) result = vectorized_squared_difference(a, b) expected = torch.tensor([0.0,...
[ { "docstring": null, "function_declaration": "def squared_difference(x, y):", "function_name": "squared_difference", "parameter_list": "(x, y)" }, { "docstring": null, "function_declaration": "def vectorized_squared_difference(a, b):", "function_name": "vectorized_squared_difference"...
[ 0, 0, 1, 0, 1, 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 torch\nfrom torch.func import vmap\n\ndef squared_difference(x, y):\n return ((x - y) ** 2).sum()\n\ndef vectorized_squared_difference(a, b):\n return vmap...
trial_gpt4o_8
{ "original_instruction": "### Question: Implement and Vectorize a Function with `torch.func.vmap`\n\nYou are required to implement a function using the `torch.func` module that performs a specific computation on a batch of input tensors. The function should be written in a manner compatible with `vmap` and must adhe...
0.559661
Docs: Pytorch_23666
C
[ "squared_difference", "vectorized_squared_difference" ]
2
[ [ "vectorized_squared_difference", "squared_difference" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
c3328d2971135ff224db2db23cfb3aa771684f94
d64d8c5eb476a42d971729b3d95bbfd29f3bde1b
v1.0
complete
Docs
Docs: Python310_23392_C
import os import sys import argparse from datetime import datetime, timedelta def get_file_creation_date(file_path): """Returns the creation date of the file in datetime format.""" pass def categorize_files(files, days): """ Categorizes the given list of files based on their creation date relative to ...
import os import sys import argparse from datetime import datetime, timedelta def get_file_creation_date(file_path): """ Returns the creation date of the file in datetime format. """ return datetime.fromtimestamp(os.path.getctime(file_path)) def categorize_files(files, days): """ Categorizes t...
import pytest from datetime import datetime, timedelta from solution import get_file_creation_date, categorize_files # Mocking os.path.getctime to simulate file creation dates def mock_getctime(file_path): creation_dates = { "file1.txt": (datetime.now() - timedelta(days=90)).timestamp(), "file2.txt...
[ { "docstring": "Returns the creation date of the file in datetime format.", "function_declaration": "def get_file_creation_date(file_path):", "function_name": "get_file_creation_date", "parameter_list": "(file_path)" }, { "docstring": "Categorizes the given list of files based on their creat...
[ 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 os\nimport argparse\nfrom datetime import datetime, timedelta\n\ndef categorize_files(filenames, days):\n \"\"\"\n Categorize files based on their creation...
trial_gpt4o_2
{ "original_instruction": "### Advanced File Management and Processing Task\n\nYou are tasked with developing a Python script that manages a file processing system. The script will read a list of filenames from the command line, check the creation dates of these files and generate a report that categorizes the files ...
0.63311
Docs: Python310_23392
C
[ "get_file_creation_date", "categorize_files", "generate_report" ]
3
[ [ "categorize_files", "get_file_creation_date" ], [ "generate_report", "categorize_files" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2e27597fb6f9ebe3df8d00e476940d1e5922dc24
f7f9c1cad793404d902d2fe5b122aa1daa5404cd
v1.0
complete
Docs
Docs: Python310_24118_C
import codecs def register_custom_codec(): """ Registers a custom codec named "reverse_codec" that reverses strings for encoding and unreverses strings for decoding. """ pass def reverse_encode(input_str: str) -> str: return input_str[::-1] def reverse_decode(input_str: str) -> str: retur...
import codecs # Custom encoding function def reverse_encode(input_str): return input_str[::-1], len(input_str) # Custom decoding function def reverse_decode(input_str): return input_str[::-1], len(input_str) # Custom error handler function def custom_error_handler(error): return ("<ERROR>", error.start +...
from solution import register_custom_codec, custom_encode, custom_decode def test_reverse_codec_encoding_decoding(): register_custom_codec() encoded_str = custom_encode("hello") assert encoded_str == "olleh" decoded_str = custom_decode(encoded_str) assert decoded_str == "hello" def test_reverse_c...
[]
[ 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 codecs\n\n# Custom encoding function\ndef reverse_encode(input_str):\n return input_str[::-1], len(input_str)\n\n# Custom decoding function\ndef reverse_decod...
trial_gpt4o_0
{ "original_instruction": "### Codec Encoding and Decoding Assessment\n\n#### Objective:\nYou are tasked with implementing a custom codec registration, encoding, and decoding system in Python. You will use the Python codec registry and support functions to create, register, and use a custom encoding and error handlin...
0.643972
Docs: Python310_24118
C
[ "reverse_encode", "reverse_decode", "custom_error_handler", "reverse_codec_search", "register_custom_codec", "custom_encode", "custom_decode" ]
7
[ [ "register_custom_codec", "custom_error_handler" ], [ "register_custom_codec", "reverse_codec_search" ] ]
2
[]
false
[ "ReverseCodec" ]
true
pytest
true
[]
true
6adc552732427e66f4d6379d7b22e839a6bd9b6f
5ea7bedcce44cd90f51e4457951578290242985a
v1.0
complete
Docs
Docs: Python310_23755_C
import cProfile import pstats import tracemalloc import random import time def slow_function(): """ Simulate a slow function that performs data processing operations. """ time.sleep(2) numbers = [random.randint(1, 100) for _ in range(10000)] squared_numbers = [n ** 2 for n in numbers] return su...
import cProfile import pstats import tracemalloc import random import time def slow_function(): time.sleep(2) numbers = [random.randint(1, 100) for _ in range(10000)] squared_numbers = [n ** 2 for n in numbers] return sum(squared_numbers) def fast_function(): numbers = range(1, 10001) squared_...
from solution import slow_function, fast_function def test_slow_function(): result = slow_function() assert isinstance(result, int) assert result > 0 def test_fast_function(): result = fast_function() assert isinstance(result, int) assert result > 0 def test_profile_execution(): import cP...
[ { "docstring": null, "function_declaration": "def slow_function():", "function_name": "slow_function", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def fast_function():", "function_name": "fast_function", "parameter_list": "()" }, { "docstring":...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cProfile\nimport pstats\nimport tracemalloc\nimport random\nimport time\n\ndef slow_function():\n time.sleep(2)\n numbers = [random.randint(1, 100) for _ i...
trial_gpt4o_1
{ "original_instruction": "### Question: Profiling and Memory Management in Python\n\nYou are given a Python script that performs some data processing operations. Your task is to analyze the script to identify any performance bottlenecks and excessive memory usage. You need to use the `cProfile` and `tracemalloc` mod...
0.47577
Docs: Python310_23755
C
[ "slow_function", "fast_function", "profile_execution", "analyze_memory" ]
4
[ [ "analyze_memory", "fast_function" ], [ "analyze_memory", "slow_function" ], [ "profile_execution", "fast_function" ], [ "profile_execution", "slow_function" ] ]
4
[]
false
[]
false
pytest
true
[]
true
b158628556b4cc0948d3001de3776ee7d57cc61d
f90abf68a9b29799be56c6365472386a6b31e2bb
v1.0
complete
Docs
Docs: Python310_23904_C
import os import logging def process_records(file_path: str) -> float: """ Processes the records in the input file, sorts them by Score (descending) and Age (ascending) if scores are equal, writes the sorted records to a new file, and returns the average score. Args: file_path (str): The p...
import os import logging from typing import List, Tuple def parse_line(line: str) -> Tuple[int, str, int, int]: """ Parse a line of input file into a tuple of (ID, Name, Age, Score). """ try: parts = line.strip().split(", ") return (int(parts[0]), parts[1], int(parts[2]), int(parts[3]))...
import os from solution import process_records def create_test_file(filepath: str, content: str) -> None: with open(filepath, 'w') as f: f.write(content) def test_process_records(): test_file = 'test_records.txt' test_content = """1, Alice, 30, 88 2, Bob, 24, 95 3, Charlie, 29, 79 """ create_t...
[ { "docstring": "Parse a line of input file into a tuple of (ID, Name, Age, Score).", "function_declaration": "def parse_line(line):", "function_name": "parse_line", "parameter_list": "(line)" }, { "docstring": "Processes the records in the input file, sorts them, writes to a new file,\nand r...
[ 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 os\nimport logging\nfrom typing import List, Tuple\n\ndef parse_line(line: str) -> Tuple[int, str, int, int]:\n \"\"\"\n Parse a line of input file into a ...
trial_gpt4o_0
{ "original_instruction": "### Python Coding Assessment Question\n\n#### Context:\nYou are working on a text processing task that involves analyzing and processing a large dataset stored in a text file. The file contains multiple records, where each record is a line formatted as follows:\n\n```\nID, Name, Age, Score\...
0.576365
Docs: Python310_23904
C
[ "parse_line", "process_records" ]
2
[ [ "process_records", "parse_line" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3642bd3380fd36cc949828f4a61e520e74506904
e8882a4087effff615381c0ab0b20346ed50bd2c
v1.0
complete
Docs
Docs: Python310_24013_C
from typing import NewType, Generic, TypeVar, List, Dict, overload # Step 1: Define User class UserId = NewType('UserId', int) class User: def __init__(self, user_id: UserId, name: str) -> None: self.user_id = user_id self.name = name # Step 2: Define Order class class Order: def __init__(sel...
from typing import NewType, Generic, TypeVar, List, Dict, overload # Step 1: Define User class UserId = NewType('UserId', int) class User: user_id: UserId name: str def __init__(self, user_id: UserId, name: str) -> None: self.user_id = user_id self.name = name # Step 2: Define Order clas...
def test_container_operations(): container = Container[int]() container.add(1) container.add(2) assert container.get_all() == [1, 2] assert container.remove(1) == True assert container.get_all() == [2] assert container.remove(3) == False def test_create_user_and_order(): user_id = UserI...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import NewType, Generic, TypeVar, List, Dict, overload\n\n# Step 1: Define User class\nUserId = NewType('UserId', int)\n\nclass User:\n user_id: UserId\n...
trial_gpt4o_0
{ "original_instruction": "You are tasked with implementing a type-safe system that utilizes multiple advanced features provided by the `typing` module. The goal is to design a small library for an e-commerce platform that includes handling users, orders, and generic functions. This assessment will test your knowledg...
0.4366
Docs: Python310_24013
C
[ "calculate_discount", "calculate_discount", "process_orders" ]
3
[ [ "process_orders", "calculate_discount" ] ]
1
[]
false
[ "User", "Order", "Container" ]
true
pytest
false
[]
true
85273e31561f8b4cdd9a19bdf214f3684021d923
33ca82f29474c545fa8b37f61b706cb7119e10bf
v1.0
complete
Docs
Docs: Python310_24148_C
import time def slow_function(): """ Simulates a slow function by sleeping for 2 seconds.""" print("Starting slow function") time.sleep(2) print("Slow function completed") def another_slow_function(): """ Simulates another slow function by performing a nested loop computation.""" print("Starti...
import time import cProfile def slow_function(): print("Starting slow function") time.sleep(2) print("Slow function completed") def another_slow_function(): print("Starting another slow function") result = 0 for i in range(10000): for j in range(10000): result += i * j ...
from solution import optimized_another_slow_function, optimized_main def test_optimized_another_slow_function(): import timeit execution_time = timeit.timeit(optimized_another_slow_function, number=1) assert execution_time < 0.1 # We expect the optimized function to be very fast def test_optimized_main()...
[ { "docstring": null, "function_declaration": "def slow_function():", "function_name": "slow_function", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def another_slow_function():", "function_name": "another_slow_function", "parameter_list": "()" }, { ...
[ 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 timeit\nimport time\n\ndef slow_function():\n print(\"Starting slow function\")\n time.sleep(2)\n print(\"Slow function completed\")\n\ndef another_slow...
trial_gpt4o_7
{ "original_instruction": "#### Objective:\nUse the provided Python debugging and profiling tools to identify and optimize a performance bottleneck in a given Python program. You will demonstrate your skill in using these tools by providing not only the optimized code but also an explanation of how you identified the...
0.515694
Docs: Python310_24148
C
[ "slow_function", "another_slow_function", "optimized_another_slow_function", "main", "optimized_main" ]
5
[ [ "optimized_main", "optimized_another_slow_function" ], [ "optimized_main", "slow_function" ] ]
2
[]
false
[]
false
pytest
true
[]
true
857905434ad1ad87eb294a943a15c1db7aebbb4c
931bc86ae2671ee2cc7c32d48fd75db9611f84ed
v1.0
complete
Docs
Docs: Python310_24142_C
import contextlib from typing import List def acquire_special_resource(): """ This function simulates the acquisition of a special resource. """ print("Special resource acquired.") return "SpecialResource" def release_special_resource(resource): """ This function simulates the release of a...
import contextlib # Provided functions def acquire_special_resource(): """ This function simulates the acquisition of a special resource. """ print("Special resource acquired.") return "SpecialResource" def release_special_resource(resource): """ This function simulates the release of a sp...
import pytest from unittest import mock from solution import manage_resources, acquire_special_resource, release_special_resource def test_manage_resources_with_no_special_resource(tmpdir): # Create temporary files with some content file1 = tmpdir.join("file1.txt") file1.write("Content of file 1") ...
[ { "docstring": "This function simulates the acquisition of a special resource.", "function_declaration": "def acquire_special_resource():", "function_name": "acquire_special_resource", "parameter_list": "()" }, { "docstring": "This function simulates the release of a special resource.", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextlib\n\ndef acquire_special_resource():\n \"\"\"\n This function simulates the acquisition of a special resource.\n \"\"\"\n print(\"Special re...
trial_gpt4o_2
{ "original_instruction": "### Context Management with `ExitStack`\n\n**Problem Statement:**\n\nYou are required to write a function `manage_resources(file_paths: List[str], special_resource_required: bool) -> List[str]` that accepts:\n1. A list of file paths (`file_paths: List[str]`) that need to be opened and read....
0.544536
Docs: Python310_24142
C
[ "acquire_special_resource", "release_special_resource", "manage_resources" ]
3
[ [ "manage_resources", "acquire_special_resource" ], [ "manage_resources", "release_special_resource" ] ]
2
[]
false
[]
false
pytest
true
[]
true
09402c8ceb363f702ead9dfab3ed5c52037b468d
ccc451982164ee652df395ac178f0bb357c699eb
v1.0
complete
Docs
Docs: Python310_24113_C
def create_bytes(input_string): """ Create a bytes object from a string. Args: input_string (str): The string to convert to bytes. Returns: bytes: The resulting bytes object. """ pass def is_bytes_object(obj): """ Check if the provided object is a bytes object....
def create_bytes(input_string): """ Create a bytes object from a string. Args: input_string (str): The string to convert to bytes. Returns: bytes: The resulting bytes object. """ try: return bytes(input_string, 'utf-8') except TypeError as e: raise V...
from solution import create_bytes, is_bytes_object, get_bytes_size, bytes_to_string, concatenate_bytes, resize_bytes def test_create_bytes(): assert create_bytes("hello") == b"hello" assert create_bytes("123") == b"123" def test_is_bytes_object(): assert is_bytes_object(b"hello") == True assert is_byt...
[ { "docstring": "Create a bytes object from a string.\n\nArgs:\n input_string (str): The string to convert to bytes.\n\nReturns:\n bytes: The resulting bytes object.", "function_declaration": "def create_bytes(input_string):", "function_name": "create_bytes", "parameter_list": "(input_string)" ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def create_bytes(string):\n \"\"\"\n Create a bytes object from a string.\n\n Args:\n - string (str): The input string to convert to bytes.\n\n Returns:\...
trial_gpt4o_2
{ "original_instruction": "As a Python developer, you are tasked with creating a Python bytes object that meets specific requirements, manipulating it, and extracting information from it using the Python/C-API functions described in the documentation.\n\n#### Requirements:\n1. **Create a bytes object from a string**....
0.499799
Docs: Python310_24113
C
[ "create_bytes", "is_bytes_object", "get_bytes_size", "bytes_to_string", "concatenate_bytes", "resize_bytes" ]
6
[ [ "bytes_to_string", "is_bytes_object" ], [ "concatenate_bytes", "is_bytes_object" ], [ "get_bytes_size", "is_bytes_object" ], [ "resize_bytes", "is_bytes_object" ] ]
4
[]
false
[]
false
pytest
true
[]
true
1a0671280414244ff0118676f348de22bb4653b0
05ebdcef68e82b4efdd7293bfcc3f6f9349cd29a
v1.0
complete
Docs
Docs: Python310_24323_C
import atexit activities = [] def add_activity(activity: str) -> None: """ Adds an activity to the list. >>> activities [] >>> add_activity("Login") >>> add_activity("View Dashboard") >>> add_activity("Logout") >>> activities ["Login", "View Dashboard", "Logout"] """ pass ...
import atexit activities = [] def add_activity(activity: str) -> None: """ Adds an activity to the list. """ activities.append(activity) @atexit.register def save_activities() -> None: """ Saves activities to a file when the program terminates. """ try: with open('activities.t...
import os import pytest from solution import add_activity, save_activities, activities, unregister_save_activities def test_add_activity(): # Clear the activities list before the test activities.clear() add_activity("Login") add_activity("View Dashboard") add_activity("Logout") assert activitie...
[ { "docstring": "Adds an activity to the list.", "function_declaration": "def add_activity(activity):", "function_name": "add_activity", "parameter_list": "(activity)" }, { "docstring": "Saves activities to a file when the program terminates.", "function_declaration": "def save_activities...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import atexit\n\nactivities = []\n\ndef add_activity(activity: str) -> None:\n \"\"\"\n Adds an activity string to the global activities list.\n \"\"\"\n ac...
trial_gpt4o_1
{ "original_instruction": "**Objective**: Demonstrate the use of Python's `atexit` module to manage cleanup functions that run on program termination.\n\n### Problem Statement\n\nYou are tasked with creating a small module that manages an in-memory list of user activities. Throughout the execution of the program, act...
0.381308
Docs: Python310_24323
C
[ "add_activity", "save_activities", "unregister_save_activities" ]
3
[ [ "unregister_save_activities", "save_activities" ] ]
1
[]
false
[]
false
pytest
true
[]
true
40d52c678fd39f6788da683099ffa2f9d4c29b30
289933c7fe42de3ab8d8dd84d94537c72c179665
v1.0
complete
Docs
Docs: Python310_24437_C
import grp from typing import List def common_groups(user1: str, user2: str) -> List[str]: """ Determine common group memberships between two Unix users. >>> common_groups('user1', 'user2') ['users'] >>> common_groups('user1', 'user3') [] """
import grp def get_user_groups(username: str) -> set: """ Helper function to get all groups a user belongs to. """ groups = set() for group in grp.getgrall(): if username == group.gr_name or username in group.gr_mem: groups.add(group.gr_name) return groups def common_groups...
def test_common_groups(): # Mock grp.getgrall() response original_getgrall = grp.getgrall class MockGroup: def __init__(self, gr_name, gr_mem): self.gr_name = gr_name self.gr_mem = gr_mem def mock_getgrall(): return [ MockGroup('admin', ['use...
[ { "docstring": "Helper function to get all groups a user belongs to.", "function_declaration": "def get_user_groups(username):", "function_name": "get_user_groups", "parameter_list": "(username)" }, { "docstring": "Returns a list of common group names that the two specified Unix users belong...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import grp\n\ndef get_user_groups(username: str) -> set:\n \"\"\"\n Helper function to get all groups a user belongs to.\n \"\"\"\n groups = set()\n for ...
trial_gpt4o_0
{ "original_instruction": "**Objective:**\n\nWrite a Python function using the `grp` module to determine common group memberships between two Unix users.\n\n**Task:**\n\nYou are required to implement a function called `common_groups(user1: str, user2: str) -> List[str]` which returns a list of common group names that...
0.501576
Docs: Python310_24437
C
[ "get_user_groups", "common_groups" ]
2
[ [ "common_groups", "get_user_groups" ] ]
1
[]
false
[]
false
pytest
false
[]
true
cf7213016effebc351206bd0a4772f024a977cb0
8b862317776af09fd3b81050954f1f8132c65b99
v1.0
complete
Docs
Docs: Python310_23959_C
import _thread import time def partial_sum(data, lock, result_holder): """ Compute the partial sum of a list segment and update the shared result holder. Args: data (List[int]): The list of integers to sum. lock (_thread.LockType): The lock for thread-safe access to the result holder. result_holder...
import _thread import time # Define a function to compute the partial sum of a list segment def partial_sum(data, lock, result_holder): # Compute sum of data partial_sum_result = sum(data) # Acquire lock and update the result_holder lock.acquire() try: result_holder[0] += partial_sum_r...
from solution import partial_sum, compute_sum import _thread import time # Test the functionality of partial_sum def test_partial_sum(): lock = _thread.allocate_lock() result_holder = [0] data = [1, 2, 3, 4, 5] partial_sum(data, lock, result_holder) assert result_holder[0] == 15 # Test comput...
[ { "docstring": null, "function_declaration": "def partial_sum(data, lock, result_holder):", "function_name": "partial_sum", "parameter_list": "(data, lock, result_holder)" }, { "docstring": null, "function_declaration": "def compute_sum(data, num_threads):", "function_name": "compute...
[ 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 _thread\n\n# This variable will hold the partial sums computed by each thread\nresult_holder = []\n\ndef partial_sum(data, lock, result_holder):\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "**Objective:** Demonstrate your understanding of creating and managing threads using the `_thread` module in Python.\n\nYou are required to write a Python program that creates multiple threads to compute the sum of integers in a list. Each thread should handle a portion of the list. Use loc...
0.563227
Docs: Python310_23959
C
[ "partial_sum", "compute_sum" ]
2
[ [ "compute_sum", "partial_sum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5cdbe059aad8a128e5a4f8cc889d262b8860c76b
3d1510b9ccb62e3ac79b7d71c13c2c606c6f77d5
v1.0
complete
Docs
Docs: Python310_24373_C
def function_3(): """ A simple function. >>> function_3() is None True """ pass def function_1(): """ Calls function_3(). >>> function_1() is None True """ function_3() def function_2(): """ Calls function_1() and function_3(). >>> function_2() is None True """ ...
def function_3(): pass def function_1(): function_3() def function_2(): function_1() function_3() def function_4(): pass def function_5(): function_4() def start(): function_1() function_2() function_3() function_4() function_5() if __name__ == "__main__": start()
from solution import function_3, function_1, function_2, function_4, function_5, start def test_function_3(): assert function_3() is None def test_function_1(): assert function_1() is None def test_function_2(): assert function_2() is None def test_function_4(): assert function_4() is None def test...
[ { "docstring": null, "function_declaration": "def function_3():", "function_name": "function_3", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def function_1():", "function_name": "function_1", "parameter_list": "()" }, { "docstring": null, "...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def function_3():\n pass\n\ndef function_1():\n function_3()\n\ndef function_2():\n function_1()\n function_3()\n\ndef function_4():\n pass\n\ndef functi...
trial_gpt4o_2
{ "original_instruction": "### Objective\nTo assess students' understanding of using SystemTap to monitor CPython processes and write scripts that gather and display specific data about the function calls within a Python script.\n\n### Task\nYou are required to write a Python script and a SystemTap script to monitor ...
0.612717
Docs: Python310_24373
C
[ "function_3", "function_1", "function_2", "function_4", "function_5", "start" ]
6
[ [ "function_1", "function_3" ], [ "function_2", "function_1" ], [ "function_2", "function_3" ], [ "function_5", "function_4" ], [ "start", "function_1" ], [ "start", "function_2" ], [ "start", "function_3" ], [ "start", "fun...
9
[]
false
[]
false
pytest
true
[]
true
2e305749aa513fd5ba267c903b02ce12b432e682
1d0106cb63633dafda82f78b52bdd05915855b00
v1.0
complete
Docs
Docs: Pytorch_24016_C
import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim import torch.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import DataLoader, Dataset class DummyDataset(Dataset): """A dummy dataset for illustration purposes"...
import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim import torch.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import DataLoader, Dataset # Dummy dataset for illustration class DummyDataset(Dataset): def __init__...
import torch from torch.utils.data import Dataset, DataLoader from solution import SimpleModel, DummyDataset, train, setup, cleanup import torch.distributed as dist import torch.multiprocessing as mp import time def test_dummy_dataset(): dataset = DummyDataset(size=100) data, target = dataset[0] assert dat...
[]
[ 0, 0, 0, 0, 0, 0, 1, 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 torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nfrom torch.nn.parallel import Di...
trial_gpt4o_6
{ "original_instruction": "### Distributed Training with PyTorch\n\nThis assessment tests your understanding of PyTorch's `torch.distributed` module, specifically its `torchrun` elastic launch utility used to facilitate distributed training across multiple nodes.\n\n#### Problem Statement\n\nYou are provided with a m...
0.593202
Docs: Pytorch_24016
C
[ "setup", "cleanup", "train", "main" ]
4
[ [ "train", "cleanup" ], [ "train", "setup" ] ]
2
[]
false
[ "DummyDataset", "SimpleModel" ]
true
pytest
true
[ "torch" ]
false
435b6577a4a5a18921a858e11e28fa6a36b33d8a
9ce987a9fcf445f497150d5e389e3fe37f147973
v1.0
complete
Docs
Docs: Python310_23899_C
import wave def read_wav_file(file_path: str) -> tuple: """ Reads a WAV file and extracts its parameters. Args: - file_path (str): Path to the input WAV file. Returns: - tuple: (number of channels, sample width (in bytes), frame rate, total number of frames) """ pass def mani...
import wave def read_wav_file(file_path): """ Reads a WAV file and extracts its parameters. Args: - file_path (str): Path to the input WAV file. Returns: - tuple: (number of channels, sample width, frame rate, total number of frames) """ with wave.open(file_path, 'rb') as wav_...
from solution import read_wav_file, manipulate_audio_data, write_wav_file import wave import os import pytest @pytest.fixture def setup_wav(): """ Create a sample WAV file for testing. """ file_path = "test.wav" with wave.open(file_path, 'wb') as wav_file: wav_file.setnchannels(1) # mono ...
[ { "docstring": "Reads a WAV file and extracts its parameters.\n\nArgs:\n- file_path (str): Path to the input WAV file.\n\nReturns:\n- tuple: (number of channels, sample width, frame rate, total number of frames)", "function_declaration": "def read_wav_file(file_path):", "function_name": "read_wav_file",...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import wave\n\ndef read_wav_file(file_path):\n \"\"\"\n Reads a WAV file and extracts its parameters.\n \n Args:\n - file_path (str): The path to the WAV...
trial_gpt4o_2
{ "original_instruction": "You are required to use the `wave` module to perform the following tasks:\n\n1. **Read a WAV file**: Open a provided WAV file and extract its parameters.\n2. **Manipulate the WAV file**: Perform some operations on the audio data.\n3. **Write a new WAV file**: Save the manipulated audio data...
0.554882
Docs: Python310_23899
C
[ "read_wav_file", "manipulate_audio_data", "write_wav_file" ]
3
[ [ "write_wav_file", "manipulate_audio_data" ], [ "write_wav_file", "read_wav_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3533749be532fbe7d794e382974f552c6610b612
22d468cdad02bc63b660fbeed84c267aada7d405
v1.0
complete
Docs
Docs: Python310_24360_C
import multiprocessing from typing import List def factorial_task(n: int) -> int: """ Function to calculate the factorial of a given integer n. >>> factorial_task(0) == 1 >>> factorial_task(5) == 120 """ def parallel_factorials(numbers: List[int], num_processes: int) -> List[int]: """ Fun...
import multiprocessing from typing import List def factorial_task(n: int) -> int: """ Function to calculate the factorial of a given integer n. """ if n == 0: return 1 factorial = 1 for i in range(1, n + 1): factorial *= i return factorial def parallel_factorials(numbers: L...
import pytest from solution import factorial_task, parallel_factorials, print_factorial_results, shared_memory_sum def test_factorial_task(): assert factorial_task(0) == 1 assert factorial_task(1) == 1 assert factorial_task(5) == 120 assert factorial_task(7) == 5040 def test_parallel_factorials(): ...
[ { "docstring": "Function to calculate the factorial of a given integer n.", "function_declaration": "def factorial_task(n):", "function_name": "factorial_task", "parameter_list": "(n)" }, { "docstring": "Function to calculate factorials of a list of numbers using multiple processes.", "f...
[ 0, 0, 0, 1, 0, 0, 0, 1, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from multiprocessing import Pool, Lock, Value\nimport os\nfrom typing import List\nimport math\n\ndef factorial_task(n: int) -> int:\n \"\"\"\n Calculate the fact...
trial_gpt4o_8
{ "original_instruction": "### Advanced Python `multiprocessing` Assessment\n\nUsing the `multiprocessing` module, write a Python program that performs the following tasks:\n\n1. **Task 1: Calculate Factorial in Parallel**\n - Create a function `factorial_task(n: int) -> int` that calculates the factorial of a giv...
0.818929
Docs: Python310_24360
C
[ "factorial_task", "parallel_factorials", "print_factorial_results", "shared_memory_sum" ]
4
[ [ "parallel_factorials", "factorial_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
14f2d40993cac1c4d3c435afdca4a2f81e07334a
390f5da42edc40559e56db9375d66e2611355ac8
v1.0
complete
Docs
Docs: Python310_24298_C
import logging class IgnoreFilter(logging.Filter): def filter(self, record): return 'ignore' not in record.getMessage() def configure_logger(): """Configure a logging system. Returns: logging.Logger: Configured logger instance. """ # Create logger logger = logging.getLogger('a...
import logging class IgnoreFilter(logging.Filter): def filter(self, record): return 'ignore' not in record.getMessage() def configure_logger(): # Create logger logger = logging.getLogger('appLogger') logger.setLevel(logging.DEBUG) # Create console handler and set level to INFO ch = lo...
import os import logging from solution import configure_logger, simulate_application def test_logging_configuration(): # Clean up previous log files if any if os.path.exists('app.log'): os.remove('app.log') logger = configure_logger() assert logger.name == 'appLogger' assert logger.lev...
[]
[ 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 logging\n\nclass IgnoreFilter(logging.Filter):\n def filter(self, record):\n return 'ignore' not in record.getMessage()\n\ndef configure_logger():\n ...
trial_gpt4o_0
{ "original_instruction": "**Objective:**\nDesign a Python program that demonstrates your understanding of the logging module in Python. Your task is to configure a logging system for a simulated application that records log messages of various severity levels to both the console and a file. Additionally, you must im...
0.510573
Docs: Python310_24298
C
[ "configure_logger", "simulate_application" ]
2
[ [ "simulate_application", "configure_logger" ] ]
1
[]
false
[ "IgnoreFilter" ]
true
pytest
true
[]
true
eace435d0fad3bb28f4a5784d399bd32911aa122
4d4bcc7d4200780ffbd02b01cb55d8d84a472864
v1.0
complete
Docs
Docs: Python310_24567_C
import asyncio async def handle_client(reader, writer): """ Handle the client connection, read data from the client and echo it back. """ pass async def run_server(host, port): """ Run the TCP echo server on the specified host and port. """ pass async def tcp_echo_client(message, host...
import asyncio # Echo Server async def handle_client(reader, writer): """ Handle the client connection, read data from the client and echo it back. """ while True: data = await reader.read(100) if not data: break message = data.decode() writer.write(data) ...
import asyncio import pytest import socket from solution import handle_client, run_server, tcp_echo_client # Utility function to check if a port is in use def is_port_in_use(port, host='localhost'): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: return s.connect_ex((host, port)) == 0 # Unit...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\n# Echo Server\nasync def handle_client(reader, writer):\n \"\"\"\n Handle the client connection, read data from the client and echo it back.\n ...
trial_gpt4o_0
{ "original_instruction": "### Asyncio TCP Echo Server and Client\n\n#### Objective:\nTo assess your understanding of the `asyncio` module, particularly focusing on event loop, networking, and async/await syntax, you are required to implement an asynchronous TCP echo server and client using `asyncio`.\n\n#### Require...
0.673559
Docs: Python310_24567
C
[ "handle_client", "run_server", "tcp_echo_client", "main" ]
4
[ [ "run_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
525f6ef0aac3e9a611e5aae1ef25d4038fadd422
5d38f635d72b1acd529346a9c3790a1715a0650e
v1.0
complete
Docs
Docs: Python310_24385_C
def sum_numbers(numbers): """ Returns the sum of a list of numbers. """ pass def mean(numbers): """ Returns the mean (average) of a list of numbers. >>> mean([1, 2, 3, 4, 5]) 3 >>> mean([0, 0, 0, 0, 0]) 0 >>> mean([-1, -2, -3, -4, -5]) -3 """ pass def variance(numbers): ...
def sum_numbers(numbers): """ Returns the sum of a list of numbers. """ return sum(numbers) def mean(numbers): """ Returns the mean (average) of a list of numbers. """ return sum_numbers(numbers) / len(numbers) def variance(numbers): """ Returns the variance of a list of number...
from solution import sum_numbers, mean, variance, standard_deviation, slow_function def test_sum_numbers(): assert sum_numbers([1, 2, 3, 4, 5]) == 15 assert sum_numbers([0, 0, 0, 0, 0]) == 0 assert sum_numbers([-1, -2, -3, -4, -5]) == -15 def test_mean(): assert mean([1, 2, 3, 4, 5]) == 3 assert m...
[ { "docstring": "Returns the sum of a list of numbers.", "function_declaration": "def sum_numbers(numbers):", "function_name": "sum_numbers", "parameter_list": "(numbers)" }, { "docstring": "Returns the mean (average) of a list of numbers.", "function_declaration": "def mean(numbers):", ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def sum_numbers(numbers):\n \"\"\"\n Returns the sum of a list of numbers.\n \"\"\"\n return sum(numbers)\n\ndef mean(numbers):\n \"\"\"\n Returns the...
trial_gpt4o_2
{ "original_instruction": "## Problem: Profiling and Optimizing a Python Function\n\nYou are given a Python module that defines several functions for computing statistics on a list of numbers. Your task is to profile the performance of these functions, analyze the profiling data, and suggest improvements to optimize ...
0.68151
Docs: Python310_24385
C
[ "sum_numbers", "mean", "variance", "standard_deviation", "slow_function" ]
5
[ [ "mean", "sum_numbers" ], [ "standard_deviation", "variance" ], [ "variance", "mean" ], [ "variance", "sum_numbers" ] ]
4
[]
false
[]
false
pytest
true
[]
true
1ed27546125877d0ed88f87d20e314aaf4b655a5
4072fdc42187717c00c4d2c0e0c22c1f49c793ff
v1.0
complete
Docs
Docs: Python310_24367_C
import itertools import heapq def add_task(pq, entry_finder, counter, task, priority): """ Add a task or update an existing task's priority. >>> pq = [] >>> entry_finder = {} >>> counter = itertools.count() >>> add_task(pq, entry_finder, counter, 'task1', 5) >>> add_task(pq, entry_finder, c...
import itertools import heapq REMOVED = '<removed-task>' def add_task(pq, entry_finder, counter, task, priority): """ Add a task or update an existing task's priority. """ if task in entry_finder: remove_task(pq, entry_finder, task) count = next(counter) entry = [priority, count, task]...
import pytest from solution import add_task, remove_task, pop_task @pytest.fixture def setup_pq(): pq = [] entry_finder = {} counter = itertools.count() return pq, entry_finder, counter def test_add_task(setup_pq): pq, entry_finder, counter = setup_pq add_task(pq, entry_finder, counter, '...
[ { "docstring": "Add a task or update an existing task's priority.", "function_declaration": "def add_task(pq, entry_finder, counter, task, priority):", "function_name": "add_task", "parameter_list": "(pq, entry_finder, counter, task, priority)" }, { "docstring": "Mark an existing task as REM...
[ 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 itertools\nimport heapq\n\nREMOVED = '<removed-task>' # placeholder for a removed task\n\ndef add_task(pq, entry_finder, counter, task, priority):\n \"\"\"\n...
trial_gpt4o_1
{ "original_instruction": "### Priority Queue Management with `heapq`\n\n#### Problem Statement\n\nYou are tasked with implementing a simple priority queue for managing tasks using the `heapq` module. The priority queue should allow adding tasks with priorities, updating the priorities of existing tasks, and retrievi...
0.555473
Docs: Python310_24367
C
[ "add_task", "remove_task", "pop_task" ]
3
[ [ "add_task", "remove_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6a5ec1451415703cecce19a563666f6799de515f
57719c67dd57a477502963c1bbe568f739a3e3b0
v1.0
complete
Docs
Docs: Python310_24198_C
import itertools from functools import reduce def infinite_iterator(dataset): """ Returns an infinite iterator that cycles through the input dataset. """ pass def even_numbers(iterator): """ A generator function that yields only the even numbers from an input iterator. """ pass def fi...
import itertools from functools import reduce def infinite_iterator(dataset): """ Returns an infinite iterator that cycles through the input dataset. """ return itertools.cycle(dataset) def even_numbers(iterator): """ A generator function that yields only the even numbers from an input iterato...
from solution import infinite_iterator, even_numbers, filtered_sum, zip_iterables def test_infinite_iterator(): dataset = [1, 2, 3] iterator = infinite_iterator(dataset) output = [next(iterator) for _ in range(6)] assert output == [1, 2, 3, 1, 2, 3] def test_even_numbers(): dataset = [1, 2, 3, 4, ...
[ { "docstring": "Returns an infinite iterator that cycles through the input dataset.", "function_declaration": "def infinite_iterator(dataset):", "function_name": "infinite_iterator", "parameter_list": "(dataset)" }, { "docstring": "A generator function that yields only the even numbers from ...
[ 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 itertools\nfrom functools import reduce\n\ndef infinite_iterator(dataset):\n \"\"\"\n Returns an infinite iterator that cycles through the dataset repeated...
trial_gpt4o_2
{ "original_instruction": "**Title:** Functional Programming: Generators and Iterators\n\n**Objective:** Implement a series of functions that demonstrate your understanding of Python's iterators, generators, and functional-style programming using itertools and functools modules.\n\n**Problem Statement:**\n\nYou are g...
0.600147
Docs: Python310_24198
C
[ "infinite_iterator", "even_numbers", "filtered_sum", "zip_iterables" ]
4
[ [ "filtered_sum", "even_numbers" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dac567f1c3efdc36718dc60be36c1e6247a030d3
8fba656cb242a2ad0d9d831d3ebd198e44f58e34
v1.0
complete
Docs
Docs: Scikit_24518_C
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def data_stream(file_path, batch_size=1000): """ Generator function to stream data from a file in mini-batches. Args: file_path (str): Path to the...
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def data_stream(file_path, batch_size=1000): """Generator function to read data in mini-batches""" texts = [] labels = [] with open(file_path, 'r', enc...
import pytest from solution import data_stream, incremental_training def test_data_stream(): file_path = 'test_data.txt' with open(file_path, 'w') as f: for i in range(2500): f.write(f'Article text {i}\tCategory{i%3}\n') batches = list(data_stream(file_path, batch_size=1000)) assert...
[ { "docstring": "Generator function to read data in mini-batches", "function_declaration": "def data_stream(file_path, batch_size=1000):", "function_name": "data_stream", "parameter_list": "(file_path, batch_size=1000)" }, { "docstring": null, "function_declaration": "def incremental_trai...
[ 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 sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\nimport numpy ...
trial_gpt4o_1
{ "original_instruction": "#### Objective\nImplement an out-of-core learning system using scikit-learn to handle a large dataset that cannot fit into memory. The task is to build a text classification model that can learn incrementally and demonstrate performance improvement over time.\n\n#### Problem Statement\nYou ...
0.576343
Docs: Scikit_24518
C
[ "data_stream", "incremental_training" ]
2
[ [ "incremental_training", "data_stream" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
99391d48e22e8b86206c8a2d274611e35b8132da
0543f32d111a536d5ef937a517541636d399dc65
v1.0
complete
Docs
Docs: Python310_24487_C
import contextvars from typing import List # Create a ContextVar for user_id and request_id user_id_var = contextvars.ContextVar('user_id', default='unknown') request_id_var = contextvars.ContextVar('request_id', default='unknown') def log_action(action: str) -> None: """ Logs the given action, user ID, and reque...
import contextvars from typing import List # Create a ContextVar for user_id and request_id user_id_var = contextvars.ContextVar('user_id', default='unknown') request_id_var = contextvars.ContextVar('request_id', default='unknown') def log_action(action: str) -> None: """ Logs the given action, user ID, and r...
import asyncio from solution import handle_request, handle_request_async # Define synchronous tests def test_handle_request(): handle_request("user123", "req456", ["login", "view_page", "logout"]) def test_handle_request_with_unknown_user_and_request(): handle_request("", "", ["action1", "action2"]) # Define...
[ { "docstring": "Logs the given action, user ID, and request ID.", "function_declaration": "def log_action(action):", "function_name": "log_action", "parameter_list": "(action)" }, { "docstring": "Process the list of actions by setting context variables and logging actions.", "function_de...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextvars\nimport asyncio\nfrom typing import List\n\n# Declare context variables\nuser_id_var = contextvars.ContextVar('user_id', default='unknown')\nrequest_...
trial_gpt4o_2
{ "original_instruction": "### Context-Aware Logging System\n\n**Objective:** Implement a context-aware logging system using the `contextvars` module to track and log actions in synchronous and asynchronous code.\n\n#### Requirements:\n1. **Context Variables Declaration:**\n - Create a `ContextVar` for `user_id` wh...
0.537981
Docs: Python310_24487
C
[ "log_action", "handle_request", "handle_request_async" ]
3
[ [ "handle_request", "log_action" ], [ "handle_request_async", "log_action" ] ]
2
[]
false
[]
false
pytest
true
[]
true
41a56df291e2614f066e89739f6fb864e316c649
93fa9c85215a73a63cfc48c47da69da56f33d33a
v1.0
complete
Docs
Docs: Python310_24251_C
def create_capsule(pointer, name, destructor): """ Create a new PyCapsule instance. :param pointer: The pointer to store in the capsule. :param name: The name of the capsule (may be None). :param destructor: The destructor function for the capsule (may be None). :return: A new PyCapsule instanc...
""" A Python extension in C using the PyCapsule API. Below is a Python representation of what the binding functions would look like if they were written in C. """ def create_capsule(pointer, name, destructor): """ Create a new PyCapsule instance. :param pointer: The pointer to store in the capsule. ...
def test_create_capsule(): capsule = create_capsule(pointer="some_pointer", name="test_capsule", destructor=None) assert isinstance(capsule, PyCapsule) assert capsule.pointer == "some_pointer" assert capsule.name == "test_capsule" assert capsule.destructor is None def test_get_pointer_from_capsule(...
[]
[ 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": "\"\"\"\nA Python extension in C using the PyCapsule API. Below is a Python representation of what the binding\nfunctions would look like if the...
trial_gpt4o_1
{ "original_instruction": "Design a Python extension in C using the PyCapsule API described in the provided documentation. This extension will have several key functions:\n\n1. `create_capsule(pointer, name, destructor)`: This function should create a new `PyCapsule` with the given pointer, name, and destructor.\n2. ...
0.328868
Docs: Python310_24251
C
[ "create_capsule", "get_pointer_from_capsule", "set_pointer_in_capsule", "is_capsule_valid", "import_capsule" ]
5
[ [ "get_pointer_from_capsule", "is_capsule_valid" ] ]
1
[]
false
[ "PyCapsule", "PyImport_ImportModule" ]
true
pytest
false
[]
true
1cf79b375cc26027c8d89abee728f1b4ca10bc14
4dc97df53492ae3b36e4977efd86fa0c0440bc8c
v1.0
complete
Docs
Docs: Python310_24759_C
def find_derangements(arr: list) -> list: """ Using the functional programming modules `itertools`, `functools`, and `operator`, write a function `find_derangements` that takes a list of distinct integers as input and returns a list of all possible derangements of this list. >>> find_derangements([1, 2, 3]) ...
import itertools from functools import partial def is_derangement(perm, original): return all(map(lambda i: perm[i] != original[i], range(len(original)))) def find_derangements(arr): all_permutations = itertools.permutations(arr) return list(filter(partial(is_derangement, original=arr), all_permutations))...
from solution import find_derangements def test_find_derangements(): # Test case 1: Basic case input_list = [1, 2, 3] expected_output = [(2, 3, 1), (3, 1, 2)] result = find_derangements(input_list) assert sorted(result) == sorted(expected_output), f"Output was {result}" # Test case 2: Longer l...
[ { "docstring": null, "function_declaration": "def is_derangement(perm, original):", "function_name": "is_derangement", "parameter_list": "(perm, original)" }, { "docstring": null, "function_declaration": "def find_derangements(arr):", "function_name": "find_derangements", "parame...
[ 0, 0, 0, 1, 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 itertools import permutations\nfrom functools import partial\nfrom operator import ne\n\ndef is_derangement(permutation, original):\n return all(map(ne, permuta...
trial_gpt4o_3
{ "original_instruction": "### Derangement Problem\n\nIn combinatorics, a derangement is a permutation of a set such that none of the elements appear in their original positions. For example, the derangements of `[1, 2, 3]` are `[2, 3, 1]`, `[3, 1, 2]`.\n\nUsing the functional programming modules `itertools`, `functo...
0.551064
Docs: Python310_24759
C
[ "is_derangement", "find_derangements" ]
2
[ [ "find_derangements", "is_derangement" ] ]
1
[]
false
[]
false
pytest
true
[]
true
810f66cc7eb4122bed4fae1f1f4f96528529d385
827330133a3dce1178507ec8ad8d7e2798042478
v1.0
complete
Docs
Docs: Pytorch_24515_C
import os import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim import torch.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel class SimpleModel(nn.Module): """ A simple neural network model. """ def __init__(self): super(SimpleModel, ...
import os import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim import torch.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.fc1 = nn.Line...
# Note: These tests would need to be run in a distributed environment which requires at least 2 GPUs. # To simplify this example, we will mock certain functionalities to emulate a distributed environment. import pytest import torch from unittest.mock import MagicMock, patch from solution import SimpleModel, custom_com...
[]
[ 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 os\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nfrom torch.nn.paralle...
trial_gpt4o_8
{ "original_instruction": "### Question: Implementing and Using a Custom DDP Communication Hook in PyTorch\n\nYou have been provided with basic information about DistributedDataParallel (DDP) and communication hooks in PyTorch. Your task is to implement a custom communication hook and use it in a DDP model. The custo...
0.579191
Docs: Pytorch_24515
C
[ "setup", "cleanup", "custom_comm_hook", "run_demo_custom_hook" ]
4
[ [ "run_demo_custom_hook", "cleanup" ], [ "run_demo_custom_hook", "custom_comm_hook" ], [ "run_demo_custom_hook", "setup" ] ]
3
[]
false
[ "SimpleModel" ]
true
pytest
true
[ "torch" ]
false
169e1dc6fe96357dac8c87baa863ccd9ff01bae9
5c469a6de7ffe89f5608fa5493ef59cd6b10734e
v1.0
complete
Docs
Docs: Python310_24718_C
class Student: def __init__(self, student_id: int, name: str, grades: list[int] = None): """ Initialize a Student with ID, name, and grades list. """ pass def add_grade(self, grade: int): """ Adds a new grade to the student's list of grades. Raises: ValueError: If gr...
class Student: def __init__(self, student_id: int, name: str, grades: list[int] = None): if grades is None: grades = [] self.student_id = student_id self.name = name self.grades = grades def add_grade(self, grade: int): if not (0 <= grade <= 100): ...
import pytest from solution import Student, create_student def test_add_grade(): student = create_student(1, "Alice") student.add_grade(85) assert student.grades == [85] with pytest.raises(ValueError): student.add_grade(110) def test_average_grade(): student = create_student(1, "Alice", [7...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Student:\n def __init__(self, student_id, name, grades=None):\n if grades is None:\n grades = []\n self.student_id = student_id\n ...
trial_gpt4o_2
{ "original_instruction": "### Student Management System\nYou are tasked with implementing a simplified student management system using Python. Your system should allow you to store student records, each containing a unique ID, name, list of grades, and compute some aggregate data about the grades.\n\n#### Requiremen...
0.708544
Docs: Python310_24718
C
[ "create_student", "manage_students" ]
2
[ [ "manage_students", "create_student" ] ]
1
[]
false
[ "Student" ]
true
pytest
true
[]
true
a8b752c6e7e4e2cf333453e20b484e6caf95ff46
e7329c846aa411f78336ee8a0f9ebc5ee83a0c60
v1.0
complete
Docs
Docs: Pytorch_24512_C
import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP class CustomDataset(Dataset): def __init__(self, data): self.data = data def __len__(self): return len(self.data) ...
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import Dataset, DataLoader from torch.distributed.algorithms.join import Join from torch.distributed.algorithms.join import Joinable, JoinHoo...
import pytest import torch import torch.distributed as dist from torch.utils.data import DataLoader from solution import CustomDataset, SimpleNeuralNet, generate_dataloader, train, main def test_custom_dataset(): data = [1, 2, 3, 4, 5] dataset = CustomDataset(data) assert len(dataset) == 5 assert datas...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "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.optim as optim\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom t...
trial_gpt4o_0
{ "original_instruction": "### PyTorch Coding Assessment Question\n\nYou are provided with multiple datasets of varying sizes and tasked with training a neural network in a distributed fashion using PyTorch. The challenge involves ensuring that all distributed workers can finish their tasks even when the datasets are...
0.590566
Docs: Pytorch_24512
C
[ "generate_dataloader", "train", "main" ]
3
[ [ "train", "generate_dataloader" ] ]
1
[]
false
[ "CustomDataset", "SimpleNeuralNet" ]
true
pytest
true
[ "torch" ]
false
060335bd798915940725a3ff0067a6e236594716
deb9c3f9cf20d26714a43f3b07b6a792f7815b1d
v1.0
complete
Docs
Docs: Python310_24526_C
import urllib.robotparser from urllib.parse import urlparse def get_hostname(url: str) -> str: parsed_url = urlparse(url) return parsed_url.scheme + '://' + parsed_url.netloc def check_robots_txt(useragent: str, url_list: list) -> dict: """ Checks if a given user agent can fetch a series of URLs from ...
import urllib.robotparser from urllib.parse import urlparse def get_hostname(url: str) -> str: parsed_url = urlparse(url) return parsed_url.scheme + '://' + parsed_url.netloc def check_robots_txt(useragent: str, url_list: list) -> dict: if not url_list: return {} hostname = get_hostname(u...
def test_get_hostname(): assert get_hostname('http://example.com/path') == 'http://example.com' assert get_hostname('https://example.com/path') == 'https://example.com' assert get_hostname('http://example.com:8080/path') == 'http://example.com:8080' assert get_hostname('https://example.com:8080/path') =...
[ { "docstring": null, "function_declaration": "def get_hostname(url):", "function_name": "get_hostname", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def check_robots_txt(useragent, url_list):", "function_name": "check_robots_txt", "parameter_list": "...
[ 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from urllib.robotparser import RobotFileParser\nfrom urllib.parse import urlparse\nimport requests\n\ndef get_hostname(url: str) -> str:\n parsed_url = urlparse(url)...
trial_gpt4o_7
{ "original_instruction": "You are tasked with creating a web scraper that is respectful of the websites it scrapes by adhering to the rules specified in their `robots.txt` files. You will use the `urllib.robotparser` module to parse and interpret these files. For this task, you will implement a function that checks ...
0.726003
Docs: Python310_24526
C
[ "get_hostname", "check_robots_txt" ]
2
[ [ "check_robots_txt", "get_hostname" ] ]
1
[]
false
[]
false
pytest
false
[]
true
3821a76ec368af8a175caf7b72ea5f41ad9154eb
91ddde78ebc8dec578c0dcdebde34bebbab60309
v1.0
complete
Docs
Docs: Python310_24791_C
class InvalidAgeError(ValueError): """ Custom exception to handle invalid age input. Attributes: age (int): The invalid age that caused the exception. message (str): Explanation of the error. """ pass class InvalidInputError(Exception): """ Custom exception to handle invalid in...
# Custom exceptions definition class InvalidAgeError(ValueError): def __init__(self, age, message="Invalid age provided"): self.age = age self.message = message super().__init__(f"{message}: {age}") class InvalidInputError(Exception): def __init__(self, input_data, message="Invalid inpu...
import pytest from solution import InvalidAgeError, InvalidInputError, check_age, validate_age_input def test_check_age_valid(): assert check_age(25) == "Valid age" assert check_age(0) == "Valid age" assert check_age(150) == "Valid age" def test_check_age_invalid(): with pytest.raises(InvalidAgeError)...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class InvalidAgeError(ValueError):\n def __init__(self, age, message=\"Invalid age provided\"):\n self.age = age\n self.message = message\n supe...
trial_gpt4o_2
{ "original_instruction": "### Custom Exception Handling and Chaining in Python\n\n**Objective:**\nWrite a Python program that demonstrates your understanding of creating custom exceptions, raising them, and properly chaining exceptions.\n\n### Task:\n\n1. **Define a Custom Exception:**\n - Create a custom exceptio...
0.522545
Docs: Python310_24791
C
[ "check_age", "validate_age_input" ]
2
[ [ "validate_age_input", "check_age" ] ]
1
[]
false
[ "InvalidAgeError", "InvalidInputError" ]
true
pytest
true
[]
true
19ba5ca57146a2c28bc3679db227d4998404945b
b77e93d31dc8519dea36bdf45516e574bb4a0473
v1.0
complete
Docs
Docs: Python310_25145_C
from typing import List, Dict, Union def process_zip_file(file_path: str) -> List[Dict[str, Union[str, int]]]: """ Opens a ZIP file and generates a report containing details about each file in the archive. Args: file_path (str): The path to the ZIP file. Returns: List[Dict[str, Union[...
from typing import List, Dict, Union import zipfile from datetime import datetime def process_zip_file(file_path: str) -> List[Dict[str, Union[str, int]]]: try: with zipfile.ZipFile(file_path, 'r') as zip_ref: report = [] for file_info in zip_ref.infolist(): file_rep...
import pytest from solution import process_zip_file import zipfile import os @pytest.fixture def create_zipfile(tmp_path): zip_path = tmp_path / "test.zip" with zipfile.ZipFile(zip_path, 'w') as zip_ref: zip_ref.writestr('file1.txt', 'This is some text data for file1.') zip_ref.writestr('file2....
[ { "docstring": null, "function_declaration": "def process_zip_file(file_path):", "function_name": "process_zip_file", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def get_compression_type(compress_type):", "function_name": "get_compression_type", ...
[ 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 zipfile\nfrom typing import List, Dict, Union\n\ndef process_zip_file(file_path: str) -> List[Dict[str, Union[str, int]]]:\n try:\n with zipfile.ZipFil...
trial_gpt4o_2
{ "original_instruction": "## Coding Assessment Question\n\n### Objective\nYou are required to write a function that takes an input ZIP file, processes its contents, and generates a report with specific details about each file in the archive.\n\n### Problem Statement\nWrite a function `process_zip_file(file_path: str...
0.704239
Docs: Python310_25145
C
[ "process_zip_file", "get_compression_type" ]
2
[ [ "process_zip_file", "get_compression_type" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ed882189ba9c834e066bb28fe6bb7d0f151e73d5
04f2ae601089c360a2e32936fa0b4984618bd2a6
v1.0
complete
Docs
Docs: Python310_25382_C
import __future__ as future_module def future_features_info(): """ Retrieves information about all features in the __future__ module. Returns: dict: A dictionary where keys are feature names and values are tuples containing optional release and mandatory release information. """ p...
import __future__ as future_module def future_features_info(): feature_info = {} for feature_name, feature in future_module.__dict__.items(): if isinstance(feature, future_module._Feature): optional = feature.optional mandatory = feature.mandatory feature_info[featur...
from solution import future_features_info, mandatory_in_version def test_future_features_info(): feature_names = ["nested_scopes", "generators", "division", "absolute_import", "print_function", "unicode_literals"] features = future_features_info() for name in feature_names: assert name in features ...
[ { "docstring": null, "function_declaration": "def future_features_info():", "function_name": "future_features_info", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def mandatory_in_version(version):", "function_name": "mandatory_in_version", "parameter_li...
[ 0, 0, 0, 1, 1, 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 __future__\n\ndef future_features_info():\n \"\"\"\n Retrieves information about all features in the __future__ module.\n \n Returns:\n dict: ...
trial_gpt4o_8
{ "original_instruction": "You are tasked with understanding the `__future__` module in Python and creating a utility function that processes data regarding the future statements and their release versions.\n\n### Problem Statement\nWrite a Python function called `future_features_info` that retrieves information abou...
0.406848
Docs: Python310_25382
C
[ "future_features_info", "mandatory_in_version" ]
2
[ [ "mandatory_in_version", "future_features_info" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1b9516662155ce13a8653e0125874c63bd1fbe25
49384119f670f11633fc044361339e903ca83af6
v1.0
complete
Docs
Docs: Seaborn_24517_C
import seaborn as sns import matplotlib.pyplot as plt def create_composite_visualization(): """ Create a composite visualization using seaborn and matplotlib that includes: 1. A scatter plot with a rug plot for the `iris` dataset, showing the relationship between `sepal_length` and `sepal_width`, wi...
import seaborn as sns import matplotlib.pyplot as plt def create_iris_scatter_with_rug(): sns.set_theme() iris = sns.load_dataset("iris") plt.figure(figsize=(12, 5)) plt.subplot(1, 2, 1) sns.scatterplot(data=iris, x='sepal_length', y='sepal_width', hue='species') sns.rugplot(data=iris, x='sepa...
import pytest from matplotlib import pyplot as plt from solution import create_composite_visualization def test_create_composite_visualization(): # Use plt.ion() to enable interactive mode to avoid blocking the test plt.ion() create_composite_visualization() figures = [plt.figure(n) for n in plt.g...
[ { "docstring": null, "function_declaration": "def create_iris_scatter_with_rug():", "function_name": "create_iris_scatter_with_rug", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def create_tips_scatter_with_custom_rug():", "function_name": "create_tips_scat...
[ 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 seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef create_composite_visualization():\n sns.set_theme()\n\n # Create scatter plot with rug plot for the ...
trial_gpt4o_2
{ "original_instruction": "#### Objective:\nYou are required to create a seaborn visualization that leverages the combination of different types of plots and rug plots with customization. This exercise will test your understanding of seaborn's capabilities for advanced visualizations.\n\n#### Problem Statement:\nYou ...
0.737288
Docs: Seaborn_24517
C
[ "create_iris_scatter_with_rug", "create_tips_scatter_with_custom_rug", "create_composite_visualization" ]
3
[ [ "create_composite_visualization", "create_iris_scatter_with_rug" ], [ "create_composite_visualization", "create_tips_scatter_with_custom_rug" ] ]
2
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn" ]
false
49a51e657297c5d9a939d8766223a634221668c4
5c3c7f62b8b70fc6db88ed07a09a5f42a0f0dd05
v1.0
complete
Docs
Docs: Scikit_25147_C
import numpy as np import matplotlib.pyplot as plt from sklearn.isotonic import IsotonicRegression from sklearn.metrics import mean_squared_error def generate_data(): """ Generate a dataset of 100 data points uniformly spaced between 0 and 1, with corresponding y values using the equation y = 3x + noise. ...
import numpy as np import matplotlib.pyplot as plt from sklearn.isotonic import IsotonicRegression from sklearn.metrics import mean_squared_error def generate_data(): np.random.seed(42) X = np.linspace(0, 1, 100) noise = np.random.normal(0, 0.1, 100) y = 3 * X + noise return X, y def fit_and_predi...
from solution import generate_data, fit_and_predict from sklearn.metrics import mean_squared_error import numpy as np def test_generate_data(): X, y = generate_data() assert len(X) == 100 assert len(y) == 100 assert np.all(np.isfinite(y)) def test_fit_and_predict(): X, y = generate_data() new_...
[ { "docstring": null, "function_declaration": "def generate_data():", "function_name": "generate_data", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def fit_and_predict(X, y, new_X, increasing=True):", "function_name": "fit_and_predict", "parameter_list"...
[ 1, 1, 1 ]
3
easy
1
{ "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.isotonic import IsotonicRegression\nfrom sklearn.metrics import mean_squared_error\n\ndef generate_dat...
trial_gpt4o_2
{ "original_instruction": "**Question: Isotonic Regression Implementation and Evaluation**\n\nYou are tasked with implementing and evaluating the `IsotonicRegression` model using the `scikit-learn` library. Your task has several components:\n\n1. **Data Preparation**:\n - Generate a dataset `X` of 100 data points u...
0.611593
Docs: Scikit_25147
C
[ "generate_data", "fit_and_predict", "evaluate_and_plot" ]
3
[ [ "evaluate_and_plot", "fit_and_predict" ], [ "evaluate_and_plot", "generate_data" ] ]
2
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "sklearn" ]
false
7ed3db1fc13ccc3dd0453b819c7daef6c591fdf1
33a0eeba4994af71c26b1b38b82684778113d4c7
v1.0
complete
Docs
Docs: Python310_24739_C
import sqlite3 class Shape: """ Base class for geometrical shapes """ pass class Circle(Shape): def __init__(self, radius: float): self.radius = radius def __repr__(self): return f"Circle(radius={self.radius})" class Rectangle(Shape): def __init__(self, length: float, wid...
import sqlite3 class Shape: pass class Circle(Shape): def __init__(self, radius): self.radius = radius def __repr__(self): return f"Circle(radius={self.radius})" class Rectangle(Shape): def __init__(self, length, width): self.length = length self.width = width...
import pytest import sqlite3 from solution import Circle, Rectangle, create_shapes_table, insert_shape, retrieve_shapes def test_insert_and_retrieve_circle(): conn = sqlite3.connect(":memory:") create_shapes_table(conn) circle = Circle(3.4) insert_shape(conn, circle) retrieved_shapes = retrieve_sha...
[]
[ 0, 0, 0, 1, 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 sqlite3\n\nclass Shape:\n pass\n\nclass Circle(Shape):\n def __init__(self, radius):\n self.radius = radius\n \n def __repr__(self):\n ...
trial_gpt4o_3
{ "original_instruction": "### Question: Implement and Manipulate a Custom SQLite Database with Custom Type Conversion\n\nYou are tasked with creating and managing a SQLite database to store and manipulate geometrical shapes. Each shape will be either a `Circle` or a `Rectangle`, with specific attributes for each:\n\...
0.470397
Docs: Python310_24739
C
[ "adapt_circle", "convert_circle", "adapt_rectangle", "convert_rectangle", "create_shapes_table", "insert_shape", "retrieve_shapes" ]
7
[ [ "insert_shape", "adapt_circle" ], [ "insert_shape", "adapt_rectangle" ], [ "retrieve_shapes", "convert_circle" ], [ "retrieve_shapes", "convert_rectangle" ] ]
4
[]
false
[ "Shape", "Circle", "Rectangle" ]
true
pytest
true
[]
true
7a1aaf07a37271d23debf63b024b136e1f4e1968
d726e541667c848bd77cdddabf39fb4b2f1ae875
v1.0
complete
Docs
Docs: Pytorch_25179_C
import torch def check_simd_support(): """ Checks for SIMD support (AVX, AVX2, AVX-512, AMX) on the current machine. Returns: dict: Dictionary containing the SIMD types supported (keys: 'AVX', 'AVX2', 'AVX-512', 'AMX'; values: boolean indicating support). """ # Your implementation here...
import torch import subprocess def check_simd_support(): """ Checks for SIMD support (AVX, AVX2, AVX-512, AMX) on the current machine. Returns: dict: Dictionary containing the SIMD types supported (keys: 'AVX', 'AVX2', 'AVX-512', 'AMX'; values: boolean indicating support). """ simd_sup...
from solution import check_simd_support, optimize_computation import torch def test_check_simd_support(): simd_support = check_simd_support() assert isinstance(simd_support, dict) assert 'AVX' in simd_support assert 'AVX2' in simd_support assert 'AVX-512' in simd_support assert 'AMX' in simd_su...
[ { "docstring": "Checks for SIMD support (AVX, AVX2, AVX-512, AMX) on the current machine.\n\nReturns:\n dict: Dictionary containing the SIMD types supported (keys: 'AVX', 'AVX2', 'AVX-512', 'AMX'; values: boolean indicating support).", "function_declaration": "def check_simd_support():", "function_na...
[ 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 subprocess\nimport torch\nimport torch.nn.functional as F\n\ndef check_simd_support():\n simd_support = {\n 'AVX': False,\n 'AVX2': False,\n ...
trial_gpt4o_7
{ "original_instruction": "### PyTorch SIMD Optimization Checker\n\n**Objective:**\n\nCreate a PyTorch utility to verify SIMD support on the current system and demonstrate optimization of a neural network computation using SIMD features if available.\n\n**Task:**\n\n1. Write a function `check_simd_support()` that che...
0.532106
Docs: Pytorch_25179
C
[ "check_simd_support", "optimize_computation" ]
2
[ [ "optimize_computation", "check_simd_support" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
1d6befbd5408b4e0035f7fd17477bbff838b590e
555ad84665bab5bb9f239685c372087e4b580d6a
v1.0
complete
Docs
Docs: Python310_25161_C
from typing import List def custom_filter(filenames: List[str], pattern: str) -> List[str]: """ Filters a list of filenames based on a given UNIX shell-style pattern. - `*`: Matches zero or more characters. - `?`: Matches exactly one character. - `[seq]`: Matches any character in `seq`. - `[!seq]`:...
from typing import List def matches_pattern(filename: str, pattern: str) -> bool: i, j = 0, 0 while i < len(filename) and j < len(pattern): if pattern[j] == '*': while j < len(pattern) and pattern[j] == '*': j += 1 if j == len(pattern): return Tru...
from solution import custom_filter def test_wildcard_star(): filenames = ["test.txt", "file.TXT", "data.csv", "report.doc"] pattern = "*.txt" assert custom_filter(filenames, pattern) == ["test.txt", "file.TXT"] def test_wildcard_question(): filenames = ["test.txt", "file.TXT", "data.csv", "report.doc"...
[ { "docstring": null, "function_declaration": "def matches_pattern(filename, pattern):", "function_name": "matches_pattern", "parameter_list": "(filename, pattern)" }, { "docstring": null, "function_declaration": "def custom_filter(filenames, pattern):", "function_name": "custom_filte...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\n\ndef custom_filter(filenames: List[str], pattern: str) -> List[str]:\n def match(filename: str, pattern: str) -> bool:\n filename = ...
trial_gpt4o_6
{ "original_instruction": "### Question: Implement a Filename Filtering Function using Shell-Style Wildcards\n\nYou are tasked with implementing a function that filters a list of filenames based on a given UNIX shell-style pattern. This function will simulate the behavior of the `fnmatch.filter` function but with som...
0.605374
Docs: Python310_25161
C
[ "matches_pattern", "custom_filter" ]
2
[ [ "custom_filter", "matches_pattern" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7bbd40f6662b7eab1ee86ac022515ba52f22b789
4487a8b7df99e73ff28b1c7e1dda139a967e85fb