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_43121_C
class Cell: """Implement a class to mimic the behavior of Python's cell objects. Methods: - __init__(self, obj): Initializes the cell with an initial value. - get(self): Returns the current value stored in the cell. - set(self, obj): Sets the cell's value to `obj`. >>> cell = Cell(5) ...
class Cell: def __init__(self, obj): """ Initializes the cell with the given object. """ self._obj = obj def get(self): """ Returns the current value stored in the cell. """ return self._obj def set(self, obj): """ Sets the ce...
from solution import Cell, make_closure def test_cell_initialization(): cell = Cell(5) assert cell.get() == 5 def test_cell_set_and_get(): cell = Cell(5) cell.set(10) assert cell.get() == 10 def test_closure_incrementor(): cell = Cell(10) def incrementor(cell): current_val = ...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Cell:\n def __init__(self, obj=None):\n self._obj = obj\n\n def get(self):\n return self._obj\n\n def set(self, obj):\n self._obj = ...
trial_gpt4o_9
{ "original_instruction": "### Python Coding Assessment Question\n\n#### Objective\nImplement a class and methods to simulate basic behaviors of Python's cell objects. This will test your understanding of variable scoping, references, and closures.\n\n#### Task\nCreate a Python class `Cell` which mimics the behavior ...
0.549563
Docs: Python310_43121
C
[ "make_closure", "test_closure" ]
2
[ [ "test_closure", "make_closure" ] ]
1
[]
false
[ "Cell" ]
true
pytest
true
[]
true
7a0abbccca253a9c18715c7f577a2612f5918a0c
d7905d3832444856825e06812b14f06d16a95f49
v1.0
complete
Docs
Docs: Python310_42829_C
import zlib from typing import List def compress_data(data: bytes, level: int = -1) -> bytes: """ Compress the input bytes data using zlib with the specified compression level. :param data: Input data in bytes to be compressed. :param level: Compression level, with -1 being the default. :return: Co...
import zlib def compress_data(data: bytes, level: int = -1) -> bytes: """ Compress the input bytes data using zlib with the specified compression level. :param data: Input data in bytes to be compressed. :param level: Compression level, with -1 being the default. :return: Compressed data in bytes. ...
import pytest from solution import compress_data, decompress_data, checksum_verification def test_compress_decompress(): original = b'This is a test string for compression and decompression.' compressed = compress_data(original, level=6) decompressed = decompress_data(compressed) assert decompress...
[ { "docstring": "Compress the input bytes data using zlib with the specified compression level.\n:param data: Input data in bytes to be compressed.\n:param level: Compression level, with -1 being the default.\n:return: Compressed data in bytes.", "function_declaration": "def compress_data(data, level=-1):", ...
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import zlib\n\ndef compress_data(data: bytes, level: int = -1) -> bytes:\n \"\"\"\n Compress the given data using zlib with the specified compression level.\n ...
trial_gpt4o_8
{ "original_instruction": "**Objective**: Implement a pair of functions that demonstrate the compression and decompression of data using Python's `zlib` library, along with checksum verification to ensure data integrity.\n\n#### Problem Statement\n\nImplement the following functions:\n\n1. `compress_data(data: bytes,...
0.636653
Docs: Python310_42829
C
[ "compress_data", "decompress_data", "checksum_verification" ]
3
[ [ "checksum_verification", "decompress_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6826fea7deadd0929857b4fefc881375bde372f0
b5b132925614565e9b4d79a10d6e4f8992fbbde3
v1.0
complete
Docs
Docs: Pytorch_43090_C
import torch # Define the functions def affected_fn(x): return x + 1 # Apply torch.compiler.disable on a_fn @torch.compile_disable def a_fn(x): """ Problematic function that needs to be bypassed during tracing. """ return affected_fn(x) + 2 def b_fn(x): """ Normal function that should be traced. """ ...
import torch # Placeholder function to simulate the effect of torch.compiler.disable (actual tracing) def torch_compile_disable(func): def wrapper(*args, **kwargs): # Directly call the function without any tracing return func(*args, **kwargs) return wrapper # Define the functions as described ...
import torch from solution import fn, compiled_fn def test_fn(): x = torch.tensor(5) result = compiled_fn(x) expected = (5 + 1 + 2) + (5 * 3) # Equivalent to a_fn(5) + b_fn(5) assert result.item() == expected def test_a_fn_disabled(): x = torch.tensor(5) result_a = a_fn(x) assert result_a...
[ { "docstring": null, "function_declaration": "def torch_compile_disable(func):", "function_name": "torch_compile_disable", "parameter_list": "(func)" }, { "docstring": null, "function_declaration": "def affected_fn(x):", "function_name": "affected_fn", "parameter_list": "(x)" }...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torchdynamo\n\ndef aa_fn(x):\n return x + 1\n\n# Apply torchdynamo.disable on a_fn\n@torchdynamo.disable\ndef a_fn(x):\n return aa_fn(x) + 2\...
trial_gpt4o_6
{ "original_instruction": "Fine-Grained Control of TorchDynamo Tracing\n\n**Objective**: Implement a portion of a PyTorch model using the TorchDynamo fine-grained tracing control APIs to manage parts of the model that may not be compatible with default tracing behavior.\n\n#### Background\nYou are provided with a sim...
0.459425
Docs: Pytorch_43090
C
[ "torch_compile_disable", "affected_fn", "a_fn", "b_fn", "fn", "mock_compile" ]
6
[ [ "a_fn", "affected_fn" ], [ "fn", "a_fn" ], [ "fn", "b_fn" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
ffb0ccdbbff2bb29b2a9f59d3449a75ac0e998c2
a5087896a91ab67d76f576adb53b7adadf001d7c
v1.0
complete
Docs
Docs: Python310_42833_C
import asyncio from typing import Tuple async def handle_client_request(reader: asyncio.StreamReader, writer: asyncio.StreamWriter, delay: int): """Handles client request by introducing a simulated processing delay. Args: reader (asyncio.StreamReader): The reader stream for the client. wri...
import asyncio from asyncio import StreamReader, StreamWriter from typing import Tuple async def handle_client_request(reader: StreamReader, writer: StreamWriter, delay: int): """Handles client request by introducing a simulated processing delay. Args: reader (StreamReader): The reader stream for ...
import asyncio import pytest from solution import start_server, simulate_client_request @pytest.mark.asyncio async def test_server_response(): server_task = asyncio.create_task(start_server('127.0.0.1', 8888, 1)) await asyncio.sleep(1) response = await simulate_client_request('127.0.0.1', 8888, 'Hello...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom asyncio import StreamReader, StreamWriter\nfrom typing import Tuple\n\nasync def handle_client_request(reader: StreamReader, writer: StreamWriter, ...
trial_gpt4o_0
{ "original_instruction": "**Complex Event-Driven Application using Asyncio**\n\n### Problem Statement\n\nYou are required to design and implement a simplified event-driven application using Python's `asyncio` module.\n\nThis application simulates a basic server-client model where multiple clients send requests to th...
0.621147
Docs: Python310_42833
C
[ "handle_client_request", "start_server", "simulate_client_request" ]
3
[ [ "start_server", "handle_client_request" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d1d166a111ff8bd835be3051b21b5439f1debb8c
9ef533f618be0f65da1c23ced1332954e98ccf7e
v1.0
complete
Docs
Docs: Python310_42058_C
import hmac import hashlib import secrets def generate_salt() -> str: """ Generates a random 16-byte hexadecimal salt. Returns: str: A random 16-byte hexadecimal string. """ pass def hash_password(password: str, salt: str, key: str) -> str: """ Generates a HMAC hash of the giv...
import hmac import hashlib import secrets def generate_salt(): """ Generates a random 16-byte hexadecimal salt. Returns: str: A random 16-byte hexadecimal string. """ return secrets.token_hex(16) def hash_password(password, salt, key): """ Generates a HMAC hash of the given pa...
from solution import generate_salt, hash_password, verify_password def test_generate_salt_length(): salt = generate_salt() assert len(salt) == 32 # 16 bytes * 2 (hex representation) def test_generate_salt_uniqueness(): salt1 = generate_salt() salt2 = generate_salt() assert salt1 != salt2 # Salts...
[ { "docstring": "Generates a random 16-byte hexadecimal salt.\n\nReturns:\n str: A random 16-byte hexadecimal string.", "function_declaration": "def generate_salt():", "function_name": "generate_salt", "parameter_list": "()" }, { "docstring": "Generates a HMAC hash of the given password us...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import secrets\nimport hmac\nimport hashlib\n\ndef generate_salt():\n \"\"\"\n Generates a random 16-byte hexadecimal string.\n \"\"\"\n return secrets.toke...
trial_gpt4o_9
{ "original_instruction": "#### Objective:\nTo assess your understanding of Python's cryptographic services, specifically the `hashlib` and `hmac` modules, you will implement a secure password storage and verification system. This system should include functionality for hashing passwords using HMAC (Keyed-Hash Messag...
0.775626
Docs: Python310_42058
C
[ "generate_salt", "hash_password", "verify_password" ]
3
[ [ "verify_password", "hash_password" ] ]
1
[]
false
[]
false
pytest
true
[]
true
93355dd751e5d28f98fe9da3ce411e3642b4570e
874b210030119425d9ec5e713b3d78ae180a27f5
v1.0
complete
Docs
Docs: Pytorch_42967_C
import torch from torch.func import grad, vmap def sum_of_squares(x: torch.Tensor) -> torch.Tensor: """ Computes the sum of squares of all elements in the tensor `x`. Args: x (torch.Tensor): Input tensor. Returns: torch.Tensor: Sum of squares of the input tensor. """ pass def gradien...
import torch from torch.func import grad, vmap def sum_of_squares(x: torch.Tensor) -> torch.Tensor: """ Computes the sum of squares of all elements in the tensor `x`. """ return torch.sum(x ** 2) def gradient_of_sum_of_squares(x: torch.Tensor) -> torch.Tensor: """ Calculates the gradient of th...
import pytest import torch from solution import sum_of_squares, gradient_of_sum_of_squares, vectorized_sum_of_squares, modified_sum_of_squares def test_sum_of_squares(): x = torch.tensor([1.0, 2.0, 3.0]) assert sum_of_squares(x).item() == 14.0 def test_gradient_of_sum_of_squares(): x = torch.tensor([1.0, ...
[ { "docstring": "Computes the sum of squares of all elements in the tensor `x`.", "function_declaration": "def sum_of_squares(x):", "function_name": "sum_of_squares", "parameter_list": "(x)" }, { "docstring": "Calculates the gradient of the sum_of_squares function.", "function_declaration...
[ 1, 0, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.func import grad, vmap\n\ndef sum_of_squares(x: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Computes the sum of the squares of all elements...
trial_gpt4o_6
{ "original_instruction": "**Coding Challenge: Pure Functions and Transformations with PyTorch**\n\n**Objective:**\nDemonstrate your understanding of transformations in `torch.func` by implementing a pure function and applying various `torch.func` transformations while complying with described constraints.\n\n**Probl...
0.582845
Docs: Pytorch_42967
C
[ "sum_of_squares", "gradient_of_sum_of_squares", "vectorized_sum_of_squares", "modified_sum_of_squares" ]
4
[ [ "gradient_of_sum_of_squares", "sum_of_squares" ], [ "vectorized_sum_of_squares", "sum_of_squares" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
90883262965cbb087db4de9a414ac3ccca8f16d3
a514957e797dc82f6eb4353925c532f34dd1d0c5
v1.0
complete
Docs
Docs: Python310_43262_C
from typing import List def validate_email_headers(headers: List[str]) -> List[str]: """ Parse and validate email headers according to RFC 5322 standards. Ensure various error conditions are handled using the appropriate exception classes from the email.errors module. >>> validate_email_headers([ "...
import re from email.errors import HeaderParseError, FirstHeaderLineIsContinuationDefect, MalformedHeaderDefect, InvalidDateDefect from typing import List def validate_email_headers(headers: List[str]) -> List[str]: errors = [] # Define a basic regex for header parsing header_pattern = re.compile(r'^[...
from solution import validate_email_headers def test_validate_email_headers_no_errors(): headers = [ "From: example@example.com", "To: user@example.com", "Date: Fri, 21 Nov 1997 09:55:06 -0600", "Subject: Test email" ] assert validate_email_headers(headers) == [] def test_v...
[ { "docstring": null, "function_declaration": "def validate_email_headers(headers):", "function_name": "validate_email_headers", "parameter_list": "(headers)" }, { "docstring": null, "function_declaration": "def validate_date(date_str):", "function_name": "validate_date", "paramet...
[ 0, 0, 1, 0, 0, 0, 1, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nfrom email.errors import HeaderParseError, FirstHeaderLineIsContinuationDefect, MalformedHeaderDefect, InvalidDateDefect\nfrom typing import List\n\ndef vali...
trial_gpt4o_7
{ "original_instruction": "You are tasked with implementing a function to parse and validate email headers according to RFC 5322 standards. The function will need to handle various error conditions using the appropriate exception classes from the `email.errors` module. \n\n#### Function Signature\n```python\ndef vali...
0.62864
Docs: Python310_43262
C
[ "validate_email_headers", "validate_date" ]
2
[ [ "validate_email_headers", "validate_date" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dd17871967b0518d14c19ae0089cb09ba80fef0b
abc7cf704775b21adb8f59807be4301fb81ae16a
v1.0
complete
Docs
Docs: Python310_42727_C
import asyncio from asyncio import Queue, PriorityQueue, LifoQueue from typing import List, Coroutine, Any class Task: def __init__(self, priority, coro): self.priority = priority self.coro = coro def __lt__(self, other): return self.priority < other.priority async def worker(queue, r...
import asyncio from asyncio import Queue, PriorityQueue, LifoQueue from typing import List, Coroutine, Any class Task: def __init__(self, priority, coro): self.priority = priority self.coro = coro def __lt__(self, other): return self.priority < other.priority async def worker(queue, r...
import asyncio import pytest from solution import schedule_tasks async def sample_task(duration: int, result: str) -> str: await asyncio.sleep(duration) return result def create_tasks(): return [ sample_task(3, "Task1"), sample_task(2, "Task2"), sample_task(1, "Task3") ] @pyte...
[]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Coroutine, Any\nfrom asyncio import Queue, PriorityQueue, LifoQueue\n\nasync def worker(queue: Queue, results: List[Any], timeo...
trial_gpt4o_4
{ "original_instruction": "**Question: Implementing an Asynchronous Task Scheduler**\n\nYou are requested to implement an asynchronous task scheduler using Python's asyncio module. The task scheduler should be able to perform the following:\n\n1. **Run multiple asynchronous tasks concurrently.**\n2. **Distribute task...
0.635197
Docs: Python310_42727
C
[ "worker", "schedule_tasks" ]
2
[ [ "schedule_tasks", "worker" ] ]
1
[]
false
[ "Task" ]
true
pytest
true
[]
true
2ddbd3821bbe41cacaa821d026b0190dcfa9bc06
d204144c7db4e2541e11eec2f2aedc88775aca14
v1.0
complete
Docs
Docs: Python310_43226_C
import asyncio from typing import List async def fetch_data(source: str) -> str: """ Fetch data from a source with simulated delay. Simulate a delay in data retrieval using `await asyncio.sleep(delay)`, where `delay` depends on the source. Return a string indicating the data retrieved from the source, ...
import asyncio from typing import List async def fetch_data(source: str) -> str: delay = len(source) * 0.1 # Example delay: 0.1 seconds per character in source await asyncio.sleep(delay) return f"Data from {source}" async def aggregate_data(sources: List[str]) -> List[str]: tasks = [fetch_data(source...
import asyncio import pytest from solution import fetch_data, aggregate_data @pytest.mark.asyncio async def test_fetch_data(): result = await fetch_data("source1") assert result == "Data from source1" @pytest.mark.asyncio async def test_aggregate_data(): sources = ["source1", "source2", "source3"] res...
[]
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List\n\nasync def fetch_data(source: str) -> str:\n delay = len(source) * 0.1 # Example delay: 0.1 seconds per character in sourc...
trial_gpt4o_0
{ "original_instruction": "### Python 310 Coding Assessment Question\n\n#### Objective:\nTo assess your understanding of asynchronous programming in Python using coroutines.\n\n#### Problem Statement:\nYou are tasked with implementing a Python module that utilizes coroutines to process data concurrently. In this exer...
0.550163
Docs: Python310_43226
C
[ "fetch_data", "aggregate_data" ]
2
[ [ "aggregate_data", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
edcb8975f0febf7598c8e166a39f599853757e03
0bb719ec72d0b93ce27c45ba16bbe3bdc74aa120
v1.0
complete
Docs
Docs: Python310_42818_C
import os from typing import List def custom_compile_dir(directory: str, recursive: bool=True, force: bool=False, optimization_level: int=0, workers: int=1, excluded_patterns: List[str]=None) -> bool: """ Recursively compile all `.py` files in the given directory into `.pyc` files. Args: directory (st...
import os import re import py_compile from multiprocessing import Pool def _compile_file(file, force, optimization_level): try: py_compile.compile(file, cfile=None, dfile=None, doraise=not force, optimize=optimization_level) return True except py_compile.PyCompileError: return False de...
import os import tempfile import shutil import pytest from solution import custom_compile_dir @pytest.fixture def setup_test_environment(): base_dir = tempfile.mkdtemp() sub_dir = os.path.join(base_dir, "sub") os.makedirs(sub_dir) # Create some .py files py_files = [ os.path.join(base_...
[ { "docstring": null, "function_declaration": "def _compile_file(file, force, optimization_level):", "function_name": "_compile_file", "parameter_list": "(file, force, optimization_level)" }, { "docstring": null, "function_declaration": "def _should_exclude(file, excluded_patterns):", ...
[ 0, 0, 0, 1, 0, 0, 0, 1, 0 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport re\nimport py_compile\nfrom pathlib import Path\nfrom multiprocessing import Pool\n\ndef should_exclude(file_path, patterns):\n if patterns is None...
trial_gpt4o_8
{ "original_instruction": "### Python Coding Assessment: Custom Byte-Compilation Function\n\nThe `compileall` module in Python provides various utility functions to compile Python source files into bytecode. This task will assess your understanding of Python file handling, recursion, and multiprocessing by asking you...
0.556811
Docs: Python310_42818
C
[ "_compile_file", "_should_exclude", "custom_compile_dir" ]
3
[ [ "custom_compile_dir", "_compile_file" ], [ "custom_compile_dir", "_should_exclude" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ee15d06a963b4f7da2385bb328d3d0bf0340a4bc
848a16d17ae3103859e2a28e721ca90f618975a2
v1.0
complete
Docs
Docs: Python310_43405_C
from typing import Dict, List from collections import defaultdict, Counter from concurrent.futures import ThreadPoolExecutor def count_words_in_file(file_path: str) -> Dict[str, int]: """ This function accepts a file path as input, reads the file, and returns a dictionary with words as keys and their counts as val...
import re from collections import defaultdict, Counter from concurrent.futures import ThreadPoolExecutor from typing import Dict, List def count_words_in_file(file_path: str) -> Dict[str, int]: word_count = defaultdict(int) try: with open(file_path, 'r') as file: for line in file: ...
import pytest from solution import count_words_in_file, aggregate_word_counts def test_count_words_in_file(tmp_path): text = "Hello world! Hello Python." file_path = tmp_path / "file1.txt" with open(file_path, "w") as f: f.write(text) expected = {'hello': 2, 'world': 1, 'python': 1} assert ...
[ { "docstring": null, "function_declaration": "def count_words_in_file(file_path):", "function_name": "count_words_in_file", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def aggregate_word_counts(file_paths):", "function_name": "aggregate_word_count...
[ 1, 1, 0, 1, 1, 0, 1, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import re\nfrom collections import defaultdict\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Dict, List\n\ndef count_words_in_file(file_path: s...
trial_gpt4o_4
{ "original_instruction": "#### Objective\nDesign a concurrent system that processes text files in parallel and aggregates word counts across multiple files.\n\n#### Task\nYou will implement two functions: `count_words_in_file` and `aggregate_word_counts`.\n\n1. **`count_words_in_file(file_path: str) -> Dict[str, int...
0.755735
Docs: Python310_43405
C
[ "count_words_in_file", "aggregate_word_counts" ]
2
[ [ "aggregate_word_counts", "count_words_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b561537c71762d91a67a0b36c64c1c8af38d9eae
b61931a70a85d2b6e66a0cfe2f12bb69c40b5acd
v1.0
complete
Docs
Docs: Python310_43260_C
import cgi import cgitb cgitb.enable() def generate_html_response(username, age, hobbies, error_message=None): """ Generate an HTML response. :param username: str, the username provided by the user :param age: int, the age provided by the user :param hobbies: list of str, the hobbies selected by ...
import cgi import cgitb cgitb.enable() def generate_html_response(username, age, hobbies, error_message=None): print("Content-Type: text/html\n") print("<html>") print("<head><title>Form Response</title></head>") print("<body>") if error_message: print(f"<h1>Error</h1><p>{error_messag...
import pytest from solution import process_form, generate_html_response from io import StringIO import sys def test_process_form_valid_data(monkeypatch): form_data = "username=JaneDoe&age=25&hobbies=Reading&hobbies=Swimming" monkeypatch.setattr(sys, "stdin", StringIO(form_data)) def dummy_print(*args, **k...
[ { "docstring": null, "function_declaration": "def generate_html_response(username, age, hobbies, error_message=None):", "function_name": "generate_html_response", "parameter_list": "(username, age, hobbies, error_message=None)" }, { "docstring": null, "function_declaration": "def process...
[ 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import cgi\nimport cgitb\n\ncgitb.enable() # Enable error reporting\n\ndef process_form():\n form = cgi.FieldStorage()\n\n # Extract form fields\n username = ...
trial_gpt4o_5
{ "original_instruction": "**CGI Form Processing and Error Handling**\n\nIn this coding assessment, you will create a CGI script that processes user input from an HTML form, handles various possible input cases, and outputs the results in a structured HTML format. Your script should demonstrate proficiency with the `...
0.483506
Docs: Python310_43260
C
[ "generate_html_response", "process_form" ]
2
[ [ "process_form", "generate_html_response" ] ]
1
[]
false
[]
false
pytest
true
[]
true
8f2fa345f85c3a7ac286bd85aa0f9ed4631e95f7
d763d3a95d2d205f7a10bc1b5d08c78d8bc8b549
v1.0
complete
Docs
Docs: Pytorch_42965_C
import torch import torch.distributed.checkpoint as dcp async def save_distributed_checkpoint(model: torch.nn.Module, optimizer: torch.optim.Optimizer, checkpoint_dir: str) -> None: """ Save a distributed model's state using DCP with asynchronous saving. Args: - model (torch.nn.Module): The distribute...
import torch import torch.distributed.checkpoint as dcp import os def get_model_state_dict(model: torch.nn.Module): """ Returns the state dict of the model ensuring it always gets the state dict of the base model if wrapped in DataParallel or DistributedDataParallel """ if isinstance(model, (torch...
import torch import torch.nn as nn import torch.optim as optim import os import shutil import pytest from solution import save_distributed_checkpoint, load_distributed_checkpoint # Dummy model and optimizer for testing class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() ...
[ { "docstring": "Returns the state dict of the model ensuring it always gets the \nstate dict of the base model if wrapped in DataParallel or DistributedDataParallel", "function_declaration": "def get_model_state_dict(model):", "function_name": "get_model_state_dict", "parameter_list": "(model)" },...
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.distributed as dist\nimport torch.distributed.checkpoint as dcp\n\ndef get_model_state_dict(model: torch.nn.Module) -> dict:\n \"\"\"\n ...
trial_gpt4o_1
{ "original_instruction": "### Distributed Checkpointing in PyTorch\n\n**Objective:**\n\nImplement a coding solution to save and load a distributed model's state using PyTorch's Distributed Checkpoint (DCP) functionality. This task will assess your understanding of distributed model parallelism, state dictionary mana...
0.392392
Docs: Pytorch_42965
C
[ "get_model_state_dict", "get_optimizer_state_dict", "save_distributed_checkpoint", "load_distributed_checkpoint" ]
4
[ [ "save_distributed_checkpoint", "get_model_state_dict" ], [ "save_distributed_checkpoint", "get_optimizer_state_dict" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
c1d1209bdaf5e4ce5586e90f19fad77b15dbdaec
94f014bb72d1f86c33fe8229adf62d595f3f6e81
v1.0
complete
Docs
Docs: Python310_43566_C
from wsgiref.simple_server import make_server from wsgiref.util import setup_testing_defaults, shift_path_info, request_uri from wsgiref.validate import validator def manipulate_environment(environ): """Manipulates WSGI environment by shifting one path component from PATH_INFO to SCRIPT_NAME. >>> environ = {'S...
from wsgiref.simple_server import make_server from wsgiref.util import request_uri, shift_path_info, setup_testing_defaults from wsgiref.validate import validator def manipulate_environment(environ): # Manipulate the environment by shifting PATH_INFO to SCRIPT_NAME shifted_path = shift_path_info(environ) p...
import pytest from wsgiref.validate import validator from wsgiref.util import setup_testing_defaults from solution import manipulate_environment, hello_app def test_manipulate_environment(): environ = { 'SCRIPT_NAME': '/app', 'PATH_INFO': '/test/path' } setup_testing_defaults(environ) o...
[ { "docstring": null, "function_declaration": "def manipulate_environment(environ):", "function_name": "manipulate_environment", "parameter_list": "(environ)" }, { "docstring": null, "function_declaration": "def hello_app(environ, start_response):", "function_name": "hello_app", "...
[ 1, 0, 1, 0, 1, 0, 0, 1, 0, 1 ]
5
medium
0.5
{ "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 request_uri, shift_path_info, setup_testing_defaults\nfrom wsgiref.validate import validator\n\n...
trial_gpt4o_2
{ "original_instruction": "#### Objective\nCreate a simple WSGI application using the `wsgiref` package and implement utilities for environment manipulation and validation.\n\n#### Problem Statement\nWrite a WSGI application that serves a \"Hello World\" message and logs the request URI and headers. Implement a funct...
0.536958
Docs: Python310_43566
C
[ "manipulate_environment", "hello_app" ]
2
[ [ "hello_app", "manipulate_environment" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a6b347c0bf6f85a315d46266b6b4d47d9889d612
bf178fd1f816bdf52d4c7b7e5cf296fba1d8a212
v1.0
complete
Docs
Docs: Python310_43162_C
class Py_complex: def __init__(self, real, imag): self.real = real self.imag = imag def from_pycomplex_to_py_complex(py_complex_obj): """ Converts a Python complex object to a Py_complex C structure. """ pass def from_py_complex_to_pycomplex(c_complex_struct): """ Converts ...
class Py_complex: def __init__(self, real, imag): self.real = real self.imag = imag def from_pycomplex_to_py_complex(py_complex_obj): """ Converts a Python complex object to a Py_complex C structure. """ return Py_complex(py_complex_obj.real, py_complex_obj.imag) def from_py_comple...
from solution import Py_complex, complex_sum, complex_diff, complex_prod, complex_quot from solution import from_pycomplex_to_py_complex, from_py_complex_to_pycomplex def test_complex_sum(): c1 = Py_complex(1.0, 2.0) c2 = Py_complex(3.0, 4.0) result = complex_sum(c1, c2) expected = Py_complex(4.0, 6.0)...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Py_complex:\n def __init__(self, real=0.0, imag=0.0):\n self.real = real\n self.imag = imag\n\ndef from_pycomplex_to_py_complex(py_complex_obj):\...
trial_gpt4o_7
{ "original_instruction": "### Complex Number Operations in Python\n\n#### Objective\nYou are tasked with implementing a set of functions to perform arithmetic operations on complex numbers in Python. You will use both C structure representations and Python object representations to demonstrate your understanding of ...
0.515172
Docs: Python310_43162
C
[ "from_pycomplex_to_py_complex", "from_py_complex_to_pycomplex", "complex_sum", "complex_diff", "complex_prod", "complex_quot" ]
6
[ [ "complex_diff", "from_py_complex_to_pycomplex" ], [ "complex_diff", "from_pycomplex_to_py_complex" ], [ "complex_prod", "from_py_complex_to_pycomplex" ], [ "complex_prod", "from_pycomplex_to_py_complex" ], [ "complex_quot", "from_py_complex_to_pycomplex" ]...
8
[]
false
[ "Py_complex" ]
true
pytest
true
[]
true
2aadaa945449fb227132cd78d7952358de37f7a0
57c90d16dcc2a5222f3b38746daf77d6c5ae0d35
v1.0
complete
Docs
Docs: Python310_43591_C
import asyncio async def multi_stage_task(sources, process_data, save_data): """ Simulates fetching data from multiple sources, processes the fetched data, and saves the processed data concurrently. :param sources: List of URLs to fetch data from. :param process_data: Asynchronous function to pro...
import asyncio import aiohttp import logging from typing import List, Callable # Configure logging logging.basicConfig(level=logging.ERROR) logger = logging.getLogger(__name__) async def fetch_data(session, url): """ Fetch data from a single URL. """ try: async with session.get(url, timeout=10...
import pytest import asyncio from unittest.mock import patch, AsyncMock # Assuming previous solution code is accessible and imported here from solution import multi_stage_task, fetch_data, example_process_data, example_save_data @pytest.mark.asyncio async def test_multi_stage_task(): # Mock URLs sources = ["h...
[]
[ 0, 1, 1, 1, 1, 1, 1, 0, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nimport logging\n\nasync def fetch_data(session, url):\n try:\n async with session.get(url) as response:\n response....
trial_gpt4o_1
{ "original_instruction": "### Question: Multi-Stage Task Execution using `asyncio`\n\n**Objective**: Implement a Python function that simulates a multi-stage task execution system using the `asyncio` module.\n\n**Problem Statement**:\nYou need to design a system that performs the following tasks concurrently:\n1. Fe...
0.517276
Docs: Python310_43591
C
[ "fetch_data", "multi_stage_task", "example_process_data", "example_save_data" ]
4
[ [ "multi_stage_task", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
39401bdda7efe8ee79e8e1443e0e7054ed672099
fdd36597926fc51a6a53757f95b7006cd3dec6c4
v1.0
complete
Docs
Docs: Python310_43224_C
import contextlib class network_resource: def __enter__(self): print("Opening network resource") return self def __exit__(self, exc_type, exc_val, exc_tb): print("Releasing network resource") def manage_resources(filenames): """ Manage multiple resource operations including file o...
import contextlib class network_resource: def __enter__(self): print("Opening network resource") return self def __exit__(self, exc_type, exc_val, exc_tb): print("Releasing network resource") def log_event(message): print(message) def manage_resources(filenames): with context...
import pytest from solution import manage_resources, network_resource def test_manage_resources_no_files(tmp_path): filenames = [] manage_resources(filenames) def test_manage_resources_with_files(tmp_path): file1 = tmp_path / "test1.txt" file1.write_text("This is a test file.\nAnother line.\n") fi...
[]
[ 1, 1, 1, 1, 1, 1, 0, 1, 0, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextlib\nfrom typing import List\n\nclass network_resource:\n def __enter__(self):\n print(\"Opening network resource\")\n return self\n\n ...
trial_gpt4o_9
{ "original_instruction": "### Advanced Python Context Management\n\n#### Context\n\nYou are tasked with managing multiple resource operations with different life cycles that need to be cleaned up properly. Specifically, you have operations that require opening multiple files, acquiring and releasing a network resour...
0.511136
Docs: Python310_43224
C
[ "log_event", "manage_resources" ]
2
[ [ "manage_resources", "log_event" ] ]
1
[]
false
[ "network_resource" ]
true
pytest
true
[]
true
7953f9fd1ae695861917728cc43e70b312bcd097
408423cb2e5f50c7853fe3a9c81d522574e5c810
v1.0
complete
Docs
Docs: Python310_43355_C
import asyncio from typing import List, Tuple async def task_scheduler(tasks: List[Tuple[int, float]]): """ Asynchronous Task Processing with Priority Queue. Implement an asynchronous function to manage a set of tasks with varying priorities and ensure that higher priority tasks are processed before lower prio...
import asyncio from typing import List, Tuple import time async def worker(queue: asyncio.PriorityQueue): while True: priority, duration = await queue.get() await asyncio.sleep(duration) queue.task_done() async def task_scheduler(tasks: List[Tuple[int, float]]): queue = asyncio.Priorit...
import asyncio import time from solution import task_scheduler def test_task_scheduler(): tasks = [(1, 2.5), (3, 1.0), (2, 3.0), (4, 0.5)] asyncio.run(task_scheduler(tasks)) def test_task_scheduler_with_no_tasks(): tasks = [] asyncio.run(task_scheduler(tasks)) def test_task_scheduler_with_equal_prior...
[]
[ 1, 1, 1, 1, 0, 1, 0, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\nimport time\n\nasync def worker(name: str, queue: asyncio.PriorityQueue):\n while True:\n priority, duration =...
trial_gpt4o_9
{ "original_instruction": "**Title:** Asynchronous Task Processing with Priority Queue\n\n**Problem Statement:**\n\nYou are tasked with implementing an asynchronous task scheduler using `asyncio.PriorityQueue`. The scheduler will manage a set of tasks with varying priorities and ensure that higher priority tasks are ...
0.632606
Docs: Python310_43355
C
[ "worker", "task_scheduler" ]
2
[ [ "task_scheduler", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c4aad40474d86b17d239dff04190b8122c0297bf
aea6a7869a5aaf07b3d6ebc5a6d01d43cbc0bc61
v1.0
complete
Docs
Docs: Python310_43560_C
import csv from datetime import datetime, timedelta from typing import List import pytz def parse_duration(seconds: int) -> str: """Convert duration in seconds to 'H hours, M minutes, S seconds'.""" hours, remainder = divmod(seconds, 3600) minutes, seconds = divmod(remainder, 60) duration_str = f"{hour...
import csv from datetime import datetime, timedelta import pytz def parse_duration(seconds): """Convert duration in seconds to 'H hours, M minutes, S seconds'.""" hours, remainder = divmod(seconds, 3600) minutes, seconds = divmod(remainder, 60) duration_str = f"{hours} hours, {minutes} minutes, {second...
import csv import os from solution import process_event_logs def setup_module(module): # Setup a sample events.csv data = [ ['event_id', 'timestamp', 'duration'], ['1', '2023-04-05T14:30:00Z', '3600'], ['2', '2023-04-05T15:00:00Z', '5400'], ] with open('events.csv', 'w', newline...
[ { "docstring": "Convert duration in seconds to 'H hours, M minutes, S seconds'.", "function_declaration": "def parse_duration(seconds):", "function_name": "parse_duration", "parameter_list": "(seconds)" }, { "docstring": null, "function_declaration": "def process_event_logs(time_zone):",...
[ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\nfrom datetime import datetime, timedelta\nimport pytz\n\ndef process_event_logs(time_zone: str) -> None:\n # Define the timezone\n target_timezone = p...
trial_gpt4o_5
{ "original_instruction": "### Advanced Date and Time Calculation Task\n\n**Problem Statement:**\n\nYou have been given a CSV file named `events.csv` which contains log data of various events. Each row in the CSV file contains an event ID, a timestamp, and the event's duration in seconds. Your task is to process this...
0.715375
Docs: Python310_43560
C
[ "parse_duration", "process_event_logs" ]
2
[ [ "process_event_logs", "parse_duration" ] ]
1
[]
false
[]
false
pytest
true
[ "pytz" ]
false
74ba6bcd2529afa78366374f78ba5bcad5a8d2ea
38cf90108c9eb8cf9ca7dbfa729517bacb0cffb6
v1.0
complete
Docs
Docs: Python310_43517_C
import turtle def draw_shape(turtle_obj: turtle.Turtle, shape: str, size: int, color: str = 'black'): """Draws a specified shape with the given size and color. Parameters: turtle_obj (turtle.Turtle): The turtle object. shape (str): The shape to draw ('square', 'triangle', 'circle'). size (int)...
import turtle def draw_shape(turtle_obj, shape, size, color='black'): """ Draws a specified shape with the given size and color. Parameters: turtle_obj (Turtle): The turtle object. shape (str): The shape to draw ('square', 'triangle', 'circle'). size (int): The size of the shape. color...
from unittest.mock import MagicMock, patch import turtle @patch('turtle.Turtle') def test_draw_shape_square(mock_turtle): turtle_obj = mock_turtle() draw_shape(turtle_obj, 'square', 100) assert turtle_obj.forward.call_count == 4 assert turtle_obj.right.call_count == 4 @patch('turtle.Turtle') def test_...
[ { "docstring": "Draws a specified shape with the given size and color.\n\nParameters:\nturtle_obj (Turtle): The turtle object.\nshape (str): The shape to draw ('square', 'triangle', 'circle').\nsize (int): The size of the shape.\ncolor (str): The color of the shape.", "function_declaration": "def draw_shape...
[ 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 turtle\n\ndef draw_shape(turtle_obj, shape, size, color='black'):\n \"\"\"\n Draws a shape with the given turtle object.\n \n Parameters:\n - turt...
trial_gpt4o_9
{ "original_instruction": "### Turtle Graphics Challenge\n\nIn this challenge, you will create a simulation using the turtle graphics module. The objective is to simulate a simple drawing application that allows for the drawing of shapes based on user inputs.\n\n#### Objectives:\n1. **Create a Function to Draw Shapes...
0.731516
Docs: Python310_43517
C
[ "draw_shape", "move_up", "move_down", "move_left", "move_right", "run_drawing_app" ]
6
[ [ "run_drawing_app", "draw_shape" ], [ "run_drawing_app", "move_down" ], [ "run_drawing_app", "move_left" ], [ "run_drawing_app", "move_right" ], [ "run_drawing_app", "move_up" ] ]
5
[]
false
[]
false
pytest
false
[]
true
ec692b738b72ced949678b85887a6b8277a94ada
37dde0a9c1b2a19bb40edef49c76096ae91fcd29
v1.0
complete
Docs
Docs: Scikit_43068_C
import pandas as pd import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier def stream_data(file_path, batch_size): """ Generator function to read data from a large CSV file in mini-batches. Args: file_path (str): The path to ...
import pandas as pd import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier def stream_data(file_path, batch_size): """ Generator function to read data from a large CSV file in mini-batches. Args: file_path (str): The path to the ...
import os import pytest from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from solution import stream_data, train_incremental_model # Mock data creation for testing purposes file_path = 'test_large_text_data.csv' mock_data = { 'text': ['sample text data'] ...
[ { "docstring": "Generator function to read data from a large CSV file in mini-batches.\n\nArgs:\nfile_path (str): The path to the CSV file.\nbatch_size (int): The number of examples in each batch.\n\nYields:\nTuple[np.array, np.array]: Batches of features and labels.", "function_declaration": "def stream_da...
[ 0, 1, 1, 0, 1, 0, 1, 1, 1, 0 ]
6
medium
0.6
{ "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\n\ndef stream_dat...
trial_gpt4o_8
{ "original_instruction": "**Out-of-Core Learning with scikit-learn**\n\nAs a data scientist, you are tasked with building an out-of-core learning system to classify text data that is too large to fit into memory. You need to implement a system that reads and processes the data in mini-batches, extracts features usin...
0.704044
Docs: Scikit_43068
C
[ "stream_data", "train_incremental_model" ]
2
[ [ "train_incremental_model", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "pandas", "sklearn" ]
false
7d2fba7e3c1df261007f1d85be8f38dca0b1e6da
76ffba87a734109e9e32409cf8029cebabebeca6
v1.0
complete
Docs
Docs: Python310_44050_C
import inspect import builtins def debug_info(): """ Prints debug information of the currently executing function, including its name, description, current line number, and all available local, global, and built-in variables. """ def sample_function(a, b): x = a + b debug_info() return...
import inspect import builtins def debug_info(): """ Prints debug information of the currently executing function, including its name, description, current line number, and all available local, global, and built-in variables. """ frame = inspect.currentframe().f_back if frame is not None: ...
from solution import debug_info, sample_function def test_debug_info(): import builtins from io import StringIO import sys old_stdout = sys.stdout sys.stdout = StringIO() # Call the sample function to initiate debug_info from within its frame sample_function(1, 2) output = sys.stdout...
[ { "docstring": "Prints debug information of the currently executing function, including its\nname, description, current line number, and all available local, global, and\nbuilt-in variables.", "function_declaration": "def debug_info():", "function_name": "debug_info", "parameter_list": "()" }, {...
[ 0, 0, 1, 0, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import inspect\n\ndef debug_info():\n \"\"\"\n This function prints the current execution state including \n function name, description, line number, and local...
trial_gpt4o_4
{ "original_instruction": "**Question: Debugging Tool Implementation**\n\nIn this task, you will implement a Python function using the Python C API functions outlined in the provided documentation. This function will act as a debugging tool to retrieve and display the current state of execution, including calling fun...
0.691212
Docs: Python310_44050
C
[ "debug_info", "sample_function" ]
2
[ [ "sample_function", "debug_info" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7214985815d16a2e7af67a8f0a2bcff9f346ba9c
1036effa4fe1e508cb352a42ecf0cfacc1613ca1
v1.0
complete
Docs
Docs: Python310_43713_C
def process_electronics(details: str) -> str: """Processes the electronics details and returns a formatted string. >>> process_electronics("Smartphone with 4GB RAM") "Processed Electronics: Smartphone with 4GB RAM" """ pass def process_clothing(details: str) -> str: """Processes clothing detail...
def process_electronics(details: str) -> str: return f"Processed Electronics: {details}" def process_clothing(details: str) -> str: return f"Processed Clothing: {details}" def process_data(data: list[dict]) -> dict: result = {} for record in data: try: category = record["categ...
from solution import process_data, process_electronics, process_clothing def test_process_electronics(): assert process_electronics("Smartphone with 4GB RAM") == "Processed Electronics: Smartphone with 4GB RAM" def test_process_clothing(): assert process_clothing("Cotton t-shirt, size L") == "Processed Clothi...
[ { "docstring": null, "function_declaration": "def process_electronics(details):", "function_name": "process_electronics", "parameter_list": "(details)" }, { "docstring": null, "function_declaration": "def process_clothing(details):", "function_name": "process_clothing", "paramete...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def process_electronics(details: str) -> str:\n return f\"Processed Electronics: {details}\"\n\ndef process_clothing(details: str) -> str:\n return f\"Processed C...
trial_gpt4o_9
{ "original_instruction": "**Objective**: Evaluate the student's understanding of function implementation, pattern matching (new in Python 3.10), and exception handling.\n\n### Problem Statement\n\nYou are required to implement a Python function named `process_data` that takes a list of dictionaries as input. Each di...
0.628951
Docs: Python310_43713
C
[ "process_electronics", "process_clothing", "process_data" ]
3
[ [ "process_data", "process_clothing" ], [ "process_data", "process_electronics" ] ]
2
[ "process_data" ]
false
[]
false
pytest
true
[]
true
0ec5dc166059908e9109da37dc3401d927d1dd49
f8b17605bc9dde58badfbbd31f7ffbf3a2e16ffc
v1.0
complete
Docs
Docs: Python310_43742_C
import asyncio async def fetch_data(data_id: int) -> asyncio.Future: """ Simulate fetching data asynchronously by sleeping for 0.5 seconds and then setting a result with a specific format. >>> result = await fetch_data(1) >>> result.result() == "data_1" True """ # Your implementation here asyn...
import asyncio async def fetch_data(data_id: int) -> asyncio.Future: """ Simulate fetching data asynchronously by sleeping for 0.5 seconds and then setting a result with a specific format. """ await asyncio.sleep(0.5) future = asyncio.Future() future.set_result(f"data_{data_id}") return fut...
import asyncio import pytest from solution import fetch_data, process_data, aggregate_results, execute_pipeline @pytest.mark.asyncio async def test_fetch_data(): result = await fetch_data(1) assert result.result() == "data_1" @pytest.mark.asyncio async def test_process_data(): fetch_future = await fetch_d...
[]
[ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def fetch_data(data_id: int) -> asyncio.Future:\n future = asyncio.Future()\n await asyncio.sleep(0.5)\n future.set_result(f\"data_{dat...
trial_gpt4o_1
{ "original_instruction": "**Programming Task: Implement an Asynchronous Data Pipeline Using asyncio Futures**\n\n### Objective\nYou are required to implement an asynchronous data processing pipeline using asyncio.Future objects. The pipeline consists of three stages:\n1. **Data Fetching**: Simulate fetching data asy...
0.519493
Docs: Python310_43742
C
[ "fetch_data", "process_data", "aggregate_results", "execute_pipeline" ]
4
[ [ "execute_pipeline", "aggregate_results" ], [ "execute_pipeline", "fetch_data" ], [ "execute_pipeline", "process_data" ] ]
3
[ "process_data" ]
false
[]
false
pytest
true
[]
true
f63d6e6ceb26ea29fdad3e0850a9cf358d25aef4
e5e3229ddbbd003396519276f9d62bd168f7e26f
v1.0
complete
Docs
Docs: Python310_44289_C
import _thread import requests # Global dictionary to store web content WEB_CONTENT = {} def fetch_content(url, lock): """ Fetch the HTML content of the given URL and store it in the global dictionary under lock protection. """ pass def scrape_urls(url_list): """ Scrape the given list of URLs using m...
import _thread import requests from time import sleep # Global dictionary to store web content WEB_CONTENT = {} def fetch_content(url, lock): try: response = requests.get(url) lock.acquire() try: WEB_CONTENT[url] = response.text finally: lock.release() e...
from solution import scrape_urls, WEB_CONTENT import _thread def test_scrape_urls_with_valid_urls(): urls = ["http://example.com"] scrape_urls(urls) assert "http://example.com" in WEB_CONTENT assert WEB_CONTENT["http://example.com"].startswith("<!doctype html>") or WEB_CONTENT["http://example.com"...
[ { "docstring": null, "function_declaration": "def fetch_content(url, lock):", "function_name": "fetch_content", "parameter_list": "(url, lock)" }, { "docstring": null, "function_declaration": "def scrape_urls(url_list):", "function_name": "scrape_urls", "parameter_list": "(url_li...
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import _thread\nimport requests\n\n# Global dictionary to store web content\nWEB_CONTENT = {}\n\ndef fetch_content(url, lock):\n \"\"\"\n Fetches the HTML content...
trial_gpt4o_1
{ "original_instruction": "#### Problem Statement\n\nYou are tasked with developing a simple multi-threaded web scraper using the `_thread` module in Python. The scraper will query a list of URLs and store the HTML content in a dictionary. To ensure thread safety when accessing the shared dictionary, you must use loc...
0.707493
Docs: Python310_44289
C
[ "fetch_content", "scrape_urls" ]
2
[ [ "scrape_urls", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
d2132f4f58c8c6183b52e271c7588d5d53b218ab
1065e41982192811af454804e1b02595b6a053f9
v1.0
complete
Docs
Docs: Python310_44056_C
from functools import lru_cache, partial from typing import Callable @lru_cache(maxsize=100) def compute_polynomial(a: int, b: int, c: int, x: int) -> int: """Compute the value of a polynomial ax^2 + bx + c using lru_cache for caching. >>> compute_polynomial(2, 3, 4, 1) 9 >>> compute_polynomial(2, 3, 4, 0)...
from functools import lru_cache, partial @lru_cache(maxsize=100) def compute_polynomial(a: int, b: int, c: int, x: int) -> int: return a * x * x + b * x + c def create_partial_polynomial(a: int, b: int, c: int): return partial(compute_polynomial, a, b, c)
from solution import compute_polynomial, create_partial_polynomial def test_compute_polynomial(): # Test polynomial: 2x^2 + 3x + 4 assert compute_polynomial(2, 3, 4, 1) == 9 assert compute_polynomial(2, 3, 4, 0) == 4 assert compute_polynomial(2, 3, 4, -1) == 3 assert compute_polynomial(2, 3, 4, 2) ...
[ { "docstring": null, "function_declaration": "def compute_polynomial(a, b, c, x):", "function_name": "compute_polynomial", "parameter_list": "(a, b, c, x)" }, { "docstring": null, "function_declaration": "def create_partial_polynomial(a, b, c):", "function_name": "create_partial_poly...
[ 0, 0, 0, 0, 0, 1, 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 functools import lru_cache, partial\n\n@lru_cache(maxsize=100)\ndef compute_polynomial(a: int, b: int, c: int, x: int) -> int:\n \"\"\"\n Returns the value o...
trial_gpt4o_8
{ "original_instruction": "**Title: Efficient function memoization using `functools.lru_cache` & custom `partial` functions**\n\n#### Objective:\nImplement a function that utilizes `functools.lru_cache` to efficiently compute the value of a mathematical function while caching its results. In addition, create a partia...
0.5983
Docs: Python310_44056
C
[ "compute_polynomial", "create_partial_polynomial" ]
2
[ [ "create_partial_polynomial", "compute_polynomial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ac33e5b37f6f53431441b9b8d27d12cde06b08b0
dc01f5f0081937e9b69fd664e62dce88b00cdb88
v1.0
complete
Docs
Docs: Pytorch_43903_C
import torch from typing import List def async_square(n: int) -> torch.futures.Future: """ Asynchronously computes the square of a number. """ future = torch.futures.Future() future.set_result(n ** 2) return future def process_data_concurrently(data: List[int]) -> List[int]: """ Proces...
import torch from typing import List def async_square(n: int) -> torch.futures.Future: """ Asynchronously computes the square of a number. """ future = torch.futures.Future() future.set_result(n ** 2) return future def process_data_concurrently(data: List[int]) -> List[int]: """ Proces...
from solution import process_data_concurrently def test_process_data_concurrently(): assert process_data_concurrently([1, 2, 3, 4]) == [1, 4, 9, 16] assert process_data_concurrently([0, 5, 10, 15]) == [0, 25, 100, 225] assert process_data_concurrently([10**6]) == [10**12] assert process_data_concurrent...
[ { "docstring": "Asynchronously computes the square of a number.", "function_declaration": "def async_square(n):", "function_name": "async_square", "parameter_list": "(n)" }, { "docstring": "Process a list of data items concurrently using torch.futures.Future.\nEach integer in the list is squ...
[ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.futures import Future\nfrom typing import List\n\ndef process_data_concurrently(data: List[int]) -> List[int]:\n \"\"\"\n Processes a lis...
trial_gpt4o_8
{ "original_instruction": "#### Objective\nYou are required to demonstrate your understanding of asynchronous execution using PyTorch's `torch.futures` package by designing a function that processes a list of data items concurrently.\n\n#### Task\nImplement a function named `process_data_concurrently` that processes ...
0.530032
Docs: Pytorch_43903
C
[ "async_square", "process_data_concurrently" ]
2
[ [ "process_data_concurrently", "async_square" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
43a4dbe36146e5958e35f9674903eece0787b9af
f28dadfd7b16a0b18916631fad5dccc892b94006
v1.0
complete
Docs
Docs: Python310_43777_C
import curses def text_editor(stdscr): """ Implement a simple text editor using the curses library in Python. The editor should support text input, cursor movement, and saving content to a file. Functional specifications: - Text input - Arrow keys for cursor movement - Ctrl-S: Save to a file ...
import curses def text_editor(stdscr): curses.curs_set(1) # Show cursor stdscr.clear() text = [[]] cursor_y, cursor_x = 0, 0 while True: stdscr.clear() for i, line in enumerate(text): stdscr.addstr(i, 0, ''.join(line)) stdscr.move(cursor_y, cursor_x) st...
import pytest import os def test_save_file(): text = [['H','e','l','l','o'], ['W','o','r','l','d']] save_to_file(text) with open('output.txt', 'r') as f: lines = f.readlines() assert lines == ['Hello\n', 'World\n'] def test_save_empty_file(): text = [[]] save_to_file(text) with ope...
[ { "docstring": null, "function_declaration": "def text_editor(stdscr):", "function_name": "text_editor", "parameter_list": "(stdscr)" }, { "docstring": null, "function_declaration": "def save_to_file(text):", "function_name": "save_to_file", "parameter_list": "(text)" } ]
[ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import curses\n\ndef text_editor(stdscr):\n curses.curs_set(1) # Show cursor\n stdscr.clear()\n text = [[]]\n cursor_y, cursor_x = 0, 0\n\n while True:\...
trial_gpt4o_0
{ "original_instruction": "#### Objective\n\nImplement a simple text editor using the `curses` library in Python. Your editor should support basic operations such as text input, cursor movement, and saving the content to a file.\n\n#### Requirements\n\n**Function:** `text_editor`\n\n**Input:**\n- The function does no...
0.553384
Docs: Python310_43777
C
[ "text_editor", "save_to_file" ]
2
[ [ "text_editor", "save_to_file" ] ]
1
[]
false
[]
false
pytest
false
[]
true
bf2414b9f777ffee58af6b8729bfb360db6cc9c0
abbf4ee746797c4d84ffb7aca83f5ffb1363d4ce
v1.0
complete
Docs
Docs: Python310_44024_C
import asyncio import random async def fetch_status(server: str) -> str: """Simulates fetching the status of a server. Simulates a network delay using asyncio.sleep, within a random interval between 1 to 3 seconds. Returns a string that says "Status from <server>". """ pass async def log_status(se...
import asyncio import random async def fetch_status(server: str) -> str: delay = random.randint(1, 3) await asyncio.sleep(delay) return f"Status from {server}" async def log_status(server: str): try: status = await asyncio.wait_for(fetch_status(server), timeout=5) print(status) exc...
import asyncio import random from unittest.mock import patch, AsyncMock from solution import fetch_status, log_status # Since the actual implementation involves non-deterministic delays and network calls, # we will mock fetch_status to control the behavior and test log_status behavior @patch('solution.fetch_status'...
[]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\n\nasync def fetch_status(server: str) -> str:\n delay = random.randint(1, 3)\n await asyncio.sleep(delay)\n return f\"Status fro...
trial_gpt4o_5
{ "original_instruction": "**Problem Statement: Asynchronous Task and Network Management with `asyncio`**\n\nYou are tasked with writing an asynchronous Python program which simulates a simple network service monitoring system. The program should periodically fetch status updates from different servers and log the re...
0.615742
Docs: Python310_44024
C
[ "fetch_status", "log_status", "main" ]
3
[ [ "log_status", "fetch_status" ] ]
1
[]
false
[]
false
pytest
true
[]
true
19fe69fd4d6e1f2db5118b19fa89241e8eb674b1
6de3d3bc734e53a9762425face97458fcff2a397
v1.0
complete
Docs
Docs: Python310_44061_C
def data_stream(data): """ Generator that yields squared values of even numbers from the input list. """ for value in data: if value % 2 == 0: yield value ** 2 def filtered_stream(data, threshold): """ Generator that filters values from data_stream based on a threshold. ...
def data_stream(data): """ Generator that yields squared values of even numbers from the input list. """ for value in data: if value % 2 == 0: yield value ** 2 def filtered_stream(data, threshold): """ Generator that filters values from data_stream based on a threshold. ...
from solution import data_stream, filtered_stream, stream_processor def test_data_stream(): data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] output = list(data_stream(data)) assert output == [4, 16, 36, 64, 100] def test_filtered_stream(): data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] threshold = 10 output = l...
[ { "docstring": "Generator that yields squared values of even numbers from the input list.", "function_declaration": "def data_stream(data):", "function_name": "data_stream", "parameter_list": "(data)" }, { "docstring": "Generator that filters values from data_stream based on a threshold.\nYi...
[ 0, 1, 0, 1, 0, 0, 1, 1, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def data_stream(data):\n \"\"\"\n Generator function that yields squared values of even numbers from the input list.\n \"\"\"\n for value in data:\n ...
trial_gpt4o_8
{ "original_instruction": "## Coding Assessment Question: Synchronization of Generator Operations\n\n### Objective\nDemonstrate your understanding of Python 3.8+ generator expressions, custom functions, synchronization, and complex expression handling in Python.\n\n### Problem Statement\nYou are tasked with creating ...
0.532225
Docs: Python310_44061
C
[ "data_stream", "filtered_stream", "stream_processor" ]
3
[ [ "filtered_stream", "data_stream" ], [ "stream_processor", "filtered_stream" ] ]
2
[]
false
[]
false
pytest
true
[]
true
80942ec0e0dcbfc5e9845324b053422f522fb6e1
4a810599b782077a66b0b9f31ca5d62a466f362c
v1.0
complete
Docs
Docs: Python310_44141_C
from typing import Iterator, List import itertools import functools import math class CustomRange: def __init__(self, start: int, stop: int, step: int=1): """ Custom iterator that mimics the behavior of Python's built-in range function :param start: Start of the range :par...
import itertools import functools import math class CustomRange: def __init__(self, start, stop, step=1): self.start = start self.stop = stop self.step = step def __iter__(self): current = self.start if self.step > 0: while current < self.stop: ...
from solution import CustomRange, prime_numbers, process_primes_and_range def test_custom_range(): assert list(CustomRange(1, 10, 2)) == [1, 3, 5, 7, 9] assert list(CustomRange(10, 1, -3)) == [10, 7, 4] assert list(CustomRange(0, 5, 1)) == [0, 1, 2, 3, 4] assert list(CustomRange(-5, 5, 2)) == [-5, -3, ...
[]
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import itertools\nimport functools\n\nclass CustomRange:\n def __init__(self, start, stop, step=1):\n self.start = start\n self.stop = stop\n se...
trial_gpt4o_3
{ "original_instruction": "#### Objective:\nYou are to demonstrate your understanding of Python's functional programming capabilities by implementing a custom iterator and a generator, as well as utilizing `itertools` and `functools` library functions.\n\n#### Task:\n1. **Custom Range Iterator**\n Implement a custo...
0.6656
Docs: Python310_44141
C
[ "prime_numbers", "process_primes_and_range" ]
2
[ [ "process_primes_and_range", "prime_numbers" ] ]
1
[]
false
[ "CustomRange" ]
true
pytest
true
[]
true
2e3ba293d5be0c4670876e89af54a365cc05527a
955390ed57ba2379b3330002dc127270e6d21d30
v1.0
complete
Docs
Docs: Python310_44493_C
def create_bound_method(func, instance): """ Create a bound method by programmatically binding a callable to an instance of a user-defined class. >>> class MyClass: ... def __init__(self, name): ... self.name = name >>> def my_function(self): ... return f"Hello, {self.name}!" ...
import ctypes import inspect # Load the Python C-API pythonapi = ctypes.PyDLL(None) class PyObject(ctypes.Structure): pass PyObject._fields_ = [("ob_refcnt", ctypes.c_long), ("ob_type", ctypes.POINTER(PyObject))] # Define C-API functions used PyMethod_New = pythonapi.PyMethod_New PyMethod_New.argtypes = [ctypes...
def test_create_and_retrieve_bound_method(): class MyClass: def __init__(self, name): self.name = name def my_function(self): return f"Hello, {self.name}!" instance = MyClass("Alice") bound_method = create_bound_method(my_function, instance) assert callable(boun...
[]
[ 1, 1, 1, 1, 0, 0, 0, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import ctypes\nimport inspect\n\n# Load the Python C-API\npythonapi = ctypes.PyDLL(None)\n\nclass PyObject(ctypes.Structure):\n pass\n\nPyObject._fields_ = [(\"ob_re...
trial_gpt4o_0
{ "original_instruction": "### Python Coding Assessment Question: Method Binding\n\n**Objective**: Implement a Python function that programmatically binds a given callable to an instance of a user-defined class and retrieves the callable from the bound method.\n\n**Description**:\nYou are given a class `MyClass` and ...
0.50281
Docs: Python310_44493
C
[ "get_pyobject_pointer", "get_python_function", "create_bound_method", "get_bound_method_function", "my_function" ]
5
[ [ "create_bound_method", "get_pyobject_pointer" ], [ "get_bound_method_function", "get_pyobject_pointer" ], [ "get_bound_method_function", "get_python_function" ] ]
3
[]
false
[ "PyObject", "MyClass" ]
true
pytest
false
[]
true
801d1f2c0fb56f602f686af86c344a91e3e61928
97d788c557f094d0156bce95a8f6e0e9ef5a0fec
v1.0
complete
Docs
Docs: Python310_44499_C
import asyncio async def process_data_streams(sources: list, timeout: float) -> dict: """ Processes data from multiple sources asynchronously. Parameters: sources (list): A list of asynchronous data source callables. timeout (float): Timeout duration for each data fetching task. Returns: ...
import asyncio async def process_data_streams(sources: list, timeout: float) -> dict: """ Processes data from multiple sources asynchronously. Parameters: sources (list): A list of asynchronous data source callables. timeout (float): Timeout duration for each data fetching task. Returns: ...
import pytest from solution import process_data_streams import asyncio async def mock_success_data_source(data, delay): await asyncio.sleep(delay) return data async def mock_failure_incomplete_read_data_source(delay): await asyncio.sleep(delay) raise asyncio.IncompleteReadError(10, b"partial data") a...
[]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def process_data_streams(sources: list, timeout: float) -> dict:\n \"\"\"\n Processes data from multiple sources asynchronously.\n \n ...
trial_gpt4o_5
{ "original_instruction": "### Advanced Python Coding Assessment: Custom Exception Handling in Asyncio\n\n#### Objective:\nYou are required to demonstrate your understanding of handling custom exceptions in Python’s `asyncio` module. This task will involve writing an asynchronous function that processes data and appr...
0.527823
Docs: Python310_44499
C
[ "process_data_streams", "fetch_data" ]
2
[ [ "process_data_streams", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5e2f84c49fe148d5c29f7863bef9c41cbf698acf
cc06bf85040d87f5c1063ff56fb195c1b476d68f
v1.0
complete
Docs
Docs: Scikit_43557_C
import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis from sklearn.metrics import accuracy_score def load_and_split_data(): """ Load the Iris dataset and ...
import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis from sklearn.metrics import accuracy_score def load_and_split_data(): # Load the Iris dataset and split ...
import pytest from solution import load_and_split_data, evaluate_lda_solver, evaluate_qda def test_load_and_split_data(): X_train, X_test, y_train, y_test = load_and_split_data() assert X_train.shape == (120, 4) assert X_test.shape == (30, 4) assert len(y_train) == 120 assert len(y_test) == 30 def...
[ { "docstring": null, "function_declaration": "def load_and_split_data():", "function_name": "load_and_split_data", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def evaluate_lda_solver(solver, shrinkage=None):", "function_name": "evaluate_lda_solver", "p...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.discriminant_analysis import LinearDiscri...
trial_gpt4o_0
{ "original_instruction": "LDA and QDA Classifiers Implementation and Evaluation\n\n#### Context\nYou are provided with a dataset containing several features and a target label representing different classes. Your task is to utilize the Linear Discriminant Analysis (LDA) and Quadratic Discriminant Analysis (QDA) clas...
0.589306
Docs: Scikit_43557
C
[ "load_and_split_data", "evaluate_lda_solver", "evaluate_qda", "main" ]
4
[ [ "evaluate_lda_solver", "load_and_split_data" ], [ "evaluate_qda", "load_and_split_data" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
875e5d2fe363c30f4682df28a93da69e559e4d9f
29d4d914a4e7ad8c250af72e7aedf74bf73acfc4
v1.0
complete
Docs
Docs: Python310_44674_C
import requests from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List def fetch_url(url: str) -> str: """Fetches the content of the given URL. Args: - url: The URL as a string. Returns: - The content of the URL as a string. If an exception occurs, returns...
import requests from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List def fetch_url(url: str) -> str: """ Fetches the content of the given URL. Args: - url: The URL as a string. Returns: - The content of the URL as a string. If an exception occurs, re...
from solution import fetch_all_urls import requests from unittest.mock import patch def test_fetch_all_urls_success(): urls = [ "http://example.com", "http://example.org", "http://example.net" ] responses = ["<html>Example Com</html>", "<html>Example Org</html>", "<html>Example...
[ { "docstring": "Fetches the content of the given URL.\n\nArgs:\n- url: The URL as a string.\n\nReturns:\n- The content of the URL as a string. If an exception occurs, returns an empty string.", "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_list": "(url)" }...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List\n\ndef fetch_url(url: str) -> str:\n try:\n response...
trial_gpt4o_3
{ "original_instruction": "### Concurrent Task Management Using `concurrent.futures`\n\n#### Objective:\nImplement a function that processes a list of URLs concurrently and returns the contents of each URL using the `concurrent.futures` module.\n\n#### Problem Statement:\nYou are given a list of URLs. Your task is to...
0.593534
Docs: Python310_44674
C
[ "fetch_url", "fetch_all_urls" ]
2
[ [ "fetch_all_urls", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
67d688d6f4a9eb4b01e93b9300defc569ad1cd84
50fb87c59a74cc36e21459c6a53eb8e0d5974dc8
v1.0
complete
Docs
Docs: Pytorch_44184_C
import torch def check_device_availability() -> bool: """ Checks if any accelerators are available. Returns: bool: True if at least one accelerator is available, False otherwise. """ pass def get_current_device() -> int: """ Gets the current accelerator device index. Returns:...
import torch def check_device_availability() -> bool: """ Checks if any accelerators are available. Returns: bool: True if at least one accelerator is available, False otherwise. """ return torch.cuda.is_available() def get_current_device() -> int: """ Gets the current accelerator...
from solution import check_device_availability, get_current_device, set_device_by_index, synchronize_device, test_accelerator_module def test_check_device_availability(): assert isinstance(check_device_availability(), bool) def test_set_and_get_current_device(): if check_device_availability(): set_dev...
[ { "docstring": "Checks if any accelerators are available.\n\nReturns:\nbool: True if at least one accelerator is available, False otherwise.", "function_declaration": "def check_device_availability():", "function_name": "check_device_availability", "parameter_list": "()" }, { "docstring": "G...
[ 1, 0, 1, 0, 0, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef check_device_availability() -> bool:\n \"\"\"\n Checks if any accelerators are available.\n \n Returns:\n bool: True if at least one ...
trial_gpt4o_8
{ "original_instruction": "### PyTorch Accelerator Management\n\nIn this task, you are required to write a few functions using PyTorch's `torch.accelerator` module to manage device resources and synchronize operations. This will demonstrate your understanding of handling GPUs in PyTorch.\n\n#### Task 1: Check Device ...
0.321932
Docs: Pytorch_44184
C
[ "check_device_availability", "get_current_device", "set_device_by_index", "synchronize_device", "test_accelerator_module" ]
5
[ [ "test_accelerator_module", "check_device_availability" ], [ "test_accelerator_module", "get_current_device" ], [ "test_accelerator_module", "set_device_by_index" ], [ "test_accelerator_module", "synchronize_device" ] ]
4
[]
false
[]
false
pytest
true
[ "torch" ]
false
7f7a3fbd7f641e40b4439e49fb384834e295b377
cee6a43a93d3e1387b23257ccd42efa7476eae6d
v1.0
complete
Docs
Docs: Python310_44727_C
import os def validate_path(path): """ Validates a given path. >>> validate_path("/valid/path") "/valid/path" >>> validate_path(b"/valid/path") b"/valid/path" >>> validate_path(CustomPath()) "/custom/path" >>> validate_path(123) raises TypeError """ pass def process_path_ha...
import os import sys def validate_path(path): if isinstance(path, (str, bytes)): return path elif isinstance(path, os.PathLike): result = path.__fspath__() if isinstance(result, (str, bytes)): return result raise TypeError("Invalid path format") def process_path_handlin...
import os import pytest from solution import process_path_handling, validate_path class CustomPath: def __fspath__(self): return "/custom/path" def test_validate_path_with_string(): assert validate_path("/valid/path") == "/valid/path" def test_validate_path_with_bytes(): assert validate_path(b"/v...
[ { "docstring": null, "function_declaration": "def validate_path(path):", "function_name": "validate_path", "parameter_list": "(path)" }, { "docstring": null, "function_declaration": "def process_path_handling(parent_path, child_path):", "function_name": "process_path_handling", "...
[ 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 sys\n\ndef validate_path(path):\n if isinstance(path, (str, bytes)):\n return os.fspath(path)\n elif hasattr(path, '__fspath__'):\n ...
trial_gpt4o_1
{ "original_instruction": "### Coding Assessment Task\n\n#### Objective:\nDemonstrate understanding of low-level Python system interaction by utilizing `os.PathLike` and process control functions.\n\n#### Problem Statement:\n\nYou are tasked with creating a Python module that integrates filesystem path handling and i...
0.600163
Docs: Python310_44727
C
[ "validate_path", "process_path_handling" ]
2
[ [ "process_path_handling", "validate_path" ] ]
1
[]
false
[]
false
pytest
true
[]
true
32b36b4062a5d7e7a722b24fd7c6af302648f0ac
d2fc382eeca182f5ed7bf07dd31981c08da66d34
v1.0
complete
Docs
Docs: Python310_43889_C
import asyncio async def start_server(host: str, port: int): """ Start an asynchronous TCP server that listens on the specified host and port. The server should accept client connections and delegate to handle_client for data processing. """ pass async def handle_client(reader: asyncio.StreamReader, w...
import asyncio import platform async def start_server(host: str, port: int): server = await asyncio.start_server(handle_client, host, port) async with server: await server.serve_forever() async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): data = await reader.read(...
# We'll create a custom test fixture to run the server in the background. # Please note that testing asyncio network code often requires a bit more # setup and teardown procedure. import asyncio import pytest import socket import aiohttp from solution import start_server, handle_client @pytest.fixture async def serv...
[]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\n\nasync def start_server(host: str, port: int):\n \"\"\"\n Starts an asynchronous TCP server that listens on the specified host a...
trial_gpt4o_2
{ "original_instruction": "**Question: Platform-Specific Asyncio Implementation**\n\nYou are tasked with implementing an asynchronous TCP server in Python 3.10 using the asyncio package. Your server should handle client connections and process data sent by clients asynchronously. However, you must account for platfor...
0.55393
Docs: Python310_43889
C
[ "start_server", "handle_client" ]
2
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
17068456b9dd8f72ed8e55e10bdcc6116bd2fe9a
2c2ed78afae8f55736b9c592441f945dfe96348d
v1.0
complete
Docs
Docs: Pytorch_44500_C
import torch import torch.testing as tt def make_tensor(shape, dtype, low, high, pin_memory): """ Helper function to generate a tensor with given shape, dtype, range and memory pinning. """ return torch.empty(shape, dtype=dtype).uniform_(low, high) def test_tensor_operations(): """ Function to...
import torch import torch.testing as tt def make_tensor(shape, dtype, low, high, pin_memory): """ Helper function to generate a tensor with given shape, dtype, range and memory pinning. """ return torch.empty(shape, dtype=dtype).uniform_(low, high) def test_tensor_operations(): """ Function to...
import torch import torch.testing as tt from solution import test_tensor_operations, make_tensor def test_tensor_operations_correctness(): """ Test to verify the tensor operations. """ test_tensor_operations() def test_make_tensor(): """ Test to verify the make_tensor function. """ sha...
[ { "docstring": "Helper function to generate a tensor with given shape, dtype, range and memory pinning.", "function_declaration": "def make_tensor(shape, dtype, low, high, pin_memory):", "function_name": "make_tensor", "parameter_list": "(shape, dtype, low, high, pin_memory)" }, { "docstring...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.testing as tt\n\ndef test_tensor_operations():\n # Generate tensor A\n A = tt.make_tensor(shape=(3, 3), dtype=torch.float, low=-10, hig...
trial_gpt4o_2
{ "original_instruction": "**Question:**\n\nIn this assessment, you are required to implement a function that performs a series of tests to ensure the correctness of tensor operations. Specifically, you will:\n\n1. Generate a tensor using the `make_tensor` function.\n2. Perform a mathematical operation on the generat...
0.585755
Docs: Pytorch_44500
C
[ "make_tensor", "test_tensor_operations" ]
2
[ [ "test_tensor_operations", "make_tensor" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
f0ae0ce3722efc11f20be74fe34e5e62f6aafcb5
6cab64026bbb86d8e7faba17d06df6ff12a4066c
v1.0
complete
Docs
Docs: Pytorch_44725_C
import torch import torch.distributed.rpc as rpc from torch.distributed.rpc import RRef def remote_tensor_sum(*tensors): """ Returns the sum of the given tensors. """ pass def distributed_tensor_sum(): """ Sets up the distributed RPC framework, performs the distribution of tensors to worker no...
import torch import torch.distributed.rpc as rpc from torch.distributed.rpc import RRef import os def remote_tensor_sum(*tensors): """ Returns the sum of the given tensors. """ return sum(tensors) def distributed_tensor_sum(): """ Sets up the distributed RPC framework, performs the distributio...
import os import pytest import torch import torch.distributed.rpc as rpc from solution import distributed_tensor_sum def init_rpc_framework(worker_name, rank, world_size): options = rpc.TensorPipeRpcBackendOptions() rpc.init_rpc( worker_name, rank=rank, world_size=world_size, r...
[ { "docstring": "Returns the sum of the given tensors.", "function_declaration": "def remote_tensor_sum(*tensors):", "function_name": "remote_tensor_sum", "parameter_list": "(*tensors)" }, { "docstring": "Sets up the distributed RPC framework, performs the distribution of tensors to worker no...
[ 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\nimport torch.distributed.rpc as rpc\nfrom torch.distributed.rpc import RRef\nimport os\n\ndef remote_tensor_sum(*tensors):\n \"\"\"\n Returns the su...
trial_gpt4o_0
{ "original_instruction": "### PyTorch Distributed RPC and RRef Protocol Implementation\n\n**Objective:**\n\nDesign and implement a function to calculate the sum of tensors located on different workers using PyTorch's distributed RPC and RRef protocol.\n\n**Task:**\n\nYou are required to implement a function `distrib...
0.440462
Docs: Pytorch_44725
C
[ "remote_tensor_sum", "distributed_tensor_sum" ]
2
[ [ "distributed_tensor_sum", "remote_tensor_sum" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
0d9db51795ba584f8e60b8456a74a589056083cc
2b020753c3988d0e4cd602628e85fe6e54b0b6c6
v1.0
complete
Docs
Docs: Python310_44272_C
import requests from multiprocessing import Pool, Manager def fetch_data(url): """ Fetch the HTML content from the provided URL and returns the URL and the content length. >>> fetch_data("http://example.com") ('http://example.com', 1270) """ pass def parallel_scraper(urls, num_workers): """ ...
import requests from multiprocessing import Pool, Manager def fetch_data(url): """ Fetch the HTML content from the provided URL and returns the URL and the content length. """ response = requests.get(url) return url, len(response.content) def parallel_scraper(urls, num_workers): """ Fetch ...
from solution import fetch_data, parallel_scraper import requests def test_fetch_data(monkeypatch): class MockResponse: def __init__(self, content): self.content = content def mock_get(url): return MockResponse(b"Test content") monkeypatch.setattr(requests, "get", mock_get) ...
[ { "docstring": "Fetch the HTML content from the provided URL and returns the URL and the content length.", "function_declaration": "def fetch_data(url):", "function_name": "fetch_data", "parameter_list": "(url)" }, { "docstring": "Fetch data from a list of URLs concurrently using a pool of w...
[ 0, 1, 0, 1, 1, 0, 1, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom multiprocessing import Pool\n\ndef fetch_data(url):\n \"\"\"\n Fetches HTML content from the provided URL.\n\n Parameters:\n url (str)...
trial_gpt4o_1
{ "original_instruction": "### Question: Implementing a Parallel Web Scraper using Python's `multiprocessing` Module\n\nYou are assigned to develop a web scraping utility that extracts data from a list of URLs concurrently. Your solution should leverage Python's `multiprocessing` module for efficiency and scalability...
0.584696
Docs: Python310_44272
C
[ "fetch_data", "parallel_scraper" ]
2
[ [ "parallel_scraper", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
75745b2af4b892dce137efc423a1b601f25b0ddf
b0addfecc3728fa2d9e098bf2afb9ffdcd91439c
v1.0
complete
Docs
Docs: Python310_44766_C
import asyncio async def manage_subprocesses(commands: list[str], timeout: float) -> dict[str, dict[str, str]]: """ Handles multiple asynchronous subprocesses using asyncio. - `commands`: A list of shell commands (strings) to be executed asynchronously. - `timeout`: A float representing the number of secon...
import asyncio import subprocess async def run_command(command, timeout): process = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) try: stdout, stderr = await asyncio.wait_for(process.communicate(), timeo...
import pytest import asyncio from solution import manage_subprocesses @pytest.mark.asyncio async def test_manage_subprocesses_success(): commands = ["echo 'Hello World'", "uname -a"] timeout = 2.0 result = await manage_subprocesses(commands, timeout) assert "echo 'Hello World'" in result assert res...
[]
[ 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 shlex\n\nasync def manage_subprocesses(commands: list[str], timeout: float) -> dict[str, dict[str, str]]:\n async def run_command(command):\n ...
trial_gpt4o_2
{ "original_instruction": "**Coding Assessment Question:**\n\n### Asynchronous Subprocess Manager\n\nYou are tasked with writing a function `manage_subprocesses` that handles multiple asynchronous subprocesses using Python's `asyncio` library. Your function should launch multiple shell commands, process their outputs...
0.655914
Docs: Python310_44766
C
[ "run_command", "manage_subprocesses" ]
2
[ [ "manage_subprocesses", "run_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4963c1894440b85e7adc420768a23aaa08ab5176
c58e6afdadfbdaaf5c479dcead801e44bb408ed1
v1.0
complete
Docs
Docs: Python310_44532_C
import os import pty import logging def master_read(fd, log_file): """Read data from the master end of the pseudo-terminal and log the output.""" data = os.read(fd, 1024) if data: log_file.write(data.decode()) log_file.flush() return data def stdin_read(fd, log_file): """Read data ...
import os import pty import logging def master_read(fd, log_file): data = os.read(fd, 1024) if data: log_file.write(data.decode()) log_file.flush() return data def stdin_read(fd, log_file): data = os.read(fd, 1024) if data: log_file.write(data.decode()) log_file.flu...
import os import subprocess from solution import interactive_shell def test_interactive_shell_execution(): log_filename = 'test_session.log' # Remove log file if it exists if os.path.exists(log_filename): os.remove(log_filename) # Start the interactive shell in a subprocess to make it tes...
[ { "docstring": null, "function_declaration": "def master_read(fd, log_file):", "function_name": "master_read", "parameter_list": "(fd, log_file)" }, { "docstring": null, "function_declaration": "def stdin_read(fd, log_file):", "function_name": "stdin_read", "parameter_list": "(fd...
[ 1, 0, 0, 0, 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 os\nimport pty\nimport sys\n\ndef interactive_shell(log_filename):\n \"\"\"\n Starts an interactive shell session and logs all input commands and their res...
trial_gpt4o_5
{ "original_instruction": "**Question: Implement a Custom Interactive Shell with Logging**\n\n**Objective:**\nCreate a custom interactive shell that mimics a simplified version of the Unix shell. Your shell should be able to execute commands entered by the user interactively and log all input commands and their respe...
0.573983
Docs: Python310_44532
C
[ "master_read", "stdin_read", "interactive_shell" ]
3
[ [ "interactive_shell", "master_read" ], [ "interactive_shell", "stdin_read" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e320f761347df84cc4b649adb981e5f48756d05d
1268f5dbf73d24743692807c25736f8c9b72c746
v1.0
complete
Docs
Docs: Python310_44162_C
import sys import platform import asyncio import selectors async def subprocess_demo(): """ Starts a subprocess and prints its PID and output. """ process = await asyncio.create_subprocess_exec( 'python', '--version', stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) ...
import sys import platform import asyncio import selectors async def subprocess_demo(): process = await asyncio.create_subprocess_exec( 'python', '--version', stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await process.communicate() print...
import platform import asyncio from solution import configure_event_loop, run_demo def test_configure_event_loop(): current_os = platform.system() configure_event_loop() if current_os == 'Windows': current_loop = asyncio.get_event_loop() assert isinstance(current_loop, asyncio.ProactorEvent...
[ { "docstring": null, "function_declaration": "def configure_event_loop():", "function_name": "configure_event_loop", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def run_demo():", "function_name": "run_demo", "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": "import sys\nimport platform\nimport asyncio\nimport selectors\n\nasync def subprocess_demo():\n process = await asyncio.create_subprocess_exec(\n 'python', '-...
trial_gpt4o_4
{ "original_instruction": "### Asynchronous Event Loop Configuration and Platform-Specific Implementation\n\n#### Problem Statement\n\nYou are tasked with implementing a Python application that needs to run different event loop configurations based on the operating system it is running on. Your application will handl...
0.628616
Docs: Python310_44162
C
[ "subprocess_demo", "server_socket_demo", "configure_event_loop", "run_demo" ]
4
[ [ "run_demo", "configure_event_loop" ], [ "run_demo", "server_socket_demo" ], [ "run_demo", "subprocess_demo" ] ]
3
[]
false
[]
false
pytest
true
[]
true
363641e59c1c4503f9f58d80d356321a74f9aea3
06b6ac33cfec387ca659aba5bf22a55dc4433bde
v1.0
complete
Docs
Docs: Scikit_44616_C
import numpy as np from sklearn.datasets import fetch_openml from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from s...
import numpy as np from sklearn.datasets import fetch_openml from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from s...
import pytest from solution import load_and_preprocess_data, train_and_evaluate def test_load_and_preprocess_data(): X_train, X_test, y_train, y_test = load_and_preprocess_data() assert X_train.shape[0] > 0 assert X_test.shape[0] > 0 assert y_train.shape[0] > 0 assert y_test.shape[0] > 0 a...
[ { "docstring": "Fetches the Mice Protein Expression dataset from OpenML, preprocesses it and returns the preprocessed data.\n\nReturn:\nTuple containing:\n- X_train: Features for training\n- X_test: Features for testing\n- y_train: Labels for training\n- y_test: Labels for testing", "function_declaration": ...
[ 1, 1, 0, 0, 1, 1, 0, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nf...
trial_gpt4o_5
{ "original_instruction": "**Title:** Data Loading and Preprocessing from OpenML with Scikit-Learn\n\n**Objective:** \nThe goal of this task is to assess your understanding of loading datasets from OpenML, handling and preprocessing the data, and implementing a basic machine learning model using scikit-learn.\n\n**P...
0.704943
Docs: Scikit_44616
C
[ "load_and_preprocess_data", "train_and_evaluate" ]
2
[ [ "train_and_evaluate", "load_and_preprocess_data" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
bfc5d74de809aeb061e1e5149ea676e718da2731
4f3862ab87e061d9ab02066b62cf4768bba592d6
v1.0
complete
Docs
Docs: Python310_44613_C
import os import json from optparse import OptionParser TODO_TEMPLATE = { "tasks": [] } def load_todo_list(filename): pass def save_todo_list(filename, todo_list): pass def add_task(filename, task_desc, verbose): """ Add a new task to the to-do list. >>> add_task('todo_list.json', 'Read a book',...
import os import json from optparse import OptionParser TODO_TEMPLATE = { "tasks": [] } def load_todo_list(filename): if not os.path.isfile(filename): with open(filename, 'w') as f: json.dump(TODO_TEMPLATE, f) with open(filename, 'r') as f: return json.load(f) def save_todo_li...
import os import pytest from solution import add_task, list_tasks, mark_as_complete, remove_task, load_todo_list, save_todo_list TEST_FILE = 'test_todo_list.json' def setup_module(module): """ setup any state specific to the execution of the given module.""" if os.path.isfile(TEST_FILE): os.remove(TES...
[ { "docstring": null, "function_declaration": "def load_todo_list(filename):", "function_name": "load_todo_list", "parameter_list": "(filename)" }, { "docstring": null, "function_declaration": "def save_todo_list(filename, todo_list):", "function_name": "save_todo_list", "paramete...
[ 1, 1, 1, 1, 0, 1, 1, 0, 0, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport json\nfrom optparse import OptionParser\n\nTODO_TEMPLATE = {\n \"tasks\": []\n}\n\ndef load_todo_list(filename):\n if not os.path.isfile(filenam...
trial_gpt4o_0
{ "original_instruction": "#### Objective\n\nDesign a command-line tool using the `optparse` module. This tool is intended to be a utility for managing a simple to-do list stored in a file. The tool should provide various commands to add tasks, list tasks, mark tasks as completed, and remove tasks.\n\n#### Requiremen...
0.546901
Docs: Python310_44613
C
[ "load_todo_list", "save_todo_list", "add_task", "list_tasks", "mark_as_complete", "remove_task", "main" ]
7
[ [ "add_task", "load_todo_list" ], [ "add_task", "save_todo_list" ], [ "list_tasks", "load_todo_list" ], [ "mark_as_complete", "load_todo_list" ], [ "mark_as_complete", "save_todo_list" ], [ "remove_task", "load_todo_list" ], [ "remove_task"...
7
[]
false
[]
false
pytest
true
[]
true
1b89c9e9d0e681098af88ef386b9ea90cdd0748b
cfb7403bde7f166f2aac6f4ef381687cd1cb3c50
v1.0
complete
Docs
Docs: Python310_44269_C
import types def is_function(obj): """ Check if the object is a function. >>> is_function(lambda x: x) == True >>> is_function(42) == False >>> is_function("not a function") == False """ def create_function(code_obj, globals_dict, qualname=None): """ Create a new function object gi...
import types def is_function(obj): """ Check if the object is a function. """ return isinstance(obj, types.FunctionType) def create_function(code_obj, globals_dict, qualname=None): """ Create a new function object given a code object, globals dictionary, and optionally, a qualified name. ...
import pytest import types from solution import is_function, create_function, get_function_details, set_function_defaults, set_function_annotations def dummy_function(a, b=2): """ A dummy function for testing purposes. """ return a + b def test_is_function(): assert is_function(dummy_function) ==...
[ { "docstring": "Check if the object is a function.", "function_declaration": "def is_function(obj):", "function_name": "is_function", "parameter_list": "(obj)" }, { "docstring": "Create a new function object given a code object, globals dictionary, and optionally,\na qualified name.", "f...
[ 1, 1, 0, 0, 1, 1, 0, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import types\n\ndef is_function(obj):\n \"\"\"\n Check if the given object is a function.\n \"\"\"\n return isinstance(obj, types.FunctionType)\n\ndef creat...
trial_gpt4o_1
{ "original_instruction": "### Function Object Manipulation in Python\n\nUsing the provided functions, your task is to create a set of utility functions in Python using the C API to perform specific operations on Python function objects.\n\nYou will implement the following functions:\n\n1. **is_function(obj)**: Given...
0.715952
Docs: Python310_44269
C
[ "is_function", "create_function", "get_function_details", "set_function_defaults", "set_function_annotations" ]
5
[ [ "get_function_details", "is_function" ], [ "set_function_annotations", "is_function" ], [ "set_function_defaults", "is_function" ] ]
3
[]
false
[]
false
pytest
true
[]
true
1f39d48472a7aa52b682daafbe2434eebf17149f
d3260fe30bb9287adf5ca4aa421d5783eb49fc3d
v1.0
complete
Docs
Docs: Python310_44158_C
from typing import List from threading import Thread from multiprocessing import Process, Queue def split_list(data: List[int], n: int) -> List[List[int]]: """Split the input list `data` into `n` equal parts. If the list cannot be divided equally, distribute the remaining elements. >>> split_list([1, 2, 3, 4, ...
from typing import List from threading import Thread from multiprocessing import Process, Queue def split_list(data: List[int], n: int) -> List[List[int]]: """ Split the input list `data` into `n` equal parts. If the list cannot be divided equally, distribute the remaining elements. """ length = l...
import pytest from solution import split_list, compute_partial_sum, compute_sum_multithreaded, aggregate_sums, concurrent_sum def test_split_list(): assert split_list([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) == [[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert split_list([1, 2, 3, 4, 5, 6], 4) == [[1, 2], [3, 4], [5], [6]] ...
[ { "docstring": "Split the input list `data` into `n` equal parts. If the list cannot be divided \nequally, distribute the remaining elements.", "function_declaration": "def split_list(data, n):", "function_name": "split_list", "parameter_list": "(data, n)" }, { "docstring": "Compute the sum ...
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport threading\nfrom multiprocessing import Process, Queue\n\ndef split_list(data: List[int], n: int) -> List[List[int]]:\n \"\"\"\n Sp...
trial_gpt4o_6
{ "original_instruction": "### Concurrent Data Processing and Synchronization\n\nYou are tasked with creating a system that processes a large dataset concurrently, divides the workload across multiple threads, and uses inter-process communication to aggregate results. This problem will help assess your understanding ...
0.638245
Docs: Python310_44158
C
[ "split_list", "compute_partial_sum", "compute_sum_multithreaded", "aggregate_sums", "concurrent_sum" ]
5
[ [ "compute_sum_multithreaded", "compute_partial_sum" ], [ "compute_sum_multithreaded", "split_list" ], [ "concurrent_sum", "aggregate_sums" ], [ "concurrent_sum", "compute_sum_multithreaded" ] ]
4
[]
false
[]
false
pytest
true
[]
true
68c80b5d48246e8dd42118aa53db0c1e28f83fcf
dd90648eb5cb9d64d5e7464840a1e425d8046850
v1.0
complete
Docs
Docs: Pytorch_44798_C
import torch def create_custom_block_mask(seq_length, block_size): """ Creates a block mask for the given sequence length and block size. Args: seq_length (int): The sequence length. block_size (int): The block size for masking. Returns: Tensor: A block mask for the attention ...
import torch import torch.nn.functional as F def create_custom_block_mask(seq_length, block_size): """ Creates a block mask for the given sequence length and block size. Args: seq_length (int): The sequence length. block_size (int): The block size for masking. Returns: ...
import pytest from solution import custom_multi_head_attention, create_custom_block_mask import torch def test_create_custom_block_mask(): seq_length = 10 block_size = 3 expected_mask = torch.tensor([ [1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0,...
[ { "docstring": "Creates a block mask for the given sequence length and block size.\n\nArgs:\n seq_length (int): The sequence length.\n block_size (int): The block size for masking.\n\nReturns:\n Tensor: A block mask for the attention mechanism.", "function_declaration": "def create_custom_block_mas...
[ 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\nimport torch.nn.functional as F\n\ndef create_custom_block_mask(seq_length, block_size):\n \"\"\"\n Creates a block mask for the given sequence leng...
trial_gpt4o_0
{ "original_instruction": "### Custom Attention Mechanism with Block Masking\n\n**Objective:**\n\nImplement a custom multi-head attention mechanism using PyTorch's `flex_attention` module and its block mask utilities. This question is intended to test your understanding of both fundamental and advanced concepts of Py...
0.493356
Docs: Pytorch_44798
C
[ "create_custom_block_mask", "custom_multi_head_attention" ]
2
[ [ "custom_multi_head_attention", "create_custom_block_mask" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
4be3448940726e63f76954261e4e0ee520b14b74
f37febe486e45b1fbfd9a2aa5be34b14b9be3e83
v1.0
complete
Docs
Docs: Python310_44590_C
c #include <Python.h> #include <stdlib.h> // Logger function for tracking allocator actions void log_action(const char* action) { printf("%s\n", action); } // Implement custom allocator functions void* my_malloc(void* ctx, size_t size) { log_action("Allocating memory"); return malloc(size); } void* my_ca...
import ctypes import logging # Configuration to output logs to the console logging.basicConfig(level=logging.DEBUG, format='%(message)s') class MyAllocator: @staticmethod def malloc(size): logging.info("Allocating memory") return ctypes.create_string_buffer(size) @staticmethod def...
from solution import set_custom_allocator, reset_allocator, custom_allocate, custom_reallocate, custom_free, test_custom_allocator def test_set_custom_allocator(): set_custom_allocator() # No outputs, just ensure no exceptions def test_reset_allocator(): reset_allocator() # No outputs, just ensure...
[]
[ 0, 0, 0, 0, 0, 0, 1, 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 ctypes\nimport logging\n\n# Set up logging\nlogging.basicConfig(level=logging.DEBUG, format='%(message)s')\nlogger = logging.getLogger(__name__)\n\nclass MyAlloc...
trial_gpt4o_9
{ "original_instruction": "### Memory Management with Python and C API\n\n#### Objective:\nYour task is to simulate a basic custom memory allocation setup using Python's memory management C API calls described in the provided documentation.\n\n#### Problem Statement:\nYou need to implement a Python extension that cre...
0.401394
Docs: Python310_44590
C
[ "set_custom_allocator", "reset_allocator", "custom_allocate", "custom_reallocate", "custom_free", "test_custom_allocator" ]
6
[ [ "test_custom_allocator", "custom_allocate" ], [ "test_custom_allocator", "custom_free" ], [ "test_custom_allocator", "custom_reallocate" ], [ "test_custom_allocator", "reset_allocator" ], [ "test_custom_allocator", "set_custom_allocator" ] ]
5
[]
false
[ "MyAllocator" ]
true
pytest
true
[]
true
ba2bf7b080c33db3ae1d9f738aed7dd8856ceaa5
048bc7b6d7d80927e3cce6e14eede6e2be34f389
v1.0
complete
Docs
Docs: Python310_44914_C
import asyncio import contextvars # Define client configuration context variable client_config = contextvars.ContextVar('client_config', default=None) def set_client_config(config: dict) -> None: """ Set the client's configuration. """ client_config.set(config) def get_client_config() -> dict: """ Get th...
import asyncio import contextvars # Define client configuration context variable client_config = contextvars.ContextVar('client_config', default=None) def set_client_config(config: dict) -> None: """Set the client's configuration.""" client_config.set(config) def get_client_config() -> dict: """Get the c...
import pytest from solution import set_client_config, get_client_config import contextvars def test_set_and_get_client_config(): config = {'test_key': 'test_value'} set_client_config(config) assert get_client_config() == config def test_get_client_config_default(): client_config = contextvars.Context...
[ { "docstring": "Set the client's configuration.", "function_declaration": "def set_client_config(config):", "function_name": "set_client_config", "parameter_list": "(config)" }, { "docstring": "Get the client's current configuration.", "function_declaration": "def get_client_config():", ...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\n\n# Define client configuration context variable\nclient_config = contextvars.ContextVar('client_config')\n\ndef set_client_config(c...
trial_gpt4o_1
{ "original_instruction": "#### Objective:\nTo assess your understanding of the `contextvars` package in Python, you will implement a function that manages context-specific configurations in an asynchronous web server setting.\n\n#### Problem Statement:\nYou are required to implement an asynchronous web server using ...
0.550943
Docs: Python310_44914
C
[ "set_client_config", "get_client_config", "handle_request", "main" ]
4
[ [ "handle_request", "get_client_config" ], [ "handle_request", "set_client_config" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3e71d25b8a6766a2aa20aad11ac740148e56573d
d4556963fa7cc3311d00cc232d8eb1d983992bb2
v1.0
complete
Docs
Docs: Python310_45009_C
import signal import threading import time import os def setup_signal_handlers(): """ Set up signal handlers for SIGINT, SIGTERM, and SIGALRM. - SIGINT: Print "SIGINT received!" and raise a KeyboardInterrupt. - SIGTERM: Print "SIGTERM received!" and terminate the program gracefully. - SIGALRM: Print "S...
import signal import threading import time import os def sigint_handler(signum, frame): print("SIGINT received!") raise KeyboardInterrupt def sigterm_handler(signum, frame): print("SIGTERM received!") os._exit(0) def sigalrm_handler(signum, frame): print("SIGALRM received!") def setup_signal_han...
import signal import os import pytest from solution import setup_signal_handlers, timer_signal def test_setup_signal_handlers(monkeypatch): def mock_sigint_handler(signum, frame): print("Mock SIGINT received!") def mock_sigterm_handler(signum, frame): print("Mock SIGTERM received!") ...
[ { "docstring": null, "function_declaration": "def sigint_handler(signum, frame):", "function_name": "sigint_handler", "parameter_list": "(signum, frame)" }, { "docstring": null, "function_declaration": "def sigterm_handler(signum, frame):", "function_name": "sigterm_handler", "pa...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import signal\nimport threading\nimport time\nimport os\n\ndef sigint_handler(signum, frame):\n print(\"SIGINT received!\")\n raise KeyboardInterrupt\n\ndef sigte...
trial_gpt4o_0
{ "original_instruction": "#### Objective:\nCreate a Python program that utilizes the `signal` module to manage timed events and demonstrates proper handling of multiple signals in a multi-threaded context.\n\n#### Problem Statement:\nYou are required to implement a function `setup_signal_handlers()` that sets up cus...
0.618886
Docs: Python310_45009
C
[ "sigint_handler", "sigterm_handler", "sigalrm_handler", "setup_signal_handlers", "timer_signal" ]
5
[ [ "setup_signal_handlers", "sigalrm_handler" ], [ "setup_signal_handlers", "sigint_handler" ], [ "setup_signal_handlers", "sigterm_handler" ] ]
3
[]
false
[]
false
pytest
true
[]
true
3af88b9f57c0c4ce3e8e36579c3149d597b845e6
fe8c7ce9e8aeff869bf67e5edca19443e8ae250f
v1.0
complete
Docs
Docs: Python310_44553_C
import contextvars def initialize_session(session_id: str, data: dict) -> None: """Initializes a new session with a given session ID and associated data.""" pass def get_session_data(session_id: str) -> dict: """Retrieves the current data associated with the session of the given session ID. If the se...
import contextvars # Creating a context variable to store session data session_data = contextvars.ContextVar("session_data", default={}) def initialize_session(session_id, data): """Initializes a new session with given session ID and associated data""" current_data = session_data.get() current_data[sessio...
import pytest from solution import (initialize_session_track_initial as initialize_session, get_session_data, update_session_data, reset_session_data) def test_initialize_session(): initialize_session("session1", {"user": "Alice", "role": "admin"...
[ { "docstring": "Initializes a new session with given session ID and associated data", "function_declaration": "def initialize_session(session_id, data):", "function_name": "initialize_session", "parameter_list": "(session_id, data)" }, { "docstring": "Retrieves the data associated with the g...
[ 0, 1, 1, 0, 0, 0, 1, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextvars\n\n# Context variable to store all session data\nsessions = contextvars.ContextVar('sessions', default={})\n\ndef initialize_session(session_id, data...
trial_gpt4o_6
{ "original_instruction": "**Advanced Python Task: Context Management with `contextvars`**\n\n**Problem Statement:**\n\nYou are to implement a Python module that manages user session data using the `contextvars` module. This module should allow storing, retrieving, and resetting user-specific session data in a thread...
0.404001
Docs: Python310_44553
C
[ "initialize_session", "get_session_data", "update_session_data", "reset_session_data", "initialize_session_track_initial" ]
5
[ [ "initialize_session_track_initial", "initialize_session" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d721c8b33fe9cd0b0f47720877039ec8d9abc726
5504effed86010f8cbd1a87169c288ee55aca036
v1.0
complete
Docs
Docs: Python310_44542_C
from typing import List, Dict, Union, AsyncGenerator import asyncio def read_transactions(transactions: List[Dict[str, Union[int, float]]]) -> List[Dict[str, Union[int, float]]]: """ Given a list of transactions, filter out the transactions where the amount is negative. :param transactions: List of tr...
from typing import List, Dict, Union, AsyncGenerator import asyncio def read_transactions(transactions: List[Dict[str, Union[int, float]]]) -> List[Dict[str, Union[int, float]]]: """ Given a list of transactions, filter out the transactions where the amount is negative. :param transactions: List of tr...
import pytest import asyncio from solution import read_transactions, compute_summary, transaction_generator, process_transactions def test_read_transactions(): transactions = [ {'transaction_id': 1, 'amount': 50.0}, {'transaction_id': 2, 'amount': -20.0}, {'transaction_id': 3, 'amount': 30...
[ { "docstring": "Given a list of transactions, filter out the transactions where the amount is negative.\n\n:param transactions: List of transaction dictionaries.\n:return: List of filtered transactions with non-negative amounts.", "function_declaration": "def read_transactions(transactions):", "function...
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Dict, Union, AsyncGenerator\n\ndef read_transactions(transactions: List[Dict[str, Union[int, float]]]) -> List[Dict[str, Union[int, float]]]:\n...
trial_gpt4o_3
{ "original_instruction": "### Advanced Python Comprehensions and Generators\n\n**Objective:** To assess the student's understanding of Python generator expressions, comprehensions, and their use in combination with asynchronous operations.\n\n**Problem Statement:**\n\nYou are tasked with creating a Python module tha...
0.512192
Docs: Python310_44542
C
[ "read_transactions", "compute_summary", "transaction_generator", "process_transactions" ]
4
[ [ "process_transactions", "transaction_generator" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ae12fb7340609e1eb25a8a4374f4502bcb0a720e
b68b4eca8e0485097e11042301ae7c9bdee756ed
v1.0
complete
Docs
Docs: Python310_44167_C
import hashlib def generate_file_hash(file_path: str, hash_alg: str) -> str: """ Generates the hash digest of a file using the specified hash algorithm. :param file_path: Path to the file :param hash_alg: Hash algorithm to use (md5, sha1, sha256, sha512, blake2b, blake2s) :return: Hexadecimal hash ...
import hashlib def generate_file_hash(file_path: str, hash_alg: str) -> str: """ Generates the hash digest of a file using the specified hash algorithm. :param file_path: Path to the file :param hash_alg: Hash algorithm to use (md5, sha1, sha256, sha512, blake2b, blake2s) :return: Hexadecimal ...
import os import pytest from solution import generate_file_hash, verify_file_integrity # Helper function to create a temporary test file def create_temp_file(filename, content): with open(filename, "w") as f: f.write(content) def test_generate_file_hash_md5(tmpdir): filename = tmpdir.join("testfile.tx...
[ { "docstring": "Generates the hash digest of a file using the specified hash algorithm.\n\n:param file_path: Path to the file\n:param hash_alg: Hash algorithm to use (md5, sha1, sha256, sha512, blake2b, blake2s)\n:return: Hexadecimal hash digest of the file content", "function_declaration": "def generate_fi...
[ 1, 1, 1, 1, 0, 1, 0, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\n\nSUPPORTED_ALGORITHMS = {\n 'md5': hashlib.md5,\n 'sha1': hashlib.sha1,\n 'sha256': hashlib.sha256,\n 'sha512': hashlib.sha512,\n 'blake...
trial_gpt4o_7
{ "original_instruction": "**Secure File Integrity Verifier**\n\nYou are tasked to implement a utility that verifies the integrity of files using secure hash functions. The program should have two parts:\n1. **Hash Generation**: Read a file and generate a hash digest using a specified hash algorithm.\n2. **Hash Verif...
0.689679
Docs: Python310_44167
C
[ "generate_file_hash", "verify_file_integrity" ]
2
[ [ "verify_file_integrity", "generate_file_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2d2757a3e3602c470b06c0c51e8e4a8410c89831
bc23058fe5bb7863c6a4fbef46ed3b22a1ad288d
v1.0
complete
Docs
Docs: Scikit_44600_C
from typing import List, Tuple from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from scipy.sparse import csr_matrix def stream_data(file_path: str, batch_size: int) -> Tuple[List[str], List[str]]: """ Streams data from the file in mini-batches of size 'ba...
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score from scipy.sparse import vstack import numpy as np def stream_data(file_path, batch_size): """ Streams data from the file in mini-batches of size 'batch_size'....
from solution import stream_data, extract_features, train_out_of_core import os def test_stream_data(): test_file_path = 'test_data.txt' with open(test_file_path, 'w') as file: file.write("text_document_1\tcategory_1\n") file.write("text_document_2\tcategory_2\n") file.write("text_docum...
[ { "docstring": "Streams data from the file in mini-batches of size 'batch_size'.\n\nYields tuples of (text data, labels).", "function_declaration": "def stream_data(file_path, batch_size):", "function_name": "stream_data", "parameter_list": "(file_path, batch_size)" }, { "docstring": "Transf...
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_...
trial_gpt4o_4
{ "original_instruction": "### Out-of-Core Learning for Text Classification\n\n#### Objective\nBuild an out-of-core learning system to classify text documents into different categories using scikit-learn. The system will stream data from a file, extract features using a stateless feature extractor, and incrementally ...
0.571299
Docs: Scikit_44600
C
[ "stream_data", "extract_features", "train_out_of_core" ]
3
[ [ "train_out_of_core", "extract_features" ], [ "train_out_of_core", "stream_data" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "scipy", "sklearn" ]
false
173605375aba2195e6c71697451fb449ea3bdcac
785eb358e831a32e5c1f74f93f2bf4d894197b0f
v1.0
complete
Docs
Docs: Seaborn_45080_C
import seaborn as sns import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap from typing import List, Union, Tuple def create_custom_palette(color_list: List[str], as_cmap: bool) -> Union[List[Tuple[float, float, float]], LinearSegmentedColormap]: """ Generates a custom color palette...
import seaborn as sns import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap from typing import List, Union, Tuple def create_custom_palette(color_list: List[str], as_cmap: bool) -> Union[List[Tuple[float, float, float]], LinearSegmentedColormap]: """ Generates a custom color pal...
from solution import create_custom_palette import seaborn as sns from matplotlib.colors import LinearSegmentedColormap def test_create_custom_palette_continuous(): colors = ["#FF5733", "blue", "xkcd:golden"] palette = create_custom_palette(colors, as_cmap=True) assert isinstance(palette, LinearSegmentedCol...
[ { "docstring": "Generates a custom color palette from a list of colors and a boolean indicating whether \nthe output should be a continuous colormap or a discrete palette.\n\n:param color_list: List of colors to blend. Can be named colors, hex codes, or numeric values.\n:param as_cmap: Boolean indicating whethe...
[ 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 seaborn as sns\nimport matplotlib.pyplot as plt\nfrom typing import List, Union, Tuple\nfrom matplotlib.colors import LinearSegmentedColormap, to_rgb\n\ndef crea...
trial_gpt4o_4
{ "original_instruction": "### Seaborn Color Palette Blending\n\n**Objective:**\nAssess your ability to work with color palettes in seaborn by generating and visualizing custom palettes using the `blend_palette` function.\n\n**Problem Statement:**\nYou are tasked with creating a custom color palette and using it to v...
0.732453
Docs: Seaborn_45080
C
[ "create_custom_palette", "plot_heatmap_with_custom_palette" ]
2
[ [ "plot_heatmap_with_custom_palette", "create_custom_palette" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn" ]
false
31a742f4db0120ad828abdb230145d085b08db59
02eeb7c55bdc095b2068aa461138465ab543bcb2
v1.0
complete
Docs
Docs: Python310_44300_C
import logging class ContextFilter(logging.Filter): """ Custom filter to add user context to log records. """ def __init__(self, user): super().__init__() self.user = user def filter(self, record): record.user = self.user return True def setup_logging(): """ Set up...
import logging class ContextFilter(logging.Filter): def __init__(self, user): super().__init__() self.user = user def filter(self, record): record.user = self.user return True def setup_logging(): user = "test_user" # assuming user is predefined # Creating and co...
import pytest import os import logging from solution import setup_logging, log_messages, ContextFilter def test_logging_system(): # Set up loggers app_logger, audit_logger = setup_logging() # Ensure loggers are configured correctly assert app_logger.level == logging.DEBUG assert audit_logger.l...
[]
[ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import logging\n\nclass ContextFilter(logging.Filter):\n def __init__(self, user):\n super().__init__()\n self.user = user\n\n def filter(self, reco...
trial_gpt4o_3
{ "original_instruction": "### Complex Logging Configuration and Custom Filtering\n\n**Objective:**\nImplement a structured logging system using the Python logging module. The logging configuration should demonstrate the ability to:\n1. Set up multiple loggers with different logging levels.\n2. Create custom handlers...
0.576056
Docs: Python310_44300
C
[ "setup_logging", "log_messages" ]
2
[ [ "log_messages", "setup_logging" ] ]
1
[]
false
[ "ContextFilter" ]
true
pytest
true
[]
true
8012d1a70c8d47b0ef1bdc8d276804bd9f69f0d5
aca09bbe59466e5a0fa699daed80e9f7922afc6e
v1.0
complete
Docs
Docs: Pytorch_45182_C
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from typing import List # Define the neural network architecture class SimpleNet(nn.Module): def __init__(self): super(SimpleNet, self).__init__() self.fc1 = nn.Linear(10, 50) self.fc2 = n...
import torch import torch.nn as nn import torch.optim as optim from torch.distributed import init_process_group, destroy_process_group from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import DataLoader, DistributedSampler from torch.multiprocessing import Process class SimpleNet(nn.Mo...
import pytest import torch from solution import distributed_train, SimpleNet class RandomDataset(torch.utils.data.Dataset): def __init__(self, size): self.data = torch.rand(size, 10) self.labels = torch.rand(size, 1) def __len__(self): return len(self.data) def __getitem__(self, i...
[]
[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torch.nn.parallel import Di...
trial_gpt4o_5
{ "original_instruction": "### Distributed Training with PyTorch Multiprocessing\n\n**Objective:**\nImplement a distributed training setup for a simple neural network using PyTorch's `torch.distributed.elastic.multiprocessing` module. The goal is to understand how to manage multiple worker processes and synchronize t...
0.659776
Docs: Pytorch_45182
C
[ "setup", "cleanup", "train", "distributed_train" ]
4
[ [ "train", "cleanup" ], [ "train", "setup" ] ]
2
[]
false
[ "SimpleNet" ]
true
pytest
true
[ "torch" ]
false
7e399d24adb08c99a3e226460389c757802d1ec3
6a64de4ca95e2d6348ff89e41b026c75f901dfba
v1.0
complete
Docs
Docs: Scikit_44558_C
import numpy as np from sklearn.svm import SVC def manhattan_distance(a, b): """ Compute the Manhattan distance between two vectors. Parameters: a (np.ndarray): 1D array, the first vector. b (np.ndarray): 1D array, the second vector. Returns: float: The Manhattan distance between ...
import numpy as np def manhattan_distance(a, b): """ Compute the Manhattan distance between two vectors. Parameters: a (np.ndarray): 1D array, the first vector. b (np.ndarray): 1D array, the second vector. Returns: float: The Manhattan distance between vectors a and b. """ ...
import numpy as np from solution import manhattan_distance, rbf_kernel, custom_rbf_kernel def test_manhattan_distance(): assert manhattan_distance(np.array([1, 2, 3]), np.array([4, 5, 6])) == 9 assert manhattan_distance(np.array([0, 0]), np.array([0, 0])) == 0 assert manhattan_distance(np.array([1, -1]), n...
[ { "docstring": "Compute the Manhattan distance between two vectors.\n\nParameters:\na (np.ndarray): 1D array, the first vector.\nb (np.ndarray): 1D array, the second vector.\n\nReturns:\nfloat: The Manhattan distance between vectors a and b.", "function_declaration": "def manhattan_distance(a, b):", "fu...
[ 0, 1, 1, 1, 1, 0, 0, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\n\ndef manhattan_distance(a, b):\n \"\"\"\n Compute the Manhattan distance between two vectors.\n \n Parameters:\n a (ndarray): 1D arr...
trial_gpt4o_9
{ "original_instruction": "Implementing Custom Pairwise Metrics and Kernels with Scikit-learn\n\n**Objective:** This task aims to assess your comprehension of pairwise metrics and kernel functions as provided by the `scikit-learn` package. You will implement custom metrics and kernels and then utilize them in a small...
0.520565
Docs: Scikit_44558
C
[ "manhattan_distance", "rbf_kernel", "custom_rbf_kernel" ]
3
[ [ "custom_rbf_kernel", "rbf_kernel" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
653bfce555be8d110d11f971045a974b18308feb
12da5883d92e4dc7a5c99b53e38f9cd7c3474d4d
v1.0
complete
Docs
Docs: Python310_44309_C
import csv def parse_csv(file_name: str, delimiter: str, quotechar: str, quoting: int, has_header: bool): """ Parses a CSV file and returns the data in structured format. Parameters: - file_name (string): The name of the CSV file. - delimiter (char): The character that separates fields in the CSV ...
import csv def parse_csv(file_name, delimiter, quotechar, quoting, has_header): """ Parses a CSV file and returns the data in structured format. Parameters: - file_name (string): The name of the CSV file. - delimiter (char): The character that separates fields in the CSV file. - quotechar ...
import pytest import csv from solution import parse_csv, merge_csv def create_test_file(file_name, content): with open(file_name, mode='w', newline='', encoding='utf-8') as file: file.write(content) def test_parse_csv_with_header(): content = 'name,age\nAlice,30\nBob,25\n' create_test_file('test_w...
[ { "docstring": "Parses a CSV file and returns the data in structured format.\n\nParameters:\n- file_name (string): The name of the CSV file.\n- delimiter (char): The character that separates fields in the CSV file.\n- quotechar (char): The character used to quote fields containing special characters.\n- quoting...
[ 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def parse_csv(file_name, delimiter, quotechar, quoting, has_header):\n import csv\n result = []\n try:\n with open(file_name, mode='r', newline='', enco...
trial_gpt4o_6
{ "original_instruction": "**Problem Statement:**\n\nYou are given a set of CSV files that hold information about books in a library. Each file has a different structure, and they all come from different sources. Your task is to:\n\n1. Create a function `parse_csv(file_name, delimiter, quotechar, quoting, has_header)...
0.730236
Docs: Python310_44309
C
[ "parse_csv", "merge_csv" ]
2
[ [ "merge_csv", "parse_csv" ] ]
1
[]
false
[]
false
pytest
true
[]
true
95105975488b8af855b97cdadf1c089d3be7cd0a
096dd3c30d9de63175b7a86c70334c8b4c5e8733
v1.0
complete
Docs
Docs: Python310_45188_C
import warnings def deprecated_function(): """ Function that issues a DeprecationWarning. """ # Implement issuing of DeprecationWarning pass def test_warnings(): """ Function that calls deprecated_function with warnings suppressed. """ # Implement warnings suppression here pass...
import warnings def deprecated_function(): """ Function that issues a DeprecationWarning. """ warnings.warn("deprecated_function is deprecated", DeprecationWarning) def test_warnings(): """ Function that calls deprecated_function with warnings suppressed. """ with warnings.catch_warnin...
import warnings import pytest from solution import deprecated_function, test_warnings, configure_warning_filters def test_deprecated_function_issues_warning(): with pytest.warns(DeprecationWarning, match="deprecated_function is deprecated"): deprecated_function() def test_deprecated_function_suppressed_wa...
[ { "docstring": "Function that issues a DeprecationWarning.", "function_declaration": "def deprecated_function():", "function_name": "deprecated_function", "parameter_list": "()" }, { "docstring": "Function that calls deprecated_function with warnings suppressed.", "function_declaration":...
[ 1, 0, 1, 0, 0, 1, 1, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import warnings\n\ndef deprecated_function():\n \"\"\"\n Function that issues a DeprecationWarning.\n \"\"\"\n warnings.warn(\"deprecated_function is deprec...
trial_gpt4o_0
{ "original_instruction": "**Question: Handling and Filtering Warnings**\n\nYou are tasked with developing components of a Python library that makes extensive use of deprecated features. To manage this, you need to implement functions that issue and handle warnings in various scenarios. \n\n**Objective:**\n\n1. Imple...
0.451104
Docs: Python310_45188
C
[ "deprecated_function", "test_warnings", "configure_warning_filters" ]
3
[ [ "test_warnings", "deprecated_function" ] ]
1
[]
false
[]
false
pytest
true
[]
true
73c698310fb2a70c01db7bbca30d386a7dc060e4
cf01f971d1089517d75bc8a8c95a465c59f5621d
v1.0
complete
Docs
Docs: Scikit_45247_C
def stream_text_data(file_path: str, batch_size: int): """ Streams text data from a file in batches. Parameters: - file_path: str, path to the text file. - batch_size: int, number of lines to yield per batch. Yields: - List of text documents (each document is a string). """ ...
def stream_text_data(file_path: str, batch_size: int): """ Streams text data from a file in batches. Parameters: - file_path: str, path to the text file. - batch_size: int, number of lines to yield per batch. Yields: - List of text documents (each document is a string). """ ...
import os import pytest from solution import stream_text_data, train_incremental_classifier # Helper function to create a temporary test file def create_test_file(file_path, content): with open(file_path, 'w') as file: file.write(content) # Define test file content test_content = """sports Soccer game in ...
[ { "docstring": "Streams text data from a file in batches.\n\nParameters:\n- file_path: str, path to the text file.\n- batch_size: int, number of lines to yield per batch.\n\nYields:\n- List of text documents (each document is a string).", "function_declaration": "def stream_text_data(file_path, batch_size):...
[ 1, 1, 1, 1, 1, 0, 0, 0, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def stream_text_data(file_path: str, batch_size: int):\n \"\"\"\n Streams text data from a file in batches.\n \n Parameters:\n - file_path: str, path t...
trial_gpt4o_8
{ "original_instruction": "## Coding Assessment Question\n\n### Objective\nDesign and implement a simple out-of-core learning system to classify text documents using scikit-learn. You will need to:\n1. Stream instances from a large text dataset.\n2. Extract features using a vectorization technique.\n3. Train an incre...
0.495966
Docs: Scikit_45247
C
[ "stream_text_data", "train_incremental_classifier" ]
2
[ [ "train_incremental_classifier", "stream_text_data" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
2294d9d9b7101dfa4a71959e9b2a5135e4b374b9
43fbc803dcd65a00561d0d3f5bfda46c69f53570
v1.0
complete
Docs
Docs: Scikit_45370_C
import numpy as np from sklearn.datasets import load_iris from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline from joblib import Parallel, delayed def simple_pipeline(): """ Implement a simple pipeline that loads the Iris da...
import numpy as np from sklearn.datasets import load_iris from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline def simple_pipeline(): # Load the Iris dataset data = load_iris() X, y = data.data, data.target # Crea...
def test_simple_pipeline(): pipeline = simple_pipeline() assert pipeline is not None def test_optimized_pipeline(): pipeline = optimized_pipeline() assert pipeline is not None def test_parallel_pipeline(): knn = parallel_pipeline() assert knn is not None def test_parallel_pipeline_correctness...
[ { "docstring": null, "function_declaration": "def simple_pipeline():", "function_name": "simple_pipeline", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def profile_pipeline():", "function_name": "profile_pipeline", "parameter_list": "()" }, { "d...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom s...
trial_gpt4o_0
{ "original_instruction": "In this assignment, you will implement, profile, and optimize a simple machine learning pipeline using scikit-learn, and then transform it into a parallelized version. The task will test your understanding of Python, Numpy, Cython, and joblib. You should follow the steps outlined below:\n\n...
0.494256
Docs: Scikit_45370
C
[ "simple_pipeline", "profile_pipeline", "optimized_pipeline", "parallel_fit_knn", "parallel_pipeline" ]
5
[ [ "parallel_pipeline", "parallel_fit_knn" ], [ "profile_pipeline", "simple_pipeline" ] ]
2
[]
false
[]
false
pytest
false
[ "joblib", "numpy", "sklearn" ]
false
b6a9d0e8e17c694480d9d36f419df36dae549790
75241348a42db40af85bb68f0cf366b50becb50a
v1.0
complete
Docs
Docs: Python310_45499_C
import asyncio import random async def async_task_manager(num_tasks: int): """ Creates and manages multiple asynchronous tasks. Parameters: - num_tasks (int): The number of tasks to create and manage. Returns: - None >>> asyncio.run(async_task_manager(5)) >>> asyncio.run(async_ta...
import asyncio import random import logging # Configure logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) async def dummy_task(task_id, lock): sleep_time = random.uniform(0.1, 2.0) try: async with lock: logger.debug(f"Task {task_id} acquired the lock.") ...
import pytest import asyncio from solution import async_task_manager @pytest.mark.asyncio async def test_async_task_manager(): await async_task_manager(5) @pytest.mark.asyncio async def test_async_task_manager_ten_tasks(): await async_task_manager(10) @pytest.mark.asyncio async def test_async_task_manager_ze...
[]
[ 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\n\nasync def worker(lock, queue):\n while True:\n priority, task_id = await queue.get()\n try:\n with await lo...
trial_gpt4o_3
{ "original_instruction": "### Advanced Python Coding Assessment \n\n**Objective:** Demonstrate your understanding of the asyncio package in Python 3.10 by implementing an asynchronous task manager that orchestrates multiple tasks with various asyncio features.\n\n### Problem Statement\n\nYou are tasked with creating...
0.535989
Docs: Python310_45499
C
[ "dummy_task", "worker", "async_task_manager" ]
3
[ [ "async_task_manager", "worker" ], [ "worker", "dummy_task" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ff43e7d01819d4b3ac40136ef549f431b4155a80
bf7b9674eb74829ee4ebe7f9588f38da2992f9f8
v1.0
complete
Docs
Docs: Scikit_44893_C
import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import KernelDensity # Generating sample data np.random.seed(0) X = np.concatenate([ np.random.normal(loc=-1.0, scale=0.5, size=(100, 2)), np.random.normal(loc=2.0, scale=0.5, size=(100, 2)) ]) def plot_kde(X, kde, ax): """ Plot the...
import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import KernelDensity # Generating sample data np.random.seed(0) X = np.concatenate([ np.random.normal(loc=-1.0, scale=0.5, size=(100, 2)), np.random.normal(loc=2.0, scale=0.5, size=(100, 2)) ]) def plot_kde(X, kde, ax): x = np.linsp...
def test_kde(): from sklearn.neighbors import KernelDensity import numpy as np np.random.seed(0) X = np.concatenate([ np.random.normal(loc=-1.0, scale=0.5, size=(100, 2)), np.random.normal(loc=2.0, scale=0.5, size=(100, 2)) ]) kernels = ['gaussian', 'tophat', 'epanechnikov', '...
[ { "docstring": null, "function_declaration": "def plot_kde(X, kde, ax):", "function_name": "plot_kde", "parameter_list": "(X, kde, ax)" }, { "docstring": null, "function_declaration": "def analyze_kde(X, kernels, bandwidths):", "function_name": "analyze_kde", "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.neighbors import KernelDensity\n\n# Given dataset\nnp.random.seed(0)\nX = np.concatenate([\n np.ran...
trial_gpt4o_2
{ "original_instruction": "### Question: Kernel Density Estimation with Different Kernels\n\n#### Background\nKernel Density Estimation (KDE) is a non-parametric way to estimate the probability density function of a random variable. It smoothens the data points by considering each point as a kernel. This technique is...
0.554267
Docs: Scikit_44893
C
[ "plot_kde", "analyze_kde" ]
2
[ [ "analyze_kde", "plot_kde" ] ]
1
[]
false
[]
false
pytest
false
[ "matplotlib", "numpy", "sklearn" ]
false
25d7c33a00387039076d3904a375ceeafff49e9e
cd51d571677a1f0ab7ae2a621c290f99d800d6aa
v1.0
complete
Docs
Docs: Python310_45629_C
import socket import threading import struct import time from select import select def handle_client(client_socket): """ Handles client connections and processes commands sent by the client. """ pass def recvall(sock, n): """ Receives n bytes from the socket. """ pass def send_message(client_socket, ...
import socket import threading import struct import time from select import select def handle_client(client_socket): while True: try: # Read message length (4 bytes) raw_msglen = recvall(client_socket, 4) if not raw_msglen: break msglen = stru...
from solution import server, client import threading import time # Automatically run the server and client to test the interaction def test_server_client_interaction(): server_thread = threading.Thread(target=server) server_thread.start() time.sleep(1) # Allow the server to start client_thread = thre...
[ { "docstring": null, "function_declaration": "def handle_client(client_socket):", "function_name": "handle_client", "parameter_list": "(client_socket)" }, { "docstring": null, "function_declaration": "def recvall(sock, n):", "function_name": "recvall", "parameter_list": "(sock, n...
[ 1, 0, 0, 0, 0, 0, 1, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "# Server Code\nimport socket\nimport threading\nimport select\nimport struct\nfrom datetime import datetime\n\ndef handle_client(client_socket):\n try:\n clie...
trial_gpt4o_9
{ "original_instruction": "#### Objective:\nTo assess the student's understanding of socket programming in Python, including creating client and server sockets, handling blocking and non-blocking communication, and ensuring proper data transmission and reception.\n\n#### Description:\nYou are to implement a simple cl...
0.764552
Docs: Python310_45629
C
[ "handle_client", "recvall", "send_message", "server", "client" ]
5
[ [ "client", "recvall" ], [ "client", "send_message" ], [ "handle_client", "recvall" ], [ "handle_client", "send_message" ], [ "server", "handle_client" ] ]
5
[]
false
[]
false
pytest
true
[]
true
3fa9eb609c57b98e25f0b8f2bad1b2dcbbf0815d
6db58e694ff3c48dd88b9abf8dc3979f444c7ff5
v1.0
complete
Docs
Docs: Scikit_45277_C
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction import DictVectorizer, FeatureHasher from scipy.sparse import hstack def extract_text_features(reviews): """ Extract TF-IDF features from a list of reviews. Args: reviews (list): List of review strings. ...
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction import DictVectorizer, FeatureHasher import numpy as np from scipy.sparse import hstack def extract_text_features(reviews): """ Extract TF-IDF features from a list of reviews. """ vectorizer = TfidfVectorizer() ...
from solution import extract_text_features, extract_categorical_features, apply_feature_hashing, preprocess_data import numpy as np def test_extract_text_features(): reviews = [ "The product quality is excellent. Highly recommend!", "Not satisfied with the product. Battery life is too short.", ...
[ { "docstring": "Extract TF-IDF features from a list of reviews.", "function_declaration": "def extract_text_features(reviews):", "function_name": "extract_text_features", "parameter_list": "(reviews)" }, { "docstring": "Extract one-hot encoded features from categorical data and numerical fea...
[ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.feature_extraction import FeatureHasher...
trial_gpt4o_9
{ "original_instruction": "**Question: Feature Extraction and Transformation with Scikit**\n\nYou are tasked with building a preprocessing pipeline for a machine learning model that can handle a mixed dataset consisting of both text and structured categorical and numerical data. The goal is to transform the input dat...
0.668477
Docs: Scikit_45277
C
[ "extract_text_features", "extract_categorical_features", "apply_feature_hashing", "preprocess_data" ]
4
[ [ "preprocess_data", "apply_feature_hashing" ], [ "preprocess_data", "extract_categorical_features" ], [ "preprocess_data", "extract_text_features" ] ]
3
[]
false
[]
false
pytest
true
[ "numpy", "scipy", "sklearn" ]
false
6fbe13aad8b06e72df8464f3db8d3ebfd0ae235f
688d0f8c53c52cf267b718b366b8143790a9f32f
v1.0
complete
Docs
Docs: Python310_45531_C
import asyncio from typing import List, Tuple async def fetch_data_concurrently(urls: List[str]) -> List[Tuple[str, str]]: """Fetch the content of each URL concurrently using asyncio. Args: urls: List of URLs to fetch data from. Returns: A list of tuples, where each tuple contains...
import aiohttp import asyncio from typing import List, Tuple async def fetch_content(session, url): try: async with session.get(url) as response: response.raise_for_status() content = await response.text() return url, content[:100] except Exception as e: retu...
import asyncio from solution import fetch_data_concurrently def test_single_url(): urls = ["https://example.com"] result = asyncio.run(fetch_data_concurrently(urls)) assert len(result) == 1 assert result[0][0] == urls[0] assert isinstance(result[0][1], str) assert len(result[0][1]) == 100 or "E...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\nimport aiohttp\n\nasync def fetch_content(session, url):\n try:\n async with session.get(url) as response:\n ...
trial_gpt4o_7
{ "original_instruction": "**Question: Implement an Asynchronous Task Management System**\n\n**Objective:**\nCreate a Python program that manages and executes multiple asynchronous tasks using the asyncio library. The program should be able to perform I/O-bound operations concurrently and synchronize the results.\n\n...
0.529135
Docs: Python310_45531
C
[ "fetch_content", "fetch_data_concurrently" ]
2
[ [ "fetch_data_concurrently", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
d23670a219ea93523e1f3b53f1d2aed336f0e78e
4b06b32f7d9f147ee2abbf7187049b8f39eb34f7
v1.0
complete
Docs
Docs: Python310_45521_C
import os from concurrent.futures import ProcessPoolExecutor from typing import List, Dict def find_files_with_extension(directories: List[str], extension: str) -> Dict[str, List[str]]: """Find files with a specific extension across multiple directories using concurrent processing. Args: directori...
import os from concurrent.futures import ProcessPoolExecutor from typing import List, Dict def search_files_in_directory(directory: str, extension: str) -> List[str]: """ Searches for files with a given extension in the specified directory. """ matching_files = [] for root, _, files in os.walk(dire...
import os import tempfile from solution import find_files_with_extension def create_temp_test_files_structure(): temp_dir = tempfile.TemporaryDirectory() dirs = [tempfile.mkdtemp(dir=temp_dir.name) for _ in range(3)] # Create some test files with open(os.path.join(dirs[0], 'file1.py'), 'w') as f: ...
[ { "docstring": "Searches for files with a given extension in the specified directory.", "function_declaration": "def search_files_in_directory(directory, extension):", "function_name": "search_files_in_directory", "parameter_list": "(directory, extension)" }, { "docstring": "Finds files with...
[ 1, 1, 0, 1, 1, 1, 0, 0, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ProcessPoolExecutor\nimport os\nfrom typing import List, Dict\n\ndef find_files_in_directory(directory: str, extension: str) -> List[str]...
trial_gpt4o_3
{ "original_instruction": "### Asynchronous Filename Search with concurrent.futures\n\nYou are tasked with implementing a function using `concurrent.futures` to improve the performance of searching for files with specific extensions within multiple directories. You should use `ProcessPoolExecutor` for this task to le...
0.604232
Docs: Python310_45521
C
[ "search_files_in_directory", "find_files_with_extension" ]
2
[ [ "find_files_with_extension", "search_files_in_directory" ] ]
1
[]
false
[]
false
pytest
true
[]
true
04e0772943bd3ce9fd6fb5b28fbae7c2dd228a8f
5aa41c690fa3c16c26dc4e9e747e03d051a627f0
v1.0
complete
Docs
Docs: Python310_45699_C
import signal import warnings import asyncio class ResourceWarning(Warning): pass def count_lines(file_path: str) -> int: """ Count the number of lines in a given file. Raises a custom ResourceWarning if the file is not explicitly closed. >>> count_lines('test_file.txt') 3 >>> count_lines('non_exi...
import signal import warnings import asyncio class ResourceWarning(Warning): pass def count_lines(file_path: str) -> int: """ Count the number of lines in a given file. Raises a custom ResourceWarning if the file is not explicitly closed. """ try: with open(file_path, 'r') as file...
import os import signal import asyncio import warnings from solution import count_lines, enable_fault_handlers, enable_asyncio_debug, ResourceWarning def test_count_lines(): test_file = 'test_file.txt' with open(test_file, 'w') as f: f.write("Line 1\nLine 2\nLine 3\n") count = count_lines(test...
[]
[ 0, 0, 1, 1, 0, 0, 1, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport os\nimport warnings\nimport signal\n\nclass ResourceWarning(Exception):\n pass\n\ndef count_lines(file_path: str) -> int:\n \"\"\"\n Thi...
trial_gpt4o_9
{ "original_instruction": "### Question: Implementing Python Development Mode Checks\n\n#### Objective\nYou need to implement Python code that simulates some effects of Python's Development Mode without actually enabling it. The goal is to help understand underlying issues like resource leakage and memory-related pro...
0.560455
Docs: Python310_45699
C
[ "count_lines", "handle_fault", "enable_fault_handlers", "enable_asyncio_debug" ]
4
[ [ "enable_fault_handlers", "handle_fault" ] ]
1
[]
false
[ "ResourceWarning" ]
true
pytest
true
[]
true
b39c7b2923875e51750f7d3814607376a739986d
5c8a41e95bd4d63b18119cd08f34ea9f0bb41ec2
v1.0
complete
Docs
Docs: Python310_45546_C
import asyncio async def handle_client(reader, writer): """ Handle client connections: read a message, echo it back, and append to a file. """ pass async def start_echo_server(): """ Starts the asynchronous echo server on localhost at port 8888. """ pass # Run the server if __name__ =...
import asyncio async def handle_client(reader, writer): """ Handle client connection, read a message, echo it back, and append to a file. """ try: data = await reader.readuntil(b'\n') message = data.decode() # Echo the message back to the client writer.write(data) ...
import asyncio import pytest from solution import handle_client, start_echo_server @pytest.mark.asyncio async def test_handle_client(): reader, writer = await asyncio.open_connection('127.0.0.1', 8888) message = "Hello, World!\n" writer.write(message.encode()) await writer.drain() data = await rea...
[]
[ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n while True:\n data = await reader.readline()\n if not data:\n break\n me...
trial_gpt4o_3
{ "original_instruction": "### Asynchronous Echo Server with Persistence\n\n#### Objective\nDesign and implement an asynchronous TCP echo server using `asyncio` streams that not only echoes back received messages to the sender but also stores each message in a persistent file. \n\n#### Task\n1. Write an asynchronous ...
0.575037
Docs: Python310_45546
C
[ "handle_client", "start_echo_server" ]
2
[ [ "start_echo_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4a8b4ddd670a4704d6073c0557549808bc48bc7d
f07fc78e3118e63d6d284345bcc37d45bfa667d4
v1.0
complete
Docs
Docs: Python310_45453_C
import os import errno from typing import Tuple, Optional, Union # Mapping of errno codes to corresponding exceptions errno_to_exception = { errno.EPERM: PermissionError, errno.ENOENT: FileNotFoundError, errno.ESRCH: ProcessLookupError, errno.EINTR: InterruptedError, errno.EIO: OSError, errno.E...
import os import errno # Mapping of errno codes to corresponding exceptions errno_to_exception = { errno.EPERM: PermissionError, errno.ENOENT: FileNotFoundError, errno.ESRCH: ProcessLookupError, errno.EINTR: InterruptedError, errno.EIO: OSError, errno.ENXIO: OSError, errno.E2BIG: OSError, ...
import pytest import errno from solution import handle_errno_code, raise_based_on_errno def test_handle_errno_code_ep(): exception_class, error_message, error_name = handle_errno_code(errno.EPERM) assert exception_class == PermissionError assert error_message == "Operation not permitted" assert err...
[]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport errno\n\ndef handle_errno_code(errno_code: int) -> tuple:\n \"\"\"\n Takes an integer errno value and returns a tuple containing:\n - The cor...
trial_gpt4o_1
{ "original_instruction": "**Objective:** \nCreate a function that takes an integer errno value as input and returns a tuple containing the corresponding exception class (if any), the error message string, and the string name representation of the error from the `errno.errorcode` dictionary. The function should then ...
0.523959
Docs: Python310_45453
C
[ "handle_errno_code", "raise_based_on_errno" ]
2
[ [ "raise_based_on_errno", "handle_errno_code" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5032024ae79c2eeb34f3b18ba34861243997e69f
579ac85f204091234c350d6c0d72e1a8165f16ac
v1.0
complete
Docs
Docs: Pytorch_45406_C
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP import argparse import random import time import os class SimpleNeuralNetwork(nn.Module): def __init__(self): """ Define a basic neural network model ...
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP import argparse import random import time import os # 1. Define a basic neural network model class SimpleNeuralNetwork(nn.Module): def __init__(self): ...
# As we cannot test a distributed training job in real-time within a unit test framework, we will simulate the unit tests for each component. def test_simple_neural_network(): model = SimpleNeuralNetwork() assert isinstance(model, nn.Module) sample_input = torch.randn(1, 10) sample_output = model(sampl...
[]
[ 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": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nimport...
trial_gpt4o_7
{ "original_instruction": "### PyTorch Distributed Training Setup\n\n**Problem Statement:**\n\nYou are tasked with setting up and managing a distributed training job for a neural network using PyTorch. Your goal is to write a Python script that simulates a distributed training setup. This script should be capable of ...
0.567452
Docs: Pytorch_45406
C
[ "simulate_node_failure", "train", "main" ]
3
[ [ "train", "simulate_node_failure" ] ]
1
[]
false
[ "SimpleNeuralNetwork" ]
true
pytest
false
[ "torch" ]
false
543aacf9958d5b8c9f939f5f695a690e3bab0616
12ee58ba8f82c86f99ad70e88b73ba909a155384
v1.0
complete
Docs
Docs: Pytorch_45396_C
import torch def custom_block_mask(size: tuple, mask_value: float) -> torch.Tensor: """ Creates a block mask of the given size where each block has the specified mask_value. Args: size (tuple): A tuple defining the size of the mask (rows, columns). mask_value (float): The value to be f...
import torch def custom_block_mask(size: tuple, mask_value: float) -> torch.Tensor: """ Creates a block mask of the given size where each block has the specified mask_value. Args: size (tuple): A tuple defining the size of the mask (rows, columns). mask_value (float): The value to be f...
import pytest import torch from solution import custom_block_mask, apply_attention_with_mask def test_custom_block_mask(): mask = custom_block_mask((3, 3), -1.0) expected_mask = torch.tensor([[-1.0, -1.0, -1.0], [-1.0, -1.0, -1.0], [-1.0, -1.0...
[ { "docstring": "Creates a block mask of the given size where each block has the specified mask_value.\n\nArgs:\n size (tuple): A tuple defining the size of the mask (rows, columns).\n mask_value (float): The value to be filled in each block of the mask.\n\nReturns:\n torch.Tensor: The created block mas...
[ 0, 1, 1, 1, 1, 0, 1, 1, 0, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.nn.functional import softmax\n\ndef custom_block_mask(size: tuple, mask_value: float) -> torch.Tensor:\n \"\"\"\n Creates a block mask of...
trial_gpt4o_7
{ "original_instruction": "Custom Block Mask Attention\n\nYour task is to implement a custom attention mechanism using PyTorch's `torch.nn.attention.flex_attention` and related BlockMask utilities. You need to create masks that selectively attenuate specific parts of the input data and apply these masks within the at...
0.477866
Docs: Pytorch_45396
C
[ "custom_block_mask", "apply_attention_with_mask" ]
2
[ [ "apply_attention_with_mask", "custom_block_mask" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
96d105a6adc284d09e26d76655e341780fcdbd08
b0f8c47647b787faaeceb6d914c05a71f522ffc3
v1.0
complete
Docs
Docs: Python310_45918_C
from contextlib import contextmanager def acquire_db_connection(): print("Acquiring connection") return "db_connection" def release_db_connection(conn): print(f"Releasing connection {conn}") def execute_query(conn, query): print(f"Executing query on {conn}: {query}") @contextmanager def DatabaseConn...
from contextlib import contextmanager def acquire_db_connection(): print("Acquiring connection") return "db_connection" def release_db_connection(conn): print(f"Releasing connection {conn}") def execute_query(conn, query): print(f"Executing query on {conn}: {query}") @contextmanager def DatabaseConn...
from solution import DatabaseConnectionManager, execute_query def test_database_connection_manager_normal_execution(capfd): queries = [ "SELECT * FROM users", "UPDATE users SET name = 'Alice' WHERE id = 1" ] with DatabaseConnectionManager() as conn: for query in queries: ...
[ { "docstring": null, "function_declaration": "def acquire_db_connection():", "function_name": "acquire_db_connection", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def release_db_connection(conn):", "function_name": "release_db_connection", "parameter_l...
[ 0, 0, 1, 0, 1, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from contextlib import contextmanager\n\ndef acquire_db_connection():\n print(\"Acquiring connection\")\n return \"db_connection\"\n\ndef release_db_connection(co...
trial_gpt4o_8
{ "original_instruction": "**Context Manager for Resource Management**\n\nIn Python, managing resources (like files, database connections, or network connections) efficiently is crucial to avoid resource leaks. The `contextlib` module provides utilities to simplify the creation and management of such resources using ...
0.402855
Docs: Python310_45918
C
[ "acquire_db_connection", "release_db_connection", "execute_query", "DatabaseConnectionManager" ]
4
[ [ "DatabaseConnectionManager", "acquire_db_connection" ], [ "DatabaseConnectionManager", "release_db_connection" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a3b08f8b9c8de91d82cf5cabbf8482c245d860e0
f94019e6da8dbd511462903d594433cd11776eb7
v1.0
complete
Docs
Docs: Python310_45840_C
import gettext import os def setup_translations(locale_dir: str) -> None: """ Set up the translation functionalities based on the provided locale directory. Parameters: locale_dir (str): The path to the directory containing the translation files. """ pass def get_current_locale(): # F...
import gettext import os def setup_translations(locale_dir: str) -> None: """ Set up the translation functionalities based on the provided locale directory. Parameters: locale_dir (str): The path to the directory containing the translation files. """ locales = ['en', 'fr', 'de'] transl...
import pytest from solution import setup_translations, greet_in_english, greet_in_french, greet_in_german # Setup translations for the tests: @pytest.fixture(scope='module', autouse=True) def setup_trans(): # Assuming a hypothetical path '/path/to/locale' for testing purposes setup_translations('/path/to/local...
[ { "docstring": "Set up the translation functionalities based on the provided locale directory.\n\nParameters:\nlocale_dir (str): The path to the directory containing the translation files.", "function_declaration": "def setup_translations(locale_dir):", "function_name": "setup_translations", "parame...
[ 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 gettext\nimport os\n\ndef setup_translations(locale_dir: str) -> None:\n \"\"\"\n Set up the translation functionalities based on the provided locale direc...
trial_gpt4o_8
{ "original_instruction": "**Internationalize and Localize a Python Application**\n\nYou are required to write a Python function to internationalize and localize a simple application that displays greeting messages in different languages based on user input. The application should support at least three languages: En...
0.477182
Docs: Python310_45840
C
[ "setup_translations", "get_current_locale", "greet_in_english", "greet_in_french", "greet_in_german" ]
5
[ [ "setup_translations", "get_current_locale" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6ff39d7e31f7d8142de4132903a0c97d15528e06
1f1dfba424c67469cc8007c2329e1a088a18ec04
v1.0
complete
Docs
Docs: Python310_45389_C
import hashlib import hmac import os def generate_file_hash(file_path: str) -> str: """ Generates SHA-256 hash for the file content located at file_path. :param file_path: Path to the file. :return: SHA-256 hash of file content in hexadecimal format. """ pass def verify_file_hash(file_pat...
import hashlib import hmac import os def generate_file_hash(file_path: str) -> str: """ Generates SHA-256 hash for the file content located at file_path. :param file_path: Path to the file. :return: SHA-256 hash of file content in hexadecimal format. """ sha256 = hashlib.sha256() try: ...
import tempfile from solution import generate_file_hash, verify_file_hash, generate_hmac, generate_secure_token def test_generate_file_hash(): with tempfile.NamedTemporaryFile(delete=False) as temp_file: temp_file.write(b"Hello, World!") temp_file_path = temp_file.name expected_hash = hashlib.s...
[ { "docstring": "Generates SHA-256 hash for the file content located at file_path.\n\n:param file_path: Path to the file.\n:return: SHA-256 hash of file content in hexadecimal format.", "function_declaration": "def generate_file_hash(file_path):", "function_name": "generate_file_hash", "parameter_lis...
[ 0, 1, 1, 0, 0, 0, 0, 0, 0, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\nimport hmac\nimport os\n\ndef generate_file_hash(file_path):\n \"\"\"\n Generate SHA-256 hash of the given file.\n \"\"\"\n try:\n sh...
trial_gpt4o_1
{ "original_instruction": "**Question: Implementing a Secure File Verification System**\n\n**Objective:**\nYou are asked to implement a secure file verification system using the cryptographic services provided by Python.\n\n**Requirements:**\n\n1. **File Hashing and Integrity Verification:**\n - Implement a functio...
0.738636
Docs: Python310_45389
C
[ "generate_file_hash", "verify_file_hash", "generate_hmac", "generate_secure_token" ]
4
[ [ "verify_file_hash", "generate_file_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d54b0c5697140de78cb893d21b32b77980885cdc
8f79aff1c94337fe754b3ba664234831a7464d89
v1.0
complete
Docs
Docs: Python310_45874_C
import asyncio async def north_south_traffic(lock, event): """ Simulate the north-south traffic light. """ while True: async with lock: if event.is_set(): print("North-South: Green Light") await asyncio.sleep(10) event.clear() ...
import asyncio async def north_south_traffic(lock, event): while True: async with lock: if event.is_set(): print("North-South: Green Light") await asyncio.sleep(10) event.clear() else: print("North-South: Red Light") ...
import asyncio from solution import traffic_light_system async def test_traffic_light_system(): """Test the traffic light system.""" awaitable = asyncio.wait_for(traffic_light_system(), timeout=25) try: await awaitable except asyncio.TimeoutError: pass # Expected def test_traffic_lig...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def north_south_traffic(lock, event):\n while True:\n async with lock:\n if event.is_set():\n print(\"North-...
trial_gpt4o_3
{ "original_instruction": "### AsyncIO Synchronization Primitives - Traffic Light Simulation\n\n#### Objective\nDesign a traffic light system at an intersection using asyncio synchronization primitives to manage the traffic flow. The intersection allows one-way traffic at a time; either north-south or east-west, but ...
0.448166
Docs: Python310_45874
C
[ "north_south_traffic", "east_west_traffic", "traffic_light_system" ]
3
[ [ "traffic_light_system", "east_west_traffic" ], [ "traffic_light_system", "north_south_traffic" ] ]
2
[]
false
[]
false
pytest
true
[]
true
afa81ce05f9c69cab191d678b4dfb47e8c8e1f7c
0fcc0ddec6f419a44e26715822d2d281ba9c7869
v1.0
complete
Docs
Docs: Pytorch_45900_C
import torch import torch.distributed as dist import torch.multiprocessing as mp import torch.nn as nn import torch.optim as optim from torch.nn.parallel import DistributedDataParallel as DDP import os class SimpleNN(nn.Module): def __init__(self): super(SimpleNN, self).__init__() self.fc1 = nn.Lin...
import torch import torch.distributed as dist import torch.multiprocessing as mp import torch.nn as nn import torch.optim as optim from torch.nn.parallel import DistributedDataParallel as DDP import os class SimpleNN(nn.Module): def __init__(self): super(SimpleNN, self).__init__() self.fc1 = nn.Lin...
from solution import generate_dummy_data, SimpleNN import torch def test_generate_dummy_data_shapes(): inputs, labels = generate_dummy_data(20, 10, 10) assert inputs.shape == (20, 10) assert labels.shape == (20, 10) def test_simple_nn_forward_pass(): model = SimpleNN() inputs = torch.randn(20, 10)...
[]
[ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.nn.parallel import Di...
trial_gpt4o_4
{ "original_instruction": "Distributed Data Parallel Training with PyTorch\n\n#### Objective\nImplement a distributed training process using `torch.nn.parallel.DistributedDataParallel` (DDP) to train a simple neural network on a dummy dataset. Demonstrate your understanding of setting up the distributed environment, ...
0.570468
Docs: Pytorch_45900
C
[ "generate_dummy_data", "train", "main" ]
3
[ [ "train", "generate_dummy_data" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
c0608d5c52341215f001c7c940470567dbb3cda5
a3f4e5d903207a306d76910969f80cb12b3fd80d
v1.0
complete
Docs
Docs: Scikit_45838_C
from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm def load_and_split_iris(): """ Load the Iris dataset and split it into training and testing sets. ...
from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm def load_and_split_iris(): """ Load the Iris dataset and split it into training and testing sets. ...
from solution import load_and_split_iris, calculate_k, train_knn, evaluate_model from sklearn.neighbors import KNeighborsClassifier def test_load_and_split_iris(): X_train, X_test, y_train, y_test = load_and_split_iris() assert len(X_train) > 0 assert len(X_test) > 0 assert len(y_train) > 0 assert ...
[ { "docstring": "Load the Iris dataset and split it into training and testing sets.\nReturns X_train, X_test, y_train, y_test.", "function_declaration": "def load_and_split_iris():", "function_name": "load_and_split_iris", "parameter_list": "()" }, { "docstring": "Calculate the number of neig...
[ 0, 1, 0, 0, 1, 0, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nimport numpy as np\nimport matpl...
trial_gpt4o_4
{ "original_instruction": "### Coding Challenge: Nearest Neighbor Classification and Performance Evaluation\n\n**Objective:**\nYour task is to implement a nearest neighbor classifier using scikit-learn and evaluate its performance on a dataset.\n\n**Description:**\n1. Load the Iris dataset provided by scikit-learn.\n...
0.547098
Docs: Scikit_45838
C
[ "load_and_split_iris", "calculate_k", "train_knn", "evaluate_model", "visualize_decision_boundaries", "nearest_neighbor_classification" ]
6
[ [ "nearest_neighbor_classification", "calculate_k" ], [ "nearest_neighbor_classification", "evaluate_model" ], [ "nearest_neighbor_classification", "load_and_split_iris" ], [ "nearest_neighbor_classification", "train_knn" ], [ "nearest_neighbor_classification", ...
5
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "sklearn" ]
false
9ec3a04d2a57b585d135aa094670174a854e15e6
fd4827c25f15256af81184ff2a0931b048696f40
v1.0
complete
Docs
Docs: Seaborn_45835_C
import seaborn as sns import seaborn.objects as so import pandas as pd import numpy as np import matplotlib.pyplot as plt # Load the dataset tips = sns.load_dataset("tips") # Basic scatter plot of total_bill vs tip def basic_scatter_plot(tips): """ Create a basic scatter plot of total_bill versus tip. >>> bas...
import seaborn as sns import seaborn.objects as so import pandas as pd import numpy as np import matplotlib.pyplot as plt # Load the dataset tips = sns.load_dataset("tips") # Basic scatter plot of total_bill vs tip def basic_scatter_plot(tips): plt.figure(figsize=(10, 6)) sns.scatterplot(x='total_bill', y='ti...
import pytest from solution import * def test_basic_scatter_plot(): basic_scatter_plot(tips) # Test if plot is created - "plot should not throw any error" assert True def test_enhanced_scatter_plot(): enhanced_scatter_plot(tips) # Test if plot is created - "plot should not throw any error" ass...
[ { "docstring": null, "function_declaration": "def basic_scatter_plot(tips):", "function_name": "basic_scatter_plot", "parameter_list": "(tips)" }, { "docstring": null, "function_declaration": "def enhanced_scatter_plot(tips):", "function_name": "enhanced_scatter_plot", "parameter...
[ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import seaborn as sns\nimport seaborn.objects as so\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Load the dataset\ntips = sns.load_dat...
trial_gpt4o_0
{ "original_instruction": "#### Context\nYou are provided with a dataset named `tips` which contains information about the total bills, tips, and several attributes like the day of the week, sex of the bill payer, etc. You need to create a series of visualizations to explore this dataset using seaborn.\n\n#### Task\n...
0.753916
Docs: Seaborn_45835
C
[ "basic_scatter_plot", "enhanced_scatter_plot", "colored_scatter_plot", "faceted_scatter_plot", "advanced_plot", "run_all_plots" ]
6
[ [ "run_all_plots", "advanced_plot" ], [ "run_all_plots", "basic_scatter_plot" ], [ "run_all_plots", "colored_scatter_plot" ], [ "run_all_plots", "enhanced_scatter_plot" ], [ "run_all_plots", "faceted_scatter_plot" ] ]
5
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "pandas", "seaborn" ]
false
10f4c3bce31e82e30f722de8d87aeb07c561ec75
a277c852d3c6f911fc8864a8a2c34886ee57936b
v1.0
complete
Docs
Docs: Scikit_45845_C
import numpy as np from sklearn.metrics import mean_squared_error def custom_mse(y_true, y_pred, scale_factor: float) -> float: """ Custom Mean Squared Error metric scaled by a factor. Args: y_true (array-like): True labels. y_pred (array-like): Predicted labels. scale_factor (...
import numpy as np from sklearn.metrics import mean_squared_error def custom_mse(y_true, y_pred, scale_factor: float) -> float: """ Custom Mean Squared Error metric scaled by a factor. Args: y_true (array-like): True labels. y_pred (array-like): Predicted labels. scale_factor (...
from solution import custom_mse, create_custom_scorer import numpy as np from sklearn.metrics import mean_squared_error def test_custom_mse(): y_true = np.array([1.0, 2.0, 3.0]) y_pred = np.array([1.1, 1.9, 3.2]) scale_factor = 2.0 mse = mean_squared_error(y_true, y_pred) assert custom_mse(y_true, ...
[ { "docstring": "Custom Mean Squared Error metric scaled by a factor.\n\nArgs:\n y_true (array-like): True labels.\n y_pred (array-like): Predicted labels.\n scale_factor (float): Factor by which to scale the MSE.\n\nReturns:\n float: Scaled Mean Squared Error.", "function_declaration": "def cust...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.metrics import mean_squared_error, make_scorer\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import cross_val_score\nfrom ...
trial_gpt4o_9
{ "original_instruction": "### Custom Metric and Model Evaluation\n\nIn this task, you'll be required to write a Python function that evaluates a model using a custom metric defined through the `make_scorer` factory in Scikit-learn. You will then apply this custom metric in a cross-validation setup.\n\n#### Problem S...
0.638218
Docs: Scikit_45845
C
[ "custom_mse", "create_custom_scorer", "evaluate_model_with_custom_metric" ]
3
[ [ "create_custom_scorer", "custom_mse" ], [ "evaluate_model_with_custom_metric", "create_custom_scorer" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
6391be6a7502266057b12762500e7e1dafa6cd13
8aca0a8af6b1a3bea52a438ac3364ce0e85f1b18
v1.0
complete
Docs
Docs: Python310_46055_C
import urllib.request import re from urllib.error import URLError, HTTPError def fetch_html(url: str) -> str: """ Takes a URL as input and returns the HTML content of the URL as a string. Raises an exception if the URL cannot be opened. """ # Implement here def extract_urls(html: str) -> list: ...
import urllib.request import re from urllib.error import URLError, HTTPError def fetch_html(url: str) -> str: """ Takes a URL as input and returns the HTML content of the URL as a string. Raises an exception if the URL cannot be opened. """ try: response = urllib.request.urlopen(url) ...
import pytest import urllib.request from unittest.mock import patch, Mock from solution import fetch_html, extract_urls, scrape_urls def mock_urlopen(url): mock_response = Mock() if url == 'http://example.com': mock_response.read.return_value = b'<a href="http://example1.com">Link1</a><a href="http://...
[ { "docstring": "Takes a URL as input and returns the HTML content of the URL as a string.\nRaises an exception if the URL cannot be opened.", "function_declaration": "def fetch_html(url):", "function_name": "fetch_html", "parameter_list": "(url)" }, { "docstring": "Takes HTML content as inpu...
[ 1, 1, 0, 0, 0, 0, 0, 0, 1, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import urllib.request\nimport re\nfrom urllib.error import URLError, HTTPError\n\ndef fetch_html(url: str) -> str:\n \"\"\"\n Takes a URL as input and returns the...
trial_gpt4o_8
{ "original_instruction": "**Question:**\n\nYou are designing a mini web scraper using Python's `urllib.request` module. Your goal is to:\n1. Fetch the HTML content of a given URL.\n2. Extract all the URLs from the fetched HTML content.\n3. Follow one level of links (i.e., fetch the HTML content of the URLs found on ...
0.811075
Docs: Python310_46055
C
[ "fetch_html", "extract_urls", "scrape_urls" ]
3
[ [ "scrape_urls", "extract_urls" ], [ "scrape_urls", "fetch_html" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a01e7117dd8e874e79cffcb40e89e17533c5a0e2
c64afadd2392327d672a971c1a77923adb1a8b26
v1.0
complete
Docs
Docs: Python310_45813_C
import dis from typing import List, Tuple def fibonacci(n): a, b = 0, 1 fib_sequence = [] for _ in range(n): fib_sequence.append(a) a, b = b, a + b return fib_sequence def analyze_fibonacci_bytecode() -> Tuple[List[Tuple[int, str, int, int]], List[str]]: """ Disassemble the giv...
import dis def fibonacci(n): a, b = 0, 1 fib_sequence = [] for _ in range(n): fib_sequence.append(a) a, b = b, a + b return fib_sequence def analyze_fibonacci_bytecode(): # Step 1: Disassemble the function bytecode = dis.Bytecode(fibonacci) # Step 2: Provide detailed a...
from solution import analyze_fibonacci_bytecode def test_analyze_fibonacci_bytecode(): analysis, optimizations = analyze_fibonacci_bytecode() assert isinstance(analysis, list) assert isinstance(optimizations, list) assert all(isinstance(item, tuple) and len(item) == 4 for item in analysis) assert a...
[ { "docstring": null, "function_declaration": "def fibonacci(n):", "function_name": "fibonacci", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def analyze_fibonacci_bytecode():", "function_name": "analyze_fibonacci_bytecode", "parameter_list": "()" } ]
[ 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 dis\n\ndef fibonacci(n):\n a, b = 0, 1\n fib_sequence = []\n for _ in range(n):\n fib_sequence.append(a)\n a, b =...
trial_gpt4o_2
{ "original_instruction": "### Advanced Python Bytecode Analysis with the `dis` Module\n\n#### Problem\nYou are given the following Python function:\n\n```python\ndef fibonacci(n):\n a, b = 0, 1\n fib_sequence = []\n for _ in range(n):\n fib_sequence.append(a)\n a, b = b, a + b\n return fib_...
0.61951
Docs: Python310_45813
C
[ "fibonacci", "analyze_fibonacci_bytecode" ]
2
[ [ "analyze_fibonacci_bytecode", "fibonacci" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3de3cf741f026d21f60815b237b9085e01be7eaa
95116b7f1da671f2e0a38de50e79a42ce8fc5372
v1.0
complete
Docs
Docs: Python310_45708_C
import asyncio async def download_files(urls: list, local_dir: str): """ Download multiple files concurrently from the given URLs and save them locally. The function must handle different asynchronous event loops based on the platform it is running on, specifically Windows and Unix-based systems (including...
import asyncio import aiohttp import os import sys async def download_file(session, url, local_dir): try: async with session.get(url) as response: if response.status == 200: filename = os.path.join(local_dir, os.path.basename(url)) with open(filename, 'wb') as fi...
import os import asyncio import aiohttp import pytest from solution import main, download_files @pytest.fixture def setup_local_dir(tmpdir): local_dir = tmpdir.mkdir("downloads") return str(local_dir) @pytest.fixture def mock_urls(): return [ 'https://httpbin.org/image/png', 'https://httpb...
[ { "docstring": null, "function_declaration": "def main(urls, local_dir):", "function_name": "main", "parameter_list": "(urls, local_dir)" } ]
[ 0, 0, 1, 0, 1, 1, 1, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nimport os\nimport platform\nfrom aiohttp import ClientSession\n\nasync def download_file(session: ClientSession, url: str, local_dir: st...
trial_gpt4o_2
{ "original_instruction": "### Advanced Python Coding Assessment Question\n\n#### Context\nYou are required to implement an asynchronous file downloader using Python’s `asyncio` module. This downloader must be compatible across different platforms, particularly focusing on handling files and subprocesses considering ...
0.528249
Docs: Python310_45708
C
[ "download_file", "download_files", "main" ]
3
[ [ "download_files", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
9985370e92b44a0f4e9fbe8baa931c6397948f8b
e1b5b176afddf5f1e3f5904bba3b8abefe5abab9
v1.0
complete
Docs
Docs: Python310_46045_C
from typing import List, Dict, Any import sys import os from pathlib import Path def add_custom_directory(path: str) -> None: """ Adds the given directory to sys.path if it exists and isn't already in sys.path. :param path: The directory to add to sys.path. :raises FileNotFoundError: If the direct...
import sys import os from pathlib import Path from typing import Dict, Any import json def add_custom_directory(path: str) -> None: """ Adds the given directory to sys.path if it exists and isn't already in sys.path. :param path: The directory to add to sys.path. :raises FileNotFoundError: If the dire...
import pytest from tempfile import TemporaryDirectory import json import os import sys from pathlib import Path # Assuming the functions are defined in a module named 'solution' from solution import add_custom_directory, process_pth_files, read_custom_configuration, initialize_custom_environment def test_add_custom_...
[ { "docstring": "Adds the given directory to sys.path if it exists and isn't already in sys.path.\n\n:param path: The directory to add to sys.path.\n:raises FileNotFoundError: If the directory does not exist.", "function_declaration": "def add_custom_directory(path):", "function_name": "add_custom_direct...
[ 0, 0, 1, 1, 1, 1, 1, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import Dict, Any\nimport os\nimport sys\nimport json\nfrom pathlib import Path\n\ndef add_custom_directory(path: str) -> None:\n \"\"\"\n Adds the giv...
trial_gpt4o_6
{ "original_instruction": "#### `site` Module Configuration and Customization\n\n**Objective**: Demonstrate understanding and practical usage of the `site` module in Python for site-specific configuration and path manipulations.\n\n#### Problem Statement:\n\nYou are tasked with creating a Python script that customize...
0.620062
Docs: Python310_46045
C
[ "add_custom_directory", "process_pth_files", "read_custom_configuration", "initialize_custom_environment" ]
4
[ [ "initialize_custom_environment", "add_custom_directory" ], [ "initialize_custom_environment", "process_pth_files" ], [ "initialize_custom_environment", "read_custom_configuration" ] ]
3
[]
false
[]
false
pytest
true
[]
true
352589f5d67cfbc4e8f8f4242a76bfdd0ccad01b
f56a3813d69bffcaf2b5fecf3e3027adcce7d858
v1.0
complete
Docs
Docs: Python310_46060_C
from ctypes import * def allocate_raw_memory(size: int) -> POINTER(c_void_p): """Allocate a specified number of bytes of raw memory. Args: size (int): Number of bytes to allocate. Returns: POINTER(c_void_p): Pointer to the allocated memory block. Raises: MemoryError: If memor...
from ctypes import * # Load the Python API shared object file pythonapi = cdll.LoadLibrary("libpython3.so") # Define the PyMem_RawMalloc, PyMem_RawRealloc, and PyMem_RawFree functions PyMem_RawMalloc = pythonapi.PyMem_RawMalloc PyMem_RawMalloc.restype = POINTER(c_void_p) PyMem_RawMalloc.argtypes = [c_size_t] PyMem_R...
from solution import allocate_raw_memory, resize_raw_memory, free_raw_memory, use_memory_management def test_allocate_raw_memory(): size = 64 mem_block = allocate_raw_memory(size) assert mem_block is not None, "Memory allocation failed" free_raw_memory(mem_block) def test_resize_raw_memory(): init...
[ { "docstring": null, "function_declaration": "def allocate_raw_memory(size):", "function_name": "allocate_raw_memory", "parameter_list": "(size)" }, { "docstring": null, "function_declaration": "def resize_raw_memory(ptr, new_size):", "function_name": "resize_raw_memory", "parame...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from ctypes import *\n\n# Load the Python C API memory management functions from the Python C library\nlibpython = CDLL(pythonapi)\n\n# Define memory management functio...
trial_gpt4o_6
{ "original_instruction": "### Advanced Memory Management in Python\n\n**Objective:**\nImplement a Python program using the `ctypes` library to interact with the C-style memory management functions provided in the documentation (specifically `PyMem_RawMalloc`, `PyMem_RawFree`, and others). This exercise will test you...
0.43865
Docs: Python310_46060
C
[ "allocate_raw_memory", "resize_raw_memory", "free_raw_memory", "use_memory_management", "memset" ]
5
[ [ "use_memory_management", "allocate_raw_memory" ], [ "use_memory_management", "free_raw_memory" ], [ "use_memory_management", "memset" ], [ "use_memory_management", "resize_raw_memory" ] ]
4
[]
false
[]
false
pytest
true
[]
true
bb4beb3493f1b055df564fcf4f357da54e0e880e
91ce70404d4468bb6194a74ae6158022641c92e6
v1.0
complete
Docs
Docs: Python310_46039_C
import hashlib def sign_message(message: bytes, secret_key: bytes) -> str: """ Produces a hexadecimal HMAC using the blake2b algorithm with a digest size of 16 bytes. >>> message = b'Hello, world!' >>> secret_key = b'secret' >>> len(sign_message(message, secret_key)) == 32 True """ d...
import hashlib def sign_message(message: bytes, secret_key: bytes) -> str: """ Produces a hexadecimal HMAC using the blake2b algorithm with a digest size of 16 bytes. """ h = hashlib.blake2b(key=secret_key, digest_size=16) h.update(message) return h.hexdigest() def verify_message(message: byte...
import pytest from solution import sign_message, verify_message, generate_personalized_hash def test_sign_message(): message = b'Hello, world!' secret_key = b'secret' expected_length = 32 # 16 bytes as hex is 32 characters hmac = sign_message(message, secret_key) assert len(hmac) == expected_length...
[ { "docstring": "Produces a hexadecimal HMAC using the blake2b algorithm with a digest size of 16 bytes.", "function_declaration": "def sign_message(message, secret_key):", "function_name": "sign_message", "parameter_list": "(message, secret_key)" }, { "docstring": "Verifies if the received H...
[ 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 hashlib\n\ndef sign_message(message: bytes, secret_key: bytes) -> str:\n \"\"\"\n Produces a hexadecimal HMAC using blake2b algorithm with a digest size of...
trial_gpt4o_9
{ "original_instruction": "<|Analysis Begin|>\n\nThe provided documentation outlines the `hashlib` library in Python 3.10, detailing various secure hash and message digest algorithms such as SHA-1, SHA-256, BLAKE2, and more. The library offers a unified interface for these algorithms, allowing users to create hash ob...
0.7847
Docs: Python310_46039
C
[ "sign_message", "verify_message", "generate_personalized_hash" ]
3
[ [ "verify_message", "sign_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d2c68b2650563045cc9ddbb2b261923940d3dda9
f4ac52d679085dbd086be92422ed5f4a3a2de6e8
v1.0
complete
Docs
Docs: Scikit_45633_C
import numpy as np import matplotlib.pyplot as plt from sklearn.calibration import CalibratedClassifierCV, calibration_curve from sklearn.metrics import brier_score_loss, log_loss def plot_calibration_curve(est, X_test, y_test, name): """ Plots the calibration curve for the given estimator. """ prob_pos = est....
import numpy as np import matplotlib.pyplot as plt from sklearn.calibration import CalibratedClassifierCV, calibration_curve from sklearn.metrics import brier_score_loss, log_loss def plot_calibration_curve(est, X_test, y_test, name): """ Plots the calibration curve for the given estimator. """ prob_pos = est....
from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier from solution import calibrate_classifier def test_calibrate_classifier(): # Generate a binary classification dataset X, y = make_classification(n_samples=1000, n_features=20, random_state=42) # Split ...
[ { "docstring": "Plots the calibration curve for the given estimator. ", "function_declaration": "def plot_calibration_curve(est, X_test, y_test, name):", "function_name": "plot_calibration_curve", "parameter_list": "(est, X_test, y_test, name)" }, { "docstring": "Calibrates a given binary cl...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.calibration import CalibratedClassifierCV, calibration_curve\nfrom sklearn.metrics import brier_score_...
trial_gpt4o_8
{ "original_instruction": "Design a function that performs probability calibration on an uncalibrated binary classifier using scikit-learn's `CalibratedClassifierCV` with both sigmoid and isotonic methods. The function should:\n1. Fit the uncalibrated model on training data.\n2. Calibrate the fitted model using `Cali...
0.647661
Docs: Scikit_45633
C
[ "plot_calibration_curve", "calibrate_classifier" ]
2
[ [ "calibrate_classifier", "plot_calibration_curve" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "sklearn" ]
false
b4d592c05fa018823732eb1854667e80537415ab
863ec1810c67d86cfded032afb70192d54224215
v1.0
complete
Docs
Docs: Python310_46196_C
import asyncio async def write_log(message: str, filename: str, delay: float) -> None: """ Writes a log message to the specified file after a delay. :param message: Log message to write. :param filename: File to write the log message to. :param delay: Time in seconds to wait before writing the log...
import asyncio async def write_log(message: str, filename: str, delay: float) -> None: """ Writes a log message to the specified file after a delay. :param message: Log message to write. :param filename: File to write the log message to. :param delay: Time in seconds to wait before writing the log...
import pytest import asyncio from solution import write_log, generate_logs import os @pytest.fixture(scope="function", autouse=True) def setup_teardown(): # Setup: create a dummy log file open('test_application.log', 'w').close() yield # Teardown: remove the dummy log file if os.path.exists('test_a...
[]
[ 1, 0, 0, 0, 1, 0, 0, 1, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def write_log(message: str, filename: str, delay: float) -> None:\n \"\"\"\n Writes a log message to the specified file after a delay.\n\n...
trial_gpt4o_0
{ "original_instruction": "### Asynchronous Logging System\n\nYou are tasked with creating an asynchronous logging system that can log messages from different parts of an application concurrently. This system should consist of a logger that writes to a file asynchronously and a main function which generates multiple ...
0.598029
Docs: Python310_46196
C
[ "write_log", "generate_logs", "main" ]
3
[ [ "generate_logs", "write_log" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4987179bbfa3ab41daa72787931dbcc60c1948cc
e30a34950eccd80ec414c3495c7c8ae15071ba56
v1.0
complete
Docs
Docs: Python310_45956_C
import types def is_cell_object(x): """ Check if an object x is a cell object. :param x: Any object to check. :return: True if x is a cell object, False otherwise. >>> cell = create_cell(10) >>> is_cell_object(cell) True >>> is_cell_object(10) False """ def create_cel...
import types def is_cell_object(x): """ Returns True if x is a cell object, False otherwise. """ return isinstance(x, types.CellType) def create_cell(value): """ Creates a cell object containing the given value. """ def cell_creator(): cell_value = value def closure(): ...
from solution import is_cell_object, create_cell, get_cell_content, set_cell_content def test_is_cell_object(): cell = create_cell(10) assert is_cell_object(cell) == True assert is_cell_object(10) == False assert is_cell_object("test") == False assert is_cell_object(None) == False def test_create_...
[ { "docstring": "Returns True if x is a cell object, False otherwise.", "function_declaration": "def is_cell_object(x):", "function_name": "is_cell_object", "parameter_list": "(x)" }, { "docstring": "Creates a cell object containing the given value.", "function_declaration": "def create_c...
[ 1, 0, 0, 1, 1, 0, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import types\n\ndef is_cell_object(x):\n \"\"\"\n Returns True if x is a cell object, False otherwise.\n \"\"\"\n return isinstance(x, types.CellType)\n\nde...
trial_gpt4o_0
{ "original_instruction": "### Cell Objects in Python\n\nIn Python, cell objects are used internally to handle variables that are referenced in multiple scopes, particularly within closures. In this assignment, you will implement a mini-framework that uses cell objects to manage variables in nested scopes. Your task ...
0.424943
Docs: Python310_45956
C
[ "is_cell_object", "create_cell", "get_cell_content", "set_cell_content" ]
4
[ [ "get_cell_content", "is_cell_object" ], [ "set_cell_content", "is_cell_object" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e7b0cac8b6535e67ecda9463c0c8722696a98369
c919e298e9b3f97e90953987f36f988395ca9a3c
v1.0
complete
Docs
Docs: Pytorch_45960_C
import torch import torch.nn as nn import torch.optim as optim from torch.distributed.elastic.multiprocessing.errors import record from torch.utils.data import DataLoader, TensorDataset def get_data_loader(batch_size=32): """Generate random data for training and return a DataLoader.""" inputs = torch.randn(100...
import torch import torch.nn as nn import torch.optim as optim from torch.distributed.elastic.multiprocessing.errors import record from torch.utils.data import DataLoader, TensorDataset def get_data_loader(batch_size=32): # Generate random data inputs = torch.randn(1000, 10) # 1000 samples with 10 features ea...
import pytest import torch from torch.utils.data import DataLoader # Importing the functions to test from solution import get_data_loader, SimpleNet def test_get_data_loader(): data_loader = get_data_loader(batch_size=32) assert isinstance(data_loader, DataLoader) batch = next(iter(data_loader)) asser...
[]
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom torch.distributed.elastic.multiprocessing...
trial_gpt4o_2
{ "original_instruction": "### Distributed Training with PyTorch Elastic\n\n#### Background\nIn distributed machine learning, we often deal with multiple computing nodes working together to train a model. PyTorch provides a package called `torch.distributed.elastic` which allows distributed jobs to be more fault-tole...
0.648483
Docs: Pytorch_45960
C
[ "get_data_loader", "train", "main" ]
3
[ [ "train", "get_data_loader" ] ]
1
[]
false
[ "SimpleNet" ]
true
pytest
true
[ "torch" ]
false
df3331358fa254b12cb3196f17f7300eb4d3d39d
b2978ed6d8b8fcba23d8d1c42a1c1e39ca819168
v1.0
complete
Docs
Docs: Pytorch_45525_C
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torchvision import datasets, transforms from torch.utils.data import DataLoader, DistributedSampler from torch.distributed.optim import ZeroRedundancyOptimizer import torch.multiprocessing as mp import os # Define the ...
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torchvision import datasets, transforms from torch.utils.data import DataLoader, DistributedSampler from torch.distributed.optim import ZeroRedundancyOptimizer import torch.multiprocessing as mp import os # Define the ...
def test_example(): assert True # Placeholder test. Manual inspection required for distributed training scripts.
[]
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torchvision import datasets...
trial_gpt4o_7
{ "original_instruction": "### Distributed Training with ZeroRedundancyOptimizer\n\nIn this task, you are required to implement a distributed training pipeline using PyTorch's `torch.distributed.optim.ZeroRedundancyOptimizer`.\n\n**Objective**: Create a PyTorch script to train a simple neural network model using `Zer...
0.626308
Docs: Pytorch_45525
C
[ "setup", "cleanup", "train", "main" ]
4
[ [ "train", "cleanup" ], [ "train", "setup" ] ]
2
[]
false
[ "SimpleNN" ]
true
pytest
false
[ "torch", "torchvision" ]
false
47f8b2262a941285755249573ef1d17854bf8962
47d06b27234bbf695ae2a0442374e611d7eaf960
v1.0
complete
Docs
Docs: Pytorch_46013_C
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP import os def setup(rank, world_size): """Initializes distributed training.""" dist.init_process_group("gloo", rank=rank, world_size=world_size) torch...
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP import os # Set this environment variable for `torchrun` os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = '12355' def setup(rank, world_size):...
from solution import setup, cleanup, generate_synthetic_data, SimpleNN import torch.distributed as dist import torch import pytest def test_setup_cleanup(): """ Test the setup and cleanup of the distributed training environment. """ world_size = 1 rank = 0 setup(rank, world_size) assert dis...
[]
[ 1, 1, 0, 1, 0, 0, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torch.nn.parallel import Di...
trial_gpt4o_1
{ "original_instruction": "You are provided with the requirement to train a PyTorch model using distributed training to speed up the training process. You are to leverage the `torchrun` tool from the `torch.distributed.run` module to train a simple neural network across multiple processes.\n\n## Task\nWrite a Python ...
0.594873
Docs: Pytorch_46013
C
[ "setup", "cleanup", "generate_synthetic_data", "train" ]
4
[ [ "train", "cleanup" ], [ "train", "generate_synthetic_data" ], [ "train", "setup" ] ]
3
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
7a9149991b292571547c04b75d98d4020a43d136
b57c3280f6e8e453c72b8c88b9625897785ff45f
v1.0
complete
Docs
Docs: Python310_44603_C
from xml.dom.minidom import Document import xml.dom.minidom from xml.dom.minidom import parse def dict_from_element(element) -> dict: # Helper function to convert XML element to dict pass def element_from_dict(document: Document, tag: str, content: dict) -> xml.dom.minidom.Element: # Helper function t...
from xml.dom.minidom import parse, Document import xml.dom.minidom def dict_from_element(element) -> dict: node_dict = {} for node in element.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.hasChildNodes() and any(child.nodeType == child.ELEMENT_NODE for child in node.childNodes)...
import pytest import os from xml.dom.minidom import parseString from solution import read_config, modify_config, save_config @pytest.fixture def sample_xml(tmp_path): content = '''<config> <database> <host>localhost</host> <port>3306</port> ...
[ { "docstring": null, "function_declaration": "def dict_from_element(element):", "function_name": "dict_from_element", "parameter_list": "(element)" }, { "docstring": null, "function_declaration": "def element_from_dict(document, tag, content):", "function_name": "element_from_dict", ...
[ 0, 0, 0, 1, 1, 0, 1, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from xml.dom.minidom import parse, parseString, Document\nfrom xml.etree.ElementTree import Element, tostring, fromstring\n\ndef read_config(file_path: str) -> dict:\n ...
trial_gpt4o_8
{ "original_instruction": "### Advanced Coding Assessment Question\n\n#### Objective:\nTo assess the comprehension of advanced XML and DOM operations using the `xml.dom.minidom` module in Python.\n\n#### Problem Statement:\nYou are tasked with developing a new XML-based configuration management system. The configurat...
0.628613
Docs: Python310_44603
C
[ "dict_from_element", "element_from_dict", "read_config", "modify_config", "save_config" ]
5
[ [ "read_config", "dict_from_element" ], [ "save_config", "element_from_dict" ] ]
2
[]
false
[]
false
pytest
true
[]
true
37675bc625c8018fcd9c85c58e92e7f13a1c15c1
30e270775b6224dcd13c885af77d6e5035ed0e2b
v1.0
complete
Docs
Docs: Python310_45526_C
import os import gzip import bz2 import lzma import zipfile import tarfile from typing import List, Dict, Any def compress_file(input_file: str, output_file: str, algorithm: str) -> int: """ Compresses the input file using the specified compression algorithm and returns the size of the compressed file. ...
import os from typing import List, Dict, Any import gzip import bz2 import lzma import zipfile import tarfile def compress_file(input_file: str, output_file: str, algorithm: str) -> int: """ Compresses the input file using the specified compression algorithm and returns the size of the compressed file. ...
import os import pytest from solution import process_files @pytest.fixture(scope="module") def setup_files(tmpdir_factory): file1 = tmpdir_factory.mktemp("data").join("file1.txt") file2 = tmpdir_factory.mktemp("data").join("file2.txt") file3 = tmpdir_factory.mktemp("data").join("file3.txt") with o...
[ { "docstring": "Compresses the input file using the specified compression algorithm and returns the size of the compressed file.\n\n:param input_file: Path to the input file to be compressed.\n:param output_file: Path to the output compressed file.\n:param algorithm: Compression algorithm (gzip, bz2, lzma)\n:re...
[ 1, 1, 0, 1, 0, 1, 1, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport gzip\nimport bz2\nimport lzma\nimport zipfile\nimport tarfile\nfrom typing import List, Dict, Any\n\ndef process_files(file_paths: List[str]) -> Dict[...
trial_gpt4o_9
{ "original_instruction": "### Advanced Python Programming Assignment\n\n#### Objective\nYou are assigned to develop a Python script that demonstrates your understanding and familiarity with Python's data compression and archiving modules. The task requires you to perform operations using multiple compression algorit...
0.731012
Docs: Python310_45526
C
[ "compress_file", "create_zip_archive", "create_tar_archive", "process_files" ]
4
[ [ "process_files", "compress_file" ], [ "process_files", "create_tar_archive" ], [ "process_files", "create_zip_archive" ] ]
3
[]
false
[]
false
pytest
true
[]
true
554ccda871426ea2bc2a38c203b7e00c43ed4c8b
eec22e0bbabe642edc71bea9b75b1c1625b58d0a
v1.0
complete
Docs
Docs: Python310_46058_C
import concurrent.futures from typing import List def fetch_html(url: str) -> str: try: response = requests.get(url, timeout=5) response.raise_for_status() return response.text except requests.RequestException as e: return f"Error fetching {url}: {str(e)}" def fetch_urls_concur...
import concurrent.futures import requests from typing import List def fetch_html(url: str) -> str: try: response = requests.get(url, timeout=5) response.raise_for_status() return response.text except requests.RequestException as e: return f"Error fetching {url}: {str(e)}" def f...
from solution import fetch_urls_concurrently def test_fetch_urls_concurrently(): urls = [ "https://www.example.com", "https://www.example.org", "https://www.example.net", ] results = fetch_urls_concurrently(urls) assert isinstance(results, list) assert len(results)...
[ { "docstring": null, "function_declaration": "def fetch_html(url):", "function_name": "fetch_html", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def fetch_urls_concurrently(urls):", "function_name": "fetch_urls_concurrently", "parameter_list": "(urls...
[ 1, 0, 0, 1, 0, 0, 0, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import concurrent.futures\nimport requests\nfrom typing import List\n\ndef fetch_url(url: str) -> str:\n try:\n response = requests.get(url, timeout=10)\n ...
trial_gpt4o_7
{ "original_instruction": "**Topic**: Parallel Task Execution with `concurrent.futures`\n\n**Objective**: To evaluate students' understanding of parallel task execution using the `concurrent.futures` module, including creating, managing, and handling results from concurrent tasks.\n\n#### Problem Statement\n\nYou are...
0.581528
Docs: Python310_46058
C
[ "fetch_html", "fetch_urls_concurrently" ]
2
[ [ "fetch_urls_concurrently", "fetch_html" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
fbb35d93ba4d9716e9e48fe6e341f46b83973b37
50b96cdb0f5edbdbdebc11089ef536437f2a3839
v1.0
complete
Docs
Docs: Python310_46093_C
import plistlib import os def save_settings(settings, filename, fmt='FMT_XML'): """ Saves the settings dictionary to a plist file. :param settings: Dictionary containing settings. :param filename: Name of the file to save settings. :param fmt: Format of the plist file (either 'FMT_XML' or 'FMT_BIN...
import plistlib import os def save_settings(settings, filename, fmt='FMT_XML'): """ Saves the settings dictionary to a plist file. :param settings: Dictionary containing settings. :param filename: Name of the file to save settings. :param fmt: Format of the plist file (either 'FMT_XML' or 'FMT_BIN...
import pytest import os import plistlib from solution import save_settings, load_settings, update_setting def test_save_and_load_settings_xml(): settings = { 'username': 'test_user', 'volume': 30 } filename = 'test_settings.xml' # Save settings save_settings(settings, filename,...
[ { "docstring": "Saves the settings dictionary to a plist file.\n\n:param settings: Dictionary containing settings.\n:param filename: Name of the file to save settings.\n:param fmt: Format of the plist file (either 'FMT_XML' or 'FMT_BINARY').", "function_declaration": "def save_settings(settings, filename, f...
[ 1, 1, 0, 1, 0, 0, 0, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import plistlib\n\ndef save_settings(settings, filename, fmt='FMT_XML'):\n \"\"\"\n Save the settings dictionary to a plist file in the specified format.\n \"\...
trial_gpt4o_9
{ "original_instruction": "You are tasked with simulating the settings management of a macOS application using Python's `plistlib` module. Specifically, you need to handle saving, loading, and updating application settings stored in plist files. \n\nYour task is to implement three functions:\n\n1. **`save_settings(se...
0.495044
Docs: Python310_46093
C
[ "save_settings", "load_settings", "update_setting" ]
3
[ [ "update_setting", "load_settings" ], [ "update_setting", "save_settings" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c6630eab90be248110a58ce3a65871009119de64
dc27c30dc78e9c7245ae5d8d4252d6ac754e3939
v1.0
complete
Docs
Docs: Python310_45973_C
import multiprocessing from itertools import product def parallel_matrix_multiply(A, B): """ Multiplies two matrices A and B using parallel processing. Returns the product matrix C. Args: A: List of lists of integers/floats. Each sublist represents a row in matrix A. B: List of lists of intege...
import multiprocessing from itertools import product def matrix_element(A, B, i, j): """ Computes the element C[i][j] for the product of matrices A and B """ return sum(A[i][k] * B[k][j] for k in range(len(B))) def parallel_matrix_multiply(A, B): """ Multiplies two matrices A and B using paral...
from solution import parallel_matrix_multiply def test_matrix_multiplication_example(): A = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] B = [ [9, 8, 7], [6, 5, 4], [3, 2, 1] ] expected_result = [ [30, 24, 18], [84, 69, 54], [138, 114, ...
[ { "docstring": "Computes the element C[i][j] for the product of matrices A and B", "function_declaration": "def matrix_element(A, B, i, j):", "function_name": "matrix_element", "parameter_list": "(A, B, i, j)" }, { "docstring": "Multiplies two matrices A and B using parallel processing.\nRet...
[ 1, 1, 0, 1, 0, 1, 0, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import multiprocessing\n\ndef matrix_multiply_worker(args):\n A, B, row_index = args\n C_row = []\n num_cols_B = len(B[0])\n \n for j in range(num_cols_B...
trial_gpt4o_5
{ "original_instruction": "### Parallel Matrix Multiplication Using Multiprocessing\n\nYou are required to implement a parallel matrix multiplication function in Python using the `multiprocessing` package. The function will take two matrices as input and return their product.\n\nMatrix multiplication is defined as fo...
0.593109
Docs: Python310_45973
C
[ "matrix_element", "parallel_matrix_multiply" ]
2
[ [ "parallel_matrix_multiply", "matrix_element" ] ]
1
[]
false
[]
false
pytest
true
[]
true
583e485d310bf2b777c79ee9bb427256a55ac9b6
635bb8e01dafd02343850f925a5e480c151a1996