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_18588_C
import fnmatch import os import tarfile import zipfile def create_source_distribution(manifest_in_file: str, output_format: str) -> None: """ Parses the `MANIFEST.in` file to generate a list of files for distribution, writes a `MANIFEST` file with the list of files, and creates a source distribution archi...
import fnmatch import os import tarfile import zipfile def parse_manifest_in(manifest_in_file): with open(manifest_in_file, 'r') as f: lines = f.readlines() files_to_include = [] for line in lines: line = line.strip() if line.startswith('include'): pattern = line.sp...
import os import shutil import pytest from solution import create_source_distribution # Fixture to setup and teardown a basic file structure for testing @pytest.fixture def setup_files(): os.mkdir('test_dist') os.chdir('test_dist') with open('README.txt', 'w') as f: f.write('This is a README f...
[ { "docstring": null, "function_declaration": "def parse_manifest_in(manifest_in_file):", "function_name": "parse_manifest_in", "parameter_list": "(manifest_in_file)" }, { "docstring": null, "function_declaration": "def write_manifest(manifest_file, files):", "function_name": "write_m...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport tarfile\nimport zipfile\nfrom glob import glob\n\ndef parse_manifest_in(manifest_in_file):\n \"\"\"\n Parse the MANIFEST.in file and generate th...
trial_gpt4o_5
{ "original_instruction": "#### Objective\nYou are required to implement a Python script that parses a `MANIFEST.in` file, generates a `MANIFEST` file listing all files for distribution, and creates a source distribution archive. This question assesses your understanding of file manipulation, parsing, and usage of Py...
0.582644
Docs: Python310_18588
C
[ "parse_manifest_in", "write_manifest", "create_archive", "create_source_distribution" ]
4
[ [ "create_source_distribution", "create_archive" ], [ "create_source_distribution", "parse_manifest_in" ], [ "create_source_distribution", "write_manifest" ] ]
3
[]
false
[]
false
pytest
true
[]
true
313a19e280782d38c19159366be7956b79ab5139
688909a14e821ceeffe027d149a73183d02c5b87
v1.0
complete
Docs
Docs: Python310_18228_C
import asyncio from contextlib import AbstractAsyncContextManager class AsyncNetworkManager(AbstractAsyncContextManager): async def __aenter__(self): """Simulate acquiring a network connection""" async def __aexit__(self, exc_type, exc, tb): """Ensure that the network connection is closed,...
import asyncio from contextlib import AbstractAsyncContextManager class AsyncNetworkManager(AbstractAsyncContextManager): async def __aenter__(self): print("Acquiring connection") await asyncio.sleep(1) # Simulate network delay return self async def __aexit__(self, exc_type, exc, tb):...
import pytest import asyncio from solution import AsyncNetworkManager, fetch_data, process_urls @pytest.mark.asyncio async def test_async_network_manager(): async with AsyncNetworkManager() as manager: assert isinstance(manager, AsyncNetworkManager) @pytest.mark.asyncio async def test_fetch_data(): ur...
[]
[ 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 contextlib import AbstractAsyncContextManager\n\nclass AsyncNetworkManager(AbstractAsyncContextManager):\n async def __aenter__(self):\n ...
trial_gpt4o_0
{ "original_instruction": "You are tasked with implementing a utility that reads data from multiple URLs and processes the data concurrently. To ensure proper resource management, you need to use asynchronous context managers.\n\n### Requirements\n1. **Context Manager**: Implement an asynchronous context manager to h...
0.601986
Docs: Python310_18228
C
[ "fetch_data", "process_urls" ]
2
[ [ "process_urls", "fetch_data" ] ]
1
[]
false
[ "AsyncNetworkManager" ]
true
pytest
true
[]
true
1e2b70595455b8682aa9ab588e9066648848e3d1
e5c6d31f374858a6673c42b88fc61baccc62dd09
v1.0
complete
Docs
Docs: Pytorch_18284_C
import torch from typing import Any, Tuple def apply_window(signal: torch.Tensor, window_type: str, **kwargs) -> torch.Tensor: """ Applies a specified window function to the input signal. Parameters: signal (torch.Tensor): The input 1-dimensional signal tensor. window_type (str): The t...
import torch from typing import Any, Tuple def apply_window(signal: torch.Tensor, window_type: str, **kwargs) -> torch.Tensor: """ Applies a specified window function to the input signal. Parameters: signal (torch.Tensor): The input 1-dimensional signal tensor. window_type (str): The t...
from solution import apply_window, analyze_window_effect import torch import pytest def test_apply_window_invalid_type(): signal = torch.ones(10) with pytest.raises(ValueError): apply_window(signal, "invalid") def test_apply_window_hamming(): signal = torch.ones(10) windowed_signal = apply...
[ { "docstring": "Applies a specified window function to the input signal.\n\nParameters:\n signal (torch.Tensor): The input 1-dimensional signal tensor.\n window_type (str): The type of window function to apply.\n kwargs (Any): Additional arguments required for specific window functions.\n\nReturns:\n ...
[ 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 torch\nimport torch.signal.windows as windows\nfrom typing import Tuple\n\ndef apply_window(signal: torch.Tensor, window_type: str, **kwargs) -> torch.Tensor:\n ...
trial_gpt4o_1
{ "original_instruction": "### Question: Signal Processing with PyTorch Windows\n\nYou are given a 1-dimensional PyTorch tensor representing a signal. Your task is to apply different window functions from the `torch.signal.windows` module to this signal and analyze the results. Specifically, you need to perform the f...
0.590478
Docs: Pytorch_18284
C
[ "apply_window", "analyze_window_effect" ]
2
[ [ "analyze_window_effect", "apply_window" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
afb130ad30e8762a71656fa0b87787265df6c64f
7c1bc9902d57a3f69baa08c5197f217b7e982fe5
v1.0
complete
Docs
Docs: Python310_18348_C
import asyncio from typing import List, Tuple async def run_commands(commands: List[str]) -> List[Tuple[str, int, str, str]]: """ Run multiple shell commands asynchronously and collect their outputs. Args: - commands (List[str]): A list of commands to run as shell commands. Returns: - List[Tu...
import asyncio from typing import List, Tuple async def run_single_command(command: str) -> Tuple[str, int, str, str]: """ Helper function to run a single shell command asynchronously and collect its output. """ process = await asyncio.create_subprocess_shell( command, stdout=asyncio.su...
import pytest import asyncio from solution import run_commands @pytest.mark.asyncio async def test_run_commands_success(): commands = ["echo 'hello world'", "echo 'this is a test'"] results = await run_commands(commands) assert results == [ ("echo 'hello world'", 0, "hello world", ""), ("ec...
[]
[ 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 run_commands(commands: List[str]) -> List[Tuple[str, int, str, str]]:\n \"\"\"\n Run multiple shell co...
trial_gpt4o_2
{ "original_instruction": "### Asyncio Subprocess Management\n\nYou are tasked with creating a Python function that asynchronously runs multiple shell commands concurrently and processes their output. Each command's output should be collected, decoded, and returned. If any command fails (i.e., returns a non-zero exit...
0.620856
Docs: Python310_18348
C
[ "run_single_command", "run_commands" ]
2
[ [ "run_commands", "run_single_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a90ecb673b8ba945f667c48f2ba4d46d1376b73b
4333820d9f3a445065fdfccbdcb41b901a08eef0
v1.0
complete
Docs
Docs: Pytorch_18573_C
import torch import torch.func as tf def compute_gradient(f: callable) -> callable: """ Computes the gradient of the function f with respect to its input. Args: - f (callable): A function that takes a 2D tensor and returns a scalar. Returns: - callable: A function that computes the gradient o...
import torch import torch.func as tf def compute_gradient(f: callable) -> callable: """ Computes the gradient of the function f with respect to its input. Args: - f (callable): A function that takes a 2D tensor and returns a scalar. Returns: - callable: A function that computes the gradient o...
import torch from solution import compute_gradient, batch_compute_gradient def test_compute_gradient_simple_function(): def f(x): return torch.sum(x ** 2) grad_f = compute_gradient(f) x = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) expected_grad = 2 * x assert torch.allclose(grad_f(x),...
[ { "docstring": "Computes the gradient of the function f with respect to its input.\n\nArgs:\n- f (callable): A function that takes a 2D tensor and returns a scalar.\n\nReturns:\n- callable: A function that computes the gradient of f.", "function_declaration": "def compute_gradient(f):", "function_name":...
[ 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 torch\nimport torch.func as tf\n\ndef compute_gradient(f: callable) -> callable:\n \"\"\"\n Computes the gradient of the function f with respect to its inp...
trial_gpt4o_2
{ "original_instruction": "### **Problem: Composable Function Transforms in PyTorch**\n\nYou are given a function `f` that takes a 2D tensor (matrix) as input and returns a scalar value. Your task is to implement a new function that computes the per-sample gradients for a batch of such matrices using `torch.func`.\n\...
0.540955
Docs: Pytorch_18573
C
[ "compute_gradient", "batch_compute_gradient", "f" ]
3
[ [ "batch_compute_gradient", "compute_gradient" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
747ac8f5e2a0b1b182ae6ae1b02671815efc5631
1e95b6c73af85d8b90be57a94908ec5baa99fdfc
v1.0
complete
Docs
Docs: Python310_18270_C
import asyncio async def fetch_piece(server_id: int, delay: int) -> str: """ Simulates fetching a piece of data from a server. Args: - server_id (int): The ID of the server to fetch from. - delay (int): The simulated time in seconds it takes to fetch the data. Returns: - str: The piece of...
import asyncio async def fetch_piece(server_id: int, delay: int) -> str: """ Simulates fetching a piece of data from a server. Args: - server_id (int): The ID of the server to fetch from. - delay (int): The simulated time in seconds it takes to fetch the data. Returns: - str: The piece of...
import asyncio import pytest from solution import fetch_piece, combine_results @pytest.mark.asyncio async def test_fetch_piece(): result = await fetch_piece(1, 1) assert result == "Data from server 1" @pytest.mark.asyncio async def test_combine_results_all_within_timeout(): servers = [(1, 1), (2, 2), (3, ...
[]
[ 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 fetch_piece(server_id: int, delay: int) -> str:\n \"\"\"\n Simulates fetching a piece of data from a server.\n\n Args:\n - serve...
trial_gpt4o_0
{ "original_instruction": "### Coding Assessment\n\n**Objective**: Demonstrate your understanding of Python's asyncio module by implementing a task that performs multiple concurrent operations and manages task synchronization and timeouts.\n\n**Problem Statement**:\n\nYou are required to implement an asynchronous sim...
0.547574
Docs: Python310_18270
C
[ "fetch_piece", "combine_results" ]
2
[ [ "combine_results", "fetch_piece" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2ac9608efbe0f0d340bd96afca166972dedc37e3
6554d20f75f6916945da990bbc2808f62c486cf8
v1.0
complete
Docs
Docs: Python310_18492_C
import warnings from typing import Callable def handle_warnings(): """ Set up warning filters: - Convert DeprecationWarning to errors. - Ignore (but log) UnicodeWarning. """ pass # Implement this function def suppress_specific_warning(fxn: Callable, *args, **kwargs): """ Temporarily s...
import warnings def handle_warnings(): """ Set up warning filters: - Convert DeprecationWarning to errors. - Ignore (but log) UnicodeWarning. """ # Turn DeprecationWarning into an error warnings.filterwarnings('error', category=DeprecationWarning) # Ignore (but log) UnicodeWarning ...
import warnings from solution import handle_warnings, suppress_specific_warning, example_function def test_handle_warnings(): handle_warnings() # Test DeprecationWarning raising an error try: warnings.warn("This is a deprecation warning.", DeprecationWarning) assert False, "DeprecationWarn...
[ { "docstring": "Set up warning filters:\n- Convert DeprecationWarning to errors.\n- Ignore (but log) UnicodeWarning.", "function_declaration": "def handle_warnings():", "function_name": "handle_warnings", "parameter_list": "()" }, { "docstring": "Temporarily suppress ResourceWarning during t...
[ 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 warnings\n\ndef handle_warnings():\n \"\"\"\n Sets the necessary warning filters.\n \"\"\"\n # Turn DeprecationWarning into an error\n warnings.si...
trial_gpt4o_7
{ "original_instruction": "**Question: Warning Customization and Control using Python's `warnings` Module**\n\nYou have been tasked with improving a legacy codebase of a Python application. The application is riddled with deprecated functions, resource mismanagement, and several other issues that raise warnings. Your...
0.499476
Docs: Python310_18492
C
[ "handle_warnings", "suppress_specific_warning", "example_function", "test_warnings" ]
4
[ [ "test_warnings", "example_function" ], [ "test_warnings", "handle_warnings" ], [ "test_warnings", "suppress_specific_warning" ] ]
3
[]
false
[]
false
pytest
true
[]
true
036caaf3902bfe545806dd00c8786cbfc137aee1
7116ceef57cb8e90118a35e6514eb9b2a21a987b
v1.0
complete
Docs
Docs: Python310_18568_C
class MyCustomType: """ A custom type that is typically defined using Python C API. """ def __init__(self): self.attributes = {} def is_subtype(obj): """ Check if the given object is a subtype of MyCustomType. >>> obj = create_instance() >>> is_subtype(obj) True >>> is_...
# The real implementation would be done in C using Python C API, but here is a Python approximation for the # purpose of demonstrating the structure. class MyCustomType: """ A custom type that is typically defined using Python C API. """ def __init__(self): self.attributes = {} def is_subtype...
from solution import MyCustomType, is_subtype, get_type_flags, modify_type, create_instance def test_create_instance(): obj = create_instance() assert isinstance(obj, MyCustomType) def test_is_subtype_with_mycustomtype_instance(): obj = create_instance() assert is_subtype(obj) def test_is_subtype_wit...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "# mycustommodule.c\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include <structmember.h>\n\n// Define the structure of our custom type\ntypedef struct {\n PyObje...
trial_gpt4o_2
{ "original_instruction": "Title: Creating and Manipulating Custom Types Using Python C API\n\n**Objective**:\nWrite a Python C extension module that defines a custom heap-allocated type. This type should include methods to check type flags and manipulate type features. \n\n**Instructions**:\n\n1. **Creating a Custom...
0.399991
Docs: Python310_18568
C
[ "is_subtype", "get_type_flags", "modify_type", "create_instance" ]
4
[ [ "get_type_flags", "is_subtype" ], [ "modify_type", "is_subtype" ] ]
2
[]
false
[ "MyCustomType" ]
true
pytest
true
[]
true
06b9d463f29160ef8de36145a9f5bd32176d6f35
a586eaad651f8db2f08da3d6ec48466281d2991a
v1.0
complete
Docs
Docs: Python310_18583_C
import asyncio import platform import aiohttp async def fetch_data(url): """ Fetch data from a given URL. Args: url (str): The URL to fetch data from. Returns: str: The content of the fetched URL. """ # Implement fetching data using aiohttp here async def gather_data(urls): ...
import asyncio import platform import aiohttp async def fetch_data(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text() async def gather_data(urls): tasks = [fetch_data(url) for url in urls] return await asyncio.gath...
import pytest import asyncio from unittest.mock import patch, Mock from solution import fetch_data, gather_data, run_subprocess @pytest.mark.asyncio async def test_fetch_data(): url = "http://example.com" expected_content = "Example Domain" with patch("aiohttp.ClientSession.get") as mock_get: mock_...
[ { "docstring": null, "function_declaration": "def main():", "function_name": "main", "parameter_list": "()" } ]
[ 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\nimport platform\nimport aiohttp\n\nasync def fetch_data(url):\n async with aiohttp.ClientSession() as session:\n async with session.get(url) a...
trial_gpt4o_0
{ "original_instruction": "### Python Asyncio and Event Loops Challenge\n\nYou are required to create a script that leverages the `asyncio` module to manage multiple asynchronous tasks. Your solution will need to create an event loop, schedule tasks, handle subprocesses on Windows and macOS, and consider the limitati...
0.568013
Docs: Python310_18583
C
[ "fetch_data", "gather_data", "run_subprocess", "main" ]
4
[ [ "gather_data", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
fff41efd4ceb60a9861f3431f38a9fb1743dcb97
83cfcef884d2abd72c47e22fd2a069682b207f6d
v1.0
complete
Docs
Docs: Python310_18272_C
import inspect call_depth = 0 def trace(func): """ Decorator that prints a message upon entering and exiting a function, including the function name, filename, and line number in the print messages. >>> @trace >>> def sample_function(): >>> pass >>> sample_function() Entering sample...
import inspect import os call_depth = 0 def trace(func): def wrapper(*args, **kwargs): global call_depth # Get calling frame for getting filename and line number frame = inspect.currentframe().f_back file_name = os.path.basename(frame.f_code.co_filename) line_no = ...
from solution import start, function_1, function_2, function_3 def test_trace_output(capsys): start() captured = capsys.readouterr() output_lines = captured.out.strip().split("\n") assert "Entering start in" in output_lines[0] assert "Entering function_1 in" in output_lines[1] assert "Ente...
[ { "docstring": null, "function_declaration": "def trace(func):", "function_name": "trace", "parameter_list": "(func)" }, { "docstring": null, "function_declaration": "def start():", "function_name": "start", "parameter_list": "()" }, { "docstring": null, "function_dec...
[ 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 inspect\nimport os\n\ncall_depth = 0\n\ndef trace(func):\n def wrapper(*args, **kwargs):\n global call_depth\n \n # Get calling frame for...
trial_gpt4o_0
{ "original_instruction": "You are tasked with writing a Python script that simulates the process of integrating tracing functionality in a simplified, educational version of CPython. The goal is to understand how tracing of function calls and their returns could be implemented.\n\n**Objective**: Implement a tracing ...
0.612107
Docs: Python310_18272
C
[ "trace", "start", "function_1", "function_2", "function_3" ]
5
[ [ "function_1", "function_3" ], [ "function_2", "function_1" ], [ "start", "function_1" ], [ "start", "function_2" ] ]
4
[]
false
[]
false
pytest
true
[]
true
a40e55eb3d0715bc601deefedf479551cab78a48
308abb95f160090d8b77a336684d76107707e338
v1.0
complete
Docs
Docs: Python310_18301_C
def fetch_clean_text_from_urls(urls: list, auth: dict = None) -> dict: """ Fetch HTML content from a list of URLs, handle HTTP basic authentication if needed, and return clean text (no HTML tags) from the fetched content. >>> urls = ["http://example.com", "https://example.org"] >>> fetch_clean_text_fro...
import urllib.request import urllib.error from urllib.request import HTTPBasicAuthHandler, HTTPPasswordMgrWithDefaultRealm, build_opener, install_opener, urlopen from html.parser import HTMLParser # Custom HTMLParser to extract text from HTML class MyHTMLParser(HTMLParser): def __init__(self): super().__in...
import pytest from solution import fetch_clean_text_from_urls # The following tests mock urlopen but in real scenario you might want to use libraries like responses to mock requests def test_fetch_clean_text_no_auth(): urls = ["http://example.com"] result = fetch_clean_text_from_urls(urls) assert "http://...
[]
[ 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 urllib.request\nimport urllib.error\nfrom urllib.request import HTTPBasicAuthHandler, HTTPPasswordMgrWithDefaultRealm, build_opener, install_opener, urlopen\nfro...
trial_gpt4o_0
{ "original_instruction": "You are required to implement a Python function that fetches the HTML content from a list of URLs, handles HTTP basic authentication if needed, and returns the clean text (no HTML tags) from the fetched content. You will use the `urllib.request` module for these operations.\n\n### Function ...
0.663416
Docs: Python310_18301
C
[ "strip_html_tags", "fetch_clean_text_from_urls" ]
2
[ [ "fetch_clean_text_from_urls", "strip_html_tags" ] ]
1
[]
false
[ "MyHTMLParser" ]
true
pytest
true
[]
true
06c73db7aa72a9d84280d077066ff5c60b26bfaf
b6179e8b5fcbc621bffe2efeddbcf5c6e9df2085
v1.0
complete
Docs
Docs: Pytorch_18341_C
import os import subprocess from typing import List, Tuple def set_environment_variables(): """ Set the relevant TorchInductor environment variables. """ os.environ['TORCHINDUCTOR_UNIQUE_KERNEL_NAMES'] = '1' os.environ['TORCHINDUCTOR_BENCHMARK_KERNEL'] = '1' def run_model(model_script: str) -> str...
import os import subprocess from typing import List, Tuple def set_environment_variables(): """ Set the relevant TorchInductor environment variables. """ os.environ['TORCHINDUCTOR_UNIQUE_KERNEL_NAMES'] = '1' os.environ['TORCHINDUCTOR_BENCHMARK_KERNEL'] = '1' def run_model(model_script: str) -> str...
import os import subprocess from solution import set_environment_variables, run_model, parse_profiling_data, optimize_kernel def test_set_environment_variables(): set_environment_variables() assert os.environ['TORCHINDUCTOR_UNIQUE_KERNEL_NAMES'] == '1' assert os.environ['TORCHINDUCTOR_BENCHMARK_KERNEL'] ==...
[ { "docstring": "Set the relevant TorchInductor environment variables.", "function_declaration": "def set_environment_variables():", "function_name": "set_environment_variables", "parameter_list": "()" }, { "docstring": "Run the given model script and collect profiling data.\n\nArgs:\n- model...
[ 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 subprocess\nfrom typing import List, Tuple\n\ndef set_environment_variables():\n \"\"\"\n Set the relevant TorchInductor environment variables.\...
trial_gpt4o_9
{ "original_instruction": "### Task\n\nYou are given a deep learning model implemented in PyTorch and you are required to perform GPU profiling to identify and optimize its performance bottlenecks using TorchInductor. Follow the steps below:\n\n1. **Setup the Environment:**\n - Implement a function to set the relev...
0.572607
Docs: Pytorch_18341
C
[ "set_environment_variables", "run_model", "parse_profiling_data", "optimize_kernel", "parse_execution_time" ]
5
[ [ "optimize_kernel", "parse_execution_time" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2104502a87ac1b38cecb7afbe7f4f7703128fdf2
72a315fee933f89c1a1901cd9a35f3eaac222979
v1.0
complete
Docs
Docs: Python310_19073_C
import asyncio import platform import socket import sys async def async_monitor_sockets(sockets): """ Asynchronously monitors multiple network socket connections and performs read and write operations based on the platform. >>> import socket >>> sockets = [socket.socket(socket.AF_INET, socket.SOCK_STR...
import asyncio import platform import socket import sys async def handle_socket(sock): loop = asyncio.get_event_loop() while True: data = await loop.sock_recv(sock, 1024) if not data: break print(f"Received data: {data.decode('utf-8')}") await loop.sock_sendall(sock,...
import pytest import socket import asyncio from solution import async_monitor_sockets @pytest.mark.asyncio async def test_async_monitor_sockets(): # Mock server to test against server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('localhost', 8000)) server.listen(5) server.setblo...
[]
[ 0, 0, 0, 0, 0, 1, 0, 1, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\nimport socket\n\n\nasync def handle_socket(sock):\n try:\n # Read data from the socket\n data = await asyncio.to_threa...
trial_gpt4o_5
{ "original_instruction": "**Objective:**\n\nCreate an asynchronous program in Python that monitors multiple network socket connections and performs specific read and write operations based on the platform it is running on.\n\n### Requirements:\n\n1. **Function Implementation:** Implement a function `async_monitor_so...
0.625687
Docs: Python310_19073
C
[ "handle_socket", "async_monitor_sockets" ]
2
[ [ "async_monitor_sockets", "handle_socket" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0c54727d687ce24aea7efa91e8ee84a7cd47eed3
fe840fc58c05c82f867229ace39483bc7434470a
v1.0
complete
Docs
Docs: Pytorch_18834_C
import torch from torch.nn.attention.flex_attention import flex_attention, create_block_mask, create_nested_block_mask, noop_mask def custom_flex_attention(input_tensor: torch.Tensor, mask_type: str) -> torch.Tensor: """ Compute the flexible attention mechanism with a custom mask. :param input_tensor: A P...
import torch from torch.nn.functional import softmax def create_block_mask(seq_len, block_size): mask = torch.zeros(seq_len, seq_len) for i in range(seq_len): start = max(0, i - block_size) end = min(seq_len, i + block_size + 1) mask[i, start:end] = 1 return mask def create_nested_...
import torch from solution import custom_flex_attention def test_custom_flex_attention_block_mask(): input_tensor = torch.randn(2, 10, 64) mask_type = "block" output_tensor = custom_flex_attention(input_tensor, mask_type) assert output_tensor.shape == input_tensor.shape def test_custom_flex_attention_...
[ { "docstring": null, "function_declaration": "def create_block_mask(seq_len, block_size):", "function_name": "create_block_mask", "parameter_list": "(seq_len, block_size)" }, { "docstring": null, "function_declaration": "def create_nested_block_mask(seq_len):", "function_name": "crea...
[ 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.nn.functional import softmax\n\ndef create_block_mask(seq_len, block_size):\n mask = torch.zeros(seq_len, seq_len)\n for i in range(seq_l...
trial_gpt4o_0
{ "original_instruction": "**Coding Question: Implement a Flexible Attention Mechanism**\n\n### Objective\nThe objective of this question is to test your understanding and ability to implement a custom attention mechanism using PyTorch's `torch.nn.attention.flex_attention` module and its associated utility functions....
0.42649
Docs: Pytorch_18834
C
[ "create_block_mask", "create_nested_block_mask", "noop_mask", "flex_attention", "custom_flex_attention" ]
5
[ [ "custom_flex_attention", "create_block_mask" ], [ "custom_flex_attention", "create_nested_block_mask" ], [ "custom_flex_attention", "flex_attention" ], [ "custom_flex_attention", "noop_mask" ] ]
4
[]
false
[]
false
pytest
true
[ "torch" ]
false
ff9ad1f20f7a07433e7ec23e3b2778bee12a0201
4dccd643b164b3307cddd8936b317c1933acfd6e
v1.0
complete
Docs
Docs: Pandas_18470_C
import pandas as pd def load_and_clean_data(file_path): """Load and clean the sales data from a CSV file. - Parses `date` column to datetime objects. - Removes any duplicate rows. - Fills missing values in `units_sold` and `unit_price` columns with the mean value of their respective columns. -...
import pandas as pd def load_and_clean_data(file_path): # Load the dataset df = pd.read_csv(file_path) # Parse the 'date' column to datetime df['date'] = pd.to_datetime(df['date']) # Remove any duplicate rows df = df.drop_duplicates() # Fill missing values in 'units_sold' and...
import os import pandas as pd import pytest from solution import load_and_clean_data, generate_summary_report, create_pivot_table, save_to_csv, process_sales_data def setup_module(module): # Setup a temporary CSV file for testing test_data = '''date,salesperson,region,product,units_sold,unit_price 2022-01-01,J...
[ { "docstring": null, "function_declaration": "def load_and_clean_data(file_path):", "function_name": "load_and_clean_data", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def generate_summary_report(df):", "function_name": "generate_summary_report", ...
[ 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 pandas as pd\n\ndef process_sales_data(input_csv, pivot_csv, summary_csv):\n # Load the dataset into a pandas DataFrame\n df = pd.read_csv(input_csv)\n ...
trial_gpt4o_4
{ "original_instruction": "### Objective:\nYou are required to manipulate a dataset using pandas to analyze sales data of a company. The dataset is provided as a CSV file named `sales_data.csv` with the following columns:\n- `date` (String): Date of the sale in YYYY-MM-DD format.\n- `salesperson` (String): Name of th...
0.766063
Docs: Pandas_18470
C
[ "load_and_clean_data", "generate_summary_report", "create_pivot_table", "save_to_csv", "process_sales_data" ]
5
[ [ "process_sales_data", "create_pivot_table" ], [ "process_sales_data", "generate_summary_report" ], [ "process_sales_data", "load_and_clean_data" ], [ "process_sales_data", "save_to_csv" ] ]
4
[]
false
[]
false
pytest
true
[ "pandas" ]
false
960ed99c162cdc27b11bfb03452ac4a22a5ddc22
7aaceba300db81113743b7b8636fb669d1c76f64
v1.0
complete
Docs
Docs: Python310_18798_C
import asyncio import aiohttp import os import platform from typing import List async def async_file_downloader(urls: List[str], dest_folder: str) -> List[str]: """ Downloads multiple files concurrently using asyncio, adapting to platform-specific limitations. Args: urls: A list of file URLs to down...
import asyncio import aiohttp import os import platform import sys from selectors import SelectSelector from typing import List async def download_file(session, url, dest_folder): try: async with session.get(url) as response: if response.status != 200: raise Exception(f"Failed t...
import os import pytest import asyncio from unittest.mock import patch, MagicMock from solution import async_file_downloader # Setup for tests @pytest.fixture def download_urls(): return ["http://example.com/file1.txt", "http://example.com/file2.txt", "http://example.com/file3.txt"] @pytest.fixture def dest_folde...
[]
[ 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\nimport aiohttp\nimport os\nimport platform\nfrom asyncio import AbstractEventLoop\nfrom typing import List\n\nasync def download_file(session: aiohttp.C...
trial_gpt4o_2
{ "original_instruction": "### Asynchronous File Downloader with Platform-Specific Limitations\n\n**Objective:** Implement an asynchronous file downloader using the \"asyncio\" module in Python that handles platform-specific limitations.\n\n#### Problem Statement:\nYou are tasked with writing a Python function, `asyn...
0.608136
Docs: Python310_18798
C
[ "download_file", "async_file_downloader" ]
2
[ [ "async_file_downloader", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
bf7938aacc1eaea9f3716a589ca7775935844b18
281147768bc4086ff86a9d3afb22b64aa9887976
v1.0
complete
Docs
Docs: Python310_18500_C
import asyncio import logging async def simulate_cpu_bound_operation(data: bytes) -> str: """ Simulate a CPU-bound task. >>> await simulate_cpu_bound_operation(b"hello") 'olleh' """ pass async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: """ Ha...
import asyncio import logging # Setting up logging logging.basicConfig(level=logging.DEBUG) async def simulate_cpu_bound_operation(data: bytes) -> str: """ Simulate a CPU-bound task. The operation will reverse the string as a simple simulation. """ # Simulate computation await asyncio.sleep(2)...
import asyncio import logging import pytest from solution import start_server, handle_client @pytest.fixture async def server(): """ Fixture to start and stop the server. """ server = await asyncio.start_server(handle_client, '127.0.0.1', 8888) yield server server.close() await server.wait_...
[]
[ 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 asyncio\nimport logging\n\n# Setting up logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger('asyncio')\nlogger.setLevel(logging.DEBUG)\...
trial_gpt4o_2
{ "original_instruction": "### Asynchronous Server with Concurrency and Proper Exception Handling\n\nYou are tasked with creating an asynchronous server that handles incoming connections from clients. The server should be able to handle multiple clients concurrently while ensuring that blocking operations do not impe...
0.574557
Docs: Python310_18500
C
[ "simulate_cpu_bound_operation", "handle_client", "start_server" ]
3
[ [ "handle_client", "simulate_cpu_bound_operation" ], [ "start_server", "handle_client" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d5252e752f6b46876d95d3aa857810e48ffab225
f3f157abb90e8eb9d75cf5a8fffcb813229a7ccf
v1.0
complete
Docs
Docs: Python310_17999_C
from typing import List, Dict def encode_strings(strings: List[str], codec: str) -> List[bytes]: """ Encode a list of strings into a specified codec. Args: strings (List[str]): List of strings to encode. codec (str): The codec to use for encoding. Returns: List[bytes]: List of encoded bytes. ...
from typing import List, Dict def encode_strings(strings: List[str], codec: str) -> List[bytes]: """ Encode a list of strings using the specified codec. """ try: return [s.encode(codec) for s in strings] except Exception as e: raise ValueError(f"Encoding failed: {e}") def decode_st...
from solution import encode_strings, decode_strings, process_strings def test_encode_strings_utf8(): strings = ["hello", "world"] assert encode_strings(strings, "utf-8") == [b'hello', b'world'] def test_encode_strings_utf16(): strings = ["hello", "world"] encoded = encode_strings(strings, "utf-16") ...
[ { "docstring": "Encode a list of strings using the specified codec.", "function_declaration": "def encode_strings(strings, codec):", "function_name": "encode_strings", "parameter_list": "(strings, codec)" }, { "docstring": "Decode a list of encoded bytes using the specified codec.", "fun...
[ 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 typing import List, Dict\n\ndef encode_strings(strings: List[str], codec: str) -> List[bytes]:\n \"\"\"\n Encodes a list of strings using the specified codec...
trial_gpt4o_2
{ "original_instruction": "## Coding Assessment Question\n\n### Objective\nImplement a function that encodes a list of strings into various Unicode codecs and then decodes them, storing the results in a dictionary.\n\n### Task\nYou are tasked with writing two functions:\n\n1. `encode_strings(strings: List[str], codec...
0.712712
Docs: Python310_17999
C
[ "encode_strings", "decode_strings", "process_strings" ]
3
[ [ "process_strings", "decode_strings" ], [ "process_strings", "encode_strings" ] ]
2
[]
false
[]
false
pytest
true
[]
true
79392e6d6bdef3bc85e20e73a8cf6ecd8606a8df
ffb695dc38c70ecf4e732422490b5a1ea43c957a
v1.0
complete
Docs
Docs: Python310_19006_C
import asyncio import logging import random from concurrent.futures import ThreadPoolExecutor logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) async def fetch_page(url): """ Simulates fetching a web page by sleeping for a random time between 0.1 to 1 second. """ # Write yo...
import asyncio import logging import random from concurrent.futures import ThreadPoolExecutor logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) async def fetch_page(url): """ Simulates fetching a web page by sleeping for a random time between 0.1 to 1 second. """ sleep_time...
import asyncio from solution import fetch_page, process_content, main def test_fetch_page(monkeypatch): class MockRandom: def uniform(self, a, b): return 0.5 monkeypatch.setattr('random.uniform', MockRandom().uniform) asyncio.run(async_test_fetch_page()) async def async_test_fetch_pag...
[ { "docstring": null, "function_declaration": "def blocking_task():", "function_name": "blocking_task", "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 asyncio\nimport logging\nimport random\nfrom concurrent.futures import ThreadPoolExecutor\n\nasync def fetch_page(url):\n \"\"\"\n Simulates fetching a web...
trial_gpt4o_1
{ "original_instruction": "### Advanced Python Coding Assessment\n\n#### Objective:\nTo assess your understanding of asynchronous programming in Python using the `asyncio` module, including debugging, concurrency, running blocking code, and proper task handling.\n\n#### Task:\nCreate an asynchronous Python applicatio...
0.561847
Docs: Python310_19006
C
[ "fetch_page", "process_content", "simulate_blocking_operation", "main", "fetch_and_process" ]
5
[ [ "fetch_and_process", "fetch_page" ], [ "fetch_and_process", "process_content" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a4b85121fc4dc711d0bad45dbb6db0bafeac52cf
ff0f491015d025041f9125e5890e294c95a8ed7a
v1.0
complete
Docs
Docs: Pytorch_18729_C
import torch def compute_fft(signal: torch.Tensor) -> torch.Tensor: """ Computes the one-dimensional FFT of a real-valued input signal. Args: signal (torch.Tensor): Real-valued input signal. Returns: torch.Tensor: Complex tensor representing the frequency domain. """ pass def recons...
import torch def compute_fft(signal: torch.Tensor) -> torch.Tensor: """ Computes the one-dimensional FFT of a real-valued input signal. Args: signal (torch.Tensor): Real-valued input signal. Returns: torch.Tensor: Complex tensor representing the frequency domain. """ return to...
import torch from solution import compute_fft, reconstruct_signal, filter_frequencies def test_compute_fft(): signal = torch.tensor([0.0, 1.0, 0.0, -1.0]) frequency_domain = compute_fft(signal) expected_frequency_domain = torch.tensor([0.0+0.0j, 0.0-2.0j, 0.0+0.0j, 0.0+2.0j]) assert torch.allclose(freq...
[ { "docstring": "Computes the one-dimensional FFT of a real-valued input signal.\n\nArgs:\nsignal (torch.Tensor): Real-valued input signal.\n\nReturns:\ntorch.Tensor: Complex tensor representing the frequency domain.", "function_declaration": "def compute_fft(signal):", "function_name": "compute_fft", ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef compute_fft(signal: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Computes the one-dimensional FFT of a given real-valued input signal.\n \"\"\...
trial_gpt4o_2
{ "original_instruction": "### Question: Implementing and Applying FFT in PyTorch\n\nIn this exercise, you will demonstrate your understanding of PyTorch's FFT functionality by implementing functions to process and analyze signals. \n\n#### Problem Statement\n\n1. **Signal Frequency Analysis:**\n - Write a functio...
0.561228
Docs: Pytorch_18729
C
[ "compute_fft", "reconstruct_signal", "filter_frequencies" ]
3
[ [ "filter_frequencies", "compute_fft" ], [ "filter_frequencies", "reconstruct_signal" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
bf7c659037dce07fe3f6e9fc146459ffc41710d7
9e8c95d224a8fadf76fab8f86583cd63cb942375
v1.0
complete
Docs
Docs: Python310_19107_C
import asyncio from typing import List, Tuple async def process_tasks_concurrently(tasks: List[Tuple[str, int]], worker_count: int) -> None: """ Processes a list of tasks concurrently using a specified number of workers. Each task is a tuple (task_name, duration). Each worker will pick tasks from the queue, ...
import asyncio from typing import List, Tuple async def worker(worker_id: int, queue: asyncio.Queue): while not queue.empty(): task_name, duration = await queue.get() await asyncio.sleep(duration) print(f"Worker {worker_id} completed task '{task_name}' in {duration} seconds") queue....
import asyncio import pytest from solution import process_tasks_concurrently @pytest.mark.asyncio async def test_process_tasks_concurrently(): tasks = [("A", 2), ("B", 3), ("C", 1)] worker_count = 2 await process_tasks_concurrently(tasks, worker_count) @pytest.mark.asyncio async def test_single_worker...
[]
[ 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 worker(worker_id: int, queue: asyncio.Queue):\n while not queue.empty():\n task_name, duration = a...
trial_gpt4o_1
{ "original_instruction": "<|Analysis Begin|>\n\nThe provided documentation describes the `asyncio` library in Python, which is utilized for writing concurrent code using the `async` and `await` syntax. It outlines the major functionalities of `asyncio`:\n\n1. High-level APIs:\n - Running coroutines concurrently.\n...
0.681006
Docs: Python310_19107
C
[ "worker", "process_tasks_concurrently" ]
2
[ [ "process_tasks_concurrently", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e18cec34fdb1ae54525c7a7722ab217ad0f2b271
16b07694ea93dcf20ba94d0ed48cee8c3aa08bee
v1.0
complete
Docs
Docs: Python310_17359_C
# chat_server.py import asyncio async def handle_client(reader, writer): """ Handle the communication with a connected client. """ pass async def main(host, port): """ Create an asyncio server that listens on a specified host and port. """ server = await asyncio.start_server(handle_client, hos...
# chat_server.py import asyncio clients = [] async def handle_client(reader, writer): addr = writer.get_extra_info('peername') clients.append(writer) print(f"Connected by {addr}") try: while True: data = await reader.read(100) if not data: break ...
import asyncio import pytest import socket from contextlib import closing # Function to find free port for testing def find_free_port(): with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: s.bind(('', 0)) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return s.get...
[ { "docstring": null, "function_declaration": "def broadcast_message(message, current_writer):", "function_name": "broadcast_message", "parameter_list": "(message, current_writer)" } ]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "# chat_server.py\nimport asyncio\n\nclients = []\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Connected by {a...
trial_gpt4o_2
{ "original_instruction": "### Asynchronous Chat Server with asyncio\n\n#### Objective:\nDesign and implement an asynchronous chat server using the `asyncio` library. The server should be able to handle multiple clients, broadcast messages to all connected clients, and properly manage network connections and exceptio...
0.62211
Docs: Python310_17359
C
[ "handle_client", "broadcast_message", "main", "handle_input", "handle_output", "main" ]
6
[ [ "handle_client", "broadcast_message" ] ]
1
[ "handle_input" ]
false
[]
false
pytest
false
[]
true
4ac14f54a2065c91388e1fb6f5f8c896d0e3d149
b3ad41692ebca547208fd70fdc919b0157560ba7
v1.0
complete
Docs
Docs: Python310_18813_C
import hashlib def create_file_hash(file_path, algorithm): """ Creates a hash for the specified file using the given algorithm. Args: - file_path (str): Path to the file that needs to be hashed. - algorithm (str): The hashing algorithm to use (e.g., 'sha256', 'sha512'). Returns: - str: The com...
import hashlib def create_file_hash(file_path, algorithm): """ Creates a hash for the specified file using the given algorithm. Args: - file_path (str): Path to the file that needs to be hashed. - algorithm (str): The hashing algorithm to use (e.g., 'sha256', 'sha512'). Returns: - str: Th...
import pytest from solution import create_file_hash, verify_file_integrity def test_create_file_hash_sha256(tmp_path): file = tmp_path / "testfile.txt" file.write_text("This is a test.") expected_hash = hashlib.sha256(b"This is a test.").hexdigest() assert create_file_hash(str(file), 'sha256') == expe...
[ { "docstring": "Creates a hash for the specified file using the given algorithm.\n\nArgs:\n- file_path (str): Path to the file that needs to be hashed.\n- algorithm (str): The hashing algorithm to use (e.g., 'sha256', 'sha512').\n\nReturns:\n- str: The computed hash of the file's contents.", "function_decla...
[ 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 hashlib\n\ndef create_file_hash(file_path, algorithm):\n \"\"\"\n Creates a hash for the specified file using the given algorithm.\n\n Args:\n - file...
trial_gpt4o_0
{ "original_instruction": "### Advanced Hashing with Python's `hashlib` Module\n\n#### Objective\nYou are tasked to implement a secure file verification mechanism using Python's `hashlib` module. The goal is to ensure the integrity of files by creating and verifying their hashes.\n\n#### Requirements\n1. **Function 1...
0.717959
Docs: Python310_18813
C
[ "create_file_hash", "verify_file_integrity" ]
2
[ [ "verify_file_integrity", "create_file_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bc5fa272ce8287b3a2c1cd5071321b16464c7ea3
7dc67c4b404bfcbc6a109ad10545a6ceb2462a6a
v1.0
complete
Docs
Docs: Seaborn_18764_C
import seaborn as sns import matplotlib.pyplot as plt def create_palettes(): """ Create various color palettes and colormaps using seaborn's dark_palette function. Returns: palette_seagreen (list): Sequential color palette from dark gray to "seagreen". palette_hex (list): Sequential color ...
import seaborn as sns import matplotlib.pyplot as plt def create_palettes(): """ Create color palettes and colormap using seaborn's dark_palette function. """ # Sequential color palette from dark gray to "seagreen" palette_seagreen = sns.dark_palette("seagreen", as_cmap=False) # Sequential...
import pytest def test_create_palettes(): from solution import create_palettes palette_seagreen, palette_hex, palette_husl, palette_golden, cmap_continuous = create_palettes() # Assert palettes are correctly created assert len(palette_seagreen) > 0 assert len(palette_hex) > 0 assert len(p...
[ { "docstring": "Create color palettes and colormap using seaborn's dark_palette function.", "function_declaration": "def create_palettes():", "function_name": "create_palettes", "parameter_list": "()" }, { "docstring": "Create and display plots using created palettes and colormap.", "fun...
[ 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 seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef create_palettes():\n \"\"\"\n Creates and returns various color palettes using seaborn's dark_palett...
trial_gpt4o_1
{ "original_instruction": "### Coding Assessment: Create and Apply Custom Seaborn Palettes\n\n**Objective:**\n\nYou will create custom color palettes using seaborn's `dark_palette` function and apply these palettes to a variety of plots. This will test your understanding of seaborn's palette creation and visualizatio...
0.729368
Docs: Seaborn_18764
C
[ "create_palettes", "create_plots" ]
2
[ [ "create_plots", "create_palettes" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn" ]
false
a38a755a3c46e365b972395820dd73cfa6a38d7c
a4165554fc5e1e5528abe5ff2b45e9ab17a2e3f1
v1.0
complete
Docs
Docs: Python310_18546_C
import json import pickle from datetime import datetime from typing import List, Dict def process_user_data(file_path: str, output_path: str) -> None: """ Read user data from a JSON file, compute the number of days since each user joined, and save the processed data using pickle. Args: file_path (str)...
import json import pickle from datetime import datetime from typing import List, Dict def read_user_data(file_path: str) -> List[Dict]: with open(file_path, 'r') as file: data = json.load(file) return data def compute_days_since_join(join_date: str) -> int: join_date_obj = datetime.strptime(join_d...
import pytest import os import json import pickle from solution import process_user_data, read_user_data, compute_days_since_join @pytest.fixture def create_test_json_file(tmp_path): data = [ {"name": "John Doe", "age": 28, "join_date": "2022-01-15"}, {"name": "Jane Smith", "age": 22, "join_date": ...
[ { "docstring": null, "function_declaration": "def read_user_data(file_path):", "function_name": "read_user_data", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def compute_days_since_join(join_date):", "function_name": "compute_days_since_join", ...
[ 0, 0, 0, 0, 1, 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 json\nimport pickle\nfrom datetime import datetime\nfrom pathlib import Path\n\n\ndef process_user_data(file_path: str, output_path: str) -> None:\n \"\"\"\n ...
trial_gpt4o_5
{ "original_instruction": "#### Objective:\nDemonstrate proficiency in using Python's standard library by creating a script that processes, manages, and persists data using specified modules.\n\n#### Problem Statement:\nYou are required to implement a function `process_user_data(file_path: str, output_path: str) -> N...
0.636947
Docs: Python310_18546
C
[ "read_user_data", "compute_days_since_join", "process_user_data" ]
3
[ [ "process_user_data", "compute_days_since_join" ], [ "process_user_data", "read_user_data" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a23f942224aee46c464a48ce671e36ca62cb79d2
6c1854d2e4935916b10f09af547b954cebcd6f18
v1.0
complete
Docs
Docs: Seaborn_19159_C
import numpy as np import seaborn as sns import matplotlib.pyplot as plt def sinplot(n=10, flip=1): x = np.linspace(0, 14, 100) for i in range(1, n + 1): plt.plot(x, np.sin(x + i * .5) * (n - i) * flip) def custom_plot(n: int, flip: int, theme: str, style: str, context: str, font_scale: float, linewid...
import numpy as np import seaborn as sns import matplotlib.pyplot as plt def sinplot(n=10, flip=1): x = np.linspace(0, 14, 100) for i in range(1, n + 1): plt.plot(x, np.sin(x + i * .5) * (n - i) * flip) def custom_plot(n: int, flip: int, theme: str, style: str, context: str, font_scale: float,...
import os from solution import custom_plot def test_custom_plot_creation(): custom_plot( n=5, flip=1, theme='darkgrid', style='whitegrid', context='notebook', font_scale=1.2, linewidth=2.0, despine_offset=5, save_filepath='test_plot.png' ) assert os.path.exists('test_plot.png') os.remov...
[ { "docstring": null, "function_declaration": "def sinplot(n=10, flip=1):", "function_name": "sinplot", "parameter_list": "(n=10, flip=1)" }, { "docstring": null, "function_declaration": "def custom_plot(n, flip, theme, style, context, font_scale, linewidth, despine_offset, save_filepath)...
[ 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 numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef sinplot(flip=1, n=7):\n x = np.linspace(0, 14, 100)\n for i in range(1, n + 1):\...
trial_gpt4o_1
{ "original_instruction": "#### Objective\nIn this task, you are required to demonstrate your understanding of seaborn by creating a function that generates and customizes various plots based on specified parameters.\n\n#### Question\nWrite a function named `custom_plot` that takes in several parameters to generate a...
0.729275
Docs: Seaborn_19159
C
[ "sinplot", "custom_plot" ]
2
[ [ "custom_plot", "sinplot" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "seaborn" ]
false
98c1a0837be3a98c1aa4d13a4cdd84ac53e29c42
966f677474c74245df6a07c6772ea4d9f502b293
v1.0
complete
Docs
Docs: Python310_19056_C
import asyncio from typing import List async def distribute_tasks(n_workers: int, tasks: List[float]) -> float: """ Distribute tasks among multiple workers using asyncio Queue and measure total processing time. Args: n_workers (int): Number of workers. tasks (List[float]): List of task dur...
import asyncio from typing import List async def worker(queue: asyncio.Queue): while True: task_duration = await queue.get() await asyncio.sleep(task_duration) queue.task_done() async def distribute_tasks(n_workers: int, tasks: List[float]) -> float: queue = asyncio.Queue() fo...
import asyncio import pytest from solution import distribute_tasks @pytest.mark.asyncio async def test_distribute_tasks_single_worker(): assert await distribute_tasks(1, [0.5, 0.5, 0.5]) == 1.5 @pytest.mark.asyncio async def test_distribute_tasks_multiple_workers(): assert await distribute_tasks(3, [0.5, 0.5,...
[]
[ 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 asyncio\nfrom typing import List\n\nasync def worker(name: str, queue: asyncio.Queue):\n while True:\n task_duration = await queue.get()\n if ta...
trial_gpt4o_2
{ "original_instruction": "**Queue Load Balancer**\n\nYou are required to implement a load balancer using the asyncio Queue. The load balancer will distribute tasks among multiple workers. Each task will have a defined processing time, and we will simulate the processing by making the workers sleep for that duration....
0.574037
Docs: Python310_19056
C
[ "worker", "distribute_tasks" ]
2
[ [ "distribute_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8886031109f55dd26c4f0fd4b4fe4a326748ae6d
1ce0f1466a08500febed8bde584cf13bca280fd7
v1.0
complete
Docs
Docs: Python310_18974_C
import hmac import hashlib def generate_hmac(key: bytes, message: str, digestmod: str) -> str: """ Generates an HMAC for a given message using the specified key and hash algorithm. Args: key (bytes): A bytestring representing the secret key. message (str): A string message to authenticate....
import hmac import hashlib def generate_hmac(key: bytes, message: str, digestmod: str) -> str: """ Generates an HMAC for a given message using the specified key and hash algorithm. """ if len(key) < 16: raise ValueError("Key must be at least 16 bytes long.") hmac_obj = hmac.new(key, message...
from solution import generate_hmac, verify_hmac def test_generate_hmac(): key = b'validkey12345678' message = "The quick brown fox jumps over the lazy dog" digestmod = 'sha256' hmac_result = generate_hmac(key, message, digestmod) assert len(hmac_result) == 64 # SHA256 produces 64 hex digits ...
[ { "docstring": "Generates an HMAC for a given message using the specified key and hash algorithm.", "function_declaration": "def generate_hmac(key, message, digestmod):", "function_name": "generate_hmac", "parameter_list": "(key, message, digestmod)" }, { "docstring": "Verifies an HMAC again...
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hmac\nimport hashlib\n\ndef generate_hmac(key: bytes, message: str, digestmod: str) -> str:\n \"\"\"\n Generates the HMAC for the given message using the s...
trial_gpt4o_5
{ "original_instruction": "You are given the task of developing a secure messaging feature for a system that ensures data integrity using HMAC (Hash-based Message Authentication Code). You will write a Python function to generate and verify the HMAC of messages.\n\n#### Function Specifications:\n1. **Function 1: `gen...
0.867246
Docs: Python310_18974
C
[ "generate_hmac", "verify_hmac" ]
2
[ [ "verify_hmac", "generate_hmac" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d626f4c8a52a9e8ecc7e51128025f35f217ccd83
bcaf2d31266b4a4b011c01383e09b882de7aa381
v1.0
complete
Docs
Docs: Python310_19617_C
import concurrent.futures import math def compute_factorial(num: int) -> int: """ Compute the factorial of a specified number. >>> compute_factorial(5) -> 120 """ pass def factorial_sum(n: int) -> int: """ Calculate the sum of the factorials of all numbers from 1 to n (inclusive) using both Th...
import concurrent.futures import math import time def compute_factorial(num: int) -> int: """ Compute the factorial of a specified number. Args: num (int): The number to compute the factorial for. Returns: int: The factorial of the number. """ return math.factorial(num) def factorial...
from solution import factorial_sum def test_factorial_sum_small_number(): assert factorial_sum(1) == 1 def test_factorial_sum_larger_number(): assert factorial_sum(3) == 9 # 1! + 2! + 3! = 1 + 2 + 6 = 9 def test_factorial_sum_upper_limit(): # We will not calculate the strict expected value here since i...
[ { "docstring": "Compute the factorial of a specified number.\n\nArgs:\nnum (int): The number to compute the factorial for.\n\nReturns:\nint: The factorial of the number.", "function_declaration": "def compute_factorial(num):", "function_name": "compute_factorial", "parameter_list": "(num)" }, { ...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import concurrent.futures\nimport math\nimport time\n\n\ndef compute_factorial(num: int) -> int:\n \"\"\"\n Computes the factorial of the given number.\n \"\"\...
trial_gpt4o_5
{ "original_instruction": "**Objective**: Demonstrate your understanding of using the `concurrent.futures` module to asynchronously execute tasks with both thread and process pools.\n\n#### Problem:\n\nYou are required to write a function `factorial_sum(n: int) -> int` that calculates the sum of the factorials of all...
0.720103
Docs: Python310_19617
C
[ "compute_factorial", "factorial_sum" ]
2
[ [ "factorial_sum", "compute_factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
083500bbe1982a17f417ed6318ffa0f1dae1975b
91aac7f5a16cae92123547718861f5c0833084b1
v1.0
complete
Docs
Docs: Python310_19467_C
import threading def factorial(n): """ Returns the factorial of a given number n. >>> factorial(0) 1 >>> factorial(5) 120 >>> factorial(10) 3628800 """ pass def calculate_factorials(numbers): """ Calculate the factorial of each number in the list 'numbers' concurrently using th...
import threading def factorial(n): """ Returns the factorial of a given number n. """ if n == 0: return 1 result = 1 for i in range(1, n + 1): result *= i return result def calculate_factorials(numbers): """ Calculate the factorial of each number in the list 'number...
from solution import factorial, calculate_factorials def test_factorial(): assert factorial(0) == 1 assert factorial(1) == 1 assert factorial(5) == 120 assert factorial(7) == 5040 assert factorial(10) == 3628800 def test_calculate_factorials(): numbers = [0, 1, 5, 7, 10] result = calculate...
[ { "docstring": "Returns the factorial of a given number n.", "function_declaration": "def factorial(n):", "function_name": "factorial", "parameter_list": "(n)" }, { "docstring": "Calculate the factorial of each number in the list 'numbers' concurrently using threads.", "function_declarat...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\n\ndef factorial(n):\n \"\"\"\n Returns the factorial of n.\n \"\"\"\n if n == 0:\n return 1\n result = 1\n for i in range(1, ...
trial_gpt4o_2
{ "original_instruction": "### Concurrent Execution with Threads\n\n**Objective:**\nWrite a Python script that demonstrates your understanding of concurrent execution using the `threading` module. You will implement a program that calculates the factorial of multiple numbers concurrently.\n\n**Description:**\n1. Crea...
0.760142
Docs: Python310_19467
C
[ "factorial", "calculate_factorials" ]
2
[ [ "calculate_factorials", "factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8f37a8f1ddfcef2bb7fc0104a7eead57d91864dc
3930031954e59b47a7aaa0e092282fbe67517abf
v1.0
complete
Docs
Docs: Python310_19280_C
import asyncio from typing import Tuple async def process_tasks(queue: asyncio.Queue, num_workers: int) -> Tuple[float, float]: """ Process tasks concurrently using worker coroutines. Args: queue (asyncio.Queue): An instance of asyncio Queue filled with processing times (floats) for different tasks. nu...
import asyncio from typing import Tuple async def worker(queue: asyncio.Queue): while True: processing_time = await queue.get() await asyncio.sleep(processing_time) queue.task_done() async def process_tasks(queue: asyncio.Queue, num_workers: int) -> Tuple[float, float]: start_time = as...
import asyncio import pytest from solution import process_tasks @pytest.mark.asyncio async def test_process_tasks_single_worker(): queue = asyncio.Queue() for time in [1.0, 2.0, 3.0]: await queue.put(time) total_time_taken, expected_time = await process_tasks(queue, 1) assert round(to...
[]
[ 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 Tuple\n\nasync def worker(queue: asyncio.Queue):\n while not queue.empty():\n processing_time = await queue.get()\n ...
trial_gpt4o_2
{ "original_instruction": "### **Task: Implement a Concurrency Control System**\nYou are tasked with designing a concurrency control system for handling a set of tasks, using Python's `asyncio` queues.\n\n### **Problem Description:**\nImplement an asynchronous function `process_tasks(queue: asyncio.Queue, num_workers...
0.587104
Docs: Python310_19280
C
[ "worker", "process_tasks" ]
2
[ [ "process_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4e930f1de113872772c474b8de53ee12c8f93392
663cc92c901d03452c1fe1f300412c0173edad6d
v1.0
complete
Docs
Docs: Python310_18797_C
class FileProcessingException(Exception): """Base class for all custom file processing exceptions""" pass class FileNotFoundErrorCustom(FileProcessingException): """Raised when a file does not exist""" pass class PermissionErrorCustom(FileProcessingException): """Raised when there are insufficient...
class FileProcessingException(Exception): """Base class for all custom file processing exceptions""" pass class FileNotFoundErrorCustom(FileProcessingException): """Raised when a file does not exist""" pass class PermissionErrorCustom(FileProcessingException): """Raised when there are insufficient...
from solution import process_files, FileNotFoundErrorCustom, PermissionErrorCustom, ProcessingErrorCustom def test_file_not_found(): file_paths = ["nonexistent.txt"] try: process_files(file_paths) except FileNotFoundErrorCustom as e: assert str(e) == "File 'nonexistent.txt' not found." 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": "class FileProcessingException(Exception):\n \"\"\"Base class for custom exceptions in file processing.\"\"\"\n pass\n\nclass FileNotFoundErrorCustom(FileProcessin...
trial_gpt4o_2
{ "original_instruction": "### Python Coding Assessment: Custom Exceptions and Exception Handling\n\n**Objective:**\nDemonstrate your understanding of Python's built-in exception hierarchy and your ability to create and handle custom exceptions.\n\n**Problem Statement:**\n\nYou are tasked with creating an application...
0.546386
Docs: Python310_18797
C
[ "file_exists", "has_permission", "read_file", "process_content", "process_files" ]
5
[ [ "process_files", "file_exists" ], [ "process_files", "has_permission" ], [ "process_files", "process_content" ], [ "process_files", "read_file" ] ]
4
[]
false
[ "FileProcessingException", "FileNotFoundErrorCustom", "PermissionErrorCustom", "ProcessingErrorCustom" ]
true
pytest
true
[]
true
57889b8831fcf71ceeb267dd99e484fa92662d0e
25d0ecec25524ce70d629b4c49a8a3cdc6920b31
v1.0
complete
Docs
Docs: Python310_19483_C
def create_bytes_from_string(s: str) -> bytes: """ Create a new bytes object from the given string. :param s: Input string :return: Corresponding bytes object """ pass def concat_bytes_objects(bytes1: bytes, bytes2: bytes) -> bytes: """ Concatenate two bytes objects. :param bytes1...
def create_bytes_from_string(s: str) -> bytes: """ Create a new bytes object from the given string. :param s: Input string :return: Corresponding bytes object """ return s.encode() def concat_bytes_objects(bytes1: bytes, bytes2: bytes) -> bytes: """ Concatenate two bytes objects. ...
from solution import create_bytes_from_string, concat_bytes_objects, resize_bytes_object, get_bytes_size def test_create_bytes_from_string(): assert create_bytes_from_string("Hello") == b"Hello" assert create_bytes_from_string("") == b"" def test_concat_bytes_objects(): assert concat_bytes_objects(b"Hello...
[ { "docstring": "Create a new bytes object from the given string.\n\n:param s: Input string\n:return: Corresponding bytes object", "function_declaration": "def create_bytes_from_string(s):", "function_name": "create_bytes_from_string", "parameter_list": "(s)" }, { "docstring": "Concatenate tw...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def create_bytes_from_string(s: str) -> bytes:\n \"\"\"\n Create a new bytes object from the given string.\n\n :param s: Input string\n :return: Correspondi...
trial_gpt4o_2
{ "original_instruction": "### Question: Python `bytes` Object Manipulation \n\nYou are tasked with implementing a series of functions that manipulate Python's bytes objects at a low level using the C API methods described in the documentation. This will require understanding of memory management, as well as accurat...
0.485107
Docs: Python310_19483
C
[ "create_bytes_from_string", "concat_bytes_objects", "resize_bytes_object", "get_bytes_size", "demo_bytes_operations" ]
5
[ [ "demo_bytes_operations", "concat_bytes_objects" ], [ "demo_bytes_operations", "create_bytes_from_string" ], [ "demo_bytes_operations", "get_bytes_size" ], [ "demo_bytes_operations", "resize_bytes_object" ] ]
4
[]
false
[]
false
pytest
true
[]
true
7df647520b9e989244c702cfaa3679d73e4dc229
c6791106de4463a78f4c5de1f3b8f81ed1f6c9ab
v1.0
complete
Docs
Docs: Python310_18913_C
import argparse import os import statistics import sys from datetime import datetime def read_integers_from_file(file_path, log_path): """ Reads integers from a given file and logs errors to a specified log file. Returns a list of read integers. """ # Your code here def log_error(log_file, message...
import argparse import os import statistics import sys from datetime import datetime def read_integers_from_file(file_path, log_path): """ Reads integers from a given file and logs errors to a specified log file. Returns a list of read integers. """ integers = [] with open(log_path, 'a') as log...
import os import pytest from solution import read_integers_from_file, calculate_statistics # Helper function to create a temporary file for testing def create_temp_file(content, filename="temp.txt"): with open(filename, 'w') as f: f.write(content) return filename def test_read_integers_from_file(): ...
[ { "docstring": "Reads integers from a given file and logs errors to a specified log file.\nReturns a list of read integers.", "function_declaration": "def read_integers_from_file(file_path, log_path):", "function_name": "read_integers_from_file", "parameter_list": "(file_path, log_path)" }, { ...
[ 0, 0, 0, 0, 1, 0, 1, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import argparse\nimport os\nimport statistics\nimport sys\nfrom datetime import datetime\n\ndef read_integers(file_path, log_file):\n integers = []\n with open(fi...
trial_gpt4o_6
{ "original_instruction": "#### Objective\nWrite a Python script that utilizes various modules from the standard library to perform the following tasks:\n\n1. Read integers from a file and calculate their statistical properties.\n2. Allow users to specify the file and some optional parameters via command line argumen...
0.657564
Docs: Python310_18913
C
[ "read_integers_from_file", "log_error", "calculate_statistics", "main" ]
4
[ [ "read_integers_from_file", "log_error" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0f53857dd15159975f86b6c63828b8920c9ad867
91dd65a4f86ebc0fb6df69c0f2bcd78ca06edcd2
v1.0
complete
Docs
Docs: Python310_19377_C
import asyncio async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: """ Function to handle client connection. Reads a message from the client, processes it, and sends back a response. :param reader: StreamReader object :param writer: StreamWriter object "...
import asyncio async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: """ Function to handle client connection. Reads a message from the client, processes it, and sends back a response. """ data = await reader.read(100) message = data.decode() addr = wr...
import asyncio import pytest from solution import handle_client, client_request_processor, main @pytest.mark.asyncio async def test_handle_client(): reader, writer = await asyncio.open_connection('127.0.0.1', 8888) writer.write(b'hello') await writer.drain() response = await reader.read(100) a...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:\n data = await reader.read(100)\n message = data.de...
trial_gpt4o_1
{ "original_instruction": "### Asynchronous Task Management and Synchronization\n\nYou are tasked with implementing a small server that handles client requests asynchronously using Python's `asyncio` module. The server must perform the following tasks:\n\n1. Accept multiple client connections concurrently.\n2. Use an...
0.555937
Docs: Python310_19377
C
[ "handle_client", "client_request_processor", "main" ]
3
[ [ "client_request_processor", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a4e088d8e76bcffaa4c7c38263b8c8811c545524
23224305a1511accee00d6b943d51295575597b5
v1.0
complete
Docs
Docs: Pytorch_19695_C
import torch from torch.func import vmap, grad def transform_and_multiply(x: torch.Tensor, y: torch.Tensor, transform) -> torch.Tensor: """ Apply transformation function to the first tensor in-place (compatible with vmap), and then return element-wise multiplication with the second tensor. Args: x...
import torch from torch.func import vmap, grad def transform_and_multiply(x: torch.Tensor, y: torch.Tensor, transform) -> torch.Tensor: """ Apply transformation function to the first tensor (without in-place modification), and then return element-wise multiplication with the second tensor. Args: x...
import torch from solution import transform_and_multiply, compute_gradient def test_transform_and_multiply_identity(): def identity_transform(tensor): return tensor x = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) y = torch.tensor([[2.0, 2.0], [2.0, 2.0]]) result = transform_and_multiply(x, y, i...
[ { "docstring": "Apply transformation function to the first tensor (without in-place modification),\nand then return element-wise multiplication with the second tensor.\n\nArgs:\nx (torch.Tensor): The input tensor to transform.\ny (torch.Tensor): The second tensor to multiply with.\ntransform (callable): The tra...
[ 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 torch\nfrom torch.func import vmap, grad\n\ndef transform_and_multiply(x: torch.Tensor, y: torch.Tensor, transform) -> torch.Tensor:\n \"\"\"\n Apply trans...
trial_gpt4o_2
{ "original_instruction": "**Function Vectorization and Differentiability with Limited In-Place Operations using PyTorch**\n\n### Objective\n\nDemonstrate your understanding of `torch.func` by implementing and transforming a function that is compatible with `vmap` and `grad`, and handles in-place operations cautiousl...
0.650259
Docs: Pytorch_19695
C
[ "transform_and_multiply", "compute_gradient" ]
2
[ [ "compute_gradient", "transform_and_multiply" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
aac18c3341c05275ca434a209b6180bdbf2b4bf7
53dc5d546ba34d07e138961c027007a70fee7a2a
v1.0
complete
Docs
Docs: Python310_19746_C
import warnings def custom_warning_emitter(inputs): """ Emit custom warnings based on the inputs provided. Args: inputs (List[Tuple[str, str, int]]): A list of tuples where each tuple contains a warning message, warning category, and line number. """ pass def apply_warning_filter(action, category)...
import warnings def custom_warning_emitter(inputs): warning_category_map = { 'UserWarning': UserWarning, 'DeprecationWarning': DeprecationWarning, 'SyntaxWarning': SyntaxWarning, 'RuntimeWarning': RuntimeWarning, 'FutureWarning': FutureWarning } for message, cat...
import warnings from solution import custom_warning_emitter, apply_warning_filter, handle_warnings def test_custom_warning_emitter(): inputs = [ ("Test UserWarning", "UserWarning", 10), ("Test DeprecationWarning", "DeprecationWarning", 20), ("Test SyntaxWarning", "SyntaxWarning", 30), ...
[ { "docstring": null, "function_declaration": "def custom_warning_emitter(inputs):", "function_name": "custom_warning_emitter", "parameter_list": "(inputs)" }, { "docstring": null, "function_declaration": "def apply_warning_filter(action, category):", "function_name": "apply_warning_f...
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import warnings\n\ndef custom_warning_emitter(inputs):\n \"\"\"\n Emit custom warnings based on the input list of tuples.\n \"\"\"\n warning_map = {\n ...
trial_gpt4o_7
{ "original_instruction": "Custom Warning Handling and Filtering\n\n#### Objective:\nImplement a function that generates various types of warnings, applies custom filters to them, and handles the warnings in specified ways.\n\n#### Task:\n\n1. **Create a function `custom_warning_emitter(inputs)`** that:\n - Takes ...
0.595836
Docs: Python310_19746
C
[ "custom_warning_emitter", "apply_warning_filter", "handle_warnings" ]
3
[ [ "handle_warnings", "apply_warning_filter" ], [ "handle_warnings", "custom_warning_emitter" ] ]
2
[]
false
[]
false
pytest
true
[]
true
651b4b14fce2b6d3f292f157286d96e9e3d0a856
99b042a7232d2cbf8267d15db7d5374756290019
v1.0
complete
Docs
Docs: Scikit_19857_C
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier import numpy as np def data_stream(documents, batch_size): """ Generator that yields mini-batches of documents. Parameters: - documents (list): List of text documents. - batch_size (int...
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier import numpy as np def data_stream(documents, batch_size): """ Generator that yields mini-batches of documents. Parameters: - documents (list): List of text documents. - batch_size (int...
from solution import train_out_of_core_model, data_stream from sklearn.feature_extraction.text import HashingVectorizer import numpy as np def test_data_stream(): documents = ["doc1", "doc2", "doc3", "doc4"] result = list(data_stream(documents, batch_size=2)) assert result == [["doc1", "doc2"], ["doc3", "d...
[ { "docstring": "Generator that yields mini-batches of documents.\n\nParameters:\n- documents (list): List of text documents.\n- batch_size (int): Size of mini-batches.\n\nYields:\n- List of documents in the current mini-batch.", "function_declaration": "def data_stream(documents, batch_size):", "functio...
[ 1, 1, 0 ]
2
easy
0.667
{ "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\nimport numpy as np\n\ndef data_stream(documents, batch_si...
trial_gpt4o_1
{ "original_instruction": "### Out-of-Core Learning System Implementation\n\n#### Objective:\nImplement an out-of-core learning system using Scikit-learn to classify text documents. Your task is to design a system that processes data in mini-batches, extracts features using vectorization, and trains an incremental cl...
0.519109
Docs: Scikit_19857
C
[ "data_stream", "train_out_of_core_model" ]
2
[ [ "train_out_of_core_model", "data_stream" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
d3ed249bcc3fd07d05dcd71e85f9865f1c1bd560
34a6e337d2d63518f3926f03193532fc53182301
v1.0
complete
Docs
Docs: Python310_19228_C
import asyncio async def worker(worker_id, task_queue, results): """ Worker coroutine that processes tasks from the queue. """ while True: task = await task_queue.get() if task is None: break task_id, duration = task await asyncio.sleep(duration) results[...
import asyncio async def worker(worker_id, task_queue, results): while True: task = await task_queue.get() if task is None: break task_id, duration = task await asyncio.sleep(duration) results[task_id] = worker_id task_queue.task_done() async def run_tas...
import asyncio from solution import run_task_scheduler def test_run_task_scheduler_simple(): tasks = [(1, 1.0), (2, 1.0), (3, 1.0)] num_workers = 2 results = asyncio.run(run_task_scheduler(tasks, num_workers)) assert results == {1: 0, 2: 1, 3: 0} or results == {1: 1, 2: 0, 3: 1} def test_run_task_sch...
[]
[ 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 worker(worker_id, task_queue, result):\n while True:\n task = await task_queue.get()\n if task is None:\n break\...
trial_gpt4o_1
{ "original_instruction": "You are tasked with implementing a simulation of a task scheduler using `asyncio.Queue` in Python 3.10. The goal is to distribute a list of tasks among a fixed number of workers, ensuring that each worker processes tasks in a fair manner. Your implementation should demonstrate your understa...
0.655654
Docs: Python310_19228
C
[ "worker", "run_task_scheduler" ]
2
[ [ "run_task_scheduler", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6dab64537124834e27b49713edadd45d214cc12c
d881530a67c5cdec24da4eed07636a1d8392291e
v1.0
complete
Docs
Docs: Python310_19796_C
import asyncio import logging import uuid from aiohttp import web logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) asyncio.get_event_loop().set_debug(True) tasks = {} def generate_task_id(): return str(uuid.uuid4()) async def long_running_task(task_id): """Simulate a long-running...
import asyncio import logging import uuid from aiohttp import web # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) asyncio.get_event_loop().set_debug(True) # Dictionary to store tasks tasks = {} def generate_task_id(): return str(uuid.uuid4()) async def long_runni...
import asyncio import pytest from aiohttp import web from aiohttp.test_utils import TestClient, TestServer, loop_context from solution import app, long_running_task, generate_task_id, tasks @pytest.mark.asyncio async def test_handle_task(): async with TestClient(TestServer(app)) as client: resp = await cli...
[ { "docstring": null, "function_declaration": "def generate_task_id():", "function_name": "generate_task_id", "parameter_list": "()" } ]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nfrom aiohttp import web\n\ntasks = {}\nstatus_map = { 'pending': 'pending', 'running': 'running', 'completed': 'completed' }\ntask_count...
trial_gpt4o_1
{ "original_instruction": "**Asynchronous HTTP Server with Task Reporting**\n\nYou are tasked with creating an asynchronous HTTP server that listens for incoming requests and performs various tasks. You must use Python's `asyncio` package to handle the concurrency. The server should have the following features:\n\n1....
0.496051
Docs: Python310_19796
C
[ "generate_task_id", "long_running_task", "handle_task", "handle_status" ]
4
[ [ "handle_task", "generate_task_id" ], [ "handle_task", "long_running_task" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
ea04fe208f506c91f6ae0b4e6cfdc2975d7ac08e
7843dfe428b3cd9612cd8b98e64dcfcbe2388611
v1.0
complete
Docs
Docs: Python310_20008_C
from contextvars import ContextVar from typing import Callable, Any def manage_context(context_vars: dict) -> Callable: """ A decorator to manage context variables. Temporarily sets provided context variables for the execution of the decorated function. Reverts context variables to their original state...
from contextvars import ContextVar, copy_context from functools import wraps def manage_context(context_vars): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): originals = {} temp_context = copy_context() for var_name, new_value in context_vars.it...
from solution import demo_function, var1, var2, manage_context def test_demo_function_var1(): original_value = var1.get() assert demo_function('var1') == 'temp_value1' assert var1.get() == original_value def test_demo_function_var2(): original_value = var2.get() assert demo_function('var2') == 'te...
[ { "docstring": null, "function_declaration": "def manage_context(context_vars):", "function_name": "manage_context", "parameter_list": "(context_vars)" }, { "docstring": null, "function_declaration": "def demo_function(var_name):", "function_name": "demo_function", "parameter_lis...
[ 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 contextvars import ContextVar, copy_context\nfrom functools import wraps\n\ndef manage_context(context_vars):\n def decorator(func):\n @wraps(func)\n ...
trial_gpt4o_2
{ "original_instruction": "### Context Variables Management in Python\n\nYou are required to demonstrate your understanding of the `contextvars` module in Python by implementing a function that manages context variables during the execution of a code block. \n\n#### Objective\n\n1. Implement a decorator function `man...
0.492371
Docs: Python310_20008
C
[ "manage_context", "demo_function" ]
2
[ [ "demo_function", "manage_context" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d10c4401c7cdfcfe0b2dc7535f0e4fdf57200e86
88db3d7d274e2451edd47d7d7edb2e80dce9de2d
v1.0
complete
Docs
Docs: Pytorch_19945_C
from typing import List import torch def fetch_data(source: int) -> torch.futures.Future: # Simulating an async fetch operation future = torch.futures.Future() def async_fetch(): import time import random time.sleep(random.uniform(0.1, 0.5)) future.set_result(f"data_from_sou...
from typing import List import torch import threading import time def fetch_data(source: int) -> torch.futures.Future: # Simulating an async fetch operation future = torch.futures.Future() def async_fetch(): time.sleep(0.1) # Simulate some delay future.set_result(f"data_from_source_{source}...
from solution import process_multiple_sources, fetch_data def test_process_multiple_sources(): sources = [1, 2, 3] expected = ['data_from_source_1', 'data_from_source_2', 'data_from_source_3'] assert process_multiple_sources(sources) == expected def test_process_multiple_sources_single_source(): sourc...
[ { "docstring": null, "function_declaration": "def fetch_data(source):", "function_name": "fetch_data", "parameter_list": "(source)" }, { "docstring": null, "function_declaration": "def process_multiple_sources(sources):", "function_name": "process_multiple_sources", "parameter_li...
[ 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 torch\nfrom typing import List\n\ndef fetch_data(source: int) -> torch.futures.Future:\n # Simulating an async fetch operation\n future = torch.futures.Fut...
trial_gpt4o_1
{ "original_instruction": "#### Objective:\nThe goal of this question is to assess your understanding of asynchronous execution using the `torch.futures` package. You will write code to handle multiple asynchronous operations and combine their results.\n\n#### Problem Statement:\nYou are given an asynchronous functio...
0.533315
Docs: Pytorch_19945
C
[ "fetch_data", "process_multiple_sources" ]
2
[ [ "process_multiple_sources", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
0b0ade7fb72b3dc430be02cbe414566f8ddfddbd
b927d5ee4f8951d8569ac55475b6ba15eb69207b
v1.0
complete
Docs
Docs: Python310_19964_C
import _thread class ThreadSafeCounter: def __init__(self): """ Initialize the counter to zero and create a lock. """ self.counter = 0 self.lock = _thread.allocate_lock() def increment(self): """ Safely increment the counter by one. """ pass def get...
import _thread from time import sleep class ThreadSafeCounter: def __init__(self): self.counter = 0 self.lock = _thread.allocate_lock() def increment(self): with self.lock: self.counter += 1 def get_value(self): with self.lock: return self.counter ...
from solution import ThreadSafeCounter, increment_counter, run_threads def test_thread_safe_counter_initial_value(): counter = ThreadSafeCounter() assert counter.get_value() == 0 def test_thread_safe_counter_increment(): counter = ThreadSafeCounter() counter.increment() assert counter.get_value() ...
[]
[ 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 threading import Event\n\nclass ThreadSafeCounter:\n \"\"\"Safe counter for multi-threading.\"\"\"\n def __init__(self):\n self.counte...
trial_gpt4o_2
{ "original_instruction": "### Question: Implement a Multi-threaded Counter with Synchronization\n\nYou are tasked with implementing a multi-threaded counter using the low-level `_thread` module. This counter will be shared among multiple threads, and proper synchronization must be used to ensure accurate results. \n...
0.596284
Docs: Python310_19964
C
[ "increment_counter", "run_threads" ]
2
[ [ "run_threads", "increment_counter" ] ]
1
[]
false
[ "ThreadSafeCounter" ]
true
pytest
true
[]
true
dd5ef0b45a24a75b3d73ea2f2b57822e01b02c1a
e2d5f9f3af105b7ab3d19e3bc785561f1a007349
v1.0
complete
Docs
Docs: Python310_19775_C
import asyncio async def manage_task(futures: list) -> dict: """ Manages multiple Future objects and sets their results asynchronously after specified delays. Args: futures: A list of tuples where each tuple contains: - An integer `delay` representing the number of seconds to wait. ...
import asyncio async def _set_future_result(future, delay, value): """ Sets the result of the provided Future object after a specified delay. """ await asyncio.sleep(delay) future.set_result(value) async def manage_task(futures): """ Manages multiple Future objects, setting their results a...
import asyncio import pytest from solution import manage_task @pytest.mark.asyncio async def test_manage_task_basic(): test_futures = [(1, 'foo'), (2, 'bar'), (3, 'baz')] result = await manage_task(test_futures) assert result == {0: 'foo', 1: 'bar', 2: 'baz'} @pytest.mark.asyncio async def test_manage_tas...
[]
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def _set_future_result(future, delay, value):\n \"\"\"\n Sets the result of the provided Future object after a specified delay.\n \"\"\...
trial_gpt4o_0
{ "original_instruction": "**Asynchronous Tasks and Future Objects**\n\n**Objective:** \nImplement and manage asynchronous operations using `asyncio.Future` objects to ensure that your function can handle low-level callback-based code and integrate it with high-level async/await code. Demonstrate the ability to set, ...
0.620877
Docs: Python310_19775
C
[ "_set_future_result", "manage_task" ]
2
[ [ "manage_task", "_set_future_result" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4ce4d102debb29826e4e3dd621faf63cb9d4cb5c
88d140f9e42312705d54b3e6e90770ab0eb3e8a3
v1.0
complete
Docs
Docs: Pytorch_19871_C
import torch from torch.autograd import Function class MyFunc(Function): @staticmethod def forward(ctx, input): """ Perform a custom operation on the input tensor and store context for backward pass. Args: ctx: Context object to save information for backward computation. ...
import torch from torch.autograd import Function class MyFunc(Function): @staticmethod def forward(ctx, input): # Compute any operation, for example, y = x^3 + 4 * x^2 - 7 * x ctx.save_for_backward(input) return input ** 3 + 4 * input ** 2 - 7 * input @staticmethod def backward...
import pytest import torch from solution import my_func, run_gradcheck def test_my_func_gradcheck(): gradcheck_result, gradgradcheck_result = run_gradcheck() assert gradcheck_result, "Gradcheck failed!" assert gradgradcheck_result, "Gradgradcheck failed!" def test_my_func_on_scalar(): input = torch.te...
[]
[ 1, 1, 1 ]
3
easy
1
{ "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 MyFunc(Function):\n @staticmethod\n def forward(ctx, input):\n # Compute any operation, for exam...
trial_gpt4o_2
{ "original_instruction": "### PyTorch Gradient Check Implementation\n\n**Objective:**\nImplement a custom PyTorch function and use `torch.autograd.gradcheck` and `torch.autograd.gradgradcheck` to verify the correctness of its gradient computations.\n\n**Instructions:**\n\n1. **Function Implementation:**\n - Imple...
0.540475
Docs: Pytorch_19871
C
[ "my_func", "run_gradcheck" ]
2
[ [ "run_gradcheck", "my_func" ] ]
1
[]
false
[ "MyFunc" ]
true
pytest
true
[ "torch" ]
false
a5e848a0f74ce4d7baee25a8655306829b0db66c
9384cceaa24c07c95e9e8ac3531c80a7f185db64
v1.0
complete
Docs
Docs: Python310_19849_C
import asyncio async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): """ Handle client connections and echo received messages. > Connected to ('127.0.0.1', 8888) > Received Hello, server! from ('127.0.0.1', 8888) > Echo: Hello, server! > Connection from ('127.0.0.1', ...
import asyncio async def handle_client(reader, writer): client_addr = writer.get_extra_info('peername') print(f"Connected to {client_addr}") writer.write("Welcome to the echo server!\n".encode()) await writer.drain() while True: data = await reader.read(100) if not data: ...
import asyncio import pytest from asyncio import StreamReader, StreamWriter from solution import start_server, handle_client, client_message, run_server_and_client @pytest.fixture def event_loop(): loop = asyncio.get_event_loop() yield loop loop.close() @pytest.mark.asyncio async def test_handle_client(ev...
[ { "docstring": null, "function_declaration": "def run_server_and_client():", "function_name": "run_server_and_client", "parameter_list": "()" } ]
[ 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\n\nasync def handle_client(reader, writer):\n client_addr = writer.get_extra_info('peername')\n print(f\"Connected to {client_addr}\")\n writer....
trial_gpt4o_0
{ "original_instruction": "You are required to develop a Python program that mimics a simple server-client model using the asyncio event loop methods. The task focuses on your understanding of scheduling callbacks, creating futures/tasks, managing network connections, and handling asynchronous IO.\n\n### Problem Stat...
0.666001
Docs: Python310_19849
C
[ "handle_client", "start_server", "client_message", "run_server_and_client" ]
4
[ [ "run_server_and_client", "client_message" ], [ "run_server_and_client", "start_server" ], [ "start_server", "handle_client" ] ]
3
[]
false
[]
false
pytest
true
[]
true
4a66aac6e3805096c5e611e6c3fa1a2016dd9a77
0fcbf8d1f100bcde5b66af5716a29169b7094dd5
v1.0
complete
Docs
Docs: Python310_19817_C
import py_compile import os from typing import List def compile_python_files(files: List[str], output_dir: str = None, optimize: int = 0, quiet: int = 0) -> List[str]: """ Compile a list of Python source files using the `py_compile` module. If a file fails to compile, handle the error gracefully and collect th...
import py_compile import os from datetime import datetime from typing import List def compile_python_files(files: List[str], output_dir: str = None, optimize: int = 0, quiet: int = 0) -> List[str]: compiled_files = [] errors = [] for file in files: try: compiled_file = py_compile.compi...
import os import pytest from solution import compile_python_files, log_compile_errors @pytest.fixture def create_files(): file_names = ["test1.py", "test2.py"] for fn in file_names: with open(fn, "w") as f: f.write("print('Hello, World!')\n") yield file_names for fn in file_names: ...
[ { "docstring": null, "function_declaration": "def compile_python_files(files, output_dir=None, optimize=0, quiet=0):", "function_name": "compile_python_files", "parameter_list": "(files, output_dir=None, optimize=0, quiet=0)" }, { "docstring": null, "function_declaration": "def log_compi...
[ 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 py_compile\nfrom typing import List\nimport os\nfrom datetime import datetime\n\ndef compile_python_files(files: List[str], output_dir: str = None, optimize: int...
trial_gpt4o_6
{ "original_instruction": "### Python Coding Assessment: Py_Compile Module\n\n**Objective**: Implement a custom Python function that utilizes the `py_compile` module to compile a list of Python source files and handle errors efficiently. Additionally, create helper functions to enhance error reporting and logging.\n\...
0.678026
Docs: Python310_19817
C
[ "compile_python_files", "log_compile_errors" ]
2
[ [ "compile_python_files", "log_compile_errors" ] ]
1
[]
false
[]
false
pytest
true
[]
true
21cf47588a13516dd6aecea1610c0a4a36f150fd
ac425376b5f5d65d5f7d646a2c2ec2188202f106
v1.0
complete
Docs
Docs: Pytorch_20003_C
def check_mps_availability() -> bool: """ Checks whether the MPS backend is available. Returns: bool: True if MPS is available, False otherwise. """ pass def perform_tensor_operations(shape: tuple, operation: str): """ Creates a tensor of ones with the given shape on the MPS device...
import torch def check_mps_availability() -> bool: """ Checks whether the MPS backend is available. Returns: bool: True if MPS is available, False otherwise. """ return torch.backends.mps.is_available() def perform_tensor_operations(shape: tuple, operation: str): """ Creates a ten...
import torch import pytest from solution import check_mps_availability, perform_tensor_operations, move_model_to_mps def test_check_mps_availability(): assert isinstance(check_mps_availability(), bool) def test_perform_tensor_operations_add(): if not check_mps_availability(): pytest.skip("MPS backend ...
[]
[ 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 torch\n\ndef check_mps_availability() -> bool:\n \"\"\"\n Checks whether the MPS backend is available.\n\n Returns:\n bool: True if MPS is availa...
trial_gpt4o_2
{ "original_instruction": "### PyTorch MPS Backend Assessment\n\nIn this question, you are required to demonstrate your understanding of the MPS backend in PyTorch. You will write functions to check MPS availability, perform tensor operations on the MPS device, and handle a simple neural network model using the MPS d...
0.512894
Docs: Pytorch_20003
C
[ "check_mps_availability", "perform_tensor_operations", "move_model_to_mps" ]
3
[ [ "move_model_to_mps", "check_mps_availability" ], [ "perform_tensor_operations", "check_mps_availability" ] ]
2
[]
false
[ "SimpleNet" ]
true
pytest
true
[ "torch" ]
false
8ee7f3c77ae65a14d8ab5e836478c44398565789
e1c1cd69b1f2929b5645d7f5b297a1ce7d1413aa
v1.0
complete
Docs
Docs: Python310_19717_C
def custom_escape(data: str, entities: dict = None) -> str: """Escape XML characters in the data string. Args: data (str): A string containing the data to be escaped. entities (dict, optional): A dictionary where each key-value pair represents a character and its escaped representation. ...
def custom_escape(data: str, entities: dict = None) -> str: """Escape XML characters in the data string.""" if entities is None: entities = {} # These are the basic XML escape entities base_entities = {"&": "&amp;", "<": "&lt;", ">": "&gt;"} # Update with additional entities if provided ...
from solution import custom_escape, custom_unescape, custom_quoteattr def test_custom_escape_basic(): assert custom_escape("5 < 6 & 7 > 4") == "5 &lt; 6 &amp; 7 &gt; 4" def test_custom_escape_with_entities(): assert custom_escape("5 < 6 & 7 > 4", {"5": "five", "4": "four"}) == "five &lt; 6 &amp; 7 &gt; four" ...
[ { "docstring": "Escape XML characters in the data string.", "function_declaration": "def custom_escape(data, entities=None):", "function_name": "custom_escape", "parameter_list": "(data, entities=None)" }, { "docstring": "Unescape XML characters in the data string.", "function_declaratio...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def custom_escape(data: str, entities: dict = None) -> str:\n \"\"\"Escape XML characters in the data string.\"\"\"\n if entities is None:\n entities = {}\...
trial_gpt4o_0
{ "original_instruction": "## Question\n\n### Objective:\nCreate utility functions for escaping and unescaping XML character entities and preparing attribute values for XML elements, similar to the functionality provided in the `xml.sax.saxutils` module.\n\n### Task:\nYou are tasked with implementing three functions:...
0.552285
Docs: Python310_19717
C
[ "custom_escape", "custom_unescape", "custom_quoteattr" ]
3
[ [ "custom_quoteattr", "custom_escape" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eb62043a9bb894200f756f9760c8d8eefbfcb247
f3455cbf5506cd159182020f19e07aba99dc7460
v1.0
complete
Docs
Docs: Python310_20058_C
class CustomType: type_name = "CustomType" def describe(self): """ Returns a string describing the type with its name. """ return f"This is a {self.type_name}" class DerivedType(CustomType): type_name = "DerivedType" def describe(self): """ Returns a string indicating ...
class CustomType: type_name = "CustomType" def describe(self): return f"This is a {self.type_name}" class DerivedType(CustomType): type_name = "DerivedType" def describe(self): return f"This is a derived type: {self.type_name}" class AnotherType: pass def is_cust...
from solution import CustomType, DerivedType, AnotherType, is_custom_type, get_type_name def test_describe_methods(): base = CustomType() assert base.describe() == "This is a CustomType" derived = DerivedType() assert derived.describe() == "This is a derived type: DerivedType" def test_is_custom_...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class CustomType:\n type_name = \"CustomType\"\n \n def describe(self):\n return f\"This is a {self.type_name}\"\n\nclass DerivedType(CustomType):\n ...
trial_gpt4o_2
{ "original_instruction": "### Custom Type Inheritance and Management in Python\n\nIn this assessment, you are required to implement custom types in Python that mimic some of the capabilities described in the `PyTypeObject` documentation. The task will assess your ability to create a complex type hierarchy, utilize t...
0.479555
Docs: Python310_20058
C
[ "is_custom_type", "get_type_name" ]
2
[ [ "get_type_name", "is_custom_type" ] ]
1
[]
false
[ "CustomType", "DerivedType", "AnotherType" ]
true
pytest
true
[]
true
576074ef7af81c7ca7829e3e77caba46f511df70
5343a308df012b10ea6010add44b4e9ca25611aa
v1.0
complete
Docs
Docs: Python310_20077_C
import socket import threading import re def extract_emails(text): """ Extract email addresses from a given text using regular expressions. >>> extract_emails("Contact us at example@example.com or at test.email@example.co.uk. Thank you.") "example@example.com,test.email@example.co.uk" """ pass def...
import socket import threading import re # Server Implementation def extract_emails(text): # Regex pattern to match email addresses email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' emails = re.findall(email_pattern, text) return ','.join(emails) def handle_client(client_socket): t...
import pytest import socket import threading from solution import start_server, start_client, extract_emails, read_file def test_extract_emails(): text = "Contact us at example@example.com or at test.email@example.co.uk. Thank you." expected = "example@example.com,test.email@example.co.uk" assert extract_e...
[ { "docstring": null, "function_declaration": "def extract_emails(text):", "function_name": "extract_emails", "parameter_list": "(text)" }, { "docstring": null, "function_declaration": "def handle_client(client_socket):", "function_name": "handle_client", "parameter_list": "(clien...
[ 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 socket\nimport threading\nimport re\n\n# Server Implementation\ndef extract_emails(text):\n # Regex pattern to match email addresses\n email_pattern = r'[a...
trial_gpt4o_0
{ "original_instruction": "#### Objective\nTo assess your understanding of Python socket programming, regular expressions, and file handling, you are tasked with implementing a server-client application where the server processes text data and the client sends requests to the server.\n\n#### Problem Statement\n\n1. *...
0.701287
Docs: Python310_20077
C
[ "extract_emails", "handle_client", "start_server", "read_file", "start_client" ]
5
[ [ "handle_client", "extract_emails" ], [ "start_client", "read_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e2d02646effb07305a0689dd5bfb949696a4f0ae
3957deb46a9c6e84dd7d5666c3ab89ee6880e57a
v1.0
complete
Docs
Docs: Python310_20132_C
import threading import multiprocessing import time def fibonacci(n: int) -> int: """Calculate the nth Fibonacci number recursively.""" if n <= 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def parallel_fibonacci(n: int) -> dict: """Calc...
import threading import multiprocessing import time def fibonacci(n): if n <= 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def fibonacci_threading(n, result, index): result[index] = fibonacci(n) def fibonacci_multiprocessing(n, result, ind...
from solution import parallel_fibonacci def test_parallel_fibonacci_small(): result = parallel_fibonacci(5) assert result['fibonacci'] == 5 assert result['threading_time'] >= 0 assert result['multiprocessing_time'] >= 0 def test_parallel_fibonacci_medium(): result = parallel_fibonacci(15) asse...
[ { "docstring": null, "function_declaration": "def fibonacci(n):", "function_name": "fibonacci", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def fibonacci_threading(n, result, index):", "function_name": "fibonacci_threading", "parameter_list": "(n, res...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\nimport multiprocessing\nimport time\n\ndef fibonacci(n):\n \"\"\"Recursive function to calculate the nth Fibonacci number.\"\"\"\n if n <= 0:\n ...
trial_gpt4o_2
{ "original_instruction": "You are tasked with improving the performance of a CPU-bound task by implementing concurrent execution. The task involves calculating the nth Fibonacci number, but with added complexity to simulate a CPU-bound workload.\n\nTo achieve this, you need to write a function `parallel_fibonacci` t...
0.615619
Docs: Python310_20132
C
[ "fibonacci", "fibonacci_threading", "fibonacci_multiprocessing", "parallel_fibonacci" ]
4
[ [ "fibonacci_multiprocessing", "fibonacci" ], [ "fibonacci_threading", "fibonacci" ] ]
2
[]
false
[]
false
pytest
true
[]
true
0f8f03c20bf7bdaaaa42265b55f6159ed7a49463
f6d3f12b45821f31b27120a3021d863da34d25d6
v1.0
complete
Docs
Docs: Python310_20260_C
import contextvars import threading import time def create_context_vars(): """ Create and return context variables for user_id and request_id. :return: Two context variables, user_id and request_id. """ user_id = contextvars.ContextVar("user_id") request_id = contextvars.ContextVar("request_id"...
import contextvars import threading import time # Function to create context variables def create_context_vars(): user_id = contextvars.ContextVar("user_id") request_id = contextvars.ContextVar("request_id") return user_id, request_id # Function to process requests with proper context management def proce...
import contextvars import threading import time from solution import create_context_vars, process_request, handle_request def test_create_context_vars(): user_id, request_id = create_context_vars() assert isinstance(user_id, contextvars.ContextVar) assert isinstance(request_id, contextvars.ContextVar) de...
[ { "docstring": null, "function_declaration": "def create_context_vars():", "function_name": "create_context_vars", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def process_request(user_id_value, request_id_value, user_id, request_id):", "function_name": "pr...
[ 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 contextvars\nimport threading\nimport time\n\n# Function to create context variables\ndef create_context_vars():\n user_id = contextvars.ContextVar(\"user_id\...
trial_gpt4o_1
{ "original_instruction": "### Context Management with `contextvars` in Python\n\nYou are required to write a Python script using the `contextvars` module to simulate context management for a multi-threaded or asynchronous environment. \n\n#### Task\n\n1. **Define Context Variables**:\n - Create two context variabl...
0.483549
Docs: Python310_20260
C
[ "create_context_vars", "process_request", "handle_request" ]
3
[ [ "handle_request", "create_context_vars" ] ]
1
[]
false
[]
false
pytest
true
[]
true
005b0fe684913cd0225939b01a06735e2142c986
f49682def635648662741f85bdd524d5cb67bc7a
v1.0
complete
Docs
Docs: Scikit_20280_C
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(file_path, batch_size): """ Generator function to read data from a file in chunks. Args: file_path (str): Path to the text data fi...
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(file_path, batch_size): """ Generator function to read data from a file in chunks. Args: file_path (str): Path to the text data fi...
from solution import stream_data, extract_features, incremental_learning import os def test_stream_data(tmp_path): file_path = tmp_path / "test_data.txt" lines = [f"Line {i}" for i in range(100)] with open(file_path, 'w') as f: f.write("\n".join(lines)) batches = list(stream_data(file_path...
[]
[ 1, 1, 1 ]
3
easy
1
{ "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\n\ndef stream_...
trial_gpt4o_2
{ "original_instruction": "### Out-of-Core Learning: Scikit-learn Incremental Learning\n\n#### Objective:\nImplement a scalable classification system utilizing out-of-core learning. Using the provided skeleton code below, complete the functions required to read data in streams, extract features using HashingVectorize...
0.59215
Docs: Scikit_20280
C
[ "stream_data", "extract_features", "incremental_learning" ]
3
[ [ "incremental_learning", "extract_features" ], [ "incremental_learning", "stream_data" ] ]
2
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
10b3445a9dedf2fe2f2bf09cd7962eef64fb662b
e380e378a16ee3c85d3b3d0e74e6869638bacdc9
v1.0
complete
Docs
Docs: Seaborn_20522_C
import numpy as np import seaborn as sns import matplotlib.pyplot as plt def sinplot(n=10, flip=1): """ Plots multiple sine waves with an increasing phase shift. """ pass def customize_plots(): """ Customizes and displays a 2x2 grid of plots with different Seaborn styles and contexts. ...
import numpy as np import seaborn as sns import matplotlib.pyplot as plt def sinplot(n=10, flip=1): """ Plots multiple sine waves with an increasing phase shift. """ x = np.linspace(0, 14, 100) for i in range(1, n + 1): plt.plot(x, np.sin(x + i * .5) * (n + 2 - i) * flip) def customize_plo...
from solution import customize_plots # Since the function customize_plots() produces visual output to be displayed, # we will test the function by verifying that it executes without errors. # Note: We won't use any assert statements here because we are testing a plot-producing function. def test_customize_plots(): ...
[ { "docstring": "Plots multiple sine waves with an increasing phase shift.", "function_declaration": "def sinplot(n=10, flip=1):", "function_name": "sinplot", "parameter_list": "(n=10, flip=1)" }, { "docstring": "Customizes and displays a 2x2 grid of plots with different Seaborn styles\nand 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 numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef sinplot(n=10, flip=1):\n x = np.linspace(0, 14, 100)\n for i in range(1, n + 1):...
trial_gpt4o_1
{ "original_instruction": "**Objective**: Demonstrate your understanding of Seaborn by creating and customizing a multi-plot figure.\n\n**Task**:\nWrite a Python function `customize_plots()` that performs the following steps:\n\n1. Import the necessary libraries (`numpy`, `seaborn`, and `matplotlib.pyplot`).\n2. Gene...
0.72511
Docs: Seaborn_20522
C
[ "sinplot", "customize_plots" ]
2
[ [ "customize_plots", "sinplot" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "seaborn" ]
false
d5485ef538c7f8801ef6477f3fcc4d605a9649c3
fb0bae24246caeae6ad4cbff1f7aa9146563803c
v1.0
complete
Docs
Docs: Python310_19616_C
import asyncio import random from typing import List, Tuple library_books = ["book1", "book2", "book3", "book4", "book5"] async def borrow_book(user_id: int, book_title: str) -> str: """Simulates a user borrowing a book. Waits for a random time between 1 to 3 seconds to simulate the time taken for the operati...
import asyncio import random from typing import List, Tuple library_books = ["book1", "book2", "book3", "book4", "book5"] async def borrow_book(user_id: int, book_title: str) -> str: await asyncio.sleep(random.randint(1, 3)) if book_title in library_books: library_books.remove(book_title) retu...
import pytest import asyncio from solution import borrow_book, return_book, manage_library, library_books @pytest.mark.asyncio async def test_borrow_book_available(): test_books = ["test_book1"] user_id = 1 book_title = "test_book1" global library_books library_books = test_books.copy() result ...
[]
[ 0, 1, 1, 1, 1, 1, 1, 1, 0 ]
7
easy
0.778
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import asyncio\nimport random\nfrom typing import List, Tuple\n\n# Shared library collection\nlibrary_books = [\"book1\", \"book2\", \"book3\",...
trial_gpt4o_8
{ "original_instruction": "**Objective**: To assess the understanding and application of asynchronous programming concepts in Python using the `asyncio` package.\n\n**Problem Statement:**\n\nYou are tasked with developing a simple asynchronous simulation of a library system where users can borrow and return books. Th...
0.479748
Docs: Python310_19616
C
[ "borrow_book", "return_book", "manage_library", "main" ]
4
[ [ "manage_library", "borrow_book" ], [ "manage_library", "return_book" ] ]
2
[]
false
[]
false
pytest
true
[]
true
bf330de3727e12dfbfbf20f4fccf9081596bb70b
dd1fdbb94e8bebf9b9f74621c048cb54176647f2
v1.0
complete
Docs
Docs: Python310_20516_C
def start(): """ Function start calls function_1 >>> start() Starting function: start In function_1 before calling function_2 In function_1 after calling function_2 In function_2 before performing arithmetic In function_2 after performing arithmetic """ def function_1(): """ Fun...
def start(): print("Starting function: start") function_1() def function_1(): print("In function_1 before calling function_2") function_2() print("In function_1 after calling function_2") def function_2(): print("In function_2 before performing arithmetic") result = 2 + 3 # Simple arithme...
from solution import start, function_1, function_2 def test_start(capsys): start() captured = capsys.readouterr() assert "Starting function: start" in captured.out assert "In function_1 before calling function_2" in captured.out assert "In function_1 after calling function_2" in captured.out as...
[ { "docstring": null, "function_declaration": "def start():", "function_name": "start", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def function_1():", "function_name": "function_1", "parameter_list": "()" }, { "docstring": null, "function_d...
[ 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 start():\n print(\"Starting function: start\")\n function_1()\n\ndef function_1():\n print(\"In function_1 before calling function_2\")\n function_2()\n...
trial_gpt4o_2
{ "original_instruction": "### Python 3.10 Coding Assessment\n\n#### **Problem Overview:**\nAs a Python developer, you are tasked with troubleshooting and optimizing a Python script that performs multiple nested function calls. To understand the flow of these function calls and identify potential bottlenecks in the e...
0.605557
Docs: Python310_20516
C
[ "start", "function_1", "function_2" ]
3
[ [ "function_1", "function_2" ], [ "start", "function_1" ] ]
2
[]
false
[]
false
pytest
true
[]
true
0bbac82bf68e733ce5e7d97cd31a82eaa8e9513d
fa9356f5b9c95c0d5fabe15b50a3fb3ed82f90c3
v1.0
complete
Docs
Docs: Python310_20514_C
def prime_generator(start: int, end: int): """ Generator that yields prime numbers in the range [start, end). >>> list(prime_generator(10, 20)) [11, 13, 17, 19] >>> list(prime_generator(1, 10)) [2, 3, 5, 7] >>> list(prime_generator(100, 110)) [101, 103, 107, 109] ...
def is_prime(n): """Check if a number is a prime number.""" if n <= 1: return False if n == 2: return True # 2 is a prime number if n % 2 == 0: return False p = 3 while p * p <= n: if n % p == 0: return False p += 2 return True def prime_...
from solution import prime_generator def test_prime_generator_basic(): primes = list(prime_generator(10, 20)) assert primes == [11, 13, 17, 19] def test_prime_generator_small_range(): primes = list(prime_generator(1, 10)) assert primes == [2, 3, 5, 7] def test_prime_generator_large_start(): prime...
[ { "docstring": "Check if a number is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generator that yields prime numbers in the range [start, end).", "function_declaration": "def prime_generator(start, ...
[ 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 prime_generator(start: int, end: int):\n \"\"\"\n A generator that yields prime numbers within a given range [start, end).\n \"\"\"\n def is_prime(n):\n...
trial_gpt4o_2
{ "original_instruction": "### Python Coding Assessment Question\n\n#### Objective:\nImplement a generator function in Python that iterates over a sequence of numbers and yields only the prime numbers from the sequence. The function should demonstrate a clear understanding of how generators work in Python.\n\n#### De...
0.686974
Docs: Python310_20514
C
[ "is_prime", "prime_generator" ]
2
[ [ "prime_generator", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
73d9db2123dc1bd4a4e43aa7e9291844b2cf3293
66150e3820f78f83fa9039aaf28cc918003f19fe
v1.0
complete
Docs
Docs: Scikit_20160_C
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn.tree import DecisionTreeClassifier from sklearn.semi_supervised import SelfTrainingClassifier, LabelPropagation, LabelSpreading from sklearn.metrics import accuracy_score # Step 1: Dataset Preparation def c...
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_classification from sklearn.tree import DecisionTreeClassifier from sklearn.semi_supervised import SelfTrainingClassifier, LabelPropagation, LabelSpreading from sklearn.metrics import accuracy_score # Step 1: Dataset Preparation def c...
def test_create_dataset(): X, y = create_dataset() assert X.shape == (300, 20) assert len(y) == 300 assert len(np.unique(y)) == 3 # Should contain 2 class labels and -1 for unlabeled def test_self_training_classifier(): X, y = create_dataset() accuracy = self_training_classifier(X, y) asse...
[ { "docstring": null, "function_declaration": "def create_dataset():", "function_name": "create_dataset", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def self_training_classifier(X, y):", "function_name": "self_training_classifier", "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.datasets import make_classification\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.sem...
trial_gpt4o_0
{ "original_instruction": "### Semi-Supervised Learning with Scikit-Learn\n\nIn this assessment, you are required to demonstrate your understanding of semi-supervised learning techniques using the `sklearn.semi_supervised` module. Follow the instructions below and implement Python code to complete the task.\n\n#### T...
0.626096
Docs: Scikit_20160
C
[ "create_dataset", "self_training_classifier", "label_propagation_methods", "compare_methods" ]
4
[ [ "compare_methods", "create_dataset" ], [ "compare_methods", "label_propagation_methods" ], [ "compare_methods", "self_training_classifier" ] ]
3
[]
false
[]
false
pytest
false
[ "matplotlib", "numpy", "sklearn" ]
false
865b3ad5c0fdf709324575fa487a757d9a55e30e
d58cc8bb18b33d05a689c1bff15cb841ca6a6bae
v1.0
complete
Docs
Docs: Python310_19872_C
import os import pty import fcntl import select import logging import threading def setup_logger(): """ Sets up the logger for logging chat messages to chat_log.txt. """ logger = logging.getLogger('chat_logger') handler = logging.FileHandler('chat_log.txt') formatter = logging.Formatter('%(asctime)s - ...
import os import pty import fcntl import select import logging LOG_FILE = 'chat_log.txt' def setup_logger(): logger = logging.getLogger('chat_logger') handler = logging.FileHandler(LOG_FILE) formatter = logging.Formatter('%(asctime)s - %(message)s') handler.setFormatter(formatter) logger.addHandle...
import os import pty import pytest import subprocess import time def test_chat_server(): server_process = subprocess.Popen(['python3', '-c', """ import os import pty import fcntl import select import logging LOG_FILE = 'chat_log.txt' def setup_logger(): logger = logging.getLogger('chat_logger') handler =...
[ { "docstring": null, "function_declaration": "def setup_logger():", "function_name": "setup_logger", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def read_from_client(client_fd, clients):", "function_name": "read_from_client", "parameter_list": "(client...
[ 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 os\nimport pty\nimport select\nimport sys\nimport threading\n\nLOG_FILE = 'chat_log.txt'\n\nclients = []\n\ndef handle_client(master_fd, client_fd):\n \"\"\"\...
trial_gpt4o_7
{ "original_instruction": "**Question: Create a Terminal-based Chat Application using the `pty` module**\n\nIn this task, you need to implement a terminal-based chat application that mimics a simple chat server-client interaction. The server and client will be separate processes, with the server process able to handl...
0.628411
Docs: Python310_19872
C
[ "setup_logger", "read_from_client", "remove_client", "broadcast_message", "start_server", "start_client" ]
6
[ [ "read_from_client", "broadcast_message" ], [ "read_from_client", "remove_client" ], [ "start_server", "read_from_client" ] ]
3
[]
false
[]
false
pytest
false
[]
true
adc9270fc31c7c5945607a06b60a7cefd2500c54
43cdf3487f703f7b8f05cb83c25a69c41b5946ac
v1.0
complete
Docs
Docs: Pytorch_19879_C
import torch import torch.func as func def f(x): return torch.sum(torch.sin(x) * torch.exp(x)) def compute_gradient(x): """ Compute the gradient of `f` at the input tensor `x`. Args: x (torch.Tensor): A 1D tensor of shape `(n,)`. Returns: torch.Tensor: A 1D tensor representing th...
import torch import torch.func as func def f(x): return torch.sum(torch.sin(x) * torch.exp(x)) def compute_gradient(x): grad_f = func.grad(f) return grad_f(x) def compute_per_sample_gradients(X): grad_f = func.grad(f) vmap_grad_f = func.vmap(grad_f) return vmap_grad_f(X)
import torch from solution import compute_gradient, compute_per_sample_gradients def test_compute_gradient(): x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True) expected_gradient = torch.cos(x) * torch.exp(x) + torch.sin(x) * torch.exp(x) actual_gradient = compute_gradient(x) assert torch.allclose(a...
[ { "docstring": null, "function_declaration": "def f(x):", "function_name": "f", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def compute_gradient(x):", "function_name": "compute_gradient", "parameter_list": "(x)" }, { "docstring": null, "fu...
[ 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 torch\nimport torch.func as func\n\ndef f(x):\n return torch.sum(torch.sin(x) * torch.exp(x))\n\ndef compute_gradient(x):\n return func.grad(f)(x)\n\ndef c...
trial_gpt4o_2
{ "original_instruction": "#### Objective\nImplement and compose different function transforms using the `torch.func` module to compute gradients and per-sample-gradients for a given function. This will test your comprehension of `torch.func`'s functionalities and your ability to apply them.\n\n#### Question\n\nYou a...
0.565012
Docs: Pytorch_19879
C
[ "f", "compute_gradient", "compute_per_sample_gradients" ]
3
[ [ "compute_gradient", "f" ], [ "compute_per_sample_gradients", "f" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
2626e11f7c4a78c895d45eb65f608dee021afa08
db6e7f38701ba3ad1af69221ad5e7bea830713a3
v1.0
complete
Docs
Docs: Python310_20311_C
from wsgiref.simple_server import make_server from wsgiref.util import setup_testing_defaults, request_uri import cgi quotes = [] def quote_app(environ, start_response): """ Implement a simple WSGI-based web application to handle HTTP GET and POST requests. 1. Serve a Form on GET request - Provid...
from wsgiref.simple_server import make_server from wsgiref.util import setup_testing_defaults, request_uri import cgi quotes = [] def quote_app(environ, start_response): setup_testing_defaults(environ) # Parse request method and URI method = environ['REQUEST_METHOD'] uri = request_uri(environ) h...
from solution import quote_app, quotes from wsgiref.util import setup_testing_defaults from io import BytesIO import pytest def start_response_dummy(status, headers): pass def test_get_request(): environ = {} setup_testing_defaults(environ) environ['REQUEST_METHOD'] = 'GET' response = quote_app(e...
[ { "docstring": null, "function_declaration": "def quote_app(environ, start_response):", "function_name": "quote_app", "parameter_list": "(environ, start_response)" }, { "docstring": null, "function_declaration": "def generate_form(environ):", "function_name": "generate_form", "pa...
[ 0, 0, 0, 0, 1, 0, 0, 1, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from wsgiref.simple_server import make_server\nfrom wsgiref.util import setup_testing_defaults, request_uri\nfrom wsgiref.headers import Headers\nimport cgi\n\n# List t...
trial_gpt4o_4
{ "original_instruction": "### Objective\n\nYour task is to demonstrate your understanding of the `wsgiref` package by implementing a simple WSGI-based web application. The application must handle HTTP GET and POST requests efficiently and use several utilities provided by the `wsgiref` module.\n\n### Task\n\nImpleme...
0.472137
Docs: Python310_20311
C
[ "quote_app", "generate_form" ]
2
[ [ "quote_app", "generate_form" ] ]
1
[]
false
[]
false
pytest
true
[]
true
46d559e2a6b7b79bab9bde4e5c565dd0aad23748
73ad1cd7bea75c1b74eafcd7ec90f98b404c4138
v1.0
complete
Docs
Docs: Pytorch_20335_C
import torch import time from typing import List def compute_async_squares(numbers: List[int]) -> List[int]: """ Calculate the squares of a given list of integers asynchronously using torch.futures. This function takes a list of integers and returns a list of their squares by simulating asynchronous c...
import torch import time from typing import List def square_with_delay(number: int) -> torch.futures.Future: future = torch.futures.Future() def delayed_computation(): time.sleep(0.1) future.set_result(number ** 2) # This simulates an asynchronous operation by calling delayed_comp...
from solution import compute_async_squares import torch def test_compute_async_squares_simple(): numbers = [1, 2, 3, 4, 5] expected = [1, 4, 9, 16, 25] assert compute_async_squares(numbers) == expected def test_compute_async_squares_single(): numbers = [10] expected = [100] assert compute_asyn...
[ { "docstring": null, "function_declaration": "def square_with_delay(number):", "function_name": "square_with_delay", "parameter_list": "(number)" }, { "docstring": null, "function_declaration": "def compute_async_squares(numbers):", "function_name": "compute_async_squares", "para...
[ 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 torch\nimport time\nfrom typing import List\n\ndef square_with_delay(n: int) -> torch.futures.Future:\n def delayed_square():\n time.sleep(0.1)\n ...
trial_gpt4o_1
{ "original_instruction": "You are required to demonstrate your understanding of the `torch.futures` package by implementing a sequence of asynchronous operations.\n\n### Problem Statement\n\nWrite a Python function `compute_async_squares` which calculates the squares of a given list of integers asynchronously. Use t...
0.572921
Docs: Pytorch_20335
C
[ "square_with_delay", "compute_async_squares" ]
2
[ [ "compute_async_squares", "square_with_delay" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
0b91928dc926c01b6901317ee658d583650536de
c66da02fa72ac105676cc41bf68cd00d0ce2ce75
v1.0
complete
Docs
Docs: Python310_20293_C
import asyncio from typing import List class AsyncTask: def __init__(self, name: str, delay: int, priority: int): self.name = name self.delay = delay self.priority = priority self.result = "Pending" async def process_individual_task(task: AsyncTask): """ Simulates processing an...
import asyncio class AsyncTask: def __init__(self, name: str, delay: int, priority: int): self.name = name self.delay = delay self.priority = priority self.result = "Pending" async def process_individual_task(task: AsyncTask): await asyncio.sleep(task.delay) task.result = "...
from solution import AsyncTask, async_process_tasks def test_async_process_tasks_basic(): tasks = [AsyncTask('Task1', 2, 1), AsyncTask('Task2', 1, 2), AsyncTask('Task3', 3, 1)] result = async_process_tasks(tasks) assert result == ['Task2', 'Task1', 'Task3'] def test_async_process_tasks_same_delay(): t...
[]
[ 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\nclass AsyncTask:\n def __init__(self, name: str, delay: int, priority: int):\n self.name = name\n self.delay = delay\n self.pr...
trial_gpt4o_1
{ "original_instruction": "### Question\n\n#### Objective:\nTo assess your understanding of Python's asyncio event loop by implementing a function that utilizes asynchronous tasks, delayed callbacks, and handles task completion.\n\n#### Problem Statement:\nImplement a function named `async_process_tasks` that simulat...
0.63838
Docs: Python310_20293
C
[ "process_individual_task", "async_process_tasks" ]
2
[ [ "async_process_tasks", "process_individual_task" ] ]
1
[]
false
[ "AsyncTask" ]
true
pytest
true
[]
true
962b8429d5496de2fa40f4fbcd53c7d3b2aa0622
34a081a9e094b248a635d84ed97f60fd4b9c74bf
v1.0
complete
Docs
Docs: Python310_20354_C
import asyncio import random async def process_data(data): """Simulate processing data by sleeping for a random short duration.""" pass async def create_worker_tasks(n, task_queue, lock, worker_task_count): """Create n worker tasks to fetch and process data from task_queue.""" pass async def fill_que...
import asyncio import random async def process_data(data): """Simulate processing data by sleeping for a random short duration.""" await asyncio.sleep(random.uniform(0.1, 0.5)) # Simulate variable processing time return f"Processed {data}" async def create_worker_tasks(n, task_queue, lock, worker_task_co...
import pytest import asyncio from solution import create_worker_tasks, fill_queue, process_data, main @pytest.mark.asyncio async def test_process_data(): data = "test_data" result = await process_data(data) assert result == f"Processed {data}" @pytest.mark.asyncio async def test_fill_queue(): data_lis...
[]
[ 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\n\nasync def process_data(data):\n \"\"\"\n Simulates processing data by sleeping for a random short duration.\n \"\"\"\n awai...
trial_gpt4o_2
{ "original_instruction": "### Asyncio Task Orchestrator\n\nYou are to implement a simplified task orchestrator system using Python's asyncio module. The system will simulate multiple workers fetching and processing data from a shared queue, with support for task cancellation, synchronization, and error handling.\n\n...
0.555618
Docs: Python310_20354
C
[ "process_data", "create_worker_tasks", "fill_queue", "main" ]
4
[ [ "create_worker_tasks", "process_data" ] ]
1
[ "process_data" ]
false
[]
false
pytest
true
[]
true
d109934587198f99b5e8789cc68512921133ab8a
e2013eb2176f70500dcc52c4aa3256eb6e4f1f57
v1.0
complete
Docs
Docs: Python310_20615_C
import asyncio async def collect_future_results(async_funcs, delay, loop=None): """ Gather results from multiple asynchronous operations concurrently and process them once all operations are complete. Args: async_funcs (list): A list of functions that return an asyncio.Future object when called. delay...
import asyncio async def complete_future(future, delay, result): await asyncio.sleep(delay) future.set_result(result) async def collect_future_results(async_funcs, delay, loop=None): if loop is None: loop = asyncio.get_event_loop() futures = [func() for func in async_funcs] tasks = [ ...
import asyncio import pytest from solution import collect_future_results async def example_future(): return asyncio.Future() @pytest.mark.asyncio async def test_collect_future_results(): async_funcs = [example_future for _ in range(3)] delay = 1 results = await collect_future_results(async_funcs, dela...
[]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def collect_future_results(async_funcs, delay, loop=None):\n if loop is None:\n loop = asyncio.get_running_loop()\n\n async def exe...
trial_gpt4o_1
{ "original_instruction": "## Coding Assessment Question\n\n### Objective:\nDesign a function that demonstrates your understanding of `asyncio.Future` and its associated methods and functionality. You will create a system that gathers results from multiple asynchronous operations concurrently and process them once al...
0.506983
Docs: Python310_20615
C
[ "complete_future", "collect_future_results" ]
2
[ [ "collect_future_results", "complete_future" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a5f11a5b48261fbcbcfa5b24162d4a0776e87cbd
76d637bd46ea8605b4ec1820bd1c92a76b4dfeb2
v1.0
complete
Docs
Docs: Python310_20021_C
import sys def custom_enable(display=1, logdir=None, context=5, format='html'): """ Replaces the default exception handler with a custom handler. Parameters: display (int): Display the traceback (1) or suppress (0). logdir (str): Directory path for logging tracebacks. None to disable. c...
import sys import os import traceback import html from datetime import datetime # Configuration variables _display = 1 _logdir = None _context = 5 _format = 'html' def custom_enable(display=1, logdir=None, context=5, format='html'): global _display, _logdir, _context, _format _display = display _logdir = ...
import pytest import sys import os import shutil from io import StringIO from solution import custom_enable, custom_text, custom_html, custom_handler def raise_exception(): raise ValueError("An error occurred") def test_custom_enable_and_handler_display_text(): custom_enable(display=1, logdir=None, context=5,...
[ { "docstring": null, "function_declaration": "def custom_enable(display=1, logdir=None, context=5, format='html'):", "function_name": "custom_enable", "parameter_list": "(display=1, logdir=None, context=5, format='html')" }, { "docstring": null, "function_declaration": "def custom_text(i...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\nimport traceback\n\ndef custom_enable(display=1, logdir=None, context=5, format='html'):\n \"\"\"\n Replaces the default exception handler with a cust...
trial_gpt4o_9
{ "original_instruction": "<|Analysis Begin|>\n\nThe provided documentation describes the \"cgitb\" module, which is deprecated since Python 3.11. The module is designed to handle and display detailed traceback information, making debugging easier, especially for CGI scripts. The documentation details how to enable \...
0.515478
Docs: Python310_20021
C
[ "custom_enable", "custom_text", "custom_html", "custom_handler" ]
4
[ [ "custom_handler", "custom_html" ], [ "custom_handler", "custom_text" ] ]
2
[]
false
[]
false
pytest
true
[]
true
4ab95407909e0ea1b453993d5dddfbd4e1317464
b35be5c3f39627c5a7ac0818a8df8ec0a41276c6
v1.0
complete
Docs
Docs: Scikit_19944_C
from typing import List, Tuple import numpy as np from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split from sklearn.linear_model import Ridge from sklearn.inspection import permutation_importance from scipy.cluster.hierarchy import linkage, fcluster def handle_correlated_feat...
from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split from sklearn.linear_model import Ridge from sklearn.inspection import permutation_importance from scipy.cluster.hierarchy import linkage, fcluster import numpy as np def handle_correlated_features(X, threshold=0.9): """...
from solution import permutation_feature_importance_analysis def test_permutation_feature_importance_analysis(): result = permutation_feature_importance_analysis(n_repeats=10, random_state=42) assert len(result) > 0, "The result should contain feature importances" for feature, importance_mean, importa...
[ { "docstring": "Identify and handle correlated features by clustering and returning one feature per cluster.", "function_declaration": "def handle_correlated_features(X, threshold=0.9):", "function_name": "handle_correlated_features", "parameter_list": "(X, threshold=0.9)" }, { "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": "from sklearn.datasets import load_diabetes\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import Ridge\nfrom sklearn.inspection import...
trial_gpt4o_0
{ "original_instruction": "### Permutation Feature Importance Analysis\n\n#### Objective\n\nYou are tasked with evaluating the importance of features in a dataset for a regression problem using permutation feature importance. You will train a regression model, compute feature importances using permutations, and handl...
0.57548
Docs: Scikit_19944
C
[ "handle_correlated_features", "permutation_feature_importance_analysis" ]
2
[ [ "permutation_feature_importance_analysis", "handle_correlated_features" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "scipy", "sklearn" ]
false
401891bbccafb2a9d26b904c22d60f16daac4e46
145f3eada7d2079ede4f67f71a341a2aa3859e42
v1.0
complete
Docs
Docs: Python310_20496_C
import curses from curses.textpad import Textbox, rectangle def main(stdscr): """ Design a text-based user interface (TUI) to capture and display user input within a defined area of the terminal screen. The TUI should update in real-time as the user types, handle navigation within the input area, and sup...
import curses from curses.textpad import Textbox, rectangle def main(stdscr): # Initialize curses and settings curses.curs_set(1) curses.noecho() curses.cbreak() stdscr.keypad(True) curses.start_color() curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) # Define window size...
# Note: Testing a curses-based TUI typically involves manual testing, but we can write some tests using `pytest-curses` or similar. # The following is a conceptual framework for manual verification. def test_placeholder(): # Placeholder test function for conceptual framework. # In practice, observe manually ...
[ { "docstring": null, "function_declaration": "def main(stdscr):", "function_name": "main", "parameter_list": "(stdscr)" }, { "docstring": null, "function_declaration": "def run_curses_ui():", "function_name": "run_curses_ui", "parameter_list": "()" }, { "docstring": null,...
[ 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 curses\nfrom curses.textpad import Textbox, rectangle\n\ndef main(stdscr):\n # Initialize curses and settings (no echo, cbreak mode, etc.)\n curses.curs_se...
trial_gpt4o_8
{ "original_instruction": "### Design a Text-based User Interface with Curses\n\n#### Objective:\nDesign a text-based user interface (TUI) to capture and display user input within a defined area of the terminal screen. The TUI should update in real-time as the user types, handle navigation within the input area, and ...
0.406571
Docs: Python310_20496
C
[ "main", "run_curses_ui" ]
2
[ [ "run_curses_ui", "main" ] ]
1
[]
false
[]
false
pytest
false
[]
true
c41bf43bd0f794cdeff8585c9a25cd808f2cdad0
28d43b2df85ee11260aaba0ffad8c699486bd748
v1.0
complete
Docs
Docs: Pandas_20147_C
import pandas as pd from scipy.stats import zscore def create_dataframe(): """ Creates the initial DataFrame containing sales transaction data. Returns: pd.DataFrame: The DataFrame containing the sales transaction data. Example: >>> df = create_dataframe() >>> len(df) 11 "...
import pandas as pd from scipy.stats import zscore def create_dataframe(): data = { "ProductID": [1, 2, 1, 3, 2, 1, 2, 3, 1, 3, 2], "StoreID": [1, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1], "Quantity": [10, 15, 8, 12, 10, 15, 9, 5, 20, 8, 7], "SalesAmount": [100, 150, 80, 120, 100, 150, 90, 50,...
def test_create_dataframe(): df = create_dataframe() assert not df.empty assert len(df) == 11 assert list(df.columns) == ['ProductID', 'StoreID', 'Quantity', 'SalesAmount', 'Date'] def test_aggregate_sales_data(): df = create_dataframe() aggregated_df = aggregate_sales_data(df) assert len(a...
[ { "docstring": null, "function_declaration": "def create_dataframe():", "function_name": "create_dataframe", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def aggregate_sales_data(df):", "function_name": "aggregate_sales_data", "parameter_list": "(df)" ...
[ 0, 1 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom scipy.stats import zscore\n\n# Step 1: Load the Data\ndata = {\n \"ProductID\": [1, 2, 1, 3, 2, 1, 2, 3, 1, 3, 2],...
trial_gpt4o_2
{ "original_instruction": "**Objective:** Demonstrate your understanding of the `pandas` `groupby` functionality by performing a series of data manipulations involving aggregation, transformation, and filtering.\n\n### Problem Statement\n\nYou are provided with a `pandas` DataFrame containing information about sales ...
0.704714
Docs: Pandas_20147
C
[ "create_dataframe", "aggregate_sales_data", "transform_sales_data", "filter_transactions", "process_sales_data" ]
5
[ [ "process_sales_data", "aggregate_sales_data" ], [ "process_sales_data", "create_dataframe" ], [ "process_sales_data", "filter_transactions" ], [ "process_sales_data", "transform_sales_data" ] ]
4
[]
false
[]
false
pytest
false
[ "pandas", "scipy" ]
false
48131dec11d58d99ef6808008e827bc7d298113b
4cd9a1a2c63f1f4681d9a35ac6dd17d8727fb9c0
v1.0
complete
Docs
Docs: Python310_20137_C
import ctypes from ctypes import CFUNCTYPE, c_void_p, py_object import builtins def PyCapsule_New(pointer, name, destructor): """ Create a new PyCapsule object. """ capsule = py_object() capsule.pointer = pointer capsule.name = name capsule.context = None capsule.destructor = destructor ret...
import ctypes from ctypes import CFUNCTYPE, c_void_p, py_object import builtins # Mocks to represent PyCapsule C API behavior in pure Python def PyCapsule_New(pointer, name, destructor): capsule = py_object() capsule.pointer = pointer capsule.name = name capsule.context = None capsule.destructor =...
from solution import create_capsule, set_new_pointer, validate_capsule, mock_destructor import pytest def test_create_capsule(): capsule = create_capsule(1000, "module.attribute", 2000) assert capsule.pointer == 1000 assert capsule.name == "module.attribute" assert capsule.context == 2000 def test_set...
[ { "docstring": null, "function_declaration": "def PyCapsule_New(pointer, name, destructor):", "function_name": "PyCapsule_New", "parameter_list": "(pointer, name, destructor)" }, { "docstring": null, "function_declaration": "def PyCapsule_GetPointer(capsule, name):", "function_name":...
[ 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 ctypes\nfrom cpython import capsule\n\ndef create_capsule(pointer: int, name: str, context: int):\n \"\"\"\n Creates a PyCapsule object encapsulating a moc...
trial_gpt4o_8
{ "original_instruction": "### Advanced Coding Assessment Question: PyCapsule Manipulation in Python\n\n#### Overview:\nIn this coding task, you will need to create and manipulate `PyCapsule` objects in Python using C extension modules. The goal is to interact with these capsules by setting and retrieving their attri...
0.350393
Docs: Python310_20137
C
[ "PyCapsule_New", "PyCapsule_GetPointer", "PyCapsule_GetName", "PyCapsule_GetContext", "PyCapsule_SetPointer", "PyCapsule_SetDestructor", "mock_destructor", "create_capsule", "set_new_pointer", "validate_capsule" ]
10
[ [ "create_capsule", "PyCapsule_New" ], [ "create_capsule", "mock_destructor" ], [ "set_new_pointer", "PyCapsule_SetPointer" ], [ "validate_capsule", "PyCapsule_GetName" ] ]
4
[]
false
[]
false
pytest
true
[]
true
82a14afd6957a7549f3f8ccb6d53e284070fd0c4
85358d8e915dc8d2bb800fc09aef286edc26089b
v1.0
complete
Docs
Docs: Python310_20552_C
def filter_users(users: list, age_threshold: int) -> list: """ Filters the users whose age is greater than or equal to the age_threshold. Parameters: users (list): A list of user dictionaries. age_threshold (int): Age threshold for filtering. Returns: list: A list of filtered u...
def filter_users(users, age_threshold): """ Filters the users whose age is greater than or equal to the age_threshold. Parameters: users (list): A list of user dictionaries. age_threshold (int): Age threshold for filtering. Returns: list: A list of filtered user dictionaries. ...
from solution import filter_users, transform_users, aggregate_data, data_pipeline def test_filter_users(): users = [ {"first_name": "John", "last_name": "Doe", "age": 25, "email": "JOHN.DOE@MAIL.COM"}, {"first_name": "Jane", "last_name": "Doe", "age": 22, "email": "JANE.DOE@MAIL.COM"}, {"fi...
[ { "docstring": "Filters the users whose age is greater than or equal to the age_threshold.\n\nParameters:\n users (list): A list of user dictionaries.\n age_threshold (int): Age threshold for filtering.\n\nReturns:\n list: A list of filtered user dictionaries.", "function_declaration": "def filter_...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def filter_users(users, age_threshold):\n \"\"\"\n Filters the users list based on the age threshold.\n \n Args:\n users (list): List of user dictionarie...
trial_gpt4o_2
{ "original_instruction": "### Question: Multi-Stage Data Transformation Pipeline\n\nYou are required to implement a data transformation pipeline. This pipeline will accept a list of dictionaries as input, each representing a user's data, and will output a list of dictionaries after processing. \n\nThe transformation...
0.558495
Docs: Python310_20552
C
[ "filter_users", "transform_users", "aggregate_data", "data_pipeline" ]
4
[ [ "data_pipeline", "aggregate_data" ], [ "data_pipeline", "filter_users" ], [ "data_pipeline", "transform_users" ] ]
3
[]
false
[]
false
pytest
true
[]
true
7f66899e9ce6ea7c68c1b40d8a7072bc1a2cca18
8eb13ee2bac1f757b5af5b083052086cdba7bc53
v1.0
complete
Docs
Docs: Python310_20721_C
import asyncio import logging import random from typing import List logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) async def fetch_data(source: str) -> str: """Simulates fetching data from a given source with a random delay.""" pass async def process_data(data: str) -> None: ...
import asyncio import logging import random import time from typing import List logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) async def fetch_data(source: str) -> str: """Simulates fetching data from a given source with a random delay.""" delay = random.uniform(0.1, 0.5) awa...
import asyncio import pytest from unittest.mock import patch from solution import fetch_data, process_data, main @pytest.mark.asyncio async def test_fetch_data(): with patch('solution.random.uniform', return_value=0.1): data = await fetch_data("source_test") assert data == "data_from_source_test" ...
[]
[ 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\nimport logging\nimport random\nimport time\nfrom typing import List\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n...
trial_gpt4o_0
{ "original_instruction": "### Asynchronous Programming with asyncio\n\nIn this assessment, you are required to create a Python program that demonstrates your understanding of Python's asyncio library, specifically focusing on concurrency, handling long-running tasks, and using the debug features of asyncio.\n\n#### ...
0.567348
Docs: Python310_20721
C
[ "fetch_data", "process_data", "main", "fetch_and_process" ]
4
[ [ "fetch_and_process", "fetch_data" ], [ "fetch_and_process", "process_data" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
9492b5b733da1d5c5cf78533c2b6fdfa26a6cab7
9007f3b221e48239020bed18d33b102f6e9c5033
v1.0
complete
Docs
Docs: Python310_20445_C
import cProfile import pstats import io def sample_function(number_list): """ Perform operations on a list of integers. >>> sample_function([1, 2, 3, 4]) == [1, 4, 27, 16] """ result = [] for num in number_list: if num % 2 == 0: result.append(num ** 2) else: ...
import cProfile import pstats import io def sample_function(number_list): result = [] for num in number_list: if num % 2 == 0: result.append(num ** 2) else: result.append(num ** 3) return result # Profiling the original function def profile_original_function(): ...
from solution import sample_function, optimized_function import time def test_function_output(): number_list = list(range(100)) assert sample_function(number_list) == optimized_function(number_list), "Outputs do not match" def test_performance_improvement(): number_list = list(range(1000000)) # T...
[ { "docstring": null, "function_declaration": "def sample_function(number_list):", "function_name": "sample_function", "parameter_list": "(number_list)" }, { "docstring": null, "function_declaration": "def profile_original_function():", "function_name": "profile_original_function", ...
[ 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 cProfile\nimport pstats\nimport io\n\ndef sample_function(number_list):\n result = []\n for num in number_list:\n if num % 2 == 0:\n resu...
trial_gpt4o_0
{ "original_instruction": "**Question:**\n\nYou are required to profile and optimize the performance of a Python program. The program includes a function that performs a specific task multiple times, which may be computationally intensive. Your task is to:\n\n1. **Profile the function execution using `cProfile`** and...
0.553011
Docs: Python310_20445
C
[ "sample_function", "profile_original_function", "optimized_function", "profile_optimized_function", "main" ]
5
[ [ "profile_optimized_function", "optimized_function" ], [ "profile_original_function", "sample_function" ] ]
2
[]
false
[]
false
pytest
true
[]
true
12df62639e9424d2bbba006442789d05753eb795
2c6f94a990de81664cc38bf45f844a72ecbcdddb
v1.0
complete
Docs
Docs: Python310_20711_C
import asyncio from typing import List, Dict, Tuple import aiohttp async def fetch_url(session, url: str) -> Tuple[str, str]: """ Fetches the content of the URL asynchronously using aiohttp. Args: session (aiohttp.ClientSession): The aiohttp client session. url (str): The URL to fetch. Re...
import asyncio from typing import List, Dict, Tuple import aiohttp async def fetch_url(session, url: str) -> Tuple[str, str]: try: async with session.get(url) as response: html = await response.text() return url, html except Exception as e: return url, "" async def fetc...
import asyncio from solution import fetch_all def test_fetch_all_single_url(): urls = ["http://httpbin.org/html"] result = asyncio.run(fetch_all(urls)) assert len(result) == 1 assert "http://httpbin.org/html" in result assert len(result["http://httpbin.org/html"]) > 0 def test_fetch_all_multiple_u...
[]
[ 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 List, Dict, Tuple\nimport aiohttp\n\nasync def fetch_url(session, url: str) -> Tuple[str, str]:\n \"\"\"\n Fetches the HTML con...
trial_gpt4o_1
{ "original_instruction": "### Asyncio Web Scraper\n\n#### Objective\nWrite an asynchronous web scraper using the `asyncio` module in Python. The web scraper should take a list of URLs, fetch their contents concurrently, and return a dictionary with URLs as keys and their HTML contents as values.\n\n#### Requirements...
0.669118
Docs: Python310_20711
C
[ "fetch_url", "fetch_all" ]
2
[ [ "fetch_all", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
51da886798091bc125baa19a23a80390fe35e228
9c74a686b3c3a8055c8ef5302337f920ec82a3ad
v1.0
complete
Docs
Docs: Python310_20388_C
# Function to implement def process_data(endpoint: str) -> None: """ Fetch data from the given endpoint, process it, and save the processed data. >>> process_data('http://example.com/api') """ pass # Placeholder implementations def fetch_data(endpoint: str) -> any: """ Simulated fetch_data...
# Placeholder implementations def fetch_data(endpoint): """ Simulated fetch_data function that gets data from an endpoint. This is a placeholder and should be replaced by a mock in tests. """ pass def transform_data(raw_data): """ Simulated transform_data function that processes raw data. ...
from unittest.mock import patch, Mock import unittest from solution import process_data, fetch_data, transform_data, save_data class TestProcessData(unittest.TestCase): @patch('solution.fetch_data') @patch('solution.save_data') @patch('solution.transform_data') def test_process_data(self, mock_transf...
[ { "docstring": "Simulated fetch_data function that gets data from an endpoint.\nThis is a placeholder and should be replaced by a mock in tests.", "function_declaration": "def fetch_data(endpoint):", "function_name": "fetch_data", "parameter_list": "(endpoint)" }, { "docstring": "Simulated t...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def fetch_data(endpoint):\n \"\"\"\n Fetches data from the given endpoint.\n This is a placeholder implementation.\n \"\"\"\n return {\"data\": \"some_da...
trial_gpt4o_2
{ "original_instruction": "#### Title: Mocking with unittest.mock\n\n#### Description:\nYou are tasked with developing a small data processing function and thoroughly testing it using the `unittest.mock` module. The functionality involves fetching data from an API, processing it, and saving the results to a database....
0.703818
Docs: Python310_20388
C
[ "fetch_data", "transform_data", "save_data", "process_data" ]
4
[ [ "process_data", "fetch_data" ], [ "process_data", "save_data" ], [ "process_data", "transform_data" ] ]
3
[ "process_data" ]
false
[]
false
pytest
true
[]
true
6a506559e788123d19870377f017dbca58c1ba10
e2e511fc60ffe4c48c0c4bed61a792f60c993dc1
v1.0
complete
Docs
Docs: Python310_20923_C
import warnings # Define a custom warning category class CustomWarning(UserWarning): pass def emit_warning(): warnings.warn("This is a custom warning", CustomWarning) def custom_warning_handler(): """ Issue and manage custom warnings using the warnings module. - Always display CustomWarning. ...
import warnings # Define a custom warning category class CustomWarning(UserWarning): pass def emit_warning(): warnings.warn("This is a custom warning", CustomWarning) def custom_warning_handler(): captured_warnings = [] # Filter to always show CustomWarning warnings.simplefilter("always", Custom...
from solution import custom_warning_handler, CustomWarning def test_custom_warning_handler(): warnings_list = custom_warning_handler() # Two warnings should be captured assert len(warnings_list) == 2 # Check the content of captured warnings assert "This is a custom warning" in warnings_li...
[]
[ 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\n# Define a custom warning category\nclass CustomWarning(UserWarning):\n pass\n\ndef emit_warning():\n warnings.warn(\"This is a custom warning\...
trial_gpt4o_2
{ "original_instruction": "### Question: Warning Management in Python\n\nYou are tasked with writing a Python function named `custom_warning_handler()` that will utilize the `warnings` module to manage and process warnings in a specific manner.\n\n#### Requirements:\n1. **Custom Warning Category**:\n - Define a cus...
0.496659
Docs: Python310_20923
C
[ "emit_warning", "custom_warning_handler" ]
2
[ [ "custom_warning_handler", "emit_warning" ] ]
1
[]
false
[ "CustomWarning" ]
true
pytest
true
[]
true
c22998fd731b559facc236e450ad027bd49b0696
b8f46d04f0b4421d42c33d2aafffa395e744f196
v1.0
complete
Docs
Docs: Pytorch_20478_C
import torch.multiprocessing as mp def dummy_task(num: int) -> int: """ Squares a given number. >>> dummy_task(2) 4 >>> dummy_task(0) 0 >>> dummy_task(-3) 9 """ pass def start_and_monitor_processes(num_processes: int, inputs: List[int]) -> List[int]: """ Starts multiple wor...
import torch.multiprocessing as mp def dummy_task(num): """ Squares the input number. Args: num (int): Number to be squared. Returns: int: The square of the input number. """ return num * num def worker(rank, num_processes, inputs, results): """ Worker functio...
from solution import dummy_task, start_and_monitor_processes def test_dummy_task(): assert dummy_task(2) == 4 assert dummy_task(0) == 0 assert dummy_task(-3) == 9 def test_start_and_monitor_processes(): # Test with 4 processes and 4 inputs inputs = [1, 2, 3, 4] num_processes = 4 results = ...
[ { "docstring": "Squares the input number.\n\nArgs:\n num (int): Number to be squared.\n\nReturns:\n int: The square of the input number.", "function_declaration": "def dummy_task(num):", "function_name": "dummy_task", "parameter_list": "(num)" }, { "docstring": "Worker function to be e...
[ 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 torch\nimport torch.multiprocessing as mp\n\ndef dummy_task(num):\n \"\"\"\n Returns the square of the input value num.\n \"\"\"\n return num * num\n...
trial_gpt4o_1
{ "original_instruction": "### Scenario\nYou have been hired by a tech company to optimize the data processing pipeline of a large machine learning project. The project involves performing computationally intensive transformations on a dataset using multiple processors to decrease the overall processing time. This is...
0.58535
Docs: Pytorch_20478
C
[ "dummy_task", "worker", "start_and_monitor_processes" ]
3
[ [ "worker", "dummy_task" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
764bf03b1deb60448a481e4813f298149a132778
059909e289576c5b59c5a5e101cdf4d797b3f55a
v1.0
complete
Docs
Docs: Pytorch_20626_C
import torch import numpy as np import random from torch.utils.data import DataLoader, Dataset def set_random_seeds(seed_value): """ Sets the random seed for PyTorch, NumPy, and Python's random module. :param seed_value: int - the seed value. """ pass def create_neural_network(): """ ...
import torch import numpy as np import random def set_random_seeds(seed_value): """ Sets the random seed for PyTorch, NumPy, and Python's random module. :param seed_value: int - the seed value. """ torch.manual_seed(seed_value) torch.cuda.manual_seed(seed_value) torch.cuda.manual_seed_...
import torch from torch.utils.data import DataLoader, Dataset import numpy as np import random from solution import set_random_seeds, create_neural_network, generate_random_input, demonstrate_determinism, demonstrate_dataloader_determinism def test_set_random_seeds(): set_random_seeds(42) assert torch.initial...
[ { "docstring": "Sets the random seed for PyTorch, NumPy, and Python's random module.\n\n:param seed_value: int - the seed value.", "function_declaration": "def set_random_seeds(seed_value):", "function_name": "set_random_seeds", "parameter_list": "(seed_value)" }, { "docstring": "Creates a s...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport numpy as np\nimport random\n\ndef set_random_seeds(seed_value):\n \"\"\"\n Sets the random seed for PyTorch, NumPy, an...
trial_gpt4o_9
{ "original_instruction": "### PyTorch Deterministic Operations and Reproducibility\n\n#### Objective\nYou are required to write a PyTorch program that demonstrates how to achieve reproducible results by controlling sources of randomness and handling nondeterministic behavior across various components including PyTor...
0.542813
Docs: Pytorch_20626
C
[ "set_random_seeds", "create_neural_network", "generate_random_input", "demonstrate_determinism", "demonstrate_dataloader_determinism" ]
5
[ [ "demonstrate_dataloader_determinism", "set_random_seeds" ], [ "demonstrate_determinism", "set_random_seeds" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "torch", "torchvision" ]
false
a8e2a2c7e9654ab02da4b0c3570a81f86258957c
b727b0410a58108dceee010a3177753090f90d8e
v1.0
complete
Docs
Docs: Python310_20604_C
import traceback class CustomException(Exception): """ Custom exception that accepts an error message. """ def __init__(self, message: str): super().__init__(message) self.message = message def raise_exception(): """ Raise a CustomException with a descriptive error message. """ ...
import traceback class CustomException(Exception): def __init__(self, message: str): super().__init__(message) self.message = message def raise_exception(): raise CustomException("This is a custom exception with a detailed error message") def handle_exception(): try: raise_excepti...
import pytest from solution import CustomException, raise_exception, handle_exception, recursive_function, query_error_state def test_custom_exception(): with pytest.raises(CustomException) as exc_info: raise_exception() assert str(exc_info.value) == "This is a custom exception with a detailed error me...
[]
[ 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 traceback\n\nclass CustomException(Exception):\n def __init__(self, message: str):\n super().__init__(message)\n self.message = message\n\ndef r...
trial_gpt4o_2
{ "original_instruction": "#### Objective:\nImplement a Python module that effectively demonstrates the comprehension of exception handling mechanisms. You will write functions to raise custom exceptions, handle those exceptions, and provide pertinent details (such as traceback and error messages).\n\n#### Task:\n\n1...
0.458062
Docs: Python310_20604
C
[ "raise_exception", "handle_exception", "recursive_function", "query_error_state" ]
4
[ [ "handle_exception", "raise_exception" ] ]
1
[]
false
[ "CustomException" ]
true
pytest
true
[]
true
2c1ce30c76441d0003b6c0f8316af75deb40e88d
e67d678539d015babe13e4e6dc3802b93713cd87
v1.0
complete
Docs
Docs: Pytorch_20540_C
import torch from torch.nn.attention.flex_attention import flex_attention, and_masks def create_custom_mask(mask1: torch.Tensor, mask2: torch.Tensor) -> torch.Tensor: """ Create a custom mask by performing an 'AND' operation on two masks. Args: mask1 (torch.Tensor): A boolean tensor mask. mask...
import torch # Note: Since torch.nn.attention.flex_attention module doesn't actually exist in PyTorch, # We will mock the flex_attention and and_masks functions for the purpose of this exercise. def and_masks(mask1: torch.Tensor, mask2: torch.Tensor) -> torch.Tensor: """ Mock function to perform 'AND' operati...
from solution import create_custom_mask, apply_flex_attention import torch def test_create_custom_mask(): mask1 = torch.tensor([[True, False], [True, True]], dtype=torch.bool) mask2 = torch.tensor([[True, True], [False, True]], dtype=torch.bool) expected = torch.tensor([[True, False], [False, True]], dtype...
[ { "docstring": "Mock function to perform 'AND' operation on two masks.", "function_declaration": "def and_masks(mask1, mask2):", "function_name": "and_masks", "parameter_list": "(mask1, mask2)" }, { "docstring": "Mock function to compute the flexible attention process, masked.", "functio...
[ 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\nfrom torch.nn.attention.flex_attention import flex_attention, and_masks\n\ndef create_custom_mask(mask1: torch.Tensor, mask2: torch.Tensor) -> torch.Tenso...
trial_gpt4o_9
{ "original_instruction": "### Advanced Coding Assessment: Implementing and Utilizing Block Masks in Flexible Attention\n\n#### Objective:\nThe goal of this assessment is to test your ability to work with attention mechanisms and block masks in PyTorch. You will implement a function that creates a customized attentio...
0.465827
Docs: Pytorch_20540
C
[ "and_masks", "flex_attention", "create_custom_mask", "apply_flex_attention" ]
4
[ [ "apply_flex_attention", "flex_attention" ], [ "create_custom_mask", "and_masks" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
25e756580c3ad3ddf28d9c3decf55f2a9349822f
c66867e35ec8ad0c793f82629d9a39d829ea477e
v1.0
complete
Docs
Docs: Scikit_21021_C
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier def stream_data(file_path): """ Generator function that reads lines from a file and yields class label and text data. Parameters: file_path (str): Path to the text data file. Yield...
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier def stream_data(file_path): """ Generator function that reads lines from a file and yields class label and text data. Parameters: file_path (str): Path to the text data file. Yield...
import os import pytest from solution import stream_data, train_model @pytest.fixture def create_test_file(): file_path = "test_text_data.txt" lines = [ "class1 This is a test sentence.", "class2 Another test sentence goes here.", "class1 Yet another test line.", "class3 A compl...
[]
[ 0, 0, 1 ]
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\nimport numpy as np\n\ndef stream_data(file_path):\n \"...
trial_gpt4o_2
{ "original_instruction": "**Question: Implementing an Out-of-Core Learning System**\n\nYou are asked to design an out-of-core learning system to handle a large text classification problem using scikit-learn. Your task is to:\n\n1. Stream text data from a hypothetical large dataset.\n2. Extract features using the Has...
0.549736
Docs: Scikit_21021
C
[ "stream_data", "train_model" ]
2
[ [ "train_model", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "sklearn" ]
false
a20dfbccac430b3f1872b143c060c6e998c6145d
7bba52c65f15bdc1a1562a7d42a40a45c116bb08
v1.0
complete
Docs
Docs: Python310_20521_C
from fractions import Fraction from decimal import Decimal def process_fractions(data: list) -> dict: """ Perform various operations on rational numbers using the `fractions` module. >>> data = [ ... ("add", 1, 2), ... ("subtract", "3/4", "1/4"), ... ("multiply", Fraction(3, 7), 2)...
from fractions import Fraction from decimal import Decimal def process_fractions(data: list) -> dict: results = {} for i, (operation, *params) in enumerate(data): if operation not in ["add", "subtract", "multiply", "divide", "limit_denominator", "as_integer_ratio"]: continue ...
from solution import process_fractions from fractions import Fraction from decimal import Decimal def test_basic_operations(): data = [ ("add", 1, 2), # 1 + 2 ("subtract", "3/4", "1/4"), # 3/4 - 1/4 ("multiply", Fraction(3, 7), 2) # 3/7 * 2 ] result = process_fr...
[ { "docstring": null, "function_declaration": "def process_fractions(data):", "function_name": "process_fractions", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def convert_to_fraction(param):", "function_name": "convert_to_fraction", "parameter_list...
[ 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": "from fractions import Fraction\nfrom decimal import Decimal\n\ndef to_fraction(value):\n if isinstance(value, (int, Fraction)):\n return Fraction(value)\n ...
trial_gpt4o_4
{ "original_instruction": "### Question:\n\n#### Objective:\nWrite a Python function that performs various operations on rational numbers using the `fractions` module. Your function should be able to handle inputs of different types and perform a series of operations as described below.\n\n#### Function Signature:\n`...
0.675679
Docs: Python310_20521
C
[ "process_fractions", "convert_to_fraction" ]
2
[ [ "process_fractions", "convert_to_fraction" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8893a6b8a5db3abc5cd53d36bc65c42cb24dfb96
69758165f8aa1b3e1e678fc6f27244edf2fcbbca
v1.0
complete
Docs
Docs: Pytorch_21030_C
import torch import torch.onnx def check_onnx_backend_support() -> bool: """ Check if the ONNX Runtime backend is supported in the current environment. >>> isinstance(check_onnx_backend_support(), bool) True """ try: return torch.onnx.is_onnxrt_backend_supported() except AttributeError:...
import torch import torch.onnx def check_onnx_backend_support() -> bool: try: return torch.onnx.is_onnxrt_backend_supported() except AttributeError: # Function is_onnxrt_backend_supported might not be available in all versions. return False def convert_and_run_model(model: torch.nn.Mod...
import torch import torch.nn as nn from solution import check_onnx_backend_support, convert_and_run_model class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.fc = nn.Linear(2, 2) def forward(self, x): return self.fc(x) def test_check_onnx_bac...
[ { "docstring": null, "function_declaration": "def check_onnx_backend_support():", "function_name": "check_onnx_backend_support", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def convert_and_run_model(model, input_tensor):", "function_name": "convert_and_run...
[ 0, 0, 0, 1, 0, 1, 1, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.onnx\n\ndef check_onnx_backend_support() -> bool:\n try:\n return torch.onnx.is_onnxrt_backend_supported()\n except AttributeErr...
trial_gpt4o_3
{ "original_instruction": "Mixed Backend Model Execution\n\n**Context:**\nYou are required to implement a functionality in PyTorch that checks if the ONNX Runtime (ONNXRT) backend is supported in the current environment and then performs model conversion and execution using this backend if supported.\n\n**Task:**\n\n...
0.435469
Docs: Pytorch_21030
C
[ "check_onnx_backend_support", "convert_and_run_model" ]
2
[ [ "convert_and_run_model", "check_onnx_backend_support" ] ]
1
[]
false
[]
false
pytest
true
[ "onnxruntime", "torch" ]
false
405420b67fb7b58021e6b07d78d4eacc2b38e906
13e36195d0eb94a8a18c91dbde8e8ace8f5a44b4
v1.0
complete
Docs
Docs: Python310_20991_C
import ftplib import hashlib def automated_ftp_client(hostname: str, username: str, password: str, directory: str, filename: str, checksum: str) -> bool: """ Connects to an FTP server, retrieves a specific file, and verifies its integrity using a given checksum. Parameters: - hostname (str): The ...
import ftplib import hashlib def calculate_sha256_checksum(file_path): """ Calculate the SHA256 checksum of the given file. :param file_path: The path to the file for which to calculate the checksum. :return: The hexadecimal SHA256 checksum string. """ sha256 = hashlib.sha256() with op...
from solution import automated_ftp_client import hashlib import os # Mock ftp server settings hostname = "test.rebex.net" username = "demo" password = "password" def test_ftp_client_success(monkeypatch): import ftplib from io import BytesIO # Create a fake FTP server for testing class MockFTP: ...
[ { "docstring": "Calculate the SHA256 checksum of the given file.\n\n:param file_path: The path to the file for which to calculate the checksum.\n:return: The hexadecimal SHA256 checksum string.", "function_declaration": "def calculate_sha256_checksum(file_path):", "function_name": "calculate_sha256_chec...
[ 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import ftplib\nimport hashlib\n\ndef automated_ftp_client(hostname: str, username: str, password: str, directory: str, filename: str, checksum: str) -> bool:\n try:\...
trial_gpt4o_4
{ "original_instruction": "**Title:** Implement an Automated FTP Client with File Verification\n\n**Objective:** \nTo assess the student's ability to utilize the `ftplib` module for performing various FTP operations, error handling, and verifying the integrity of downloaded files.\n\n**Problem Statement:**\n\nYou are...
0.611443
Docs: Python310_20991
C
[ "calculate_sha256_checksum", "automated_ftp_client" ]
2
[ [ "automated_ftp_client", "calculate_sha256_checksum" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cc64353d9a49dd89ed1a5afd57b3cdeed8c10a07
88b1e4528abb271c439199c158e407a1952f4192
v1.0
complete
Docs
Docs: Pytorch_21342_C
import torch import torch.nn as nn class SimpleNN(nn.Module): """ Create a simple Feedforward Neural Network in Pytorch. The network should have: - An input layer of size 10. - One hidden layer of size 5. - An output layer of size 2. - Use ReLU activation for the hidden layer. """ def _...
# Step 1: Implement the Custom Model import torch import torch.nn as nn class SimpleNN(nn.Module): def __init__(self): super(SimpleNN, self).__init__() self.fc1 = nn.Linear(10, 5) self.relu = nn.ReLU() self.fc2 = nn.Linear(5, 2) def forward(self, x): x = self.fc1(x) ...
import torch from solution import SimpleNN, simple_nn_model, load_from_hub def test_model_structure(): model = SimpleNN() assert isinstance(model, nn.Module) assert isinstance(model.fc1, nn.Linear) assert isinstance(model.fc2, nn.Linear) assert isinstance(model.relu, nn.ReLU) assert model.fc1.i...
[]
[ 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 torch\nimport torch.nn as nn\nimport torch.hub\n\nclass SimpleFFNN(nn.Module):\n def __init__(self):\n super(SimpleFFNN, self).__init__()\n self...
trial_gpt4o_2
{ "original_instruction": "**Coding Assessment Question:**\n\n### Objective\nDemonstrate your understanding of Pytorch Hub by implementing and publishing a custom model, and then loading and using this model from the Hub. \n\n### Task\n1. Create a simple custom neural network model using Pytorch.\n2. Define an entryp...
0.611111
Docs: Pytorch_21342
C
[ "simple_nn_model", "load_from_hub" ]
2
[ [ "load_from_hub", "simple_nn_model" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
3d258c8316be9241f369024aabde89518b1da17d
0ee149503317d33282ed4eb7d62f384f56310f9e
v1.0
complete
Docs
Docs: Python310_21308_C
import codecs def custom_error_handler(exception): """ Custom error handler to replace problematic sections with "(error)". """ def register_custom_error_handler(): """ Registers the custom error handler with the codec registry. """ codecs.register_error("custom_error", custom_error_handle...
import codecs def custom_error_handler(exception): """ Custom error handler to replace problematic sections with "(error)". """ # exception is a UnicodeEncodeError or UnicodeDecodeError object if isinstance(exception, (UnicodeEncodeError, UnicodeDecodeError)): return ("(error)", exception.s...
from solution import register_custom_error_handler, custom_encode, custom_decode def test_register_custom_error_handler(): register_custom_error_handler() def test_custom_encode_ascii(): register_custom_error_handler() result = custom_encode("hello π world", encoding='ascii') assert result == b'hello ...
[ { "docstring": "Custom error handler to replace problematic sections with \"(error)\".", "function_declaration": "def custom_error_handler(exception):", "function_name": "custom_error_handler", "parameter_list": "(exception)" }, { "docstring": "Registers the custom error handler with the cod...
[ 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 codecs\n\ndef custom_error_handler(exception):\n if isinstance(exception, (UnicodeEncodeError, UnicodeDecodeError)):\n return (\"(error)\", exception.e...
trial_gpt4o_1
{ "original_instruction": "**Objective:**\n\nIn this assessment, you are required to demonstrate your understanding of the Python codec registry and support functions. Specifically, you will implement functions to register a custom error handler for encoding errors and create mechanisms to encode and decode strings u...
0.658266
Docs: Python310_21308
C
[ "custom_error_handler", "register_custom_error_handler", "custom_encode", "custom_decode" ]
4
[ [ "register_custom_error_handler", "custom_error_handler" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b7fb2e0635e4e2c76bfb94a60b39d668d054858c
d8e636b2c70c0e19f0b2371fb36004407a775bdd
v1.0
complete
Docs
Docs: Python310_20155_C
import json from typing import List class Person: def __init__(self, name: str, age: int, friends: List['Person'] = None): self.name = name self.age = age self.friends = friends if friends else [] def add_friend(self, friend: 'Person'): if isinstance(friend, Person) and friend ...
import json from json import JSONDecodeError class Person: def __init__(self, name, age, friends=None): self.name = name self.age = age self.friends = friends if friends is not None else [] def add_friend(self, friend): if isinstance(friend, Person) and friend not in se...
import pytest from solution import Person, PersonEncoder, deserialize_persons def test_person_serialization(): alice = Person("Alice", 30) bob = Person("Bob", 25) charlie = Person("Charlie", 20) alice.add_friend(bob) bob.add_friend(charlie) persons = [alice, bob, charlie] # Serial...
[]
[ 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 json\n\nclass Person:\n def __init__(self, name, age, friends=None):\n if isinstance(name, str) and isinstance(age, (int, float)) and (friends is None ...
trial_gpt4o_1
{ "original_instruction": "#### Objective\nYou are required to demonstrate your understanding of Python's `json` library by implementing custom serialization and deserialization. This task involves creating a custom JSON encoder and decoder for a specific Python object and handling edge cases like NaN, Infinity, circ...
0.509697
Docs: Python310_20155
C
[ "person_decoder", "resolve_friends", "deserialize_persons" ]
3
[ [ "deserialize_persons", "resolve_friends" ] ]
1
[]
false
[ "Person", "PersonEncoder" ]
true
pytest
true
[]
true
50c015bb51734f07940e51bc879ae69d4d5603e8
9032a22f17fdaa187d99ef3a376c2c55f43bdf53
v1.0
complete
Docs
Docs: Scikit_21147_C
from sklearn.decomposition import NMF from sklearn.datasets import load_digits import numpy as np def original_nmf(): """ Implement Non-Negative Matrix Factorization (NMF) using the `sklearn.decomposition.NMF` class on the `digits` dataset from `sklearn.datasets`. >>> W, H = original_nmf() >>> W.shape ...
from sklearn.decomposition import NMF from sklearn.datasets import load_digits import numpy as np # Step 1: Load digits dataset X, _ = load_digits(return_X_y=True) # Step 2: Implement and profile the NMF fitting def original_nmf(): model = NMF(n_components=16, tol=1e-2, init='random', random_state=0) W = mode...
from solution import original_nmf, optimized_nmf import numpy as np def test_original_nmf(): W, H = original_nmf() assert W.shape[0] == 1797 # Number of samples in digits dataset assert W.shape[1] == 16 # Number of components assert H.shape[0] == 16 # Number of components assert H.shape[1] =...
[ { "docstring": null, "function_declaration": "def original_nmf():", "function_name": "original_nmf", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def profile_original_nmf():", "function_name": "profile_original_nmf", "parameter_list": "()" }, { ...
[ 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.decomposition import NMF\nfrom sklearn.datasets import load_digits\nimport numpy as np\nimport timeit\n\n# Step 1: Load digits dataset\nX, _ = load_digits(...
trial_gpt4o_1
{ "original_instruction": "### Code Optimization and Profiling with scikit-learn\n\nIn this assessment, you are required to demonstrate your understanding of code optimization using the scikit-learn library. You will be given a simple machine learning task, where you need to implement, profile, and optimize the code....
0.506393
Docs: Scikit_21147
C
[ "original_nmf", "profile_original_nmf", "optimized_nmf", "profile_optimized_nmf" ]
4
[ [ "profile_optimized_nmf", "optimized_nmf" ], [ "profile_original_nmf", "original_nmf" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
480a813fa733b4fa64e545069669565d33cebd5f
e57b0f6ad7eb56015ce0e1cec7dfe58ce477e2b5
v1.0
complete
Docs
Docs: Scikit_20919_C
import pandas as pd from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt def stream_data(file_path: str, batch_size: int): """ Function to stream data in mini-batches from a CSV fi...
import pandas as pd import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt def stream_data(file_path, batch_size): """ Function to stream data in mini-batches from...
import pandas as pd import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt import tempfile import os # Testing the functions and pipeline def test_stream_data(): # Cre...
[ { "docstring": "Function to stream data in mini-batches from a CSV file with columns 'text' and 'label'.", "function_declaration": "def stream_data(file_path, batch_size):", "function_name": "stream_data", "parameter_list": "(file_path, batch_size)" }, { "docstring": "Implements an out-of-co...
[ 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 pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.met...
trial_gpt4o_1
{ "original_instruction": "#### Objective:\nDemonstrate understanding of out-of-core learning in scikit-learn by building an incremental learning pipeline.\n\n#### Problem Statement:\nYou are given a text dataset that is too large to fit into memory at once. Your task is to implement an out-of-core learning pipeline ...
0.622559
Docs: Scikit_20919
C
[ "stream_data", "out_of_core_learning_pipeline" ]
2
[ [ "out_of_core_learning_pipeline", "stream_data" ] ]
1
[]
false
[]
false
pytest
false
[ "matplotlib", "numpy", "pandas", "sklearn" ]
false
020595559120088cf283515b48f355c1e3aa4f0a
d3a2b7d62e92a0e6e8bd236fc5587313bb61adc4
v1.0
complete
Docs
Docs: Pytorch_21370_C
import torch.multiprocessing as mp from typing import List, Any, Dict def compute(proc_id: int) -> Dict[str, Any]: """ Simple computation function that takes an integer proc_id as input and returns a dictionary with the proc_id and the square of proc_id. >>> compute(0) {'proc_id': 0, 'value': 0} ...
import torch.multiprocessing as mp from typing import List, Any, Dict def compute(proc_id: int) -> Dict[str, Any]: result = { "proc_id": proc_id, "value": proc_id * proc_id } return result def run_computation_process(proc_id: int, results: List): results.append(compute(proc_id)) def r...
def test_run_distributed_computation(): from solution import run_distributed_computation def equivalent_to_compute(proc_id): return {"proc_id": proc_id, "value": proc_id * proc_id} num_procs = 4 expected_results = [equivalent_to_compute(i) for i in range(num_procs)] results = run_distribut...
[ { "docstring": null, "function_declaration": "def compute(proc_id):", "function_name": "compute", "parameter_list": "(proc_id)" }, { "docstring": null, "function_declaration": "def run_computation_process(proc_id, results):", "function_name": "run_computation_process", "parameter...
[ 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.multiprocessing as mp\nfrom typing import List, Any, Dict\n\ndef compute(proc_id: int) -> Dict[str, Any]:\n result = {\n \"proc_id\": proc_id,\n ...
trial_gpt4o_0
{ "original_instruction": "**Coding Assessment Question**\n\n### Distributed Multiprocessing with Subprocesses in PyTorch\n\n**Objective**:\nImplement a function that demonstrates the usage of PyTorch's `SubprocessHandler` to manage multiple subprocesses running a simple distributed computation task.\n\n### Problem S...
0.645085
Docs: Pytorch_21370
C
[ "compute", "run_computation_process", "run_distributed_computation" ]
3
[ [ "run_computation_process", "compute" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
b20922259e22ba2b455d1720776b43f8f7f41c92
e9e886174efdd1d1c53d60a0d4b20e5d17fe3115
v1.0
complete
Docs
Docs: Pytorch_20606_C
import torch import torch.distributed.rpc as rpc from torch.distributed.rpc import RRef def add_tensors(t1, t2): """ Add two tensors. >>> t1 = torch.ones((3, 3)) >>> t2 = torch.full((3, 3), 2) >>> add_tensors(t1, t2) tensor([[3., 3., 3.], [3., 3., 3.], [3., 3., 3.]]) """...
import torch import torch.distributed.rpc as rpc from torch.distributed.rpc import RRef def add_tensors(t1, t2): return t1 + t2 def multiply_tensors(t1, t2): return t1 * t2 def worker_a_task(): # Create an RRef to a tensor of ones on worker_A rref = RRef(torch.ones((3, 3))) return rref def worke...
import torch import torch.distributed.rpc as rpc from solution import add_tensors, multiply_tensors, worker_a_task, worker_b_task, worker_c_task def test_add_tensors(): t1 = torch.ones((3, 3)) t2 = torch.full((3, 3), 2) result = add_tensors(t1, t2) expected = torch.full((3, 3), 3) assert torch.equa...
[ { "docstring": null, "function_declaration": "def add_tensors(t1, t2):", "function_name": "add_tensors", "parameter_list": "(t1, t2)" }, { "docstring": null, "function_declaration": "def multiply_tensors(t1, t2):", "function_name": "multiply_tensors", "parameter_list": "(t1, t2)"...
[ 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 torch\nimport torch.distributed.rpc as rpc\nfrom torch.distributed.rpc import RRef\n\ndef add_tensors(rref, tensor):\n return rref.to_here() + tensor\n\ndef m...
trial_gpt4o_2
{ "original_instruction": "**Question:**\n\n**Implement and Manage Remote References (RRefs) using PyTorch Distributed RPC**\n\n### Objective:\nDemonstrate your understanding of Remote References (RRefs) by implementing, sharing, and managing RRef instances in a distributed PyTorch environment.\n\n### Problem Stateme...
0.468984
Docs: Pytorch_20606
C
[ "add_tensors", "multiply_tensors", "worker_a_task", "worker_b_task", "worker_c_task", "run_worker" ]
6
[ [ "run_worker", "worker_a_task" ], [ "run_worker", "worker_b_task" ], [ "run_worker", "worker_c_task" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
6a56fd3093cfb093703ac283108fb3ee3153d3d2
7839a0f193a61da910df334c47291cb1eb5d0deb
v1.0
complete
Docs
Docs: Python310_21372_C
import cProfile import pstats from io import StringIO # Dummy process_data function provided for testing purposes def process_data(data: list) -> list: def helper_func(item): time.sleep(random.uniform(0.001, 0.003)) return item ** 2 result = [] for item in data: result.append(helpe...
import cProfile import pstats from io import StringIO import os import time import random # Dummy process_data function provided for testing purposes def process_data(data: list) -> list: def helper_func(item): time.sleep(random.uniform(0.001, 0.003)) return item ** 2 result = [] for item ...
import os from solution import profile_process_data, analyze_profile_results def test_profile_process_data(): data = [i for i in range(100)] profile_filename = profile_process_data(data) assert os.path.isfile(profile_filename) == True def test_analyze_profile_results(): data = [i for i in range(100)] ...
[ { "docstring": null, "function_declaration": "def process_data(data):", "function_name": "process_data", "parameter_list": "(data)" }, { "docstring": "Profile the process_data function using cProfile.\n\nParameters:\ndata (list): The input data to be processed.\n\nReturns:\nstr: The name of ...
[ 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 io\n\ndef profile_process_data(data: list) -> str:\n \"\"\"\n Profiles the process_data function, stores the profiling resu...
trial_gpt4o_1
{ "original_instruction": "**Coding Question: Profiling and Analyzing a Python Function**\n\n### Objective\nThe goal of this exercise is to assess your understanding of Python's profiling tools (\"cProfile\", \"pstats\") and your ability to analyze the performance of a given function.\n\n### Description\nYou are give...
0.545263
Docs: Python310_21372
C
[ "process_data", "profile_process_data", "analyze_profile_results" ]
3
[ [ "profile_process_data", "process_data" ] ]
1
[ "process_data" ]
false
[]
false
pytest
true
[]
true
ccb2bdbec1a69a8a28096a003e1b3f13a4c43fe6
6368c209c7a92312b8bbb70e8a6b5b851c3a9cdb
v1.0
complete
Docs
Docs: Python310_21417_C
import hashlib from typing import List def hash_password(password: str, salt: str) -> str: """ Hashes the given password concatenated with the salt using SHA-256. Args: password (str): The plain-text password. salt (str): The salt string. Returns: str: The hexadecimal ...
import hashlib def hash_password(password: str, salt: str) -> str: """ Hashes the given password concatenated with the salt using SHA-256. Args: password (str): The plain-text password. salt (str): The salt string. Returns: str: The hexadecimal digest of the hashed pas...
from solution import hash_password, validate_password def test_hash_password(): assert hash_password("SuperSecurePassword123!", "16CharSaltString") == hashlib.sha256(("SuperSecurePassword123!" + "16CharSaltString").encode()).hexdigest() def test_hash_password_invalid_salt(): try: hash_password("SuperS...
[ { "docstring": "Hashes the given password concatenated with the salt using SHA-256.\n\nArgs:\n password (str): The plain-text password.\n salt (str): The salt string.\n\nReturns:\n str: The hexadecimal digest of the hashed password concatenated with the salt.", "function_declaration": "def hash_pas...
[ 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 hashlib\n\ndef hash_password(password: str, salt: str) -> str:\n \"\"\"\n Hashes a password with a given salt using SHA-256 and returns the hex digest stri...
trial_gpt4o_2
{ "original_instruction": "### Password Hashing and Validation\n\n**Objective**: Implement a secure password hashing and validation system using the `hashlib` module in Python.\n\n### Problem Statement\n\nYou are required to develop two functions `hash_password` and `validate_password` that utilizes the `hashlib` mod...
0.734455
Docs: Python310_21417
C
[ "hash_password", "validate_password" ]
2
[ [ "validate_password", "hash_password" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6e0dfd434d4da913e526cf56077a2752f14b35a3
7f774f0f304c2e99482479342f569bc0f64c2a27
v1.0
complete
Docs
Docs: Python310_21510_C
import asyncio async def fetch_and_process(urls: list, processing_func) -> list: """ Fetches data asynchronously from a list of URLs and processes it using a provided function. Args: urls: A list of strings, where each string is a URL to fetch data from. processing_func: An asynchronous functi...
import asyncio async def fetch(url): """ Simulates fetching data from a URL by sleeping for a random time between 1 and 5 seconds. """ await asyncio.sleep(1) return url async def fetch_and_process(urls: list, processing_func) -> list: """ Fetches data asynchronously from a list of URLs and...
import asyncio from solution import fetch_and_process async def mock_processing_func(data): await asyncio.sleep(1) return f"processed_{data}" def test_fetch_and_process(): urls = ["url1", "url2", "url3"] processed_data = asyncio.run(fetch_and_process(urls, mock_processing_func)) assert processed_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 asyncio\n\nasync def fetch(url):\n \"\"\"\n Simulates fetching data from a URL. \n The simulated fetch will just wait for a random period between 1 and ...
trial_gpt4o_1
{ "original_instruction": "#### Objective\nImplement a function using the asyncio library that fetches data from multiple dummy URLs concurrently, processes the fetched data, and combines the results into a single output.\n\n#### Function Signature\n```python\nimport asyncio\n\nasync def fetch_and_process(urls: list,...
0.642105
Docs: Python310_21510
C
[ "fetch", "fetch_and_process" ]
2
[ [ "fetch_and_process", "fetch" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f0658477cb4f0ca66040fb32bf013122026cac93
dea7826052aacb01b8daa038342222190f8e30d6
v1.0
complete
Docs
Docs: Python310_21156_C
from typing import List, Dict class FileStatistics: def __init__(self): self.total_words = 0 self.unique_words = set() def process_file(self, file_content: str): words = file_content.split() self.total_words += len(words) self.unique_words.update(words) def...
import os from typing import List, Dict import asyncio import time from collections import defaultdict class FileStatistics: def __init__(self): self.total_words = 0 self.unique_words = set() def process_file(self, file_content: str): words = file_content.split() self.total...
from solution import read_and_process_files, async_read_and_process, write_statistics_to_file, FileStatistics import asyncio def create_test_file(filename, content): with open(filename, 'w', encoding='utf-8') as file: file.write(content) def test_read_and_process_files(): content1 = "Hello world" ...
[]
[ 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\nfrom typing import List, Dict\nimport asyncio\nimport time\nfrom collections import defaultdict\n\nclass FileStatistics:\n def __init__(self):\n se...
trial_gpt4o_0
{ "original_instruction": "### Advanced Python Programming Assessment\n\n**Objective:**\n\nImplement a file processing utility in Python that demonstrates your understanding of various compound statements, exception handling, context management, function definitions, class designs, and asynchronous programming.\n\n**...
0.630293
Docs: Python310_21156
C
[ "read_and_process_files", "async_read_and_process", "read_file", "write_statistics_to_file" ]
4
[ [ "async_read_and_process", "read_file" ] ]
1
[]
false
[ "FileStatistics" ]
true
pytest
true
[]
true
b2c3f33b920f3c23d124b1ba77f796b0d2d14932
353a277da163d44a2c95f115823950ff2de13ad1
v1.0
complete
Docs
Docs: Python310_21632_C
import urllib.request def check_urls(urls: list, interval: int) -> None: """ Periodically checks each URL and prints the status code. If a URL returns a status code other than 200, print an alert message. Args: urls (list): List of URLs to check. interval (int): Interval in seconds be...
import urllib.request import time import logging logging.basicConfig(level=logging.INFO) def check_url(url): try: response = urllib.request.urlopen(url) status_code = response.getcode() if status_code != 200: logging.warning(f"ALERT: {url} is down! Status: {status_code}") ...
from unittest.mock import patch, Mock from solution import check_url def test_check_url_200(): with patch('urllib.request.urlopen', return_value = Mock(getcode = lambda: 200)): check_url("http://www.example.com") def test_check_url_404(): with patch('urllib.request.urlopen', return_value = Mock(getcod...
[ { "docstring": null, "function_declaration": "def check_url(url):", "function_name": "check_url", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def check_urls(urls, interval):", "function_name": "check_urls", "parameter_list": "(urls, interval)" } ]
[ 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 urllib.request\nimport time\n\ndef check_urls(urls: list, interval: int) -> None:\n \"\"\"\n Periodically checks the status of multiple URLs and alerts whe...
trial_gpt4o_1
{ "original_instruction": "You are tasked with creating a Python script that periodically checks the status of multiple URLs and alerts when any of the URLs become inaccessible (i.e., return a status code other than 200).\n\n**Requirements**:\n1. Your solution should use the `urllib.request` module.\n2. Implement a f...
0.722617
Docs: Python310_21632
C
[ "check_url", "check_urls" ]
2
[ [ "check_urls", "check_url" ] ]
1
[]
false
[]
false
pytest
true
[]
true
167797916ca961089ce8bbfe23c4779e8a077ad9
a10ef29aa5c56822f5627dc976688f60d03e6bcd
v1.0
complete
Docs
Docs: Python310_21043_C
from fractions import Fraction from typing import List, Dict, Any, Union def manipulate_fractions(operations: List[Dict[str, Any]]) -> List[Union[str, int, float]]: """ Perform various operations on fractions based on the input list of operations. Args: operations (list of dict): A list of dictionarie...
from fractions import Fraction def parse_fraction(fraction): if isinstance(fraction, str): return Fraction(fraction) elif isinstance(fraction, list) and len(fraction) == 2: return Fraction(fraction[0], fraction[1]) return Fraction(fraction) # handle any other input cases as appropriate de...
from solution import manipulate_fractions def test_create_fractions(): operations = [{'operation': 'create', 'args': [3, 4]}, {'operation': 'create', 'args': "2/3"}] expected = ["3/4", "2/3"] assert manipulate_fractions(operations) == expected def test_add_fractions(): operations = [...
[ { "docstring": null, "function_declaration": "def parse_fraction(fraction):", "function_name": "parse_fraction", "parameter_list": "(fraction)" }, { "docstring": null, "function_declaration": "def manipulate_fractions(operations):", "function_name": "manipulate_fractions", "param...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from fractions import Fraction\n\ndef manipulate_fractions(operations):\n results = []\n \n for op in operations:\n operation = op['operation']\n ...
trial_gpt4o_2
{ "original_instruction": "**Objective:**\nImplement a function to perform various operations using the `fractions` module in Python. This task will assess your ability to create and manipulate `Fraction` instances, utilize arithmetic operations, and apply methods like `limit_denominator` and rounding.\n\n**Instructi...
0.671627
Docs: Python310_21043
C
[ "parse_fraction", "manipulate_fractions" ]
2
[ [ "manipulate_fractions", "parse_fraction" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7142a5cb6f0263bf8336d382347a3255b50b5026
e44c314440078afc9fbc2bf5a5817e2ea4926eb6
v1.0
complete
Docs
Docs: Python310_21465_C
import optparse import os TASK_FILE = 'tasks.txt' def load_tasks(): """Load tasks from the tasks file.""" if not os.path.exists(TASK_FILE): return [] with open(TASK_FILE, 'r') as file: tasks = file.readlines() return [task.strip() for task in tasks] def save_tasks(tasks): """Save ...
import os import optparse TASK_FILE = 'tasks.txt' def load_tasks(): """Load tasks from the tasks file.""" if not os.path.exists(TASK_FILE): return [] with open(TASK_FILE, 'r') as file: tasks = file.readlines() return [task.strip() for task in tasks] def save_tasks(tasks): """Save ...
import os import pytest import shutil from solution import add_task, list_tasks, delete_task, TASK_FILE @pytest.fixture def setup_tasks_file(): """Prepare a clean tasks.txt file before each test.""" if os.path.exists(TASK_FILE): shutil.copyfile(TASK_FILE, TASK_FILE + '.bak') yield if os.path.ex...
[ { "docstring": "Load tasks from the tasks file.", "function_declaration": "def load_tasks():", "function_name": "load_tasks", "parameter_list": "()" }, { "docstring": "Save tasks to the tasks file.", "function_declaration": "def save_tasks(tasks):", "function_name": "save_tasks", ...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nfrom optparse import OptionParser\n\nTASKS_FILE = 'tasks.txt'\n\ndef save_tasks(tasks):\n with open(TASKS_FILE, 'w') as file:\n for task in tasks:\...
trial_gpt4o_3
{ "original_instruction": "#### Task\n\nYou are required to implement a command-line utility using the deprecated `optparse` module in Python. The utility will be a simplified version of a task manager that allows users to add, list, and delete tasks. You must demonstrate your understanding of the `optparse` module b...
0.49962
Docs: Python310_21465
C
[ "load_tasks", "save_tasks", "add_task", "list_tasks", "delete_task", "main" ]
6
[ [ "add_task", "load_tasks" ], [ "add_task", "save_tasks" ], [ "delete_task", "load_tasks" ], [ "delete_task", "save_tasks" ], [ "list_tasks", "load_tasks" ] ]
5
[]
false
[]
false
pytest
true
[]
true
0fce475514f0427dcd1b689d443ade8ec5f63068
30da062204a0c4f459aaa00b156bc87b9941e976
v1.0
complete
Docs
Docs: Python310_21475_C
[Completion Task in Python] import os def copy_file_with_metadata(src: str, dst: str): """ Copy file from src to dst, preserving metadata """ pass def sync_directories(src_dir: str, dst_dir: str) -> None: """Synchronize the contents of the source directory to the destination directory. Parameter...
import os import shutil def copy_file_with_metadata(src: str, dst: str): shutil.copy2(src, dst) def sync_directories(src_dir: str, dst_dir: str) -> None: if not os.path.exists(dst_dir): os.makedirs(dst_dir) for root, dirs, files in os.walk(src_dir): relative_path = os.path.relpath(root, s...
import os import pytest import shutil from solution import sync_directories def setup_test_environment(src_content, dst_content): src_dir = 'test_src_dir' dst_dir = 'test_dst_dir' if os.path.exists(src_dir): shutil.rmtree(src_dir) if os.path.exists(dst_dir): shutil.rmtree(dst_dir) ...
[ { "docstring": null, "function_declaration": "def copy_file_with_metadata(src, dst):", "function_name": "copy_file_with_metadata", "parameter_list": "(src, dst)" }, { "docstring": null, "function_declaration": "def sync_directories(src_dir, dst_dir):", "function_name": "sync_director...
[ 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 os\nimport shutil\nfrom filecmp import dircmp\n\ndef sync_directories(src_dir: str, dst_dir: str) -> None:\n \"\"\"\n Recursively synchronizes the contents...
trial_gpt4o_1
{ "original_instruction": "**File Synchronizer Application**\n\n### Problem Statement\nYou are required to implement a Python function `sync_directories(src_dir: str, dst_dir: str) -> None` using the `os` module. The function should synchronize the contents of the source directory (`src_dir`) to the destination direc...
0.711474
Docs: Python310_21475
C
[ "copy_file_with_metadata", "sync_directories" ]
2
[ [ "sync_directories", "copy_file_with_metadata" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a346f21dbb8d0fbc7703d7d120fef06a723058aa
63aadfc5f6b38199bc5620452c760a8703ffef36