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
instruct
Docs
Docs: Pytorch_14268_I
#### Objective Implement a function that creates a complex mask by combining several basic masks using the block mask utilities provided in the `torch.nn.attention.flex_attention` module. Then, apply this combined mask to a given tensor to filter out specific elements as defined by the mask. #### Problem Statement Wri...
import torch import torch.nn.functional as F def create_block_mask(shape, fill_value): """Utility to create a simple block mask.""" return torch.full(shape, fill_value) def create_mask(shape, fill_value): """Utility to create a simple mask.""" return torch.full(shape, fill_value) def and_masks(mask1,...
import pytest import torch from solution import apply_complex_mask def test_apply_complex_mask_basic(): tensor = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) mask_shape = (3, 3) result = apply_complex_mask(tensor, mask_shape) expected = tensor # Since all masks are true, the output should be the sa...
[ { "docstring": "Utility to create a simple block mask.", "function_declaration": "def create_block_mask(shape, fill_value):", "function_name": "create_block_mask", "parameter_list": "(shape, fill_value)" }, { "docstring": "Utility to create a simple mask.", "function_declaration": "def c...
[ 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 torch\nfrom torch.nn.attention.flex_attention import create_block_mask, create_mask, and_masks, or_masks\n\ndef apply_complex_mask(tensor: torch.Tensor, mask_sha...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00014268", "row_id": 14268, "seed_ids": "[0]" }
0.478842
Docs: Pytorch_14268
I
[ "create_block_mask", "create_mask", "and_masks", "or_masks", "apply_complex_mask" ]
5
[ [ "apply_complex_mask", "and_masks" ], [ "apply_complex_mask", "create_block_mask" ], [ "apply_complex_mask", "create_mask" ], [ "apply_complex_mask", "or_masks" ] ]
4
[]
false
[]
false
pytest
true
[ "torch" ]
false
cee29182eb8c8480afff52007c3f29a4709548df
75e914ea6cd2d77ea06ad1e7311996e894d19023
v1.0
instruct
Docs
Docs: Python310_14291_I
### AsyncIO Concurrency Problem #### Description You are tasked with writing a Python script that performs multiple I/O-bound operations concurrently using the asyncio library. The problem is designed to assess your understanding of async/await syntax, task creation, managing concurrent execution, handling timeouts, ...
import asyncio # Coroutine to simulate I/O-bound operation async def io_bound_task(task_name, delay): print(f"Task {task_name} started") await asyncio.sleep(delay) print(f"Task {task_name} completed") # Main execution function async def main_execution(): task_configs = [("A", 2), ("B", 6), ("C", 3)] ...
import asyncio import pytest from solution import io_bound_task, main_execution @pytest.mark.asyncio async def test_io_bound_task(capsys): await io_bound_task("X", 1) captured = capsys.readouterr() assert "Task X started" in captured.out assert "Task X completed" in captured.out @pytest.mark.asyncio a...
[]
[ 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 asyncio\n\n# Coroutine to simulate I/O-bound operation\nasync def io_bound_task(task_name, delay):\n print(f\"Task {task_name} started\")\n await asyncio.s...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00014291", "row_id": 14291, "seed_ids": "[317]" }
0.597944
Docs: Python310_14291
I
[ "io_bound_task", "main_execution" ]
2
[ [ "main_execution", "io_bound_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dea7678ae7225c6e54ae53ff7ae522e9714341c7
0fe60edde6f143214d837cc78272392e84086bd5
v1.0
instruct
Docs
Docs: Python310_14299_I
**Question: Ambiguous Indentation Checker** **Objective:** Implement a function `custom_tab_nanny(file_or_dir, verbose=False, filename_only=False)` that mimics the functionality of the `tabnanny` module but with the following custom features: 1. The function should accept a directory or file path. 2. It should check f...
import os import tokenize from io import StringIO class CustomNannyNag(Exception): """Exception raised for ambiguous indentation detected by the customized tab nanny.""" pass def check_indentation(file_content): """ Check for indentation issues in the given file content. Returns the number of inde...
import os import tempfile from solution import custom_tab_nanny, CustomNannyNag def test_check_single_file_with_no_issues(): temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".py") temp_file.write(b"def foo():\n pass\n") temp_file.close() custom_tab_nanny(temp_file.name, verbose=Tru...
[]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport tokenize\n\nclass CustomNannyNag(Exception):\n pass\n\ndef check_indentation_issues(file_path):\n issues = []\n with open(file_path, 'r') as ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00014299", "row_id": 14299, "seed_ids": "[293]" }
0.515306
Docs: Python310_14299
I
[ "check_indentation", "custom_tab_nanny" ]
2
[ [ "custom_tab_nanny", "check_indentation" ] ]
1
[]
false
[ "CustomNannyNag" ]
true
pytest
true
[]
true
29483c8c66ecf9642ef2ee8674249a72403fa029
1652d8b86540f1a4b057f41eac2e20bcbe8e2668
v1.0
instruct
Docs
Docs: Python310_14363_I
#### Objective: Design and implement a Python function using the `multiprocessing` module to perform parallel computations on a large dataset. #### Problem Statement: You are provided with a list of integers. Your task is to compute the square of each integer in the list using parallel processing for increased perform...
from multiprocessing import Pool from typing import List def square_number(n: int) -> int: """ Returns the square of the given number n. """ return n * n def parallel_square_computation(numbers: List[int], num_processes: int) -> List[int]: """ Compute the square of each integer in the list usi...
from solution import parallel_square_computation def test_empty_list(): numbers = [] num_processes = 2 assert parallel_square_computation(numbers, num_processes) == [] def test_single_element(): numbers = [4] num_processes = 2 assert parallel_square_computation(numbers, num_processes) == [16] ...
[ { "docstring": "Returns the square of the given number n.", "function_declaration": "def square_number(n):", "function_name": "square_number", "parameter_list": "(n)" }, { "docstring": "Compute the square of each integer in the list using parallel processing.\n\nArgs:\nnumbers: List of integ...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport multiprocessing\n\ndef parallel_square_computation(numbers: List[int], num_processes: int) -> List[int]:\n \"\"\"\n Function to co...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00014363", "row_id": 14363, "seed_ids": "[206]" }
0.643236
Docs: Python310_14363
I
[ "square_number", "parallel_square_computation" ]
2
[ [ "parallel_square_computation", "square_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
977bc1bd8c9d8e2f6714819e665ad8182d9bd40d
47f0034302b40f65d1e183c7973120072204ef21
v1.0
instruct
Docs
Docs: Pytorch_14370_I
### Advanced PyTorch Coding Challenge: Attention Masks #### Background In attention mechanisms, masks are used to control which positions can be attended to, allowing you to build more complex and flexible models. PyTorch provides various utilities to create and manipulate these masks within the `torch.nn.attention.fl...
import torch from torch.nn.functional import softmax def create_block_mask(seq_length, block_size): mask = torch.zeros(seq_length, seq_length, dtype=torch.bool) for i in range(0, seq_length, block_size): mask[i:i+block_size, i:i+block_size] = 1 return mask def custom_attention(input_tensor: torch....
import torch from solution import custom_attention def test_custom_attention_basic(): input_tensor = torch.randn(2, 10, 64) # (batch_size, seq_length, embedding_dim) block_size = 3 output_tensor = custom_attention(input_tensor, block_size) assert output_tensor.shape == input_tensor.shape def test_cus...
[ { "docstring": null, "function_declaration": "def create_block_mask(seq_length, block_size):", "function_name": "create_block_mask", "parameter_list": "(seq_length, block_size)" }, { "docstring": "Apply a custom attention mechanism using block masks to the input tensor.\n\nArgs:\n input_t...
[ 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\nfrom torch.nn.functional import softmax\n\ndef create_block_mask(seq_length, block_size):\n \"\"\"\n Creates a block mask of shape (seq_length, seq_...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00014370", "row_id": 14370, "seed_ids": "[0]" }
0.499073
Docs: Pytorch_14370
I
[ "create_block_mask", "custom_attention" ]
2
[ [ "custom_attention", "create_block_mask" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
186ac1ac0a6e914cafc90ff4ecdc42297d78a46c
5e5572a2ccdfc0f913e21aa45719523c5a7ce1d4
v1.0
instruct
Docs
Docs: Python310_14418_I
In this assessment, your task is to implement a Python program that uses the `multiprocessing` module to simulate a simplified version of a concurrent web scraper. You will create multiple worker processes to fetch data from a list of URLs concurrently, process the fetched data, and store the results. #### Requirement...
import multiprocessing import requests from multiprocessing import Pool, Queue import logging def fetch_url(queue, url): """ Function that fetches the content of a URL and puts it into a queue. """ try: response = requests.get(url) response.raise_for_status() queue.put((url, res...
from solution import concurrent_web_scraper def test_concurrent_web_scraper(): urls = [ "https://httpbin.org/get", "https://httpbin.org/status/404" ] results = concurrent_web_scraper(urls, num_workers=2) assert "https://httpbin.org/get" in results assert "https://httpbin.o...
[ { "docstring": "Function that fetches the content of a URL and puts it into a queue.", "function_declaration": "def fetch_url(queue, url):", "function_name": "fetch_url", "parameter_list": "(queue, url)" }, { "docstring": "Fetch HTML content from a list of URLs concurrently using multiproces...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import multiprocessing\nimport requests\nfrom multiprocessing import Pool, Queue\nimport logging\n\ndef fetch_url(queue, url):\n \"\"\"\n Function that fetches th...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00014418", "row_id": 14418, "seed_ids": "[338]" }
0.605282
Docs: Python310_14418
I
[ "fetch_url", "concurrent_web_scraper" ]
2
[ [ "concurrent_web_scraper", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
91e6514b9aea04bafebbd29c681ba280e624db39
93401576a977a944a0011fc23c0c6d10ab867c91
v1.0
instruct
Docs
Docs: Python310_14445_I
### Question: PyLongObject Conversion Utility You are tasked with implementing a utility that deals with Python integer objects (`PyLongObject`). This utility should perform multiple operations, including type checking, conversions, and error handling. #### Functions to Implement 1. `is_pylong_object(obj: Any) -> b...
def is_pylong_object(obj): """ Returns True if the object is an instance of int, False otherwise. """ return isinstance(obj, int) def create_pylong_from_c_long(value): """ Returns a Python integer created from a C long, which is conceptually similar to a regular int in Python. Raises Va...
import pytest from solution import ( is_pylong_object, create_pylong_from_c_long, convert_pylong_to_c_long, create_pylong_from_string ) def test_is_pylong_object(): assert is_pylong_object(123) is True assert is_pylong_object(0) is True assert is_pylong_object(-123) is True assert is_p...
[ { "docstring": "Returns True if the object is an instance of int, False otherwise.", "function_declaration": "def is_pylong_object(obj):", "function_name": "is_pylong_object", "parameter_list": "(obj)" }, { "docstring": "Returns a Python integer created from a C long, which is\nconceptually ...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_pylong_object(obj):\n \"\"\"\n Returns True if the object is an instance of int, False otherwise.\n \"\"\"\n return isinstance(obj, int)\n\ndef creat...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00014445", "row_id": 14445, "seed_ids": "[52]" }
0.496047
Docs: Python310_14445
I
[ "is_pylong_object", "create_pylong_from_c_long", "convert_pylong_to_c_long", "create_pylong_from_string" ]
4
[ [ "convert_pylong_to_c_long", "is_pylong_object" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1d236d9153aba20d542447a7da928906245c741e
30d6f79ad30cd4f982362ae83ef7f202f4146308
v1.0
instruct
Docs
Docs: Python310_14449_I
<|Analysis Begin|> The provided documentation pertains to the `heapq` module in Python, which implements the heap queue algorithm, also known as the priority queue algorithm. The module supports various operations on heaps, such as pushing elements, popping the smallest element, pushing and then popping, transforming ...
import heapq import itertools def add_task(scheduler, task, priority): """ Add a new task or update the priority of an existing task. """ if task in scheduler['entry_finder']: remove_task(scheduler, task) count = next(scheduler['counter']) entry = [priority, count, task] scheduler['...
import pytest from solution import add_task, remove_task, pop_task, change_task_priority def test_add_task(): scheduler = {'pq': [], 'entry_finder': {}, 'REMOVED': '<removed-task>', 'counter': itertools.count()} add_task(scheduler, 'task1', 2) add_task(scheduler, 'task2', 1) assert 'task1' in scheduler...
[ { "docstring": "Add a new task or update the priority of an existing task.", "function_declaration": "def add_task(scheduler, task, priority):", "function_name": "add_task", "parameter_list": "(scheduler, task, priority)" }, { "docstring": "Mark a task as removed. Raise KeyError if not found...
[ 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 heapq\nimport itertools\n\ndef add_task(scheduler, task, priority):\n \"\"\"\n Add a new task or update the priority of an existing task.\n \"\"\"\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00014449", "row_id": 14449, "seed_ids": "[241]" }
0.620289
Docs: Python310_14449
I
[ "add_task", "remove_task", "pop_task", "change_task_priority" ]
4
[ [ "add_task", "remove_task" ], [ "change_task_priority", "add_task" ], [ "change_task_priority", "remove_task" ] ]
3
[]
false
[]
false
pytest
true
[]
true
e29014a962860ae4206b8233ec0ef50f5416a27a
3095bf1836254b5b84691c9236d287dbb767583d
v1.0
instruct
Docs
Docs: Python310_14547_I
**Question: HMAC Authentication System** You are tasked with designing a secure authentication system for a sensitive application. The system should use the HMAC (Keyed-Hashing for Message Authentication) algorithm to generate and verify message digests to ensure the integrity and authenticity of the data transmitted ...
import hmac import hashlib from typing import Tuple def generate_hmac(key: bytes, message: bytes, digestmod: str) -> str: """ Generates an HMAC digest for the given message using the provided key and digest method. Parameters: - key (bytes): The secret key used for HMAC generation. - messa...
from solution import generate_hmac, verify_hmac, authenticate_message def test_generate_hmac(): key = b'secret_key' message = b'This is a critical message.' digestmod = 'sha256' hmac_digest = generate_hmac(key, message, digestmod) assert isinstance(hmac_digest, str) assert len(hmac_digest) == 6...
[ { "docstring": "Generates an HMAC digest for the given message using the provided key\nand digest method.\n\nParameters:\n- key (bytes): The secret key used for HMAC generation.\n- message (bytes): The message to generate the HMAC for.\n- digestmod (str): The hash algorithm to use (e.g., 'sha256').\n\nReturns:\...
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import hmac\nimport hashlib\nfrom typing import Tuple\n\ndef generate_hmac(key: bytes, message: bytes, digestmod: str) -> str:\n \"\"\"\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00014547", "row_id": 14547, "seed_ids": "[298]" }
0.725333
Docs: Python310_14547
I
[ "generate_hmac", "verify_hmac", "authenticate_message" ]
3
[ [ "authenticate_message", "generate_hmac" ], [ "authenticate_message", "verify_hmac" ], [ "verify_hmac", "generate_hmac" ] ]
3
[]
false
[]
false
pytest
true
[]
true
b73686934756b3a4f510ec744426913d01aadc5f
a26228ed270aa90a8a2e82deb98ca417d5b38dfa
v1.0
instruct
Docs
Docs: Python310_14571_I
### Custom Codec Implementation #### Objective You are required to implement a custom codec for encoding and decoding data. Your custom codec should be able to encode a given string by shifting each character's Unicode code point by a specified number and decode it by reversing the process. #### Function Specificatio...
import codecs class CustomCodec(codecs.Codec): def __init__(self, shift): self.shift = shift def encode(self, input, errors='strict'): output = shift_encode(input, self.shift) return output, len(input) def decode(self, input, errors='strict'): output = shift_decode...
import codecs def test_shift_encode(): assert shift_encode("Hello, World!", 3) == b'Khoor/#Zruog$' def test_shift_decode(): assert shift_decode(b'Khoor/#Zruog$', 3) == "Hello, World!" def test_codec_encode(): codec = CustomCodec(3) assert codec.encode("Hello, World!")[0] == b'Khoor/#Zruog$' def test...
[]
[ 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 codecs\n\nclass CustomCodec(codecs.Codec):\n def __init__(self, shift=3):\n self.shift = shift\n \n def encode(self, input, errors='strict'):\n ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00014571", "row_id": 14571, "seed_ids": "[211]" }
0.635284
Docs: Python310_14571
I
[ "shift_encode", "shift_decode", "getregentry", "register_custom_codec" ]
4
[ [ "register_custom_codec", "getregentry" ] ]
1
[]
false
[ "CustomCodec", "IncrementalEncoder", "IncrementalDecoder" ]
true
pytest
false
[]
true
8b77b75598e53cc5a9698551620dc5bc9e131d54
c649b8d0739d74df29dab006f4f01b3a02e8b78b
v1.0
instruct
Docs
Docs: Scikit_14718_I
### Advanced Coding Assessment Question on scikit-learn #### Context You are a data scientist working on a project that involves clustering and classification of image data represented as feature vectors. Your task is to compute the similarity between different images using various kernels and apply these similarities...
import numpy as np from sklearn.metrics.pairwise import linear_kernel, polynomial_kernel, rbf_kernel def compute_kernel(X, kernel='linear', **kwargs): """ Computes the pairwise kernel matrix for the given dataset. Parameters: X (numpy array): Dataset of shape (n_samples, n_features). kernel (s...
import numpy as np from solution import compute_kernel, compute_similarity, knn_classify def test_compute_kernel_linear(): X = np.array([[1, 2], [3, 4], [5, 6]]) K = compute_kernel(X, kernel='linear') expected_K = np.dot(X, X.T) assert np.allclose(K, expected_K) def test_compute_kernel_polynomial(): ...
[ { "docstring": "Computes the pairwise kernel matrix for the given dataset.\n\nParameters:\nX (numpy array): Dataset of shape (n_samples, n_features).\nkernel (str): The type of kernel to use ('linear', 'polynomial', 'rbf').\n**kwargs: Additional keyword arguments for the specific kernel parameters.\n\nReturns:\...
[ 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 numpy as np\nfrom sklearn.metrics.pairwise import linear_kernel, polynomial_kernel, rbf_kernel\nfrom scipy.stats import mode\n\ndef compute_kernel(X, kernel, **k...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00014718", "row_id": 14718, "seed_ids": "[38]" }
0.543169
Docs: Scikit_14718
I
[ "compute_kernel", "compute_similarity", "knn_classify" ]
3
[ [ "knn_classify", "compute_similarity" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
20bc8761ff27448a966ca4613669a1fdb22a671c
fd0d716974b6f8dbf9c67b5e0ef276f5a9f35f30
v1.0
instruct
Docs
Docs: Python310_14720_I
**Problem Statement:** The Python `time` module offers various functions that assist in manipulating and converting times. Your task is to write a utility that takes a list of strings representing date-times in different formats and returns a list of date-times converted into a standardized format. Additionally, your ...
from typing import List import time def convert_date_times(date_time_strings: List[str], date_format: str) -> List[str]: """ Converts a list of date-time strings into a standardized format. :param date_time_strings: List of strings representing date-times in various formats. :param date_format: The de...
import pytest from solution import convert_date_times, measure_conversion_time def test_convert_date_times_standard_format(): date_time_strings = ["2023-10-01 13:45:30", "01-10-2023 14:50:15", "10/01/2023 01:55 PM"] expected_output = ["2023-10-01 13:45:30", "2023-10-01 14:50:15", "2023-10-01 13:55:00"] out...
[ { "docstring": "Converts a list of date-time strings into a standardized format.\n\n:param date_time_strings: List of strings representing date-times in various formats.\n:param date_format: The desired output format for the date-times.\n:return: A list of strings where each string represents a date-time conver...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport time\n\ndef convert_date_times(date_time_strings: List[str], date_format: str) -> List[str]:\n \"\"\"\n Converts a list of date-ti...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00014720", "row_id": 14720, "seed_ids": "[122]" }
0.664114
Docs: Python310_14720
I
[ "convert_date_times", "measure_conversion_time" ]
2
[ [ "measure_conversion_time", "convert_date_times" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f4ba63eebad0c0773c50520beae39fe5807d2823
e101aecb6e97b5d2134eaa785d2fcdd0a19c5aa5
v1.0
instruct
Docs
Docs: Python310_14723_I
**Question: Optimize a Batch Processing System with String Templating, Binary Data Handling, and Multi-threading** You are tasked with designing and implementing a batch processing system that will handle large datasets. This system must: 1. Use templating to generate consistent file names for processed output files. ...
import os from datetime import datetime import threading import struct def generate_filename(template: str, record_id: int, date: str, orig_name: str) -> str: """ Generates a filename based on a given template. template: str - The template string containing placeholders for record_id, date, and orig_n...
import os import tempfile import struct import threading import pytest from solution import generate_filename, process_dataset, batch_process def test_generate_filename(): template = "processed_%date%_%record_id%_%orig_name%" record_id = 123 date = "25Oct23" orig_name = "dataset1.bin" expected_file...
[ { "docstring": "Generates a filename based on a given template.\n\ntemplate: str - The template string containing placeholders for record_id, date, and orig_name.\nrecord_id: int - The ID of the record.\ndate: str - The date string to be included in the filename.\norig_name: str - The original file name.\n\nRet...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nfrom datetime import datetime\nimport threading\nimport struct\n\ndef generate_filename(template: str, record_id: int, date: str, orig_name: str) -> str:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00014723", "row_id": 14723, "seed_ids": "[420]" }
0.369572
Docs: Python310_14723
I
[ "generate_filename", "process_dataset", "batch_process" ]
3
[ [ "process_dataset", "generate_filename" ] ]
1
[ "process_dataset" ]
false
[]
false
pytest
true
[]
true
4a15f05589093899ab59ff3c331c45b8bc559c8c
7e50f15bd65a30afdcdc3beb021aa7995730b23f
v1.0
instruct
Docs
Docs: Python310_14737_I
#### Problem Statement You are required to implement a Python program that creates a simple echo server and client using the socket module. The server should be able to handle multiple clients using the `selectors` module to multiplex the I/O. 1. **Server Requirements**: - It should listen on a specified IP addres...
# server.py import selectors import socket sel = selectors.DefaultSelector() def accept(sock, mask): conn, addr = sock.accept() print('accepted', conn, 'from', addr) conn.setblocking(False) sel.register(conn, selectors.EVENT_READ, read) def read(conn, mask): data = conn.recv(1000) if data: ...
# test_echo_server.py import socket import subprocess import time import threading def start_server(): subprocess.run(['python', 'server.py']) def test_echo_server(): # Start the server in a separate thread server_thread = threading.Thread(target=start_server, daemon=True) server_thread.start() #...
[ { "docstring": null, "function_declaration": "def accept(sock, mask):", "function_name": "accept", "parameter_list": "(sock, mask)" }, { "docstring": null, "function_declaration": "def read(conn, mask):", "function_name": "read", "parameter_list": "(conn, mask)" }, { "doc...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "# server.py\nimport selectors\nimport socket\n\nsel = selectors.DefaultSelector()\n\ndef accept(sock, mask):\n conn, addr = sock.accept()\n print('accepted', conn...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00014737", "row_id": 14737, "seed_ids": "[151]" }
0.716067
Docs: Python310_14737
I
[ "accept", "read", "main", "main" ]
4
[ [ "accept", "read" ] ]
1
[]
false
[]
false
pytest
false
[]
true
2f26b717c3ee9be3e6484c3da3696a6c80a67ba6
8403e14ef41e91df3b53b450da72595b4820674c
v1.0
instruct
Docs
Docs: Python310_14755_I
You are required to implement a Python program using the asyncio library to simulate a simplified multi-user chat server. The server will allow multiple clients to connect, send messages, and broadcast them to all connected clients simultaneously. ### Objectives 1. **Create a Chat Server**: - Implement an asynchro...
import asyncio import traceback clients = set() async def handle_client(reader, writer): addr = writer.get_extra_info('peername') print(f"{addr} is connected") clients.add(writer) try: while True: data = await reader.read(100) # Customize the buffer size as needed ...
import asyncio import pytest from solution import start_server, handle_client, broadcast_message from asyncio import StreamReader, StreamWriter @pytest.fixture def event_loop(): loop = asyncio.new_event_loop() yield loop loop.close() @pytest.mark.asyncio async def test_broadcast_message(): clients = ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nclients = []\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Connected with {addr}\")\n cli...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00014755", "row_id": 14755, "seed_ids": "[270]" }
0.571134
Docs: Python310_14755
I
[ "handle_client", "broadcast_message", "start_server" ]
3
[ [ "handle_client", "broadcast_message" ], [ "start_server", "handle_client" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b7ee9990c1587ba97ee6d9b4785cd3e022d2016c
3cc8a3d37a04fed0bc39e2dfc0a38d8318604585
v1.0
instruct
Docs
Docs: Pytorch_14826_I
#### Asynchronous Model Training using PyTorch Multiprocessing **Objective:** Implement a function to train a neural network model asynchronously using PyTorch's multiprocessing package. Ensure efficient use of resources and proper handling of potential pitfalls such as deadlocks and CPU oversubscription. **Problem S...
import torch import torch.optim as optim import torch.utils.data as data import torch.multiprocessing as mp from torch.multiprocessing import Pool def data_loader(dataset): return torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True) def loss_fn(output, target): return torch.nn.functional.cross_en...
import torch import torch.nn as nn import torch.utils.data as data import torch.multiprocessing as mp from solution import asynchronous_train class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.linear = nn.Linear(784, 10) def forward(self, x): ret...
[ { "docstring": null, "function_declaration": "def data_loader(dataset):", "function_name": "data_loader", "parameter_list": "(dataset)" }, { "docstring": null, "function_declaration": "def loss_fn(output, target):", "function_name": "loss_fn", "parameter_list": "(output, target)"...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.optim as optim\nimport torch.utils.data as data\nfrom torch.multiprocessing import Pool\nimport torch.multiprocessing as mp\n\ndef data_loade...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00014826", "row_id": 14826, "seed_ids": "[160]" }
0.559837
Docs: Pytorch_14826
I
[ "data_loader", "loss_fn", "train_model", "asynchronous_train" ]
4
[ [ "train_model", "data_loader" ], [ "train_model", "loss_fn" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
c26f93d458c0a976047a868078059474aac00087
86c3c68e58d28b02a7ffee0df579da6b6d6a5e6f
v1.0
instruct
Docs
Docs: Scikit_14853_I
### Question: Implementing a Custom Kernel SVM for Classification with Class Imbalance Handling You are provided with a dataset that you need to classify using a Support Vector Machine (SVM). However, this problem has certain nuances: 1. You need to implement a custom kernel function. 2. The dataset is imbalanced, and...
import numpy as np from sklearn.svm import SVC def polynomial_rbf_kernel(X, Y, d=3, gamma=0.1): """ Custom kernel function that combines polynomial and RBF kernels. Args: - X: np.ndarray, first input matrix of shape (n_samples_X, n_features) - Y: np.ndarray, second input matrix of shape (n_sam...
import numpy as np from solution import polynomial_rbf_kernel, svm_with_custom_kernel def test_polynomial_rbf_kernel(): X = np.array([[1, 2], [3, 4]]) Y = np.array([[5, 6], [7, 8]]) result = polynomial_rbf_kernel(X, Y, d=3, gamma=0.1) assert result.shape == (2, 2) assert np.all(result > 0) def tes...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from sklearn.svm import SVC\nimport numpy as np\n\ndef polynomial_rbf_kernel(X, Y, d=3, gamma=0.1):\n polynomial = (np.dot(X, Y.T) + 1) ** d\n rbf = np.exp(-gamma...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00014853", "row_id": 14853, "seed_ids": "[31]" }
0.558225
Docs: Scikit_14853
I
[ "polynomial_rbf_kernel", "svm_with_custom_kernel" ]
2
[ [ "svm_with_custom_kernel", "polynomial_rbf_kernel" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
d3383acc8d4a5a111444f24e0d58b223ee4611f3
60fbafae64858c94b82256d42213157bddab3848
v1.0
instruct
Docs
Docs: Python310_14855_I
**Programming Task: Work with Future and Task Objects in Asyncio** **Objective:** Write a Python program to create and manage `Future` and `Task` objects using the `asyncio` library. **Task Description:** 1. Create an asynchronous function `async compute_square(fut, n)` that takes a `Future` object `fut` and an integ...
import asyncio async def compute_square(fut, n): # Simulate a delay await asyncio.sleep(2) # Set the result of the Future fut.set_result(n * n) async def gather_squares(numbers): loop = asyncio.get_running_loop() futures = [] for number in numbers: fut = loop.create_future() ...
import asyncio from solution import compute_square, gather_squares, main async def test_compute_square(): loop = asyncio.get_running_loop() fut = loop.create_future() await compute_square(fut, 3) assert fut.result() == 9 async def test_gather_squares(): result = await gather_squares([1, 2, 3]) ...
[]
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def compute_square(fut, n):\n # Simulate a delay\n await asyncio.sleep(2)\n # Set the result of the Future\n fut.set_result(n * n)\n...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00014855", "row_id": 14855, "seed_ids": "[113]" }
0.489719
Docs: Python310_14855
I
[ "compute_square", "gather_squares", "main" ]
3
[ [ "gather_squares", "compute_square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7f2215cfa97977fe31e340150537885b4d1b0e1e
1ca5189bcb2fac2ec4fe1636d7ac91acc39d03e1
v1.0
instruct
Docs
Docs: Python310_14870_I
#### Objective To assess the understanding and ability to use Python's `concurrent.futures` module, specifically focusing on `ThreadPoolExecutor` and `ProcessPoolExecutor` for managing asynchronous tasks. #### Question You are tasked with processing a list of URLs to check whether they are reachable (i.e., return a st...
import concurrent.futures from typing import List, Dict import urllib.request def fetch_status(url: str, timeout: float) -> bool: try: with urllib.request.urlopen(url, timeout=timeout) as response: return response.status == 200 except: return False def check_urls(urls: List[str], m...
from solution import check_urls def test_check_urls_all_reachable(): urls = [ "http://www.google.com", "http://www.python.org" ] results = check_urls(urls, max_workers=2, timeout=5.0) assert results == { "http://www.google.com": True, "http://www.python.org": True } ...
[ { "docstring": null, "function_declaration": "def fetch_status(url, timeout):", "function_name": "fetch_status", "parameter_list": "(url, timeout)" }, { "docstring": null, "function_declaration": "def check_urls(urls, max_workers, timeout):", "function_name": "check_urls", "param...
[ 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 concurrent.futures\nfrom typing import List, Dict\nimport urllib.request\n\ndef fetch_status(url: str, timeout: float) -> bool:\n try:\n with urllib.re...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00014870", "row_id": 14870, "seed_ids": "[347]" }
0.640969
Docs: Python310_14870
I
[ "fetch_status", "check_urls" ]
2
[ [ "check_urls", "fetch_status" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9d7a87dde68df48b0ab38600bd53ffa6f05fd1f8
9bb532de2ff58949186020be10531df2c1465b08
v1.0
instruct
Docs
Docs: Python310_14932_I
You are tasked with creating a Python module that mimics some of the functionalities provided by the `PyFunction` C API, specifically for creating and inspecting function objects. Your implementation will involve: 1. Verifying if an object is a function. 2. Creating a new function object. 3. Retrieving and setting the...
from types import FunctionType, CodeType def is_function(obj) -> bool: """ Check if the given object is a function object. :param obj: Object to check. :type obj: Any :return: True if object is a function, False otherwise. :rtype: bool """ return isinstance(obj, FunctionType) def crea...
import pytest from types import CodeType from solution import is_function, create_function, get_function_details, set_function_globals def test_is_function(): def sample_func(): pass assert is_function(sample_func) == True assert is_function(42) == False assert is_function("string") == Fal...
[ { "docstring": "Check if the given object is a function object.\n\n:param obj: Object to check.\n:type obj: Any\n:return: True if object is a function, False otherwise.\n:rtype: bool", "function_declaration": "def is_function(obj):", "function_name": "is_function", "parameter_list": "(obj)" }, {...
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_function(obj) -> bool:\n \"\"\"\n Check if the given object is a function object.\n\n :param obj: Object to check.\n :type obj: Any\n :return: Tru...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00014932", "row_id": 14932, "seed_ids": "[2]" }
0.663111
Docs: Python310_14932
I
[ "is_function", "create_function", "get_function_details", "set_function_globals" ]
4
[ [ "get_function_details", "is_function" ], [ "set_function_globals", "is_function" ] ]
2
[]
false
[]
false
pytest
true
[]
true
c2505cfc83f6dd7958c5ee6e825b20d06ed27b46
15355dd497bd2f41903d258ce216988bf046a0f0
v1.0
instruct
Docs
Docs: Python310_14975_I
### Question: Implementing and Validating Logging Configuration using `logging.config.dictConfig()` #### Objective Your task is to configure and validate a logging setup using the `logging.config.dictConfig()` function from the `logging.config` module in Python. #### Problem Statement 1. Implement a function `confi...
import logging.config def configure_logging(config_dict): """ Configures logging using the provided configuration dictionary. """ logging.config.dictConfig(config_dict) def validate_logging_configuration(config_dict): """ Validates the provided logging configuration dictionary. Returns Tru...
from solution import configure_logging, validate_logging_configuration import pytest def test_valid_config(): valid_config = { 'version': 1, 'formatters': { 'simple': { 'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s' } }, 'han...
[ { "docstring": "Configures logging using the provided configuration dictionary.", "function_declaration": "def configure_logging(config_dict):", "function_name": "configure_logging", "parameter_list": "(config_dict)" }, { "docstring": "Validates the provided logging configuration dictionary....
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import logging\nimport logging.config\n\ndef configure_logging(config_dict):\n \"\"\"\n Configures logging using the provided configuration dictionary.\n \"\"\...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00014975", "row_id": 14975, "seed_ids": "[195]" }
0.56309
Docs: Python310_14975
I
[ "configure_logging", "validate_logging_configuration", "test_logging_configuration" ]
3
[ [ "test_logging_configuration", "configure_logging" ], [ "test_logging_configuration", "validate_logging_configuration" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3b800ea7169cd574f3c53198ea52aef2e74afcaf
4c556c3f861077b5a4803f83911b93a8743ea666
v1.0
instruct
Docs
Docs: Python310_14999_I
### Formatted String Handling and Case-Insensitive Comparison You are required to implement functions that will read formatted data from a given string, convert it to numbers, perform specific operations, and then output the result as a formatted string. Additionally, you will perform case-insensitive comparisons betw...
def convert_string_to_double(s: str) -> float: """ Converts the given string `s` to a floating-point number. Parameters: s (str): The string to convert. Returns: float: The converted floating point number. Raises: ValueError: If the string is not a valid floating-point num...
import pytest from solution import convert_string_to_double, convert_double_to_string, case_insensitive_compare, format_and_compare def test_convert_string_to_double(): assert convert_string_to_double("123.456") == 123.456 assert convert_string_to_double("0.567") == 0.567 assert convert_string_to_double("-...
[ { "docstring": "Converts the given string `s` to a floating-point number.\n\nParameters:\ns (str): The string to convert.\n\nReturns:\nfloat: The converted floating point number.\n\nRaises:\nValueError: If the string is not a valid floating-point number.", "function_declaration": "def convert_string_to_doub...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def convert_string_to_double(s: str) -> float:\n \"\"\"\n Converts the given string `s` to a floating-point number.\n \n Parameters:\n s (str): The strin...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00014999", "row_id": 14999, "seed_ids": "[31]" }
0.61942
Docs: Python310_14999
I
[ "convert_string_to_double", "convert_double_to_string", "case_insensitive_compare", "format_and_compare" ]
4
[ [ "format_and_compare", "case_insensitive_compare" ], [ "format_and_compare", "convert_double_to_string" ], [ "format_and_compare", "convert_string_to_double" ] ]
3
[]
false
[]
false
pytest
true
[]
true
6f6c775ecffd14999767467b0456531eb988d5cf
554abc64db1c59f9ad4d84082e4a74522a4d75eb
v1.0
instruct
Docs
Docs: Python310_15033_I
### Asynchronous Programming with asyncio #### Problem Statement You are tasked with implementing an asynchronous program that simulates tasks performed by a group of workers. Each worker performs several asynchronous operations, some of which may involve blocking I/O and CPU-bound tasks. Implement the following func...
import asyncio import logging from concurrent.futures import ThreadPoolExecutor import time logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) async def io_bound_task(id): await asyncio.sleep(2) # Simulating an I/O-bound task, e.g., reading from a file logger.debug(f"Worker {id} co...
import asyncio from solution import main def test_async_program_execution(): # This test will just run the main function and ensure it completes without errors. try: asyncio.run(main()) except Exception as e: pytest.fail(f"Worker execution raised an unexpected exception: {e}") # Note: It i...
[ { "docstring": null, "function_declaration": "def cpu_bound_task(id):", "function_name": "cpu_bound_task", "parameter_list": "(id)" } ]
[ 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 logging\nfrom concurrent.futures import ThreadPoolExecutor\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.get...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015033", "row_id": 15033, "seed_ids": "[200]" }
0.53506
Docs: Python310_15033
I
[ "io_bound_task", "cpu_bound_task", "worker", "main" ]
4
[ [ "worker", "cpu_bound_task" ], [ "worker", "io_bound_task" ] ]
2
[]
false
[]
false
pytest
true
[]
true
ff54649e1523c847dec5c24eec85a13ad987106c
0eaa49efdb29757726667b75d4ba6ed38af428da
v1.0
instruct
Docs
Docs: Python310_15055_I
### Coding Assessment: Parallel Processing with `multiprocessing` #### Objective: The aim of this exercise is to assess your understanding and utilization of the `multiprocessing` package in Python. You will be required to implement a function that processes a list of numbers in parallel and applies different mathemat...
import multiprocessing def square(x): return x * x def cube(x): return x * x * x def double(x): return x * 2 def process_operation(operation_value_tuple): operation, value = operation_value_tuple operation_map = { 'square': square, 'cube': cube, 'double': double } ...
import multiprocessing from solution import parallel_process_operations def test_parallel_process_operations_basic(): operations = [('square', 2), ('cube', 3), ('double', 4)] expected = [4, 27, 8] assert parallel_process_operations(operations) == expected def test_parallel_process_operations_different_ord...
[ { "docstring": null, "function_declaration": "def square(x):", "function_name": "square", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def cube(x):", "function_name": "cube", "parameter_list": "(x)" }, { "docstring": null, "function_declara...
[ 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 multiprocessing\n\ndef square(x):\n return x * x\n\ndef cube(x):\n return x * x * x\n\ndef double(x):\n return x * 2\n\ndef parallel_process_operations(...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00015055", "row_id": 15055, "seed_ids": "[338]" }
0.707497
Docs: Python310_15055
I
[ "square", "cube", "double", "process_operation", "parallel_process_operations" ]
5
[ [ "parallel_process_operations", "process_operation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c268e7f5de779dba2afd6d187eb782b1d3ee421e
8f1c26e367475ad9afa3cfd9468f20c38a08230b
v1.0
instruct
Docs
Docs: Pytorch_15058_I
<|Analysis Begin|> The provided documentation outlines several environment variables specific to PyTorch's use of Apple's Metal Performance Shaders (MPS). These variables control various aspects such as logging, profiling, and memory allocation behaviors. Key aspects include setting high and low watermark ratios for m...
import os import torch def configure_pytorch_mps(): """ Configures the PyTorch MPS environment variables. """ os.environ['PYTORCH_MPS_FAST_MATH'] = '1' os.environ['PYTORCH_MPS_HIGH_WATERMARK_RATIO'] = '0.95' os.environ['PYTORCH_MPS_LOW_WATERMARK_RATIO'] = '0.85' os.environ['PYTORCH_DEBUG_MP...
import os from unittest.mock import patch def test_configure_pytorch_mps(): from solution import configure_pytorch_mps with patch.dict(os.environ, {}, clear=True): configure_pytorch_mps() assert os.environ['PYTORCH_MPS_FAST_MATH'] == '1' assert os.environ['PYTORCH_MPS_HIGH...
[ { "docstring": "Configures the PyTorch MPS environment variables.", "function_declaration": "def configure_pytorch_mps():", "function_name": "configure_pytorch_mps", "parameter_list": "()" }, { "docstring": "Creates and trains a dummy linear regression model to demonstrate the applied MPS co...
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport torch\n\ndef configure_pytorch_mps():\n \"\"\"\n Configures the PyTorch MPS environment variables.\n \"\"\"\n os.environ['PYTORCH_MPS_FAST...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00015058", "row_id": 15058, "seed_ids": "[64]" }
0.390098
Docs: Pytorch_15058
I
[ "configure_pytorch_mps", "train_dummy_model" ]
2
[ [ "train_dummy_model", "configure_pytorch_mps" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
cd7ec439ded96cc1b2e2430cfb2531ecdc903630
3f8dc3b34ec869713ee950f8e382f1aaba95d5fe
v1.0
instruct
Docs
Docs: Python310_15101_I
#### Objective Create an advanced interactive command-line prompt that uses features from the `readline` module to enhance user experience. The prompt should be able to handle command history, support custom tab completion, and save the session history to a file. #### Task 1. Implement an interactive command-line prom...
import readline import atexit import os def setup_readline(history_file, commands): # Initialize history try: readline.read_history_file(history_file) except FileNotFoundError: open(history_file, 'wb').close() readline.set_history_length(500) readline.parse_and_bind("tab: c...
import os import readline from solution import setup_readline, run_prompt def test_setup_readline(): history_file = "test_history" commands = ["hello", "exit"] # Remove file if it exists if os.path.exists(history_file): os.remove(history_file) # Setup readline with test history fi...
[ { "docstring": null, "function_declaration": "def setup_readline(history_file, commands):", "function_name": "setup_readline", "parameter_list": "(history_file, commands)" }, { "docstring": null, "function_declaration": "def run_prompt():", "function_name": "run_prompt", "paramet...
[ 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 readline\nimport atexit\nimport os\n\ndef setup_readline(history_file, commands):\n # Initialize history\n try:\n readline.read_history_file(history...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00015101", "row_id": 15101, "seed_ids": "[362]" }
0.391214
Docs: Python310_15101
I
[ "setup_readline", "run_prompt" ]
2
[ [ "run_prompt", "setup_readline" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d7970da316334f94789394fc614edc0541415c78
582a6aa366c363bc58102a214f6cb9a9353838d2
v1.0
instruct
Docs
Docs: Pytorch_15115_I
## Problem Statement You are required to implement a multiprocessing system using PyTorch's `torch.distributed.elastic.multiprocessing` package. Your task is to simulate a distributed training setup where multiple worker processes perform computations on separate portions of input data, and then aggregate the results....
import torch.multiprocessing as mp def compute_worker(data_segment): return [x ** 2 for x in data_segment] def distributed_computation(data, num_workers): def worker_process(data_partition, return_list, index): result = compute_worker(data_partition) return_list[index] = result # Splittin...
from solution import distributed_computation import pytest def test_distributed_computation_basic(): data = [1, 2, 3, 4, 5, 6] num_workers = 2 expected_output = [1, 4, 9, 16, 25, 36] assert distributed_computation(data, num_workers) == expected_output def test_distributed_computation_single_worker(): ...
[ { "docstring": null, "function_declaration": "def compute_worker(data_segment):", "function_name": "compute_worker", "parameter_list": "(data_segment)" }, { "docstring": null, "function_declaration": "def distributed_computation(data, num_workers):", "function_name": "distributed_com...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.distributed.elastic.multiprocessing import start_processes\nimport math\n\ndef compute_worker(data_segment, return_list, index):\n \"\"\"\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015115", "row_id": 15115, "seed_ids": "[143]" }
0.56273
Docs: Pytorch_15115
I
[ "compute_worker", "distributed_computation" ]
2
[ [ "distributed_computation", "compute_worker" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
d18fa4f5920a397a33c295a4353cbbc68eaee199
3f64713089a8045f47a64a21b608448f1f092cca
v1.0
instruct
Docs
Docs: Python310_15173_I
**Objective:** To assess your understanding of the `asyncio` exceptions in Python 3.10, you will write a function that performs asynchronous I/O operations and handles specific `asyncio` exceptions gracefully. **Problem Statement:** Implement an asynchronous function `perform_async_operations()` which performs the f...
import asyncio from typing import List async def read_file(path: str) -> str: try: reader = await asyncio.open_file(path, mode='r') data = await reader.read() await reader.close() return data except asyncio.TimeoutError: print(f'Timeout error reading {path}') except ...
import pytest import asyncio from tempfile import NamedTemporaryFile from unittest.mock import patch from solution import perform_async_operations @pytest.mark.asyncio async def test_perform_async_operations(): with NamedTemporaryFile(delete=False) as temp_input1, \ NamedTemporaryFile(delete=False) as tem...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List\n\nasync def perform_async_operations(input_files: List[str], output_file: str) -> None:\n try:\n async with aiofiles....
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015173", "row_id": 15173, "seed_ids": "[396]" }
0.487478
Docs: Python310_15173
I
[ "read_file", "write_file", "perform_async_operations" ]
3
[ [ "perform_async_operations", "read_file" ], [ "perform_async_operations", "write_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6569ae6eefbc40b0efd2da7c756afe21b6dfe81c
cad1acfcedfe1ee00624f22899e1c4d6da74d3ff
v1.0
instruct
Docs
Docs: Python310_15199_I
### Question: Data Encoding and Decoding with Base64 Module You are tasked to create a Python program that can encode and decode given binary data using different base encoding schemes (Base16, Base32, Base64, and Base85). The program should handle exceptions gracefully and print meaningful error messages when an enco...
import base64 def encode_data(data: bytes, encoding: str) -> bytes: if encoding == "base16": return base64.b16encode(data) elif encoding == "base32": return base64.b32encode(data) elif encoding == "base64": return base64.b64encode(data) elif encoding == "base85": return ...
import pytest from solution import encode_data, decode_data, compare_encodings def test_encode_decode_base16(): original_data = b"test_data" encoding = "base16" encoded_data = encode_data(original_data, encoding) decoded_data = decode_data(encoded_data, encoding) assert original_data == decoded_dat...
[ { "docstring": null, "function_declaration": "def encode_data(data, encoding):", "function_name": "encode_data", "parameter_list": "(data, encoding)" }, { "docstring": null, "function_declaration": "def decode_data(encoded_data, encoding):", "function_name": "decode_data", "param...
[ 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 base64\n\ndef encode_data(data: bytes, encoding: str) -> bytes:\n \"\"\"\n Encodes the given data with the specified encoding scheme.\n \n :param dat...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00015199", "row_id": 15199, "seed_ids": "[123]" }
0.681075
Docs: Python310_15199
I
[ "encode_data", "decode_data", "compare_encodings" ]
3
[ [ "compare_encodings", "decode_data" ], [ "compare_encodings", "encode_data" ] ]
2
[]
false
[]
false
pytest
true
[]
true
81a18854a73f1226e491bda550e7504351dacce7
0a972733e02b9a6d82468f8c1e22cb819976fb85
v1.0
instruct
Docs
Docs: Python310_15206_I
### Advanced Python310 Coding Assessment **Objective**: Demonstrate your understanding of Python's `contextvars` module by creating a complex multi-threaded application that utilizes context variables to maintain state. **Problem Statement**: You are required to write a Python program that manages the execution of t...
from concurrent.futures import ThreadPoolExecutor import contextvars import threading import time import random # Step 1: Create a context variable named task_id task_id = contextvars.ContextVar('task_id') def set_task_id(id): task_id.set(id) # Step 2: Implement the start_task function def start_task(task_number...
from solution import start_task, run_tasks_in_threads def test_start_task(): task_number = 42 assert start_task(task_number) == task_number def test_run_tasks_in_threads_single_task(): task_numbers = [1] results = run_tasks_in_threads(task_numbers) assert results == task_numbers def test_run_task...
[ { "docstring": null, "function_declaration": "def set_task_id(id):", "function_name": "set_task_id", "parameter_list": "(id)" }, { "docstring": null, "function_declaration": "def start_task(task_number):", "function_name": "start_task", "parameter_list": "(task_number)" }, { ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ThreadPoolExecutor\nimport contextvars\nimport threading\nimport time\nimport random\n\n# Step 1: Create a context variable named task_id...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015206", "row_id": 15206, "seed_ids": "[60]" }
0.590493
Docs: Python310_15206
I
[ "set_task_id", "start_task", "run_tasks_in_threads" ]
3
[ [ "run_tasks_in_threads", "start_task" ], [ "start_task", "set_task_id" ] ]
2
[]
false
[]
false
pytest
true
[]
true
95de0405604e625efbe14a5a7c2d7d3107bc415e
93e827979e780e7196c73660795d3551d86e4c43
v1.0
instruct
Docs
Docs: Python310_15279_I
Asynchronous Web Scraper **Objective**: The goal of this exercise is to demonstrate your understanding of Python's `asyncio` library, including creating and running coroutines, managing tasks, handling concurrency, and implementing timeouts and cancellations. **Problem Statement**: You are required to create an async...
import asyncio import aiohttp from typing import List async def fetch_data(url: str) -> str: """ Performs an HTTP GET request to the given URL and returns the response text. Implements a timeout of 3 seconds. """ async with aiohttp.ClientSession() as session: try: async with ses...
import asyncio from solution import fetch_data, scrape_urls async def test_fetch_data(): result = await fetch_data("https://jsonplaceholder.typicode.com/posts") assert "userId" in result async def test_fetch_data_timeout(): result = await fetch_data("https://httpbin.org/delay/5") # This URL delays respon...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nfrom typing import List\n\nasync def fetch_data(url: str) -> str:\n \"\"\"\n Performs an HTTP GET request to the given URL and ret...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00015279", "row_id": 15279, "seed_ids": "[317]" }
0.639594
Docs: Python310_15279
I
[ "fetch_data", "scrape_urls", "main" ]
3
[ [ "scrape_urls", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
5c67b1fae88393fe27f388c5a72fdbf8196f92ac
62207d63a56504b26b9c49f55ae595bacbc82990
v1.0
instruct
Docs
Docs: Python310_15321_I
**Objective**: Demonstrate a deep understanding of asyncio's `Future` class and related functionalities in Python. **Requirements**: Implement a function that coordinates multiple asynchronous operations using `Future` objects. Specifically, you will write a function `process_tasks` that: 1. Schedules three asynchrono...
import asyncio async def set_future_after_delay(future, result, delay): await asyncio.sleep(delay) future.set_result(result) async def process_tasks() -> list: loop = asyncio.get_event_loop() future1 = loop.create_future() future2 = loop.create_future() future3 = loop.create_future() ...
import pytest import asyncio from solution import process_tasks @pytest.mark.asyncio async def test_process_tasks(): results = await process_tasks() assert results == ['result1', 'result2', 'result3']
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def set_future_after_delay(future, result, delay):\n await asyncio.sleep(delay)\n future.set_result(result)\n\nasync def process_tasks() -...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00015321", "row_id": 15321, "seed_ids": "[113]" }
0.566644
Docs: Python310_15321
I
[ "set_future_after_delay", "process_tasks" ]
2
[ [ "process_tasks", "set_future_after_delay" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3611f9d8348296127470d9f0d469988ab5493a05
aacdd4cdc16754fb3f7c149e8c752b394ed78394
v1.0
instruct
Docs
Docs: Python310_15334_I
### Asynchronous Web Scraper with asyncio #### Problem Statement: You are tasked with creating an asynchronous web scraper using the `asyncio` package. Your scraper should perform the following tasks: 1. Fetch the HTML content from multiple URLs concurrently. 2. Parse the HTML to extract specific information (for th...
import aiohttp import asyncio from bs4 import BeautifulSoup async def fetch_url(session, url): try: async with session.get(url, timeout=10) as response: return await response.text() except asyncio.TimeoutError: print(f"Timeout while fetching {url}") except Exception as e: ...
import pytest import asyncio from solution import fetch_url, parse_html, scrape_titles # Helper function to run async functions for testing def run_async(func, *args): return asyncio.run(func(*args)) # Note: These tests require live internet connections and access to the URLs. async def mock_fetch_url(session, u...
[ { "docstring": null, "function_declaration": "def parse_html(html):", "function_name": "parse_html", "parameter_list": "(html)" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import aiohttp\nimport asyncio\nfrom bs4 import BeautifulSoup\n\nasync def fetch_url(session, url):\n try:\n async with session.get(url, timeout=10) as respon...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015334", "row_id": 15334, "seed_ids": "[360]" }
0.625871
Docs: Python310_15334
I
[ "fetch_url", "parse_html", "scrape_titles" ]
3
[ [ "scrape_titles", "fetch_url" ], [ "scrape_titles", "parse_html" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp", "bs4" ]
false
2552cff1d21720812c5b377dae1aae09f946418e
e62e91ab2a593ad027698be64d607ba9fb86fae2
v1.0
instruct
Docs
Docs: Python310_15343_I
Cross-Platform Asynchronous Task Manager You are tasked with creating a cross-platform asynchronous task manager using Python's `asyncio` module. The task manager must be able to: 1. Schedule and wait for completion of multiple asynchronous tasks. 2. Handle cross-platform differences in the event loop implementations....
import asyncio import random import selectors import platform async def sample_task(): await asyncio.sleep(random.randint(1, 5)) return random.randint(1, 5) def configure_event_loop(): sys_platform = platform.system() if sys_platform == 'Windows': asyncio.set_event_loop(asyncio.ProactorEventLo...
import pytest import asyncio import random from solution import sample_task, schedule_tasks @pytest.mark.asyncio async def test_schedule_tasks(): # Create a list of sample tasks tasks = [sample_task() for _ in range(5)] results = await schedule_tasks(tasks) # Check that we have results for each ta...
[ { "docstring": null, "function_declaration": "def configure_event_loop():", "function_name": "configure_event_loop", "parameter_list": "()" } ]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\nimport random\nimport selectors\n\nasync def sample_task():\n \"\"\"\n A sample task that waits for a random time between 1 and 5...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015343", "row_id": 15343, "seed_ids": "[370]" }
0.597542
Docs: Python310_15343
I
[ "sample_task", "configure_event_loop", "schedule_tasks" ]
3
[ [ "schedule_tasks", "configure_event_loop" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5e15a62538a34d9e50469fbce99e97c8529a98ad
019e1e1d44332f0fc9d1e21a7e9b1f5332f03a30
v1.0
instruct
Docs
Docs: Pytorch_15348_I
### Distributed Training with PyTorch: Implementing a Simple Distributed Data-Parallel Model **Objective:** Your task is to implement a basic distributed data-parallel model using the `torch.distributed` package. This will involve initializing the process group, defining a simple neural network model, applying a colle...
import os import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim from torch.multiprocessing import spawn from torch.utils.data import DataLoader, TensorDataset # 1. Environment variables setup def setup(rank, world_size, master_addr='localhost', master_port='12355'): os.env...
import pytest import torch import torch.distributed as dist from torch.multiprocessing import spawn from solution import setup, SimpleNN, train_model def test_setup(): rank = 0 world_size = 2 master_addr = 'localhost' master_port = '12355' setup(rank, world_size, master_addr, master_port) asser...
[]
[ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.multiprocessing import spawn\n\n# 1. Environme...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00015348", "row_id": 15348, "seed_ids": "[131]" }
0.494594
Docs: Pytorch_15348
I
[ "setup", "train_model", "main" ]
3
[ [ "train_model", "setup" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
f37e8c8357f70511b1bd8eefab73af2676903313
295b337d64b3958cb7b1962073ee8de068605efb
v1.0
instruct
Docs
Docs: Python310_15390_I
### Asynchronous Network Communication with Python's `asyncio` Streams #### Objective Write a Python program using the `asyncio` streams module to implement a custom server-client architecture. You need to demonstrate skills in network connection management, asynchronous data transmission, and graceful connection term...
import asyncio # Server Code async def handle_client(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') log_message = f"Received {message!r} from {addr!r}" print(log_message) response = f"Received {message!r}" writer.write(respo...
import pytest import asyncio from solution import handle_client, start_server, send_message @pytest.mark.asyncio async def test_server_client_interaction(capfd): # Start server server_task = asyncio.create_task(start_server()) # Allow server some time to start up await asyncio.sleep(1) # ...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
1
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import asyncio\n\n# Server Code\nasync def handle_client(reader, writer):\n data = await reader.read(100)\n message = data.decode()\n ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00015390", "row_id": 15390, "seed_ids": "[182]" }
0.678964
Docs: Python310_15390
I
[ "handle_client", "start_server", "send_message", "main" ]
4
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5221c814c2a8e50e26966d332688b51551b90377
845cabbd46ee1c6e662e65b650f29bc9a15256f4
v1.0
instruct
Docs
Docs: Python310_15392_I
### Coding Assessment: Audit Event Logger #### Objective: You are to implement a Python function that sets up an audit hook, logs specific audit events to a file, and then provides a summary of these events. #### Requirements: 1. Implement a function `setup_audit_logger(events_to_log: List[str], log_file: str) -> Non...
import sys import os from typing import List, Dict def audit_hook(event, args): """ This function will be used as the audit hook to log events. """ if event in sys.audit_events_to_log: with open(sys.audit_log_file, "a") as f: f.write(f"{event}: {args}\n") def setup_audit_logger(eve...
import os import sys from solution import setup_audit_logger, summarize_events def test_setup_audit_logger(): # Setting up for test events = ["os.remove", "os.rmdir"] log_file_path = "test_audit_log.txt" # Clearing log file with open(log_file_path, "w"): pass # Setting up the audit log ...
[ { "docstring": "This function will be used as the audit hook to log events.", "function_declaration": "def audit_hook(event, args):", "function_name": "audit_hook", "parameter_list": "(event, args)" }, { "docstring": "Sets up the audit logger to listen for specific events and logs them to a ...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import audit\nimport json\nfrom typing import List, Dict\n\ndef setup_audit_logger(events_to_log: List[str], log_file: str) -> None:\n def audit_hook(event, args):\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015392", "row_id": 15392, "seed_ids": "[167]" }
0.642569
Docs: Python310_15392
I
[ "audit_hook", "setup_audit_logger", "summarize_events" ]
3
[ [ "setup_audit_logger", "audit_hook" ] ]
1
[]
false
[]
false
pytest
true
[]
true
38de958db16074d47d942ce4acd7cadb0765f499
bbd9b315a37b205afa710860ba1dc709342d38a6
v1.0
instruct
Docs
Docs: Python310_15399_I
**Objective:** Implement a TCP echo server and client using the asyncio streams functionality provided in Python 3.10. This exercise will test your understanding of asynchronous programming, handling network connections, and using the StreamReader and StreamWriter classes. **Task 1: TCP Echo Server** 1. Define an asy...
import asyncio async def handle_client(reader, writer): """ Handles communication with the client. Reads a message from the client, echoes it back, and then closes the connection. """ data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f...
import asyncio import pytest from solution import handle_client, start_server, tcp_echo_client @pytest.mark.asyncio async def test_handle_client(): reader, writer = await asyncio.open_connection('localhost', 8888) message = "test_message" # Simulate client sending message writer.write(message.encode()...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Connection from {addr}\")\n\n while True:\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015399", "row_id": 15399, "seed_ids": "[182]" }
0.663733
Docs: Python310_15399
I
[ "handle_client", "start_server", "tcp_echo_client" ]
3
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a9272daca9d428b43dab2ec5761119303490c2f8
77f93bf2738c041f56876f277031125a1ea1a990
v1.0
instruct
Docs
Docs: Python310_15404_I
### Problem: You are tasked with implementing a task scheduler that works based on priorities. The scheduler should be able to handle tasks with various priorities, allowing you to efficiently add tasks, remove tasks, and fetch the highest priority task. You need to implement the following functions using the `heapq`...
import heapq def add_task(task_list, task, priority, entry_finder): """ Adds a new task with a given priority to the task list. """ if task in entry_finder: remove_task(task_list, task, entry_finder, '<removed-task>') entry = [priority, task] entry_finder[task] = entry heapq.heappus...
import pytest from solution import add_task, remove_task, pop_task, get_n_highest_priority_tasks def test_add_task(): task_list = [] entry_finder = {} removed_marker = '<removed-task>' add_task(task_list, 'task1', 2, entry_finder) assert 'task1' in entry_finder and entry_finder['task1'][0] == ...
[ { "docstring": "Adds a new task with a given priority to the task list.", "function_declaration": "def add_task(task_list, task, priority, entry_finder):", "function_name": "add_task", "parameter_list": "(task_list, task, priority, entry_finder)" }, { "docstring": "Removes a specific task fr...
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\n\ndef add_task(task_list, task, priority, entry_finder):\n \"\"\"\n Adds a new task with the given priority to the task list.\n If the task alrea...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00015404", "row_id": 15404, "seed_ids": "[241]" }
0.579474
Docs: Python310_15404
I
[ "add_task", "remove_task", "pop_task", "get_n_highest_priority_tasks" ]
4
[ [ "add_task", "remove_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
39b7ebee5a66f793fef005e9bc584c5c335080cf
13c03dfc3ae2527f31169f63e75adf0e48946345
v1.0
instruct
Docs
Docs: Python310_15419_I
### Resource Management and Monitoring in Python Given the following scenario: You are developing a Python application that performs heavy computations and file processing. To prevent the application from consuming too many system resources (which could affect other applications running on the same system), you need ...
import resource import functools import os def set_resource_limits(cpu_time_limit, file_size_limit): """ Sets the resource limits for CPU time and file size. Parameters: cpu_time_limit (int): Maximum CPU time in seconds. file_size_limit (int): Maximum file size in bytes. Returns: None ...
from solution import set_resource_limits, get_resource_usage, resource_limited_execution def test_set_resource_limits(): set_resource_limits(10, 10485760) # 10 seconds CPU time limit, 10 MB file size limit cpu_limit = resource.getrlimit(resource.RLIMIT_CPU) file_size_limit = resource.getrlimit(resource.RL...
[ { "docstring": "Sets the resource limits for CPU time and file size.\n\nParameters:\ncpu_time_limit (int): Maximum CPU time in seconds.\nfile_size_limit (int): Maximum file size in bytes.\n\nReturns:\nNone", "function_declaration": "def set_resource_limits(cpu_time_limit, file_size_limit):", "function_n...
[ 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 resource\nimport functools\nimport os\n\ndef set_resource_limits(cpu_time_limit, file_size_limit):\n \"\"\"\n Sets the resource limits for CPU time and fil...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00015419", "row_id": 15419, "seed_ids": "[312]" }
0.603449
Docs: Python310_15419
I
[ "set_resource_limits", "get_resource_usage", "resource_limited_execution" ]
3
[ [ "resource_limited_execution", "get_resource_usage" ], [ "resource_limited_execution", "set_resource_limits" ] ]
2
[]
false
[]
false
pytest
true
[]
true
294457e0488acf5efdcd3b2576a59dcbc909c983
443e8e2a474358640d18f1fd14baae9b2ac62286
v1.0
instruct
Docs
Docs: Python310_15423_I
## Coding Assessment Question ### Problem Statement You are given a log file containing multiple raw email messages, concatenated one after another. Each message is separated by a special delimiter string `"====="`. You need to implement a function `parse_emails_from_log(log_file)`, which reads the log file, parses ea...
import email from email.parser import BytesFeedParser def parse_emails_from_log(log_file: str) -> list[str]: subjects = [] delimiter = b"=====\n" with open(log_file, 'rb') as f: message_data = [] for line in f: if line == delimiter: if message_data: ...
import pytest from solution import parse_emails_from_log def test_parse_emails_from_log(tmp_path): # Create a temporary log file log_content = ( "From: user1@example.com\n" "Subject: Meeting Today\n" "To: user2@example.com\n" "\n" "Please join the meeting at 10 AM.\n" ...
[ { "docstring": null, "function_declaration": "def parse_emails_from_log(log_file):", "function_name": "parse_emails_from_log", "parameter_list": "(log_file)" }, { "docstring": null, "function_declaration": "def parse_email_subject(raw_message):", "function_name": "parse_email_subject...
[ 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 email\nfrom email.parser import BytesFeedParser\n\ndef parse_emails_from_log(log_file: str) -> list[str]:\n subjects = []\n delimiter = b\"=====\"\n wit...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015423", "row_id": 15423, "seed_ids": "[262]" }
0.623213
Docs: Python310_15423
I
[ "parse_emails_from_log", "parse_email_subject" ]
2
[ [ "parse_emails_from_log", "parse_email_subject" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b1f169bab9ddb0df83bde1227e2e9a9b3638b766
6504070e58bccd265452164ec2363c9598f82eac
v1.0
instruct
Docs
Docs: Python310_15466_I
**Question: Introspecting Function Calls** Given the functions described in the `python310` package, your task is to implement a function `introspect_function_calls` that returns detailed information about the currently executing function. Specifically, you will make use of the following functions: - `PyEval_GetGlobal...
import inspect def introspect_function_calls() -> dict: """ This function returns a dictionary containing detailed information about the currently executing function. """ # Get the current frame current_frame = inspect.currentframe() if current_frame is None: return {} # G...
def test_introspect_function_calls_example_function(): info = example_function() assert info["function_name"] == "example_function" assert info["globals"] is not None assert info["locals"] is not None assert "a" in info["locals"] assert "b" in info["locals"] assert info["current_line"] > 0 ...
[ { "docstring": "This function returns a dictionary containing detailed information about the currently executing function.", "function_declaration": "def introspect_function_calls():", "function_name": "introspect_function_calls", "parameter_list": "()" }, { "docstring": null, "function_...
[ 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 inspect\n\ndef introspect_function_calls() -> dict:\n \"\"\"\n Return detailed information about the currently executing function.\n \"\"\"\n current...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015466", "row_id": 15466, "seed_ids": "[51]" }
0.659449
Docs: Python310_15466
I
[ "introspect_function_calls", "example_function" ]
2
[ [ "example_function", "introspect_function_calls" ] ]
1
[]
false
[]
false
pytest
false
[]
true
b0f42cc5e78f7d4a18fae8b6299e6bd2a23057fa
d0663121c4a4d50e9ecb843936bf53e282da930d
v1.0
instruct
Docs
Docs: Python310_15488_I
You are tasked with creating a Python function that simulates the behavior of the `mailcap.findmatch` function from the deprecated `mailcap` module. Your function should process a single mailcap file and return the command to handle a specified MIME type given certain conditions. ### Function Signature ```python def ...
import re def parse_mailcap_file(mailcap_file): mailcap_entries = [] with open(mailcap_file, 'r') as f: for line in f: line = line.strip() if not line or line.startswith('#'): continue mime_type, rest = line.split(';', 1) mime_type = mime_...
import pytest from solution import custom_findmatch, parse_mailcap_file def test_parse_mailcap_file(): mock_mailcap_content = """ text/plain; cat %s video/mpeg; xmpeg %s; test=test -n $DISPLAY """ with open('mock.mailcap', 'w') as f: f.write(mock_mailcap_content.strip()) expected_o...
[ { "docstring": null, "function_declaration": "def parse_mailcap_file(mailcap_file):", "function_name": "parse_mailcap_file", "parameter_list": "(mailcap_file)" }, { "docstring": null, "function_declaration": "def custom_findmatch(mailcap_file, MIMEtype, key='view', filename='/dev/null', ...
[ 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 re\nfrom typing import Tuple, List, Dict\n\ndef custom_findmatch(mailcap_file: str, MIMEtype: str, key: str = 'view', filename: str = '/dev/null', plist: list = ...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00015488", "row_id": 15488, "seed_ids": "[399]" }
0.576275
Docs: Python310_15488
I
[ "parse_mailcap_file", "custom_findmatch" ]
2
[ [ "custom_findmatch", "parse_mailcap_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
7017b61c88e0f88aa8c0168de1907e1b772753a7
38f2eaba9fe18cb46a63731de4b9afb3e4d16065
v1.0
instruct
Docs
Docs: Python310_15502_I
**Coding Assessment Question:** ### Objective Write a Python program that demonstrates the use of both `asyncio` and `socket` modules for creating a simple asynchronous TCP server that echoes back any data it receives from clients. ### Requirements 1. **Server Implementation**: - Use the `asyncio` module to manag...
import asyncio import socket async def handle_client(reader, writer): try: data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message} from {addr}") print(f"Send: {message}") writer.write(data) aw...
import asyncio from solution import run_server, client async def test_server_client_interaction(): server_task = asyncio.create_task(run_server('127.0.0.1', 8888)) await asyncio.sleep(1) # Give the server a moment to start client_task1 = asyncio.create_task(client('127.0.0.1', 8888, "Hello, World!")) ...
[ { "docstring": null, "function_declaration": "def main():", "function_name": "main", "parameter_list": "()" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport socket\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Accepted connection from {addr}\")...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015502", "row_id": 15502, "seed_ids": "[151]" }
0.639207
Docs: Python310_15502
I
[ "handle_client", "run_server", "client", "main" ]
4
[ [ "run_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2535947c2ec58b084933d10f6cc6d608ecaa34e2
f32be271356d74eaaa5a8054d4525e1d33715fdc
v1.0
instruct
Docs
Docs: Pytorch_15505_I
**Coding Assessment Question: Understanding and Implementing Function Transformations Using `torch.func`** ### Objective Implement a function using PyTorch that computes a specific mathematical operation on batched tensor inputs and ensure it adheres to the constraints and limitations of the `vmap` transformation prov...
import torch from torch.func import vmap def f(x: torch.Tensor) -> torch.Tensor: # Compute sine of x, then the square of the sine, and return the sum of the squared sine values sine_x = torch.sin(x) squared_sine_x = sine_x ** 2 return torch.sum(squared_sine_x) def transformed_f(x: torch.Tensor) -> tor...
import torch from solution import transformed_f, batched_f def test_transformed_f_single_input(): x = torch.tensor([0.1, 0.2, 0.3]) result = transformed_f(x) expected_result = torch.sum(torch.sin(x) ** 2) assert torch.isclose(result, expected_result), f"Expected {expected_result}, but got {result}" de...
[ { "docstring": null, "function_declaration": "def f(x):", "function_name": "f", "parameter_list": "(x)" }, { "docstring": "Transforms the given function f to be compatible with torch.func.vmap.\n\nParameters:\nx (torch.Tensor): A tensor of arbitrary shape.\n\nReturns:\ntorch.Tensor: A transf...
[ 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 torch\nfrom torch.func import vmap\n\ndef f(x: torch.Tensor) -> torch.Tensor:\n # Compute sine of x, then the square of the sine, and return the sum of the sq...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00015505", "row_id": 15505, "seed_ids": "[136]" }
0.535693
Docs: Pytorch_15505
I
[ "f", "transformed_f", "batched_f" ]
3
[ [ "batched_f", "transformed_f" ], [ "transformed_f", "f" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
788c48c18a81eec37b7b38b97a7c3e45d7b951a3
9d269c12e8ab3a4d941d1a872c1c9529b6339adc
v1.0
instruct
Docs
Docs: Scikit_15516_I
### Question: Model Evaluation with Custom Scoring Metrics You have just trained several machine learning models on a classification dataset. To ensure the reliability of your models, you need to evaluate their performance using multiple scoring metrics and compare them. Additionally, for a specific business case, you...
import numpy as np from sklearn.model_selection import cross_validate from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score def custom_weighted_scoring(y_true, y_pred): """ Custom scoring function that weighs false negatives more heavily than false positives. Parameters: ...
import numpy as np from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import make_classification from solution import evaluate_models def test_evaluate_models(): X, y = make_classification(n_samples=100, n_features=20, random_state=42) model1 = DecisionTreeClassifier(random_state=42) ...
[ { "docstring": "Custom scoring function that weighs false negatives more heavily than false positives.\n\nParameters:\n- y_true (numpy array): True labels\n- y_pred (numpy array): Predicted labels\n\nReturns:\n- score: Weighted accuracy score", "function_declaration": "def custom_weighted_scoring(y_true, y_...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score\n\ndef cu...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015516", "row_id": 15516, "seed_ids": "[25]" }
0.560254
Docs: Scikit_15516
I
[ "custom_weighted_scoring", "evaluate_models" ]
2
[ [ "evaluate_models", "custom_weighted_scoring" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
cd0de115b7f58f386a6d2456f4fa257ce1c27e2c
c70595ca1832b43fea85adede3ac89cb43f94a17
v1.0
instruct
Docs
Docs: Python310_15570_I
### Advanced Python Programming Problem Using the `curses` Library **Objective:** Demonstrate your ability to create a complex text-based user interface using the `curses` library in Python. ### Problem Description: You are tasked with creating a simple text editor using the `curses` library. The editor should have ...
import curses def save_to_file(buffer, filename="output.txt"): with open(filename, "w") as f: for line in buffer: f.write(line + "\n") def run_editor(): def main(stdscr): # Init curses curses.curs_set(1) # Make the cursor visible curses.noecho() curses.cbre...
import pytest import os def test_save_to_file(): buffer = ["Hello", "World"] filename = "test_output.txt" save_to_file(buffer, filename) with open(filename, "r") as f: lines = f.readlines() assert lines == ["Hello\n", "World\n"] os.remove(filename) def test_insert_m...
[ { "docstring": null, "function_declaration": "def save_to_file(buffer, filename='output.txt'):", "function_name": "save_to_file", "parameter_list": "(buffer, filename='output.txt')" }, { "docstring": null, "function_declaration": "def run_editor():", "function_name": "run_editor", ...
[ 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import curses\n\ndef run_editor():\n def main(stdscr):\n curses.curs_set(1)\n \n # Set color pairs for status bar indication\n curses.sta...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00015570", "row_id": 15570, "seed_ids": "[294]" }
0.43017
Docs: Python310_15570
I
[ "save_to_file", "run_editor" ]
2
[ [ "run_editor", "save_to_file" ] ]
1
[]
false
[]
false
pytest
false
[]
true
994799fd99f8c30ce173315aaff3f7eabe934435
23bf45e4f3c5529ad4282ba6e8b2e92bf5094434
v1.0
instruct
Docs
Docs: Python310_15571_I
### CSV File Operations and Custom Dialect Creation You are provided with a CSV file named `data.csv` containing the following data: ``` Name,Age,Department Alice,30,Engineering Bob,25,HR Charlie,35,Finance ``` Your task is to perform three operations: 1. **Create a custom dialect named `semicolon_dialect`**, where...
import csv def create_semicolon_dialect(): """ Creates a CSV dialect for semicolon-separated values with minimal quoting. """ csv.register_dialect( 'semicolon_dialect', delimiter=';', quoting=csv.QUOTE_MINIMAL, quotechar='"', doublequote=True ) def convert_t...
import csv import os from solution import convert_to_semicolon_dialect, read_semicolon_dialect def test_create_and_convert_csv(tmp_path): input_file = tmp_path / "data.csv" output_file = tmp_path / "output.csv" with open(input_file, 'w', newline='') as f: f.write("Name,Age,Department\nAlice,30...
[ { "docstring": "Creates a CSV dialect for semicolon-separated values with minimal quoting.", "function_declaration": "def create_semicolon_dialect():", "function_name": "create_semicolon_dialect", "parameter_list": "()" }, { "docstring": "Converts a CSV file from default format to a semicolo...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import csv\n\ndef create_semicolon_dialect():\n \"\"\"\n Creates a CSV dialect for semicolon-separated values with minimal quoting.\n \"\"\"\n csv.register_...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00015571", "row_id": 15571, "seed_ids": "[272]" }
0.685058
Docs: Python310_15571
I
[ "create_semicolon_dialect", "convert_to_semicolon_dialect", "read_semicolon_dialect" ]
3
[ [ "convert_to_semicolon_dialect", "create_semicolon_dialect" ], [ "read_semicolon_dialect", "create_semicolon_dialect" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e31406771187a8516c6bd19c308770cbb5f44134
e4beb4de0a9c2638b1179cd2e6ba342a894274b9
v1.0
instruct
Docs
Docs: Python310_15649_I
### Shadow Password Management with `spwd` Module In this task, you are required to write a Python script that interacts with the Unix shadow password database using the `spwd` module. Your script should perform the following operations: 1. **Fetch User Details**: Write a function `fetch_user_details(username: str...
import spwd import time def fetch_user_details(username): """ Fetch the user details from the shadow password database. Parameters: username (str): The username to fetch details for. Returns: dict: Dictionary of user details. Raises: PermissionError: I...
import pytest import spwd from solution import fetch_user_details, password_expiry_status, list_all_usernames @pytest.fixture def mock_spwd(monkeypatch): class MockShadowUser: def __init__(self, sp_namp, sp_pwdp, sp_lstchg, sp_min, sp_max, sp_warn, sp_inact, sp_expire, sp_flag): self.sp_namp = ...
[ { "docstring": "Fetch the user details from the shadow password database.\n\nParameters:\n username (str): The username to fetch details for.\n \nReturns:\n dict: Dictionary of user details.\n \nRaises:\n PermissionError: If necessary privileges are not available.\n KeyError: If the user is 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 spwd\nimport time\n\ndef fetch_user_details(username):\n \"\"\"\n Fetch the user details from the shadow password database.\n \n Parameters:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00015649", "row_id": 15649, "seed_ids": "[230]" }
0.519992
Docs: Python310_15649
I
[ "fetch_user_details", "password_expiry_status", "list_all_usernames" ]
3
[ [ "password_expiry_status", "fetch_user_details" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c91bf08128bb0cf63b824bbb136977de63cb8a47
0d56be8429f181fe3f54beb3c18a58e70216dcf9
v1.0
instruct
Docs
Docs: Python310_15702_I
### Coding Assignment: #### Custom Exception Handling and Propagation **Objective:** Create a custom exception class hierarchy and write functions that demonstrate raising and handling these exceptions properly. **Problem Statement:** You are tasked with implementing a small module that simulates a file processing s...
class FileProcessingError(Exception): """Base exception class for file processing errors.""" pass class FileNotFound(FileProcessingError): """Exception raised when the specified file does not exist.""" def __init__(self, file_path): self.file_path = file_path super().__init__(f"File {se...
import pytest from solution import FileNotFound, FileCorrupted, PermissionDenied, read_file, process_file def test_read_nonexistent_file(): with pytest.raises(FileNotFound) as exc_info: read_file("nonexistent.txt") assert str(exc_info.value) == "File nonexistent.txt not found." def test_read_corrupted...
[]
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class FileProcessingError(Exception):\n \"\"\"Base class for file processing errors.\"\"\"\n pass\n\nclass FileNotFound(FileProcessingError):\n \"\"\"Raised wh...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015702", "row_id": 15702, "seed_ids": "[256]" }
0.528878
Docs: Python310_15702
I
[ "read_file", "process_file" ]
2
[ [ "process_file", "read_file" ] ]
1
[]
false
[ "FileProcessingError", "FileNotFound", "FileCorrupted", "PermissionDenied" ]
true
pytest
true
[]
true
edd376ee92ddbb5fdef36c58fdccdcf0d89fd3b0
5df2f0a9210a0e49f5e901231ff778124502fb3b
v1.0
instruct
Docs
Docs: Python310_15735_I
**Objective:** Create a Python script that interacts with the runtime environment using the `sys` module to provide custom runtime debugging and logging. **Task:** You are required to write a function `custom_debugger(logfile)` that sets up a custom debugging and logging environment. This function should: 1. Set up a...
import sys import traceback def tracefunc(frame, event, arg): if event not in ('call', 'return', 'exception'): return tracefunc func_name = frame.f_code.co_name if event == 'call': args = frame.f_locals log_message = f"{event} - {func_name} - {args}\n" elif event == 'return...
import sys import os # Importing the solution from solution import custom_debugger def example_function(a, b): return a + b def function_with_exception(): raise ValueError("An error occurred") def test_custom_debugger(tmpdir): log_file = tmpdir.join("log.txt") # Start the custom debugger cu...
[ { "docstring": null, "function_declaration": "def tracefunc(frame, event, arg):", "function_name": "tracefunc", "parameter_list": "(frame, event, arg)" }, { "docstring": null, "function_declaration": "def custom_debugger(logfile):", "function_name": "custom_debugger", "parameter_...
[ 0, 0, 0, 0, 1, 0, 0, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\nimport inspect\n\ndef custom_debugger(logfile: str):\n def tracefunc(frame, event, arg):\n if event == 'call':\n function_name = frame....
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00015735", "row_id": 15735, "seed_ids": "[348]" }
0.529437
Docs: Python310_15735
I
[ "tracefunc", "custom_debugger" ]
2
[ [ "custom_debugger", "tracefunc" ] ]
1
[]
false
[]
false
pytest
true
[]
true
83f67a7f02eb55d0a6b1a8f805061f8c57a21d81
aa72f2e44f8b99383147ae91a1dcff52e196fdf1
v1.0
instruct
Docs
Docs: Python310_15784_I
### Asyncio Cross-Platform Event Loop Implementation **Background:** You are tasked with designing an asyncio-based application that works consistently across multiple platforms, including Windows and macOS. Your solution should take into account the platform-specific limitations as detailed in the documentation prov...
import asyncio import platform import subprocess async def windows_subprocess_example(): process = await asyncio.create_subprocess_shell( 'ping google.com', stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await process.communicate() if...
import asyncio import platform import pytest from solution import cross_platform_event_loop @pytest.mark.skipif(platform.system() != 'Windows', reason="Test on Windows only") def test_cross_platform_event_loop_windows(): asyncio.run(cross_platform_event_loop()) # Since this function involves actual subprocess ...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\nimport subprocess\n\nasync def windows_subprocess_example():\n process = await asyncio.create_subprocess_shell(\n 'ping googl...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00015784", "row_id": 15784, "seed_ids": "[370]" }
0.494522
Docs: Python310_15784
I
[ "windows_subprocess_example", "macos_server_client_example", "cross_platform_event_loop" ]
3
[ [ "cross_platform_event_loop", "macos_server_client_example" ], [ "cross_platform_event_loop", "windows_subprocess_example" ] ]
2
[]
false
[]
false
pytest
true
[]
true
aa0440a69634b09659be5cd4445502426e62b384
dc8e6bb9d3680e99fd37d36a41bf68646d472dfd
v1.0
instruct
Docs
Docs: Python310_15834_I
**Context Management in an Asynchronous Framework** As a developer, you are tasked with creating a small web server using `asyncio` that handles multiple clients asynchronously and keeps track of the session data using `contextvars`. **Requirements:** 1. **Session Management**: Each client should have a unique sessi...
import asyncio import contextvars import uuid # Context variable for storing session ID session_id_var = contextvars.ContextVar('session_id') def generate_session_id() -> str: """Generate a unique session ID.""" return str(uuid.uuid4()) async def handle_client(reader, writer): ctx = contextvars.copy_cont...
import asyncio import pytest from solution import generate_session_id, handle_client, main import socket import threading def test_generate_session_id(): session_id_1 = generate_session_id() session_id_2 = generate_session_id() assert session_id_1 != session_id_2 assert len(session_id_1) > 0 a...
[ { "docstring": "Generate a unique session ID.", "function_declaration": "def generate_session_id():", "function_name": "generate_session_id", "parameter_list": "()" } ]
[ 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\nimport uuid\n\n# Context variable for storing session ID\nsession_id_var = contextvars.ContextVar('session_id')\n\ndef generate_sess...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015834", "row_id": 15834, "seed_ids": "[392]" }
0.450586
Docs: Python310_15834
I
[ "generate_session_id", "handle_client", "main" ]
3
[ [ "handle_client", "generate_session_id" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d53e973c43a5da036f7fbbcbdbe2acb175a5f6b6
6e0ea14bee3c9117edb34a0def04444c696cbccd
v1.0
instruct
Docs
Docs: Python310_15919_I
### Question: Advanced Asynchronous Programming with asyncio Future You are tasked with developing a small Python program to simulate a series of asynchronous operations using the `asyncio` library's `Future` objects. This question assesses your understanding of creating, manipulating, and handling Future objects. Pay...
import asyncio async def execute_after_delay(fut, delay, value): await asyncio.sleep(delay) fut.set_result(value) async def main(): loop = asyncio.get_event_loop() fut = loop.create_future() # Execute the delay function asynchronously asyncio.create_task(execute_after_delay(fut, 2, "... w...
import asyncio import pytest from solution import execute_after_delay, main, ensure_future_example, main_with_exception_handling @pytest.mark.asyncio async def test_execute_after_delay(): fut = asyncio.Future() await execute_after_delay(fut, 1, "Test Value") assert fut.result() == "Test Value" @pytest.mar...
[ { "docstring": "Ensures the provided coroutine or awaitable is scheduled as a Task.\nRaises a ValueError if the provided argument is not a valid coroutine.", "function_declaration": "def ensure_future_example(coro):", "function_name": "ensure_future_example", "parameter_list": "(coro)" } ]
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def execute_after_delay(fut, delay, value):\n \"\"\"\n Sleeps for `delay` seconds and sets the `value` as the result of the Future `fut`.\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00015919", "row_id": 15919, "seed_ids": "[113]" }
0.51703
Docs: Python310_15919
I
[ "execute_after_delay", "main", "ensure_future_example", "main_with_exception_handling" ]
4
[ [ "main_with_exception_handling", "ensure_future_example" ], [ "main_with_exception_handling", "execute_after_delay" ] ]
2
[]
false
[]
false
pytest
true
[]
true
1c78b0ebd43b5cf45a476dbbf69ae9c1460900f4
f8e5cc24f77cc1a147f49ac6e896e9122a2e227e
v1.0
instruct
Docs
Docs: Python310_16056_I
You have been given a list of URLs and you are required to check if the content of these URLs contains a specific keyword. You will need to use both `ThreadPoolExecutor` and `ProcessPoolExecutor` to achieve this. You should also handle potential exceptions and timeouts gracefully. ### Input: 1. A list of URLs (`urls`)...
import concurrent.futures import requests from typing import List, Dict, Union def fetch_url_content(url: str, timeout: int) -> Union[str, Exception]: """ Fetches content from a URL with a specified timeout. """ try: response = requests.get(url, timeout=timeout) response.raise_for_statu...
from solution import check_keyword_in_urls def mock_requests_get(url, timeout): class MockResponse: def __init__(self, text='', status_code=200): self.text = text self.status_code = status_code def raise_for_status(self): if self.status_code != 200: ...
[ { "docstring": "Fetches content from a URL with a specified timeout.", "function_declaration": "def fetch_url_content(url, timeout):", "function_name": "fetch_url_content", "parameter_list": "(url, timeout)" }, { "docstring": "Searches for the keyword in the given content.", "function_de...
[ 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 concurrent.futures\nimport requests\nfrom typing import List, Dict, Union\n\ndef fetch_url_content(url: str, timeout: int) -> Union[str, Exception]:\n \"\"\"\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016056", "row_id": 16056, "seed_ids": "[347]" }
0.618085
Docs: Python310_16056
I
[ "fetch_url_content", "search_keyword", "check_keyword_in_urls" ]
3
[ [ "check_keyword_in_urls", "fetch_url_content" ], [ "check_keyword_in_urls", "search_keyword" ] ]
2
[]
false
[]
false
pytest
true
[ "requests" ]
false
0ec37069d2caa2c68d1c8003d009d642a2687687
2630cb156e1524fdeac3d95465e848396f168cbe
v1.0
instruct
Docs
Docs: Python310_16062_I
### Asynchronous Web Scraper with Timeouts and Logging You are to develop an asynchronous web scraper using the asyncio package in Python. The web scraper should be capable of fetching multiple web pages concurrently, process their content for a specific keyword, and log the results. This problem will test your unders...
import aiohttp import asyncio import logging logging.basicConfig(level=logging.DEBUG) async def fetch_page(session, url): """ Fetches a web page within a timeout. Logs a timeout error if it takes longer than 5 seconds. """ try: async with session.get(url, timeout=5) as response: ...
import pytest import asyncio from unittest.mock import patch, AsyncMock from solution import fetch_page, process_content, main @pytest.mark.asyncio async def test_fetch_page_success(): mock_session = AsyncMock() mock_response = AsyncMock() mock_response.text = AsyncMock(return_value="Success") mock_res...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import aiohttp\nimport asyncio\nimport logging\nfrom aiohttp import ClientTimeout\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG)\n\nasync def fetch_pa...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016062", "row_id": 16062, "seed_ids": "[200]" }
0.597486
Docs: Python310_16062
I
[ "fetch_page", "process_content", "main", "fetch_and_process" ]
4
[ [ "fetch_and_process", "fetch_page" ], [ "fetch_and_process", "process_content" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
09d42b9ff5d5efb891d8341c84e0a541306a9718
a0fd2d107e629d491d62771b4d5103ac7d323236
v1.0
instruct
Docs
Docs: Scikit_16070_I
**Advanced Coding Assessment Question** ### Objective: Assess the understanding of implementing custom scoring metrics using scikit-learn and applying them to a supervised learning problem. ### Scenario: You are given a dataset and asked to train a regression model. After training the model, you are required to evalu...
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error, r2_score, make_scorer def load_and_prepare_data(csv_path): """ Load dataset and preprocess by splitting into train and t...
from solution import load_and_prepare_data, train_regression_model, mean_bias_deviation, root_relative_squared_error, evaluate_model import numpy as np import pandas as pd from sklearn.metrics import r2_score, mean_absolute_error def test_load_and_prepare_data(): df = pd.DataFrame({ 'feature1': np.random.r...
[ { "docstring": "Load dataset and preprocess by splitting into train and test sets.\n\nParameters:\ncsv_path (str): Path to the CSV file containing the dataset.\n\nReturns:\ntuple: Splitted data (X_train, X_test, y_train, y_test).", "function_declaration": "def load_and_prepare_data(csv_path):", "functio...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics i...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016070", "row_id": 16070, "seed_ids": "[25]" }
0.621832
Docs: Scikit_16070
I
[ "load_and_prepare_data", "train_regression_model", "mean_bias_deviation", "root_relative_squared_error", "evaluate_model" ]
5
[ [ "evaluate_model", "mean_bias_deviation" ], [ "evaluate_model", "root_relative_squared_error" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "pandas", "sklearn" ]
false
b800b529c0bf855681bbb02a7d9fe1bfa0fb4cb8
1702b6ea41ffdbb0a6aaaf33570ef02d8c34e74d
v1.0
instruct
Docs
Docs: Python310_16164_I
**Objective:** To assess your understanding of the Python `codecs` package and its functionalities related to custom encoding, decoding, error handling, and incremental processing. **Problem:** You are provided with a task to implement a text processing utility that dynamically handles multiple text encodings. The ut...
import codecs def custom_encode(input_text: str, encoding: str, errors: str) -> bytes: """ Encode the input text using the specified encoding and custom error handling. Parameters: - input_text (str): The text to be encoded. - encoding (str): The encoding format to use. - errors (str): The err...
from solution import (custom_encode, custom_decode, register_custom_error_handler, incremental_process) def test_custom_encode_ascii(): register_custom_error_handler() result = custom_encode("Hello, World!", "ascii", "strict") assert result == b"Hello, World!" def test_custom_encode_custom_error_handler()...
[ { "docstring": "Encode the input text using the specified encoding and custom error handling.\n\nParameters:\n- input_text (str): The text to be encoded.\n- encoding (str): The encoding format to use.\n- errors (str): The error handling scheme.\n\nReturns:\n- bytes: The encoded byte sequence.", "function_de...
[ 0, 0, 0, 1, 0, 1, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import codecs\n\ndef custom_encode(input_text: str, encoding: str, errors: str) -> bytes:\n \"\"\"\n Encode the input text using the specified encoding and custom...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00016164", "row_id": 16164, "seed_ids": "[211]" }
0.625189
Docs: Python310_16164
I
[ "custom_encode", "custom_decode", "hex_replace", "register_custom_error_handler", "incremental_process" ]
5
[ [ "register_custom_error_handler", "hex_replace" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c439ce988d084a0c87101a90d3f17e94a1589aa5
70e473a57da5020ddee9b301e86c682fa166574e
v1.0
instruct
Docs
Docs: Python310_16172_I
#### Objective You are required to write a Python script that demonstrates your understanding of signal handling using the Python `signal` module. You will implement a custom signal handler that responds to specific signals and performs designated actions. #### Task 1. **Signal Handler Setup**: Write a function named...
import signal import time import sys def sigint_handler(signum, frame): print("SIGINT received, graceful shutdown.") sys.exit(0) def sigalrm_handler(signum, frame): print("Alarm signal received.") def setup_signal_handlers(): signal.signal(signal.SIGINT, sigint_handler) signal.signal(signal.SIGAL...
import os import signal import subprocess import time def run_script_and_test_signals(): # Start the script as a subprocess proc = subprocess.Popen(['python', 'solution.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: # Allow some time for the process to start and print "Running..." ...
[ { "docstring": null, "function_declaration": "def sigint_handler(signum, frame):", "function_name": "sigint_handler", "parameter_list": "(signum, frame)" }, { "docstring": null, "function_declaration": "def sigalrm_handler(signum, frame):", "function_name": "sigalrm_handler", "pa...
[ 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 signal\nimport time\nimport sys\n\ndef sigint_handler(signum, frame):\n print(\"SIGINT received, graceful shutdown.\")\n sys.exit(0)\n\ndef sigalrm_handler...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016172", "row_id": 16172, "seed_ids": "[253]" }
0.524917
Docs: Python310_16172
I
[ "sigint_handler", "sigalrm_handler", "setup_signal_handlers", "main" ]
4
[ [ "setup_signal_handlers", "sigalrm_handler" ], [ "setup_signal_handlers", "sigint_handler" ] ]
2
[]
false
[]
false
pytest
false
[]
true
c139eb84c601418f8ad8e803331407cdd0d301f2
c766b04827fd7f4871bada7c7789da41709c9414
v1.0
instruct
Docs
Docs: Python310_16205_I
#### Objective To assess the student's understanding and ability to work with lists and dictionaries, using various list methods and comprehensions. #### Problem Statement You are given an input list of integers. Your task is to create a function that processes this list through several steps and then uses a dictionar...
def is_prime(n): """ Check if the number `n` is a prime number. """ if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def process_primes(input_list: list) -> dict: """ Process the input list to find prime numb...
from solution import process_primes def test_process_primes_basic(): input_list = [10, 15, 3, 7, 11, 17, 2] expected_output = {17: 1, 11: 2, 7: 3, 3: 4, 2: 5, 'sum': 40} assert process_primes(input_list) == expected_output def test_process_primes_with_no_primes(): input_list = [4, 6, 8, 9, 10, 12] ...
[ { "docstring": "Check if the number `n` is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Process the input list to find prime numbers, sort them, and create a dictionary\nmapping each prime number to its ...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(number):\n \"\"\"\n Helper function to check if a number is a prime number.\n \"\"\"\n if number < 2:\n return False\n for i in range...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016205", "row_id": 16205, "seed_ids": "[411]" }
0.662769
Docs: Python310_16205
I
[ "is_prime", "process_primes" ]
2
[ [ "process_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
af0e0d51c98b7f1b3c3a2ced7e31cda264b314d2
0c919fda5767f61acc972e6b67439c2e27a5bc80
v1.0
instruct
Docs
Docs: Python310_16229_I
**Problem Statement:** You are tasked with building a concurrent command execution utility utilizing Python's asyncio and subprocess functionalities. The goal is to create a function that takes a list of shell commands, executes them as subprocesses in parallel, and returns their respective outputs. ### Function Sign...
import asyncio from typing import List, Tuple async def run_command(command: str) -> Tuple[str, str]: process = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await process.communicate() return (...
import pytest import asyncio from solution import run_commands @pytest.mark.asyncio async def test_single_command(): commands = ["echo 'Hello, world!'"] output = await run_commands(commands) assert output == [("Hello, world!\n", "")] @pytest.mark.asyncio async def test_multiple_commands(): commands = ...
[]
[ 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\nfrom typing import List, Tuple\n\nasync def run_command(command: str) -> Tuple[str, str]:\n process = await asyncio.create_subprocess_shell(\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016229", "row_id": 16229, "seed_ids": "[264]" }
0.767718
Docs: Python310_16229
I
[ "run_command", "run_commands" ]
2
[ [ "run_commands", "run_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6978faade8e938f44f666a6cd58f55bc58b05292
06c0398b31c912ecc6fa039651f965f38e1085c7
v1.0
instruct
Docs
Docs: Python310_16247_I
### Python Coding Assessment Question #### Objective Demonstrate understanding of Python's functional programming modules (`itertools` and `functools`) by implementing a solution that utilizes iterators and partial function application. #### Problem Statement Implement a function `prime_generator_partial_sum` that g...
from typing import List import itertools import functools def is_prime(n: int) -> bool: """Check if a number is a prime number.""" if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n ...
from solution import prime_generator_partial_sum def test_prime_generator_partial_sum_5(): assert prime_generator_partial_sum(5) == [2, 5, 10, 17, 28] def test_prime_generator_partial_sum_1(): assert prime_generator_partial_sum(1) == [2] def test_prime_generator_partial_sum_10(): assert prime_generator_p...
[ { "docstring": "Check if a number is a prime number.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generate an infinite sequence of prime numbers.", "function_declaration": "def generate_primes():", "function_nam...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport itertools\nfrom functools import partial\n\ndef is_prime(num):\n \"\"\" Helper function to check if a number is prime. \"\"\"\n if...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016247", "row_id": 16247, "seed_ids": "[387]" }
0.732676
Docs: Python310_16247
I
[ "is_prime", "generate_primes", "prime_generator_partial_sum" ]
3
[ [ "generate_primes", "is_prime" ], [ "prime_generator_partial_sum", "generate_primes" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2a99c1cab550d4e893a74d6cc30676c6380d573a
a79b7bc2ed678f305a43a8e21f9b0bfbcff4d1e8
v1.0
instruct
Docs
Docs: Python310_16268_I
**Title: Implement a Multi-threaded C Extension Module with Python Embedding** **Objective**: In this question, you will implement a simple multi-threaded C extension module that utilizes Python 3.10’s embedding features. This module should demonstrate the proper use of the Global Interpreter Lock (GIL) and thread sta...
# solution.py import threading import math def calculate_factorial(n): """ Calculate and return the factorial of n. """ return math.factorial(n) def thread_function(n): result = calculate_factorial(n) print(f"Thread for n={n}: {result}") def main(): numbers = [5, 6, 7, 8, 9] threads ...
# test_solution.py from solution import calculate_factorial, thread_function import threading def test_calculate_factorial(): assert calculate_factorial(5) == 120 assert calculate_factorial(6) == 720 assert calculate_factorial(7) == 5040 # Mock print for testing thread_function def test_thread_function(m...
[ { "docstring": "Calculate and return the factorial of n.", "function_declaration": "def calculate_factorial(n):", "function_name": "calculate_factorial", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def thread_function(n):", "function_name": "thread_functi...
[ 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": "# solution/multi_threaded.c\n\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include <pthread.h>\n#include <math.h>\n\n#define THREAD_COUNT 3\n\nvoid* thread_func(voi...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00016268", "row_id": 16268, "seed_ids": "[55]" }
0.539974
Docs: Python310_16268
I
[ "calculate_factorial", "thread_function", "main" ]
3
[ [ "thread_function", "calculate_factorial" ] ]
1
[]
false
[]
false
pytest
true
[]
true
66e2e437b7d0e0e655158a891c07381a7f566155
2ddbcdee551a1759f6638c92cebc0007a41e139a
v1.0
instruct
Docs
Docs: Python310_16279_I
### Advanced Command-Line Interface Application **Objective:** Create a Python script using the `argparse` module that simulates a file processing utility with advanced command-line argument parsing. **Problem Statement:** You are tasked with writing a Python script named `file_processor.py` that takes various comma...
import os import argparse from datetime import datetime def list_files(directory, ext=None): try: files = os.listdir(directory) if ext: files = [file for file in files if file.endswith(ext)] return files except FileNotFoundError: print(f"Error: The directory {directo...
import os import tempfile import pytest from datetime import datetime from solution import list_files, search_file, file_details # Testing the list_files function def test_list_files(): with tempfile.TemporaryDirectory() as tmpdir: dirname = tmpdir assert list_files(dirname) == [] tmpfile1 ...
[ { "docstring": null, "function_declaration": "def list_files(directory, ext=None):", "function_name": "list_files", "parameter_list": "(directory, ext=None)" }, { "docstring": null, "function_declaration": "def search_file(directory, filename):", "function_name": "search_file", "...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport argparse\nfrom datetime import datetime\n\ndef list_files(directory, ext=None):\n try:\n files = os.listdir(directory)\n if ext:\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016279", "row_id": 16279, "seed_ids": "[65]" }
0.642305
Docs: Python310_16279
I
[ "list_files", "search_file", "file_details", "main" ]
4
[ [ "search_file", "list_files" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d400c62972b2ed563a7adff2f7d69a017d59bc63
a343329b048f16272cdcb6f3230818aa2c95acf1
v1.0
instruct
Docs
Docs: Python310_16286_I
### Question: #### Documentation Summarizer and HTML Exporter You are tasked with implementing a Python function that uses the "pydoc" module to generate a summary of the documentation for a given module and saves it as an HTML file. The function must also be able to serve this HTML documentation via an HTTP server. ...
import os import pydoc import http.server import socketserver import threading from typing import Optional def generate_html_summary(doc: str, module_name: str) -> str: """ Generate the HTML content for the summary of the module documentation. Args: - doc (str): The full documentation string of the mo...
from solution import generate_and_serve_doc import os def test_generate_and_serve_doc_existing_module(tmp_path): module_name = "sys" output_dir = tmp_path url = generate_and_serve_doc(module_name, str(output_dir)) assert url.startswith("http://localhost:") assert os.path.exists(os.path.join(ou...
[ { "docstring": "Generate the HTML content for the summary of the module documentation.\n\nArgs:\n- doc (str): The full documentation string of the module.\n- module_name (str): The name of the module.\n\nReturns:\n- str: Formatted HTML content.", "function_declaration": "def generate_html_summary(doc, modul...
[ 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 os\nimport pydoc\nimport http.server\nimport socketserver\nimport threading\n\ndef generate_and_serve_doc(module_name: str, output_dir: str, port: int = 0) -> st...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00016286", "row_id": 16286, "seed_ids": "[240]" }
0.532047
Docs: Python310_16286
I
[ "generate_html_summary", "generate_and_serve_doc" ]
2
[ [ "generate_and_serve_doc", "generate_html_summary" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5e1f7dc19cb173ca76b7e55d8658e154951e6324
0813f5f18615824fa1eab9aecb6c2dccf1842305
v1.0
instruct
Docs
Docs: Python310_16300_I
**Title:** Advanced Asynchronous Task Management with asyncio **Objective:** Demonstrate your understanding of Python's asyncio package by implementing a function that concurrently processes data from multiple sources with timeouts and task cancellations. **Description:** You are tasked with simulating the fetching o...
import asyncio from typing import List async def fetch_data_from_source(source_id: int) -> str: """ Simulated function to fetch data from a remote source. """ await asyncio.sleep(source_id) # Simulate delay based on source_id return f"data_from_source_{source_id}" async def gather_data(sources: L...
import pytest import asyncio from solution import fetch_data_from_source, gather_data @pytest.mark.asyncio async def test_fetch_data_from_source(): assert await fetch_data_from_source(1) == "data_from_source_1" assert await fetch_data_from_source(2) == "data_from_source_2" @pytest.mark.asyncio async def test_...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List\n\nasync def fetch_data_from_source(source_id: int) -> str:\n \"\"\"\n Simulates fetching data from a remote source.\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016300", "row_id": 16300, "seed_ids": "[317]" }
0.558591
Docs: Python310_16300
I
[ "fetch_data_from_source", "gather_data" ]
2
[ [ "gather_data", "fetch_data_from_source" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eb6615f401c00610ddfb2c6cd8a21000f68a07f2
fc7d6f2306233feaccad5be84f45d541555ccd4e
v1.0
instruct
Docs
Docs: Python310_16312_I
### Python Thread Management with C-Extensions You have been assigned to extend the functionality of a Python application by integrating a C-extension module. This extension will perform some heavy computations and interact with Python objects. Your task is to write a Python C-extension module that creates threads per...
from concurrent.futures import ThreadPoolExecutor import ctypes import threading # Load the shared object (C-extension) compiled as `my_extension.so` # Here we simulate the C-extension using ctypes # Let's assume we have a C function `heavy_computation` that takes an int and returns an int # For the sake of this simul...
import pytest from solution import run_computation_in_threads def test_single_thread(): data = [1, 2, 3, 4] expected_results = [1, 4, 9, 16] assert run_computation_in_threads(1, data) == expected_results def test_multiple_threads(): data = [1, 2, 3, 4, 5, 6, 7, 8] expected_results = [1, 4, 9, 16, ...
[ { "docstring": null, "function_declaration": "def heavy_computation(x):", "function_name": "heavy_computation", "parameter_list": "(x)" }, { "docstring": "Spawns 'num_threads' each processing a portion of 'data'.\nReturns the combined result from all threads.\n\n:param num_threads: Number of...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "# This is a simulated example of what the C extension and Python integration would look like.\n\nfrom threading import Thread\nimport ctypes\nfrom ctypes import cdll, p...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016312", "row_id": 16312, "seed_ids": "[55]" }
0.548801
Docs: Python310_16312
I
[ "heavy_computation", "run_computation_in_threads" ]
2
[ [ "run_computation_in_threads", "heavy_computation" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dc164f53e1e39721782832baf281ef7179d82c4f
a5dcca4ff589444334496a825a3e6e23274782d8
v1.0
instruct
Docs
Docs: Python310_16406_I
### Question: Implementing MIME Type Matching in Mailcap You are tasked to implement a simplified version of Python's `mailcap` module. Specifically, you need to define two functions to handle MIME type entries and match them to appropriate commands. #### Step 1: Implement the `getcaps` function ```python def getcap...
import os MAILCAP_FILES = [ os.path.expanduser('~/.mailcap'), '/etc/mailcap', '/usr/etc/mailcap', '/usr/local/etc/mailcap' ] def read_mailcap_file(filepath): caps = {} try: with open(filepath, 'r') as file: for line in file: line = line.strip() ...
from solution import getcaps, findmatch, read_mailcap_file import pytest def test_getcaps(): caps = getcaps() assert type(caps) is dict assert 'video/mpeg' in caps or 'text/plain' in caps # Depending on system mailcap files def test_findmatch_view(): test_caps = { 'video/mpeg': [{'view': 'xmp...
[ { "docstring": null, "function_declaration": "def read_mailcap_file(filepath):", "function_name": "read_mailcap_file", "parameter_list": "(filepath)" }, { "docstring": null, "function_declaration": "def getcaps():", "function_name": "getcaps", "parameter_list": "()" }, { ...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\n\ndef getcaps():\n \"\"\"\n Reads and parses mailcap files on the system to return a dictionary\n mapping MIME types to lists of mailcap file entrie...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00016406", "row_id": 16406, "seed_ids": "[399]" }
0.560995
Docs: Python310_16406
I
[ "read_mailcap_file", "getcaps", "findmatch" ]
3
[ [ "getcaps", "read_mailcap_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9b76f77b83c95dc39663205263dc9b5af2b7ec8a
a08caaa7da91e6c431156f8126a7bff6f4a8bc88
v1.0
instruct
Docs
Docs: Pytorch_16434_I
#### Objective Implement a custom PyTorch function that operates on complex inputs and produces real-valued outputs. Then, use `torch.autograd.gradcheck` to verify the correctness of the gradients computed for this function. #### Problem Statement You are required to implement a complex-valued function `complex_to_rea...
import torch def complex_to_real_function(z: torch.Tensor) -> torch.Tensor: """ Computes a real-valued function of a complex input tensor. The function computes the magnitude squared of the complex input, which is a real number. Parameters: z (torch.Tensor): A complex-valued tensor of shape (N...
from solution import complex_to_real_function, verify_gradients import torch def test_complex_to_real_function(): # Test with a known complex tensor z = torch.complex(torch.tensor([3.0, 4.0]), torch.tensor([1.0, 2.0])) output = complex_to_real_function(z) expected_output = torch.tensor([10.0, 20.0]) #...
[ { "docstring": "Computes a real-valued function of a complex input tensor.\nThe function computes the magnitude squared of the complex input,\nwhich is a real number.\n\nParameters:\nz (torch.Tensor): A complex-valued tensor of shape (N,)\n\nReturns:\ntorch.Tensor: A real-valued tensor of shape (N,)", "func...
[ 1, 1, 0 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef complex_to_real_function(z: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Computes a real value function of a complex input tensor.\n The funct...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016434", "row_id": 16434, "seed_ids": "[179]" }
0.434605
Docs: Pytorch_16434
I
[ "complex_to_real_function", "verify_gradients" ]
2
[ [ "verify_gradients", "complex_to_real_function" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
271ab6bd28fd4a1ae1badf5c4bdf4f6acd059799
3623b4c53aadcd3d4533261659682f99aab44b1e
v1.0
instruct
Docs
Docs: Python310_16481_I
### Context: Context Management with `contextvars` and Asynchronous Programming **Question:** You are tasked with developing a concurrent HTTP request handler that stores request-specific data using context variables. This involves simulating an environment where separate asynchronous tasks handle different client re...
import asyncio import contextvars import random # Define the context variable request_info = contextvars.ContextVar('request_info', default='No info') def log_request_info(info: str) -> contextvars.Token: """ Sets the request information to the context variable. """ return request_info.set(info) def ...
import pytest from contextvars import ContextVar import asyncio import random # Mock random.uniform to make tests deterministic @pytest.fixture(autouse=True) def deterministic_random(monkeypatch): def mock_random(): return 0.1 # fixed delay for test purposes monkeypatch.setattr(random, 'uniform', mock...
[ { "docstring": "Sets the request information to the context variable.", "function_declaration": "def log_request_info(info):", "function_name": "log_request_info", "parameter_list": "(info)" }, { "docstring": "Retrieves the currently set value of request_info.", "function_declaration": "...
[ 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\nimport random\n\n# Define the context variable\nrequest_info = contextvars.ContextVar('request_info', default='No info')\n\ndef log_...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00016481", "row_id": 16481, "seed_ids": "[392]" }
0.511565
Docs: Python310_16481
I
[ "log_request_info", "retrieve_request_info", "handle_request", "main" ]
4
[ [ "handle_request", "log_request_info" ], [ "handle_request", "retrieve_request_info" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a6cba38db47284e2348b78b3f8ea4c91574250d7
b85e961a17cdf03fbc4e409cc313f91de850d2fe
v1.0
instruct
Docs
Docs: Python310_16488_I
**Objective:** Implement functions to manipulate and transform collections using operations and techniques highlighted in the documentation. **Question:** You are provided with a list of words. Your task is to perform several operations on this list and return the required results. Implement the following functions: ...
from typing import List, Dict def remove_duplicates(words: List[str]) -> List[str]: """ Removes duplicate words from the list, preserving the original order. """ seen = set() result = [] for word in words: if word not in seen: seen.add(word) result.append(word) ...
from solution import remove_duplicates, word_frequencies, sort_words_by_frequency, transpose_matrix def test_remove_duplicates(): assert remove_duplicates(['apple', 'banana', 'apple', 'orange', 'banana', 'grape']) == ['apple', 'banana', 'orange', 'grape'] assert remove_duplicates([]) == [] assert remove_du...
[ { "docstring": "Removes duplicate words from the list, preserving the original order.", "function_declaration": "def remove_duplicates(words):", "function_name": "remove_duplicates", "parameter_list": "(words)" }, { "docstring": "Counts the frequency of each word in the list and returns a di...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Dict\n\ndef remove_duplicates(words: List[str]) -> List[str]:\n \"\"\"\n Removes duplicate words from the list, preserving the original o...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00016488", "row_id": 16488, "seed_ids": "[411]" }
0.626695
Docs: Python310_16488
I
[ "remove_duplicates", "word_frequencies", "sort_words_by_frequency", "transpose_matrix" ]
4
[ [ "sort_words_by_frequency", "word_frequencies" ] ]
1
[]
false
[]
false
pytest
true
[]
true
01940f532101c9373e87d2fe866adda70c9a5963
013002e9689b46eaa84e405e0ef01be08149df6e
v1.0
instruct
Docs
Docs: Python310_16509_I
### Question: Advanced List Manipulation and Operations You are tasked to implement a function named `process_lists` that takes in two lists of integers and returns a dictionary with the following keys and values: * `"merged"`: A list containing all elements from both input lists, merged and sorted in ascending order,...
from typing import List, Dict, Union, Tuple from math import isqrt def is_prime(n: int) -> bool: """ Return True if n is a prime number, else False.""" if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False for i in range(5, isqrt(n) + 1, 6)...
from solution import process_lists def test_process_lists_basic(): result = process_lists([1, 2, 3, 5], [3, 4, 5, 7]) assert result == { "merged": [1, 2, 3, 4, 5, 7], "intersection": [3, 5], "prime_counts": (3, 3), "common_diffs": [2, 2, 2, 2] } def test_process_lists_no_ov...
[ { "docstring": "Return True if n is a prime number, else False.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Count the number of prime numbers in a given list.", "function_declaration": "def count_primes(lst):", ...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Dict, Union, Tuple\n\ndef is_prime(n: int) -> bool:\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n return False\n if ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016509", "row_id": 16509, "seed_ids": "[234]" }
0.598885
Docs: Python310_16509
I
[ "is_prime", "count_primes", "process_lists" ]
3
[ [ "count_primes", "is_prime" ], [ "process_lists", "count_primes" ] ]
2
[]
false
[]
false
pytest
true
[]
true
49c1bb5e033478c6cb1d387682cfb3b6b1891b88
148d9c84a05b55ac5349f67cc1cb9d89411e942f
v1.0
instruct
Docs
Docs: Python310_16560_I
**Coding Assessment Question:** You are required to implement a function `future_features_info()` that extracts and formats information about features from the `__future__` module. ### Function Signature ```python def future_features_info() -> str: ``` ### Objective The function should return a formatted string cont...
import __future__ def format_version(version): if version is None: return "None" major, minor, micro, level, _ = version level_char = level[0].upper() if level else 'F' return f"{major}.{minor}.{micro}-{level_char}" def future_features_info() -> str: features = [attr for attr in dir(__futu...
from solution import future_features_info def test_future_features_info_format(): output = future_features_info() # Check if the output starts with "Feature: " and contains expected attributes assert "Feature: " in output assert "Optional: " in output assert "Mandatory: " in output assert "Comp...
[ { "docstring": null, "function_declaration": "def format_version(version):", "function_name": "format_version", "parameter_list": "(version)" }, { "docstring": null, "function_declaration": "def future_features_info():", "function_name": "future_features_info", "parameter_list": ...
[ 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 __future__\n\ndef format_version(version):\n if version is None:\n return \"None\"\n major, minor, micro, level, _ = version\n level_char = level...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016560", "row_id": 16560, "seed_ids": "[181]" }
0.465296
Docs: Python310_16560
I
[ "format_version", "future_features_info" ]
2
[ [ "future_features_info", "format_version" ] ]
1
[]
false
[]
false
pytest
true
[]
true
64465f10abbb579f6d78a6d9d2b6aae38b73d842
ab231cde744500550af4b1806ed2d60a2e5dabb2
v1.0
instruct
Docs
Docs: Pytorch_16565_I
**Question: Working with `torch.cuda.tunable` Module** In this assignment, you are required to interact with the `torch.cuda.tunable` module to demonstrate your understanding of enabling features, configuring parameters, and managing file operations in PyTorch. ### Task: 1. **Enable the Tunable Operations:** Impl...
import torch.cuda.tunable def enable_tunable_ops(): """ Enables the tunable operations. """ torch.cuda.tunable.enable() def configure_tuning_params(duration: int, iterations: int): """ Configures the tuning parameters. Args: duration (int): The maximum tuning duration in milliseconds....
import os import torch.cuda.tunable from solution import enable_tunable_ops, configure_tuning_params, write_tuning_results_to_file, perform_tuning # Mocks to simulate the actual behavior since we can't perform real GPU tuning in this environment def mock_enable(): pass def mock_set_tuning_duration(duration): ...
[ { "docstring": "Enables the tunable operations.", "function_declaration": "def enable_tunable_ops():", "function_name": "enable_tunable_ops", "parameter_list": "()" }, { "docstring": "Configures the tuning parameters.\n\nArgs:\nduration (int): The maximum tuning duration in milliseconds.\nit...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch.cuda.tunable\n\ndef enable_tunable_ops():\n \"\"\"\n Enables the tunable operations.\n \"\"\"\n torch.cuda.tunable.enable()\n\ndef configure_tu...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016565", "row_id": 16565, "seed_ids": "[130]" }
0.342057
Docs: Pytorch_16565
I
[ "enable_tunable_ops", "configure_tuning_params", "write_tuning_results_to_file", "perform_tuning" ]
4
[ [ "perform_tuning", "configure_tuning_params" ], [ "perform_tuning", "enable_tunable_ops" ], [ "perform_tuning", "write_tuning_results_to_file" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
a6aca0c3c32d2cbbb08cdc4ac0754784e7f19a2a
f0de727c3a37dc5b7b03c3a6c4ae6c34c69557a4
v1.0
instruct
Docs
Docs: Python310_16596_I
**Objective:** Write a Python function that demonstrates the creation and management of an asynchronous TCP server and client using `asyncio`. Your implementation should incorporate creating tasks, handling callbacks, and performing network I/O operations. #### Task: 1. Implement an asynchronous TCP server that: -...
import asyncio async def handle_client(reader, writer): addr = writer.get_extra_info('peername') print(f"New client connected: {addr}") welcome_message = "Welcome to the async TCP server!" writer.write(welcome_message.encode()) await writer.drain() while True: data = await reader.read...
import asyncio import pytest from solution import run_tcp_server, tcp_client @pytest.fixture def event_loop(): loop = asyncio.get_event_loop() yield loop loop.close() @pytest.mark.asyncio async def test_run_tcp_server(event_loop): port = 8888 server_task = asyncio.ensure_future(run_tcp_server(port...
[ { "docstring": null, "function_declaration": "def main():", "function_name": "main", "parameter_list": "()" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n \"\"\"\n Handle individual client connection. Sends a welcome message and echoes received messages.\n...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016596", "row_id": 16596, "seed_ids": "[267]" }
0.641938
Docs: Python310_16596
I
[ "handle_client", "run_tcp_server", "tcp_client", "main" ]
4
[ [ "run_tcp_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
73aa5731dd3fa5a6688eefd6e654542ab01c53fd
f655a3b0ad0a805b6ec15ddf4f5b7848d8d3c340
v1.0
instruct
Docs
Docs: Python310_16651_I
### Problem: Asynchronous Server-Client Communication using asyncio You are required to implement an asynchronous server-client communication system using Python's `asyncio` package. This task will demonstrate your understanding of event loops, asynchronous tasks, and networking with asyncio. #### Requirements: 1. *...
import asyncio # Server-side code async def handle_client(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message!r} from {addr!r}") response = message[::-1] print(f"Send {response!r} to {addr!r}") writer.wr...
import asyncio import pytest from threading import Thread from solution import run_server, run_client def start_server_in_thread(): server_thread = Thread(target=run_server, daemon=True) server_thread.start() return server_thread # Run the server once for all tests server_thread = start_server_in_thread()...
[ { "docstring": null, "function_declaration": "def run_server():", "function_name": "run_server", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def run_client(message):", "function_name": "run_client", "parameter_list": "(message)" } ]
[ 0, 0, 0, 0, 1, 1, 1, 1, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\n# Server-side code\nasync def handle_client(reader, writer):\n data = await reader.read(100)\n message = data.decode()\n addr = writer.get_ex...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00016651", "row_id": 16651, "seed_ids": "[101]" }
0.617325
Docs: Python310_16651
I
[ "handle_client", "main", "tcp_client", "run_server", "run_client" ]
5
[ [ "run_client", "tcp_client" ], [ "run_server", "main" ] ]
2
[]
false
[]
false
pytest
true
[]
true
3ca6cb4580ad9b2c50a3fc499f213217f21a69ec
1c77e013e3ddd032936b5260b46e736675726866
v1.0
instruct
Docs
Docs: Python310_16710_I
**Problem Statement:** You are required to implement a simplified version of the "tabnanny" module to gain a better understanding of recursive file handling and exception management in Python. Your task is to write a program that: 1. Recursively searches through a given directory for Python (.py) files. 2. For each Py...
import os class AmbiguousIndentationError(Exception): def __init__(self, filename, lineno, line): self.filename = filename self.lineno = lineno self.line = line super().__init__(f"Ambiguous indentation in {filename} at line {lineno}: {line}") def check_file_for_indentation_issues(f...
import os import pytest from solution import check_indentation test_dir = "test_dir" sub_dir = os.path.join(test_dir, "sub_dir") os.makedirs(test_dir, exist_ok=True) os.makedirs(sub_dir, exist_ok=True) # Create test files with open(os.path.join(test_dir, "script1.py"), "w", encoding="utf-8") as f: f.write("if Tru...
[]
[ 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\n\nclass AmbiguousIndentationError(Exception):\n def __init__(self, file_name, line_number, line_content):\n self.file_name = file_name\n sel...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016710", "row_id": 16710, "seed_ids": "[293]" }
0.546137
Docs: Python310_16710
I
[ "check_file_for_indentation_issues", "check_indentation" ]
2
[ [ "check_indentation", "check_file_for_indentation_issues" ] ]
1
[]
false
[ "AmbiguousIndentationError" ]
true
pytest
true
[]
true
a8e32da7f84b900a85672e9f717418ddab3c2bbe
5a134d90b1a7eb4678daa8296755401ec0679c1a
v1.0
instruct
Docs
Docs: Python310_16736_I
### Python asyncio Queue Task #### Objective: Implement an asyncio-based task manager that can schedule and execute tasks using different types of queues provided by the `asyncio` module: `Queue`, `PriorityQueue`, and `LifoQueue`. #### Task Description: Create a Python function `manage_tasks(queue_type: str, tasks: L...
import asyncio from typing import List, Tuple, Union async def worker(queue: asyncio.Queue, completed_tasks: List[str]): while not queue.empty(): priority, task_name, duration = await queue.get() await asyncio.sleep(duration) completed_tasks.append(task_name) queue.task_done() asyn...
import pytest import asyncio from solution import manage_tasks @pytest.mark.asyncio async def test_fifo_queue(): tasks = [(1, "task1", 1), (2, "task2", 1), (3, "task3", 1)] assert await manage_tasks("FIFO", tasks) == ["task1", "task2", "task3"] @pytest.mark.asyncio async def test_priority_queue(): tasks =...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple, Union\n\nasync def worker(queue: asyncio.Queue, completed_tasks: List[str]):\n while not queue.empty():\n prio...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016736", "row_id": 16736, "seed_ids": "[111]" }
0.645992
Docs: Python310_16736
I
[ "worker", "manage_tasks" ]
2
[ [ "manage_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fe7f2c1ce3587462fe6aaf334f9655c3aade6a3b
4da24280ac6b8f1f3a2e2ca168de2537b714d107
v1.0
instruct
Docs
Docs: Python310_16776_I
**Objective:** To assess the student's understanding of Python's `sys` module, specifically dealing with command-line arguments, exception handling, and auditing hooks. ### Problem Statement: You are required to create a Python script that uses functionalities from the `sys` module to handle command-line arguments,...
import sys import os def handle_command_line_arguments(arguments): """ Handles command-line arguments, separating the script name from the other arguments. Parameters: arguments (list of str): List of command-line arguments. Returns: dict: A dictionary with 'script_name' a...
import pytest from solution import handle_command_line_arguments, custom_excepthook, setup_custom_excepthook, audit_hook, add_audit_hook import sys import os def test_handle_command_line_arguments(): args = ['script.py', 'arg1', 'arg2'] expected_output = {'script_name': 'script.py', 'arguments': ['arg1', 'arg2...
[ { "docstring": "Handles command-line arguments, separating the script name from the other arguments.\n\nParameters:\n arguments (list of str): List of command-line arguments.\n \nReturns:\n dict: A dictionary with 'script_name' and 'arguments'.", "function_declaration": "def handle_command_line_arg...
[ 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 sys\nimport os\n\ndef handle_command_line_arguments(arguments):\n \"\"\"\n Handles command-line arguments, separating the script name from the other argume...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016776", "row_id": 16776, "seed_ids": "[348]" }
0.515532
Docs: Python310_16776
I
[ "handle_command_line_arguments", "custom_excepthook", "setup_custom_excepthook", "audit_hook", "add_audit_hook" ]
5
[ [ "add_audit_hook", "audit_hook" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3410dd7ce2a4b22342628d731532f1aad2d04bae
352695cc5e691b95a32da239f42f94573ec9b1f6
v1.0
instruct
Docs
Docs: Python310_16824_I
As a developer, you need to create a command-line utility for processing a database of user data. The utility should support the following functionalities: 1. **Create a new user** with a name, age, and email. 2. **Delete an existing user** by email. 3. **Update the age** of an existing user. 4. **List all users** in a...
import argparse import re users = [] def valid_email(email): regex = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$' return re.match(regex, email) def create_user(args): global users name = args.name age = args.age email = args.email if not valid_email(email): print(f"Error: ...
import pytest from io import StringIO import sys from solution import users, create_user, delete_user, update_age, list_users @pytest.fixture def reset_users(): global users users.clear() yield users.clear() def test_create_user(reset_users): args = argparse.Namespace(name="John Doe", age=30, emai...
[ { "docstring": null, "function_declaration": "def valid_email(email):", "function_name": "valid_email", "parameter_list": "(email)" }, { "docstring": null, "function_declaration": "def create_user(args):", "function_name": "create_user", "parameter_list": "(args)" }, { "d...
[ 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 argparse\nimport re\n\nusers = []\n\ndef valid_email(email):\n regex = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'\n return re.match(regex, email)...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016824", "row_id": 16824, "seed_ids": "[139]" }
0.501192
Docs: Python310_16824
I
[ "valid_email", "create_user", "delete_user", "update_age", "list_users", "main" ]
6
[ [ "create_user", "valid_email" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ce1d578645697c2d2cdcbaeb048c1641373c0c5f
89891a380f2efdd97cee3f5311eeecafba5be12b
v1.0
instruct
Docs
Docs: Python310_16868_I
You are given a list of URLs, and your task is to fetch data from these URLs concurrently using the `concurrent.futures` module. The objective is to implement a function that uses both `ThreadPoolExecutor` and `ProcessPoolExecutor` to perform the fetch operation and compare their performance. ### Function Signature ``...
import requests import time from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor from typing import List, Dict def fetch_url(url: str) -> str: """ Fetches the content of a given URL. """ try: response = requests.get(url) response.raise_for_status() return respo...
from solution import fetch_data_concurrently def test_fetch_data_concurrently(): # Mock URLs for testing urls = [ "http://example.com/data1", "http://example.com/data2", "http://example.com/data3", "http://example.com/data4" ] result = fetch_data_concurrently(urls) ...
[ { "docstring": "Fetches the content of a given URL.", "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_list": "(url)" }, { "docstring": "Fetches data from a list of URLs concurrently using ThreadPoolExecutor and ProcessPoolExecutor,\nand returns the tim...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import concurrent.futures\nimport requests\nimport time\nfrom typing import List, Dict\n\ndef fetch_url(url: str) -> str:\n \"\"\"\n Fetch the content of the give...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016868", "row_id": 16868, "seed_ids": "[224]" }
0.513982
Docs: Python310_16868
I
[ "fetch_url", "fetch_data_concurrently" ]
2
[ [ "fetch_data_concurrently", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
07109572b7cf93a58390dcce4825a05005e1e514
4228052cfc30813e305ae7531480a51b7a9217d9
v1.0
instruct
Docs
Docs: Python310_16875_I
### Advanced Multiprocessing Task: Web Scraping with Concurrent Downloads **Problem Statement:** You are tasked with writing a Python function that downloads content from a set of URLs concurrently and processes the data using the `multiprocessing` package. The goal is to maximize the use of multiple processors for f...
from multiprocessing import Pool import requests from typing import List def fetch_content(url): try: response = requests.get(url, timeout=10) response.raise_for_status() return response.text.upper() except (requests.RequestException, requests.HTTPError) as e: return f"Error fe...
import pytest from solution import download_and_process def test_download_and_process(): # Using example URLs for testing example_urls = [ "https://www.example.com", "https://www.nonexistenturl.org" # Invalid URL to test error handling ] results = download_and_process(example_urls) ...
[ { "docstring": null, "function_declaration": "def fetch_content(url):", "function_name": "fetch_content", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def download_and_process(urls, timeout=None):", "function_name": "download_and_process", "parameter...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from multiprocessing import Pool\nimport requests\nfrom typing import List\n\n\ndef fetch_content(url):\n try:\n response = requests.get(url, timeout=10)\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016875", "row_id": 16875, "seed_ids": "[338]" }
0.568102
Docs: Python310_16875
I
[ "fetch_content", "download_and_process" ]
2
[ [ "download_and_process", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
544a501b54be0169af5deacba0d6cdc576a61254
de1ea458148810a5023b804b64d198d33d89e029
v1.0
instruct
Docs
Docs: Pytorch_16912_I
### Distributed Training and Fault Tolerance with PyTorch You have been tasked with writing a Python script that implements a basic distributed training setup using PyTorch. Your goal is to design a flexible and fault-tolerant distributed training mechanism. #### Requirements: 1. **Distributed Initialization**: I...
import os import torch.distributed as dist import logging logging.basicConfig(level=logging.INFO) def initialize_distributed_training(nnodes: int, nproc_per_node: int, rdzv_id: str, rdzv_backend: str, rdzv_endpoint: str): """ Initializes the distributed training environment with given arguments. """ ...
import pytest import os from unittest.mock import patch, MagicMock import solution @pytest.fixture def patch_os_system(): with patch("os.system") as mock_system: yield mock_system @pytest.fixture def patch_torch_distributed_init(): with patch("torch.distributed.init_process_group") as mock_init: ...
[ { "docstring": "Initializes the distributed training environment with given arguments.", "function_declaration": "def initialize_distributed_training(nnodes, nproc_per_node, rdzv_id, rdzv_backend, rdzv_endpoint):", "function_name": "initialize_distributed_training", "parameter_list": "(nnodes, nproc...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport logging\nimport torch.distributed as dist\nfrom torch.distributed.elastic.multiprocessing.errors import record\n\nlogging.basicConfig(level=logging.IN...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00016912", "row_id": 16912, "seed_ids": "[157]" }
0.425872
Docs: Pytorch_16912
I
[ "initialize_distributed_training", "manage_fault_tolerance", "handle_scaling_events", "main", "run_training" ]
5
[ [ "manage_fault_tolerance", "run_training" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
72de9c303dcc365c9ce58eaa25bd07479a86e718
7ea696ee4125827ada8ce1b15fa8de7dde260913
v1.0
instruct
Docs
Docs: Python310_16924_I
## Coding Assessment Question ### Objective You are required to design a Python program that performs specific file management operations and measures the performance of these operations using the given modules in the standard library. ### Problem You need to write a Python script that does the following: 1. **Cre...
import os import shutil import random import string import timeit import zipfile def create_random_string(length=10): """ Generates a random alphanumeric string of given length. """ return ''.join(random.choices(string.ascii_letters + string.digits, k=length)) def perform_file_operations_and_measure_p...
from solution import perform_file_operations_and_measure_performance def test_perform_file_operations_and_measure_performance(): # Note: This test checks the execution of the main function and ensures it runs without error. # Difficult to check print outputs and timings without specific testing frameworks for ...
[ { "docstring": "Generates a random alphanumeric string of given length.", "function_declaration": "def create_random_string(length=10):", "function_name": "create_random_string", "parameter_list": "(length=10)" }, { "docstring": null, "function_declaration": "def perform_file_operations_...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport shutil\nimport random\nimport string\nimport timeit\nimport zipfile\n\ndef create_random_string(length=10):\n \"\"\"\n Generates a random alphan...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00016924", "row_id": 16924, "seed_ids": "[422]" }
0.617172
Docs: Python310_16924
I
[ "create_random_string", "perform_file_operations_and_measure_performance" ]
2
[ [ "perform_file_operations_and_measure_performance", "create_random_string" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ca76c42de563ccdd93805409a571d1290297b44b
afb86b925cab67c92256f9b136ffcd9a5902171b
v1.0
instruct
Docs
Docs: Python310_16991_I
**Question: Implement a Logging System Using the syslog Module** You have been tasked with creating a logging system for a Unix-based application. The logging system needs to handle various types of messages with different levels of severity and send them to appropriate syslog facilities. ### Requirements 1. **Funct...
import syslog _syslog_initialized = False def initialize_syslog(ident: str, logoption: int, facility: int) -> None: global _syslog_initialized syslog.openlog(ident, logoption, facility) _syslog_initialized = True def log_message(priority: int, message: str) -> None: global _syslog_initialized if ...
import syslog from solution import initialize_syslog, log_message, set_priority_mask, close_syslog def test_initialize_syslog(): initialize_syslog('testApp', syslog.LOG_PID, syslog.LOG_USER) # Verify syslog is initialized by logging a message and inspecting the syslog output (manual step required) def test_lo...
[ { "docstring": null, "function_declaration": "def initialize_syslog(ident, logoption, facility):", "function_name": "initialize_syslog", "parameter_list": "(ident, logoption, facility)" }, { "docstring": null, "function_declaration": "def log_message(priority, message):", "function_n...
[ 0, 1, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import syslog\n\nis_syslog_initialized = False\n\ndef initialize_syslog(ident: str, logoption: int, facility: int) -> None:\n global is_syslog_initialized\n\n sys...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00016991", "row_id": 16991, "seed_ids": "[133]" }
0.566767
Docs: Python310_16991
I
[ "initialize_syslog", "log_message", "set_priority_mask", "close_syslog" ]
4
[ [ "log_message", "initialize_syslog" ] ]
1
[]
false
[]
false
pytest
true
[]
true
405bf25b69109e967a71cd0ff357ea5004071d40
f94c43b60848112d72daf32874323d87fa29c39d
v1.0
instruct
Docs
Docs: Python310_17008_I
### Advanced Coding Assessment Question **Objective**: Implement a Python function that uses generators to process a sequence of data efficiently. **Problem Statement**: You are tasked with creating a custom generator function and a utility function that works with this generator. The generator will yield numbers fro...
def divisible_generator(numbers: list, divisor: int): """ A generator function that yields numbers from the input list that are divisible by the given divisor. Arguments: numbers : list : a list of integers divisor : int : the divisor to check divisibility Yields: int : numbers fr...
from solution import divisible_generator, sum_of_divisibles def test_divisible_generator(): numbers = [10, 20, 33, 46, 50] divisor = 10 gen = divisible_generator(numbers, divisor) assert list(gen) == [10, 20, 50] numbers = [1, 2, 3, 4, 5, 6] divisor = 2 gen = divisible_generator(number...
[ { "docstring": "A generator function that yields numbers from the input list that are divisible by the given divisor.\n\nArguments:\nnumbers : list : a list of integers\ndivisor : int : the divisor to check divisibility\n\nYields:\nint : numbers from the input list that are divisible by the divisor", "func...
[ 0, 1, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def divisible_generator(numbers: list, divisor: int):\n \"\"\"\n A generator function that yields numbers from the input list that are divisible by the given divi...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017008", "row_id": 17008, "seed_ids": "[27]" }
0.691581
Docs: Python310_17008
I
[ "divisible_generator", "sum_of_divisibles" ]
2
[ [ "sum_of_divisibles", "divisible_generator" ] ]
1
[]
false
[]
false
pytest
true
[]
true
4975a4ff7c400359935ddd3bf400b001af08e1dd
7d9c16d3ca430a3810a403f72a006fcdfafbcad1
v1.0
instruct
Docs
Docs: Seaborn_17015_I
**Objective**: Demonstrate your understanding of Seaborn's functionality for controlling figure aesthetics and context by creating a customized visualization. **Task**: 1. Create a function named `custom_plot` that: - Accepts an integer `n` for the number of sine waves to plot. - Accepts a string `style` repre...
import seaborn as sns import matplotlib.pyplot as plt import numpy as np def sinplot(n=10, flip=1): x = np.linspace(0, 14, 100) for i in range(1, n + 1): plt.plot(x, np.sin(x + i * 0.5) * (n - i) * flip) def custom_plot(n: int, style: str, context: str, custom_rc: dict = None) -> None: """ Gen...
import pytest from solution import custom_plot def test_valid_custom_plot(): # Basic plot should not raise any exceptions try: custom_plot(10, "whitegrid", "talk") assert True except Exception as e: assert False, f"Unexpected exception {e}" # Testing with custom rc para...
[ { "docstring": null, "function_declaration": "def sinplot(n=10, flip=1):", "function_name": "sinplot", "parameter_list": "(n=10, flip=1)" }, { "docstring": "Generates a custom plot with sine waves.\n\nParameters:\nn (int): Number of sine waves to plot.\nstyle (string): One of seaborn's prede...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\ndef sinplot(n=10, flip=1):\n x = np.linspace(0, 14, 100)\n for i in range(1, n+1):\n...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017015", "row_id": 17015, "seed_ids": "[2]" }
0.634399
Docs: Seaborn_17015
I
[ "sinplot", "custom_plot" ]
2
[ [ "custom_plot", "sinplot" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "seaborn" ]
false
e1bc962008e6b1e5a7b28df47a9f05cad9a1b63b
6425c464f9d447c77135c53039f539e69d33c37d
v1.0
instruct
Docs
Docs: Pytorch_17038_I
### PyTorch DDP Communication Hooks Assessment #### Objective Implement a custom communication hook for a DistributedDataParallel (DDP) model in PyTorch. This hook should perform an allreduce operation on the bucket's gradients and apply a custom transformation to the reduced gradients. Additionally, demonstrate check...
import os import tempfile import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim import torch.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel from torch.distributed import ReduceOp def custom_allreduce_hook(state, bucket): # Perform allreduce ope...
import os import tempfile import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel import torch.multiprocessing as mp # We will reuse the defined functions: custom_allreduce_hook, SimpleModel, # setup, cleanup, and run_demo in...
[]
[ 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 tempfile\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nfrom...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017038", "row_id": 17038, "seed_ids": "[92]" }
0.528976
Docs: Pytorch_17038
I
[ "custom_allreduce_hook", "setup", "cleanup", "run_demo", "demo_custom_hook" ]
5
[ [ "demo_custom_hook", "cleanup" ], [ "demo_custom_hook", "custom_allreduce_hook" ], [ "demo_custom_hook", "setup" ] ]
3
[]
false
[ "SimpleModel" ]
true
pytest
false
[ "torch" ]
false
3639d5f40a29bbc4a9752e1a33ce0d403272adcc
975b7eb7eaf9276ff1c474d21b8be35d9643a8b7
v1.0
instruct
Docs
Docs: Python310_17121_I
### Asynchronous Web Scraping with asyncio (instead of asyncore) **Objective**: You are required to implement an asynchronous web scraping tool using the `asyncio` package. This tool should be able to fetch and print the content of multiple web pages concurrently. **Problem Statement**: Write a Python function `fetc...
import aiohttp import asyncio async def fetch_content(session, url): try: async with session.get(url) as response: response.raise_for_status() content = await response.text() print(f"Content from {url}:\n{content[:500]}\n") except Exception as e: print(f"Fail...
import asyncio from unittest.mock import patch, AsyncMock from solution import fetch_webpages @patch('aiohttp.ClientSession.get') def test_fetch_webpages_single_url(mock_get): mock_response = AsyncMock() mock_response.text = AsyncMock(return_value="<html>Some content</html>") mock_response.raise_for_status...
[]
[ 1, 0, 1 ]
2
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import aiohttp\nimport asyncio\n\nasync def fetch_content(session, url):\n try:\n async with session.get(url) as response:\n response.raise_for_sta...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00017121", "row_id": 17121, "seed_ids": "[345]" }
0.640147
Docs: Python310_17121
I
[ "fetch_content", "fetch_webpages" ]
2
[ [ "fetch_webpages", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
b2a21b30822a8053e89f9991f5ca2e4c9e969906
6c536dbb6530b7218dcfa1b5633c808f78661221
v1.0
instruct
Docs
Docs: Python310_17123_I
**Objective:** Implement a function to manage file inclusion and exclusion based on the provided Unix-style glob patterns. **Function Signature:** ```python def manage_files(file_list, commands): """ This function takes a list of file paths and a list of command strings. It processes the commands to retur...
import fnmatch import os def match_files(pattern, files): return [file for file in files if fnmatch.fnmatch(file, pattern)] def recursive_match_files(directory, pattern, files): matched_files = [] for file in files: if file.startswith(directory): relative_path = file[len(directory):].l...
from solution import manage_files def test_example_scenario(): files = [ 'src/module1.py', 'src/module2.py', 'src/sub/extra.py', 'data/settings.json', 'data/config.yaml', 'scripts/install.py', 'README.md' ] commands = [ 'include *.py', 'exclude data/*', 'r...
[ { "docstring": null, "function_declaration": "def match_files(pattern, files):", "function_name": "match_files", "parameter_list": "(pattern, files)" }, { "docstring": null, "function_declaration": "def recursive_match_files(directory, pattern, files):", "function_name": "recursive_m...
[ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import fnmatch\nimport os\n\ndef manage_files(file_list, commands):\n def match(pattern, filename):\n return fnmatch.fnmatch(filename, pattern)\n \n def...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00017123", "row_id": 17123, "seed_ids": "[430]" }
0.680972
Docs: Python310_17123
I
[ "match_files", "recursive_match_files", "manage_files" ]
3
[ [ "manage_files", "match_files" ], [ "manage_files", "recursive_match_files" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5a47226e45f978b5453129f71dabe9e256e84d25
140d18a03d5f8cfc554880b31f4aaf6be3386eb6
v1.0
instruct
Docs
Docs: Python310_17126_I
**Question**: Implement a Python function that mimics the behavior of creating a floating point number from a string and safely converting it into a double, depending on whether the input is valid. Your task involves: 1. Checking if the given input is a valid float string. 2. Creating a float object from the valid st...
def PyFloat_Check(float_str): """ Mimics checking if a given string can be a valid float. """ try: float(float_str) return True except ValueError: return False def PyFloat_CheckExact(float_str): """ Mimics exact checking if the input string is a valid float. It b...
from solution import float_string_to_safe_double def test_valid_float_string(): assert float_string_to_safe_double("123.456") == 123.456 def test_invalid_float_string(): assert float_string_to_safe_double("not_a_float") is None def test_integer_string(): assert float_string_to_safe_double("100") == 100.0...
[ { "docstring": "Mimics checking if a given string can be a valid float.", "function_declaration": "def PyFloat_Check(float_str):", "function_name": "PyFloat_Check", "parameter_list": "(float_str)" }, { "docstring": "Mimics exact checking if the input string is a valid float.\nIt behaves the ...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def float_string_to_safe_double(float_str: str) -> float:\n \"\"\"\n Converts a float string into a double safely.\n \n Args:\n float_str: A string repre...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017126", "row_id": 17126, "seed_ids": "[59]" }
0.542926
Docs: Python310_17126
I
[ "PyFloat_Check", "PyFloat_CheckExact", "PyFloat_FromString", "PyFloat_AsDouble", "float_string_to_safe_double" ]
5
[ [ "PyFloat_CheckExact", "PyFloat_Check" ], [ "PyFloat_FromString", "PyFloat_CheckExact" ], [ "float_string_to_safe_double", "PyFloat_AsDouble" ], [ "float_string_to_safe_double", "PyFloat_FromString" ] ]
4
[]
false
[]
false
pytest
true
[]
true
49d5aabdf388751292b2a14f7aa210431d870fd8
f19dbad9430fb56ab04c999826137de29a8ed9d6
v1.0
instruct
Docs
Docs: Python310_17136_I
**Title: Implementing and Utilizing Generators in Python** **Objective:** Design a generator in Python that processes a given list of numbers to yield only those which are prime. Additionally, implement a function that utilizes this generator to return the sum of the first N prime numbers generated. **Function Defini...
import math def is_prime(n: int) -> bool: """ Returns True if n is a prime number, False otherwise. """ if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: return F...
import pytest from solution import is_prime, prime_generator, sum_of_primes def test_is_prime(): assert is_prime(2) == True assert is_prime(3) == True assert is_prime(4) == False assert is_prime(29) == True assert is_prime(1) == False assert is_prime(0) == False assert is_prime(-7) == False...
[ { "docstring": "Returns True if n is a prime number, False otherwise.", "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": "Generator that yields prime numbers from the given list of numbers.", "function_declaration": "def p...
[ 0, 0, 0, 1, 0, 0, 1, 1, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def is_prime(n: int) -> bool:\n \"\"\"\n Check if a number is a prime number.\n \n Parameters:\n - n (int): The number to check for primality.\n \n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00017136", "row_id": 17136, "seed_ids": "[27]" }
0.68492
Docs: Python310_17136
I
[ "is_prime", "prime_generator", "sum_of_primes" ]
3
[ [ "prime_generator", "is_prime" ], [ "sum_of_primes", "prime_generator" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d8ee08e95ead80e8aa6b8f58d0ab22391b01feba
4f64f4267de6870d071eecdabdb5399e79f87643
v1.0
instruct
Docs
Docs: Python310_17148_I
#### Objective: Design and implement a Python program utilizing the `contextvars` module to handle context-specific state within an asynchronous framework. #### Problem Statement: You are tasked with developing a URL shortener service with a basic logging feature. Each request to shorten a URL will have a unique reque...
import asyncio import contextvars from urllib.parse import urlparse, urljoin # Context Variable for holding request ID request_id_var = contextvars.ContextVar('request_id', default=None) async def shorten_url(request_id, url): """ Asynchronously imitates shortening a URL and logs the request ID and URL. "...
import os import pytest import asyncio from solution import handle_request, request_id_var @pytest.fixture(autouse=True) def clean_log_file(): # Ensure the log file is clean before each test if os.path.exists("requests.log"): os.remove("requests.log") yield # Clean up the log file after each te...
[ { "docstring": "Logs the request ID and the URL to the 'requests.log' file.", "function_declaration": "def log_request(request_id, url):", "function_name": "log_request", "parameter_list": "(request_id, url)" } ]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\nimport re\n\n# Context Variable for holding request ID\nrequest_id_var = contextvars.ContextVar('request_id', default=None)\n\nasync...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017148", "row_id": 17148, "seed_ids": "[392]" }
0.515542
Docs: Python310_17148
I
[ "shorten_url", "log_request", "handle_request" ]
3
[ [ "handle_request", "shorten_url" ], [ "shorten_url", "log_request" ] ]
2
[]
false
[]
false
pytest
true
[]
true
00666b910f1a6d3e5792f966bc5a372890767cc3
a0bd60e8aa84ab4f093082672676547e1ddae670
v1.0
instruct
Docs
Docs: Scikit_17205_I
You are required to demonstrate your understanding of Gaussian Mixture Models (GMM) and Bayesian Gaussian Mixture Models (BGMM) using scikit-learn. Follow the tasks below to design and analyze a dataset using these models. ### Tasks: 1. **Generate a Synthetic Dataset**: - Use `numpy` to generate a synthetic dataset...
import numpy as np import matplotlib.pyplot as plt from sklearn.mixture import GaussianMixture, BayesianGaussianMixture # Task 1: Generate Dataset np.random.seed(42) def generate_synthetic_data(): # Means of the clusters mean1 = [0, 0] mean2 = [5, 5] mean3 = [10, 0] # Covariance matrices of the c...
def test_generate_synthetic_data(): data = generate_synthetic_data() assert data.shape == (300, 2) def test_gmm_optimal_components(): assert optimal_n_components == 3 # Expecting 3 distinct clusters def test_gmm_bic_scores(): assert len(bic_scores) == 6 assert np.argmin(bic_scores) == 2 # Index ...
[ { "docstring": null, "function_declaration": "def generate_synthetic_data():", "function_name": "generate_synthetic_data", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def plot_gmm_results(X, labels, gmm):", "function_name": "plot_gmm_results", "paramet...
[ 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 numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.mixture import GaussianMixture, BayesianGaussianMixture\n\n# Set the random seed for reproducibility\n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00017205", "row_id": 17205, "seed_ids": "[23]" }
0.54259
Docs: Scikit_17205
I
[ "generate_synthetic_data", "plot_gmm_results", "draw_ellipse" ]
3
[ [ "plot_gmm_results", "draw_ellipse" ] ]
1
[]
false
[]
false
pytest
false
[ "matplotlib", "numpy", "sklearn" ]
false
ba517dc5d67a8118e5ebb0139822327c627dca8d
e8e968006d9c7362ea9d4b16e0e678f2a15f9cef
v1.0
instruct
Docs
Docs: Scikit_17350_I
**Question: Optimizing Prediction Latency and Throughput with scikit-learn** **Problem Statement:** You are provided with a dataset and a requirement to build a machine learning pipeline in scikit-learn, focusing on optimizing prediction latency and throughput. Your task is to implement functions to evaluate and comp...
import numpy as np import pandas as pd import time from typing import Tuple, Dict, Any, List from sklearn.linear_model import LinearRegression from sklearn.svm import SVR from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_erro...
import numpy as np from sklearn.linear_model import LinearRegression from sklearn.svm import SVR from sklearn.ensemble import RandomForestRegressor # Assuming 'solution' is the module name where above functions are defined from solution import load_preprocess_data, train_evaluate_model, compare_models, optimize_model_...
[ { "docstring": "Load and preprocess the dataset from the given file path.\n\nArgs:\n- file_path (str): Path to the dataset file.\n\nReturns:\n- Tuple[np.ndarray, np.ndarray]: Features and target arrays.", "function_declaration": "def load_preprocess_data(file_path):", "function_name": "load_preprocess_d...
[ 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 numpy as np\nimport pandas as pd\nimport time\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.svm import SVR\nfrom sklearn.ensemble import Rando...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00017350", "row_id": 17350, "seed_ids": "[64]" }
0.602424
Docs: Scikit_17350
I
[ "load_preprocess_data", "train_evaluate_model", "compare_models", "optimize_model_performance" ]
4
[ [ "compare_models", "train_evaluate_model" ], [ "optimize_model_performance", "compare_models" ] ]
2
[]
false
[]
false
pytest
true
[ "numpy", "pandas", "sklearn" ]
false
cbe5ef0797b7ee16eb2eb42de9f441d8d4b330c6
ba7ef9025969a64f897d15f3b910bd7898d3f38c
v1.0
instruct
Docs
Docs: Python310_17359_I
### Asynchronous Chat Server with asyncio #### Objective: Design and implement an asynchronous chat server using the `asyncio` library. The server should be able to handle multiple clients, broadcast messages to all connected clients, and properly manage network connections and exceptions. #### Requirements: 1. **Ser...
# chat_server.py import asyncio clients = [] async def handle_client(reader, writer): addr = writer.get_extra_info('peername') clients.append(writer) print(f"Connected by {addr}") try: while True: data = await reader.read(100) if not data: break ...
import asyncio import pytest import socket from contextlib import closing # Function to find free port for testing def find_free_port(): with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: s.bind(('', 0)) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return s.get...
[ { "docstring": null, "function_declaration": "def broadcast_message(message, current_writer):", "function_name": "broadcast_message", "parameter_list": "(message, current_writer)" } ]
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "# chat_server.py\nimport asyncio\n\nclients = []\n\nasync def handle_client(reader, writer):\n addr = writer.get_extra_info('peername')\n print(f\"Connected by {a...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017359", "row_id": 17359, "seed_ids": "[267]" }
0.580542
Docs: Python310_17359
I
[ "handle_client", "broadcast_message", "main", "handle_input", "handle_output", "main" ]
6
[ [ "handle_client", "broadcast_message" ] ]
1
[ "handle_input" ]
false
[]
false
pytest
false
[]
true
cb33864fd556754b24ff487cb6b18d1f67587d2c
b3ad41692ebca547208fd70fdc919b0157560ba7
v1.0
instruct
Docs
Docs: Scikit_17361_I
**Incremental Learning with Scikit-learn** **Objective:** Design and implement a pipeline for handling and learning from a large dataset that does not fit into memory using scikit-learn. This will involve: 1. Streaming data from a file or generated data. 2. Extracting features using a suitable method. 3. Training an ...
import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score def stream_data(file_path, batch_size): """ Streams data from a file in mini-batches. Parameters: file_path (str): Path to the inpu...
import numpy as np import os from solution import stream_data, extract_features, incremental_learning def test_stream_data(tmpdir): # Create a temporary file with sample data file_path = os.path.join(tmpdir, 'sample.txt') lines = [f"Line {i}\n" for i in range(100)] with open(file_path, 'w') as f: ...
[ { "docstring": "Streams data from a file in mini-batches.\n\nParameters:\nfile_path (str): Path to the input text file.\nbatch_size (int): Number of lines to read per batch.\n\nYields:\nList[str]: A batch of lines from the file.", "function_declaration": "def stream_data(file_path, batch_size):", "funct...
[ 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 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": "", "prompt_id": "00017361", "row_id": 17361, "seed_ids": "[63]" }
0.433093
Docs: Scikit_17361
I
[ "stream_data", "extract_features", "incremental_learning" ]
3
[ [ "incremental_learning", "extract_features" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
81ab0f1a7770e7b0da03c6ee4cac3005afa58b69
b359698ea81737c84922f2396c7025dc3e03f037
v1.0
instruct
Docs
Docs: Python310_17402_I
**Task: Secure Message Transmission Using SSLContext** In this task, you are required to implement a Python program that demonstrates secure client-server communication using Python's `ssl` module. Follow the guidelines below to meet the requirements: ### Requirements 1. **SSL Context Setup:** - Create an `SSLCo...
import ssl import socket from threading import Thread def setup_server_context(): """ Sets up the SSL context for the server using TLS and requires client authentication. """ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain(certfile="server_cert.pem", keyfile="server_key.pe...
import subprocess from threading import Thread import time import socket import ssl # Generate a simple self-signed certificate using OpenSSL def generate_certificates(): subprocess.run([ "openssl", "req", "-new", "-newkey", "rsa:2048", "-days", "1", "-nodes", "-x509", "-subj", "/C=US/ST=Test/L=Tes...
[ { "docstring": "Sets up the SSL context for the server using TLS and requires client authentication.", "function_declaration": "def setup_server_context():", "function_name": "setup_server_context", "parameter_list": "()" }, { "docstring": "Handles communication with the client.", "funct...
[ 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 ssl\nimport socket\nfrom threading import Thread\n\ndef setup_server_context():\n \"\"\"\n Setup the SSLContext for the server with secure defaults.\n L...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017402", "row_id": 17402, "seed_ids": "[311]" }
0.762818
Docs: Python310_17402
I
[ "setup_server_context", "handle_client", "start_server", "setup_client_context", "start_client" ]
5
[ [ "start_client", "setup_client_context" ], [ "start_server", "setup_server_context" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5236e982473454ac2483503157df93d0dbad3d0e
03f43ee66ba15c7532e63e4517046af09db69b82
v1.0
instruct
Docs
Docs: Python310_17466_I
#### Objective Implement a Python script that utilizes the `time` module to perform and measure various time-related tasks efficiently. #### Description You are required to implement a program that performs the following tasks: 1. **Get Current Time:** - Print the current local time in the format "YYYY-MM-DD HH:MM...
import time def measure_function_runtime(func): """ Measures the runtime of a given function. """ start_time = time.time() func() end_time = time.time() return end_time - start_time def convert_to_gmt(struct_time_obj): """ Converts a local struct_time object to a GMT time string. ...
import time from solution import measure_function_runtime, convert_to_gmt def test_measure_function_runtime(): def quick_func(): pass def slow_func(): time.sleep(1) quick_time = measure_function_runtime(quick_func) slow_time = measure_function_runtime(slow_func) assert quick_time...
[ { "docstring": "Measures the runtime of a given function.", "function_declaration": "def measure_function_runtime(func):", "function_name": "measure_function_runtime", "parameter_list": "(func)" }, { "docstring": "Converts a local struct_time object to a GMT time string.", "function_decl...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\n\ndef get_current_local_time():\n \"\"\"\n Returns the current local time in the format \"YYYY-MM-DD HH:MM:SS\".\n \"\"\"\n return time.strftim...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00017466", "row_id": 17466, "seed_ids": "[122]" }
0.613576
Docs: Python310_17466
I
[ "measure_function_runtime", "convert_to_gmt", "compare_performance" ]
3
[ [ "compare_performance", "measure_function_runtime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
83f3cbaf49f904d5f70a15bac64bc32d36f56dda
cfe14944de263a6976cd0f4669b55a625fcd3774
v1.0
instruct
Docs
Docs: Python310_17481_I
**Question: Implement an Audit Event Logger in Python** Python 3.8 introduced the ability to audit and log events through `sys.audit` calls. This allows developers to monitor certain sensitive actions more closely. For this task, you need to implement an auditing hook that logs specific events into a file. **Task:** ...
import sys def log_audit_event(event, args): """ Log the audit event to a file. Parameters: - event (str): The name of the event. - args (tuple): The arguments associated with the event. """ try: with open("audit_log.txt", "a") as log_file: log_file.write(f"{event}:...
import os import sys import subprocess from pathlib import Path def test_log_file_exists(): # Clean up before the test audit_log = Path("audit_log.txt") if audit_log.exists(): audit_log.unlink() # Run the script subprocess.run([sys.executable, "solution.py"], input="Test Input\n", text...
[ { "docstring": "Log the audit event to a file.\n\nParameters:\n- event (str): The name of the event.\n- args (tuple): The arguments associated with the event.", "function_declaration": "def log_audit_event(event, args):", "function_name": "log_audit_event", "parameter_list": "(event, args)" }, {...
[ 0, 0, 1 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\n\ndef log_audit_event(event, args):\n \"\"\"\n Logs the event name and its arguments to a file named 'audit_log.txt'.\n Each event is on a new line...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00017481", "row_id": 17481, "seed_ids": "[167]" }
0.55202
Docs: Python310_17481
I
[ "log_audit_event", "setup_audit_hook" ]
2
[ [ "setup_audit_hook", "log_audit_event" ] ]
1
[]
false
[]
false
pytest
false
[]
true
f64fda5cff6254387bec9c3a077a93378c31ebd6
9ffc05158d888393b4b334406de7ae04ff7a2608