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: Python310_30459_I
### Context Management in Python 3.7+ In Python, context variables enable the isolation of data between different execution contexts. Using the `contextvars` module in Python, you can create and manipulate context variables to achieve this isolation. This is especially useful in asynchronous programming, where differe...
import contextvars import asyncio def create_context_variable(name, default_value): """ Create a new context variable. Parameters: name (str): The name of the context variable. default_value: The default value of the context variable. Returns: ContextVar: A new context variable instance. ...
import contextvars import pytest from solution import create_context_variable, set_context_value, get_context_value, reset_context_value def test_create_context_variable(): var = create_context_variable("test_var", "default_value") assert get_context_value(var) == "default_value" def test_set_context_value():...
[ { "docstring": "Create a new context variable.\n\nParameters:\nname (str): The name of the context variable.\ndefault_value: The default value of the context variable.\n\nReturns:\nContextVar: A new context variable instance.", "function_declaration": "def create_context_variable(name, default_value):", ...
[ 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextvars\n\ndef create_context_variable(name, default_value):\n \"\"\"\n Create a new context variable.\n\n Parameters:\n name (str): The name of ...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00030459", "row_id": 30459, "seed_ids": "[60]" }
0.445737
Docs: Python310_30459
I
[ "create_context_variable", "set_context_value", "get_context_value", "reset_context_value", "task", "main" ]
6
[ [ "task", "get_context_value" ], [ "task", "reset_context_value" ], [ "task", "set_context_value" ] ]
3
[]
false
[]
false
pytest
true
[]
true
a797a2fb2e6f7d0b0936328bfacf7f7b9c685f8e
d1dd34c49ca141a61042ba7f96f64df044813793
v1.0
instruct
Docs
Docs: Python310_30487_I
### Asynchronous Web Scraper You are tasked to implement an asynchronous web scraper using the `asyncio` and `aiohttp` libraries. The scraper will concurrently fetch data from multiple URLs and process the content. #### Requirements 1. **Function Name**: `async_scrape(urls: List[str]) -> List[Tuple[str, int]]` 2. **...
import asyncio from typing import List, Tuple import aiohttp async def fetch(url: str) -> Tuple[str, int]: try: async with aiohttp.ClientSession() as session: async with session.get(url) as response: content = await response.text() return url, len(content) ex...
import asyncio from solution import async_scrape def test_async_scrape_valid_urls(): urls = ["http://example.com"] result = asyncio.run(async_scrape(urls)) assert isinstance(result, list) assert len(result) == 1 assert result[0][0] == "http://example.com" assert isinstance(result[0][1], int) d...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\nimport aiohttp\n\nasync def fetch(url: str) -> Tuple[str, int]:\n try:\n async with aiohttp.ClientSession() as...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00030487", "row_id": 30487, "seed_ids": "[270]" }
0.639784
Docs: Python310_30487
I
[ "fetch", "async_scrape" ]
2
[ [ "async_scrape", "fetch" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
a205031ee7cdb8b86747c1f20a74ef9e2a41e189
48e46c4f40ee9125b92116f7268af89da8dfd205
v1.0
instruct
Docs
Docs: Python310_30500_I
**Challenging Python Coding Assessment** You are tasked with implementing a concurrent system for processing a number of independent tasks using Python's `concurrent.futures` module. Your function will simulate a real-world scenario where each task involves fetching data, processing the data, and saving the results. Y...
import time import concurrent.futures def fetch_data(task_id): """ Simulates fetching data for a given task_id. """ print(f"Fetching data for task {task_id}") time.sleep(1) return f"Data for task {task_id}" def process_data(data): """ Simulates processing the fetched data. """ ...
import pytest from solution import process_tasks_concurrently def test_process_tasks_using_threads(capfd): task_ids = [1, 2, 3] process_tasks_concurrently(task_ids, use_threads=True) captured = capfd.readouterr() assert all(f"Fetching data for task {i}" in captured.out for i in task_ids) assert all...
[]
[ 1, 1, 0, 1, 1, 0, 0, 1, 0, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import time\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed\n\ndef fetch_data(task_id):\n print(f\"Fetching data for task {task...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00030500", "row_id": 30500, "seed_ids": "[224]" }
0.626267
Docs: Python310_30500
I
[ "fetch_data", "process_data", "save_result", "process_task", "process_tasks_concurrently" ]
5
[ [ "process_task", "fetch_data" ], [ "process_task", "process_data" ], [ "process_task", "save_result" ], [ "process_tasks_concurrently", "process_task" ] ]
4
[ "process_data" ]
false
[]
false
pytest
true
[]
true
0cef2dca777d44ad9d2e18a6eaa015de5cc8f660
0c0d736780822e33042fc84ba39580c5b70d05a9
v1.0
instruct
Docs
Docs: Python310_30518_I
Write a function `optimize_tail_call` that transforms a given Python function to optimize tail-call recursion. Tail-call recursion occurs when a function calls itself as its final action, allowing for optimizations like reusing stack frames. Python does not optimize tail calls natively, so the solution should involve...
import dis import types import functools def optimize_tail_call(func: callable) -> callable: """ Transforms a given Python function to optimize tail-call recursion. """ @functools.wraps(func) def wrapper(*args, **kwargs): stack = [(args, kwargs)] while stack: args, kwarg...
from solution import optimize_tail_call, tail_call def factorial(n, acc=1): if n == 0: return acc return tail_call((n-1, n*acc), {}) def fibonacci(n, a=0, b=1): if n == 0: return a if n == 1: return b return tail_call((n-1, b, a+b), {}) optimized_factorial = optimize_tail_...
[]
[ 0, 1, 1, 0, 1, 0, 1, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import dis\nimport types\nimport functools\n\ndef optimize_tail_call(func):\n \"\"\"\n Transform the given Python function to optimize tail-call recursion.\n \...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00030518", "row_id": 30518, "seed_ids": "[382]" }
0.470535
Docs: Python310_30518
I
[ "optimize_tail_call", "tail_call", "factorial" ]
3
[ [ "factorial", "tail_call" ] ]
1
[]
false
[ "TailCall" ]
true
pytest
true
[]
true
85ac8b4402cfed047af927f38b9059b930495adb
acfa10211f463cdc57afa765c820c0f446863205
v1.0
instruct
Docs
Docs: Python310_30523_I
### Question: Prime Number Calculation with Threading You are required to write a Python function that computes the number of prime numbers within a given range concurrently using threads. The goal of this task is to efficiently use threading to improve the performance of your computation. ### Function Signature ```p...
from threading import Thread, Lock def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def worker...
from solution import count_primes_in_range def test_count_primes_small_range(): assert count_primes_in_range(1, 10, 2) == 4 # Primes: 2, 3, 5, 7 def test_count_primes_medium_range(): assert count_primes_in_range(1, 100, 4) == 25 def test_count_primes_large_range(): assert count_primes_in_range(1, 10...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def worker(start, end, result, lock):", "function_name": "worker", "parameter_list": "(start, end, result, lock)"...
[ 0, 0, 0, 1, 0, 0, 1, 1, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from threading import Thread, Lock\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00030523", "row_id": 30523, "seed_ids": "[206]" }
0.639697
Docs: Python310_30523
I
[ "is_prime", "worker", "count_primes_in_range" ]
3
[ [ "worker", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1b477629f0f025d75007e4a64be8a40852e2aa32
4716c302276c596c1a2634759e277d76dbada85e
v1.0
instruct
Docs
Docs: Python310_30550_I
**Question: Custom Exception Handling with Recursive Calls** You are tasked with implementing a custom exception handling system in Python, using advanced exception handling techniques. Your goal is to create specific exception classes, manage error indicators properly, and handle recursion effectively. ### Requireme...
import sys import traceback class CustomError(Exception): pass class CustomRecursionError(CustomError): pass def raise_custom_error(condition): if condition == "error": raise CustomError("A custom error occurred") def raise_custom_recursion_error(): raise CustomRecursionError("Recursion dept...
from solution import CustomError, CustomRecursionError, raise_custom_error, recursive_function, handle_errors import pytest def test_raise_custom_error(): with pytest.raises(CustomError, match="A custom error occurred"): raise_custom_error("error") def test_raise_custom_recursion_error(): with pytest....
[]
[ 1, 1, 0, 1, 0, 0, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class CustomError(Exception):\n \"\"\"\n A custom general exception for demonstration purposes.\n \"\"\"\n pass\n\nclass CustomRecursionError(CustomError):\...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00030550", "row_id": 30550, "seed_ids": "[33]" }
0.413245
Docs: Python310_30550
I
[ "raise_custom_error", "raise_custom_recursion_error", "handle_errors", "recursive_function" ]
4
[ [ "recursive_function", "raise_custom_recursion_error" ] ]
1
[]
false
[ "CustomError", "CustomRecursionError" ]
true
pytest
true
[]
true
0a91cd96bcc5ed686871321327f0104a1b4ecd94
131cc3a97212186265c84e04b3dea81d49046957
v1.0
instruct
Docs
Docs: Python310_30585_I
## Question: Using `concurrent.futures` for Web Scraping ### Objective: Design a web scraper that concurrently fetches the content of multiple web pages. You will demonstrate your understanding of the `concurrent.futures` module by writing a Python function that uses `ThreadPoolExecutor` to parallelize the fetching of...
import requests from concurrent.futures import ThreadPoolExecutor, as_completed def fetch_url(url): """ Fetch the content of the URL. Parameters: - url (str): The URL to fetch. Returns: - str: The content of the web page if successful, None otherwise. """ try: response...
import pytest from solution import scrape_web_pages def test_scrape_web_pages_success(): urls = [ "http://example.com", "http://example.org" ] results = scrape_web_pages(urls) assert "http://example.com" in results and results["http://example.com"] is not None assert "http://example...
[ { "docstring": "Fetch the content of the URL.\n\nParameters:\n- url (str): The URL to fetch.\n\nReturns:\n- str: The content of the web page if successful, None otherwise.", "function_declaration": "def fetch_url(url):", "function_name": "fetch_url", "parameter_list": "(url)" }, { "docstring...
[ 0, 1, 1, 1, 1, 0, 1, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef fetch_url(url):\n \"\"\"\n Fetches the content of a given URL.\n If the...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00030585", "row_id": 30585, "seed_ids": "[224]" }
0.55669
Docs: Python310_30585
I
[ "fetch_url", "scrape_web_pages" ]
2
[ [ "scrape_web_pages", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
1606d8b94bd8344ccbcdd953aae345e63cf1c691
03789e81c6651dbb85f2a4461858cedd27e71e0f
v1.0
instruct
Docs
Docs: Python310_30629_I
### Question You have been tasked with implementing a simple echo TCP server using the asyncio module in Python. The server should be able to handle multiple clients simultaneously, echoing back any message it receives from a client. Here are the requirements: 1. Create an event loop and set it as the default event l...
import asyncio async def handle_client(reader, writer): address = writer.get_extra_info('peername') print(f"Connection from {address}") try: while True: data = await reader.read(100) if not data: break message = data.decode() print(f"...
import asyncio import pytest from async_timeout import timeout from solution import start_server, handle_client @pytest.mark.asyncio async def test_echo_server(): server_task = asyncio.create_task(start_server('127.0.0.1', 8888)) await asyncio.sleep(1) # Give the server time to start reader, writer = aw...
[]
[ 1, 1, 1, 1, 0, 0, 0, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n address = writer.get_extra_info('peername')\n print(f\"Connection from {address}\")\n\n try:\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00030629", "row_id": 30629, "seed_ids": "[101]" }
0.655236
Docs: Python310_30629
I
[ "handle_client", "start_server" ]
2
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[ "async_timeout" ]
false
c68e1dca448cc6a7a40e5d9172cf2afb927d8722
483f67d20cf2bc37874af49c992ceb3e9c3b3b0f
v1.0
instruct
Docs
Docs: Pytorch_30667_I
### PyTorch Distributed Training with Elasticity PyTorch's `torch.distributed.elastic` package allows for dynamically resizing distributed training jobs, making it easier to handle worker failures and resource fluctuations. Inside this package, the `control_plane` module provides tools for added debugging and control ...
import os import torch import torch.distributed as dist import torch.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel as DDP from torch.distributed.elastic.multiprocessing.errors import record def setup(rank, world_size): os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_POR...
# Note: Due to the nature of distributed training requiring multiple GPUs # and the environment setup, it is not feasible to provide unit test code # for the script in a typical pytest framework. The distributed training # script inherently requires execution in a distributed compute environment # which pytest alone ca...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nimport torch.distributed as dist\nfrom torch.nn.parallel import Di...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00030667", "row_id": 30667, "seed_ids": "[146]" }
0.47809
Docs: Pytorch_30667
I
[ "setup", "cleanup", "train_loop", "main" ]
4
[ [ "train_loop", "cleanup" ], [ "train_loop", "setup" ] ]
2
[]
false
[ "SimpleNN" ]
true
pytest
false
[ "torch" ]
false
91d5698a54f5259e07727bcb2e0e4393691ee8f6
0382a28cdbc4afdca507acd260709bfeaa41ff27
v1.0
instruct
Docs
Docs: Python310_30761_I
### Advanced Python Logging with syslog Module You are required to create a Python logging utility using the `syslog` module that simulates a system processing multiple tasks. The utility should demonstrate advanced functionalities such as setting log options, sending messages with different priority levels, and filte...
import syslog def configure_logging(): """ Configure the syslog with identifier 'TaskProcessor', log options to include process ID, and log to the user facility. """ syslog.openlog(ident='TaskProcessor', logoption=syslog.LOG_PID, facility=syslog.LOG_USER) def log_message(priority, message): """ ...
import pytest from solution import configure_logging, log_message, set_log_mask, simulate_tasks def test_configure_logging(): """ Test that the logging configuration doesn't raise any exceptions. """ try: configure_logging() except Exception as e: pytest.fail(f"configure_logging rai...
[ { "docstring": "Configure the syslog with identifier 'TaskProcessor', log options to include process ID, and log to the user facility.", "function_declaration": "def configure_logging():", "function_name": "configure_logging", "parameter_list": "()" }, { "docstring": "Log a message with the ...
[ 1, 0, 0, 0, 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": "import syslog\n\ndef configure_logging():\n \"\"\"\n Configure the syslog with identifier 'TaskProcessor', log options to include process ID, and log to the user ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00030761", "row_id": 30761, "seed_ids": "[133]" }
0.607426
Docs: Python310_30761
I
[ "configure_logging", "log_message", "set_log_mask", "simulate_tasks" ]
4
[ [ "simulate_tasks", "log_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bd9119cd27c6fcb2c01d71c90fbb6d1d390e6597
001f31ba79aad7317825f6ddf6cb715e49a7c6a1
v1.0
instruct
Docs
Docs: Python310_30836_I
You are required to implement a program that calculates the sum of squares of a list of numbers using parallel processing techniques. You'll need to create a function `sum_of_squares` that can leverage both multi-threading and multi-processing. ### Function Signature ```python from typing import List import concurrent...
from typing import List import concurrent.futures def chunkify(numbers: List[int], n: int) -> List[List[int]]: """Break the list into n-sized chunks.""" return [numbers[i:i + n] for i in range(0, len(numbers), n)] def square_numbers(nums: List[int]) -> int: """Return the sum of squares of the given list o...
import pytest from solution import sum_of_squares def test_sum_of_squares_threading(): numbers = [1, 2, 3, 4, 5] result = sum_of_squares(numbers, method='threading') assert result == 55 def test_sum_of_squares_multiprocessing(): numbers = [1, 2, 3, 4, 5] result = sum_of_squares(numbers, method='mu...
[ { "docstring": "Break the list into n-sized chunks.", "function_declaration": "def chunkify(numbers, n):", "function_name": "chunkify", "parameter_list": "(numbers, n)" }, { "docstring": "Return the sum of squares of the given list of numbers.", "function_declaration": "def square_number...
[ 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": "from typing import List\nimport concurrent.futures\n\ndef chunkify(numbers: List[int], n: int) -> List[List[int]]:\n \"\"\"Break the list into n-sized chunks.\"\"\"\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00030836", "row_id": 30836, "seed_ids": "[206]" }
0.691306
Docs: Python310_30836
I
[ "chunkify", "square_numbers", "sum_of_squares" ]
3
[ [ "sum_of_squares", "chunkify" ], [ "sum_of_squares", "square_numbers" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b30a71de52f5239a67a4a7c64c2153e2f0aebcb4
31b3a97b213114a4c4cfc72a74f21be5c2b08c84
v1.0
instruct
Docs
Docs: Python310_30850_I
### Email Address Manipulation and Parsing **Objective**: Implement a set of functions to manipulate and parse email addresses using the `email.utils` module. This assessment will test your ability to handle common email-related operations in Python. #### Part 1: Parse Email Address Write a function `parse_email` th...
from email.utils import parseaddr, formataddr, getaddresses def parse_email(address: str, strict: bool = True) -> tuple: real_name, email_address = parseaddr(address) if strict and '@' not in email_address: return ('', '') return (real_name, email_address) def format_email(address_tuple: tuple, ch...
from solution import parse_email, format_email, extract_addresses def test_parse_email(): assert parse_email("John Doe <john@example.com>") == ('John Doe', 'john@example.com') assert parse_email("invalid email") == ('', '') assert parse_email("No Name <noemail@here>") == ('No Name', 'noemail@here') ass...
[ { "docstring": null, "function_declaration": "def parse_email(address, strict=True):", "function_name": "parse_email", "parameter_list": "(address, strict=True)" }, { "docstring": null, "function_declaration": "def format_email(address_tuple, charset='utf-8'):", "function_name": "for...
[ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from email.utils import parseaddr, formataddr, getaddresses\n\ndef parse_email(address: str, strict: bool = True) -> tuple:\n \"\"\"\n Parse the given email addre...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00030850", "row_id": 30850, "seed_ids": "[215]" }
0.616944
Docs: Python310_30850
I
[ "parse_email", "format_email", "extract_addresses" ]
3
[ [ "extract_addresses", "parse_email" ] ]
1
[]
false
[]
false
pytest
true
[]
true
27ae176fa32e92b57e8412091c2d9e592b54436f
e830507fb73a3243d93f081581d62c37e0cbfbab
v1.0
instruct
Docs
Docs: Python310_30868_I
### Problem: Multi-threaded Data Processing In this assessment, you are required to write a Python program that uses the `_thread` module to process a list of integers in parallel. The goal is to split the list into several chunks, process each chunk in a separate thread, and then combine the results safely using thre...
from typing import List import _thread import time # Function to process a chunk def process_chunk(chunk: List[int]) -> int: return sum(chunk) # Function to process list in parallel def parallel_sum(lst: List[int], n_threads: int) -> int: # Validate number of threads assert 1 <= n_threads <= len(lst), "Nu...
from solution import process_chunk, parallel_sum def test_process_chunk(): assert process_chunk([1, 2, 3]) == 6 assert process_chunk([-1, -2, -3]) == -6 assert process_chunk([0, 0, 0]) == 0 assert process_chunk([]) == 0 def test_parallel_sum_single_thread(): assert parallel_sum([1, 2, 3, 4, 5], 1)...
[ { "docstring": null, "function_declaration": "def process_chunk(chunk):", "function_name": "process_chunk", "parameter_list": "(chunk)" }, { "docstring": null, "function_declaration": "def parallel_sum(lst, n_threads):", "function_name": "parallel_sum", "parameter_list": "(lst, n...
[ 1, 1, 0, 0, 0, 0, 1, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport _thread\nimport time\n\n# Function to process a chunk\ndef process_chunk(chunk: List[int]) -> int:\n return sum(chunk)\n\n# Function ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00030868", "row_id": 30868, "seed_ids": "[223]" }
0.549227
Docs: Python310_30868
I
[ "process_chunk", "parallel_sum" ]
2
[ [ "parallel_sum", "process_chunk" ] ]
1
[]
false
[]
false
pytest
true
[]
true
05b875b92baf78bac1b23b40924015e7fa42555d
62fdd7e794f2949a2156090fa816f2f3486b2e66
v1.0
instruct
Docs
Docs: Scikit_30927_I
## Coding Assessment Question ### Objective: To assess your understanding of linear models in `scikit-learn`, you are required to implement a machine-learning pipeline to solve a regression problem. Specifically, you will preprocess the data, select a linear model, perform hyperparameter tuning, and evaluate the model...
import pandas as pd from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.linear_model import LinearRegression, Ridge from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler from sklearn.metrics import r2_score, mean_squar...
import os import pytest from solution import preprocess_and_train # Here we'll create a temporary CSV file for testing @pytest.fixture def create_csv_file(tmpdir): data = { 'feature1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'feature2': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], 'target': [3, 6, 9, 12, 15, ...
[ { "docstring": null, "function_declaration": "def load_data(file_path):", "function_name": "load_data", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def preprocess_and_train(data_path):", "function_name": "preprocess_and_train", "parameter_list...
[ 1, 0, 1, 0, 0, 1, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.linear_model import LinearRegression, Ridge\nfrom sklearn.metrics ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00030927", "row_id": 30927, "seed_ids": "[53]" }
0.725019
Docs: Scikit_30927
I
[ "load_data", "preprocess_and_train" ]
2
[ [ "preprocess_and_train", "load_data" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
4101f87e1a867afec78decd06d2d0dbf4f177b38
bb5e46556ceccfa016facfac523df9924e075cee
v1.0
instruct
Docs
Docs: Python310_30953_I
### Asynchronous Web Scraper Challenge You have been tasked with writing an asynchronous web scraper using the `asyncio` library. This scraper will retrieve data from multiple websites concurrently to demonstrate your understanding of asynchronous programming with Python. #### Objective Write a function `async scrape...
import asyncio import aiohttp from typing import List, Dict, Any async def fetch(session, url, timeout): try: async with session.get(url, timeout=timeout) as response: content = await response.text() return { 'url': url, 'status': 'success', ...
import asyncio from solution import scrape_websites async def test_scrape_websites_success(): urls = ["https://www.example.com", "https://www.python.org"] timeout = 5.0 result = await scrape_websites(urls, timeout) assert len(result) == 2 for res in result: assert res['status'] == 'success'...
[]
[ 1, 1, 0, 1, 0, 0, 1, 1, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nfrom typing import List, Dict, Any\n\nasync def fetch(session, url, timeout):\n try:\n async with session.get(url, timeout=tim...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00030953", "row_id": 30953, "seed_ids": "[270]" }
0.653484
Docs: Python310_30953
I
[ "fetch", "scrape_websites" ]
2
[ [ "scrape_websites", "fetch" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
491704d32c44caaa2f12fe227d3214fd9131fcab
161d4c66d47d000aef6d01761cbe484bb9ed19c2
v1.0
instruct
Docs
Docs: Python310_31011_I
**Python Coding Challenge: Enhanced Command Line Interface** The goal of this exercise is to test your ability to create a comprehensive command-line interface using the `argparse` module. ### Problem Statement: You are required to create a Python script that processes a series of command-line options and sub-comman...
import argparse import json import os # Define default database file path DEFAULT_DB_FILE = 'items.json' def load_items(db_file=DEFAULT_DB_FILE): # Function to load items from the database file if not os.path.exists(db_file): return [] with open(db_file, 'r') as f: return json.load(f) def...
import pytest import json import os from solution import load_items, save_items, add_item, query_items, delete_item, DEFAULT_DB_FILE TEST_DB_FILE = 'test_items.json' @pytest.fixture(autouse=True) def run_around_tests(): # Code to run before each test if os.path.exists(TEST_DB_FILE): os.remove(TEST_DB_...
[ { "docstring": null, "function_declaration": "def load_items(db_file=DEFAULT_DB_FILE):", "function_name": "load_items", "parameter_list": "(db_file=DEFAULT_DB_FILE)" }, { "docstring": null, "function_declaration": "def save_items(items, db_file=DEFAULT_DB_FILE):", "function_name": "s...
[ 1, 0, 0, 1, 0, 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 argparse\nimport json\nimport os\n\n# Define default database file path\nDEFAULT_DB_FILE = 'items.json'\n\ndef load_items(db_file=DEFAULT_DB_FILE):\n # Functi...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00031011", "row_id": 31011, "seed_ids": "[139]" }
0.44579
Docs: Python310_31011
I
[ "load_items", "save_items", "add_item", "query_items", "delete_item", "main" ]
6
[ [ "add_item", "load_items" ], [ "add_item", "save_items" ], [ "delete_item", "load_items" ], [ "delete_item", "save_items" ], [ "query_items", "load_items" ] ]
5
[]
false
[]
false
pytest
true
[]
true
871f01788aec6ae9987dbed0cd74f6ba0fd65dba
54d30104b7152d9784ddc2c1e41e8fdc482151ef
v1.0
instruct
Docs
Docs: Python310_31067_I
### Python Coding Assessment Question #### Objective: This question assesses your ability to use the `concurrent.futures` module to manage parallel task execution efficiently. #### Problem Statement: You are given a list of URLs and need to fetch the content from each URL concurrently. Implement a function `fetch_all...
import requests from concurrent.futures import ThreadPoolExecutor, as_completed def fetch_content(url): try: response = requests.get(url) response.raise_for_status() return response.text except requests.RequestException as e: return str(e) def fetch_all_urls(urls, max_workers):...
import pytest import requests from unittest.mock import patch, MagicMock from solution import fetch_all_urls def test_fetch_all_urls_success(): urls = ["http://example.com"] mock_response = MagicMock() mock_response.raise_for_status = MagicMock() mock_response.text = "Example content" wi...
[ { "docstring": null, "function_declaration": "def fetch_content(url):", "function_name": "fetch_content", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def fetch_all_urls(urls, max_workers):", "function_name": "fetch_all_urls", "parameter_list": "(url...
[ 1, 1, 0, 0, 1, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef fetch_content(url):\n try:\n response = requests.get(url)\n res...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00031067", "row_id": 31067, "seed_ids": "[224]" }
0.546575
Docs: Python310_31067
I
[ "fetch_content", "fetch_all_urls" ]
2
[ [ "fetch_all_urls", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
c6c2eb6a9d5699148b25075864db6db4eb93af5d
9714e53b94c7105c18d3fa031b9e03023515e18d
v1.0
instruct
Docs
Docs: Python310_31179_I
**Question: Implement a Concurrent HTTP/1.0 Server Using asyncio Streams** In this assessment, you will write a simplified HTTP/1.0 server using the asyncio streams library documented above. The server should handle multiple clients concurrently, serving static files from a directory. ### Specifications: 1. **Server ...
import asyncio from pathlib import Path BASE_DIR = Path('./www') # Mime type mapping for basic file types MIME_TYPES = { 'html': 'text/html', 'txt': 'text/plain', 'css': 'text/css', 'js': 'application/javascript', 'json': 'application/json', 'png': 'image/png', 'jpg': 'image/jpeg', 'jp...
import asyncio import pytest import tempfile import os from pathlib import Path from solution import main, BASE_DIR # Helper function to run the server as a task @pytest.fixture async def http_server(): # Create temporary directory structure for serving files with tempfile.TemporaryDirectory() as tempdir: ...
[ { "docstring": null, "function_declaration": "def get_mime_type(file_path):", "function_name": "get_mime_type", "parameter_list": "(file_path)" } ]
[ 0, 1, 0, 1, 1, 0, 1, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom pathlib import Path\n\nBASE_DIR = Path('./www')\n\nasync def handle_client(reader, writer):\n try:\n # Read and parse the request\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00031179", "row_id": 31179, "seed_ids": "[182]" }
0.519267
Docs: Python310_31179
I
[ "get_mime_type", "handle_client", "main" ]
3
[ [ "handle_client", "get_mime_type" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c73ac6b56f259aaf40c53c231bac775d8912800f
eab188e6641ba55f55a503be86e32645485473fd
v1.0
instruct
Docs
Docs: Seaborn_31194_I
You are asked to demonstrate your understanding of seaborn's `cubehelix_palette` function by creating custom color palettes and using them in a seaborn plot. ### Task 1. **Create three custom color palettes** using the `sns.cubehelix_palette` function: - **Palette 1:** Should have 10 colors, starting at 1.5, rotat...
import seaborn as sns import matplotlib.pyplot as plt import numpy as np def create_custom_palettes(): """ Creates three custom color palettes using seaborn's cubehelix_palette. Returns a tuple of three palettes. """ # Palette 1: 10 colors, starting at 1.5, rotating by -0.8, with gamma 1.2 pale...
def test_custom_palettes_creation(): from solution import create_custom_palettes # Ensure palettes are created as expected palette1, palette2, palette3 = create_custom_palettes() assert len(palette1) == 10, "Palette 1 should have 10 colors." assert callable(palette2), "Palette 2 should be ...
[ { "docstring": "Creates three custom color palettes using seaborn's cubehelix_palette.\nReturns a tuple of three palettes.", "function_declaration": "def create_custom_palettes():", "function_name": "create_custom_palettes", "parameter_list": "()" }, { "docstring": "Plots a seaborn barplot i...
[ 0, 1, 0, 1, 1, 0, 0, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef create_palettes():\n \"\"\"\n Creates three custom color palettes using seaborn'...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00031194", "row_id": 31194, "seed_ids": "[88]" }
0.643711
Docs: Seaborn_31194
I
[ "create_custom_palettes", "plot_with_custom_palettes" ]
2
[ [ "plot_with_custom_palettes", "create_custom_palettes" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "seaborn" ]
false
a0909ae9ad21456c8661867fcc7f07e3abd6b177
b430734f250d21530baf77b27371dffe713df1b3
v1.0
instruct
Docs
Docs: Python310_31200_I
You are tasked with creating a Python application that simulates a concurrent task processing system using asyncio. The system must read tasks from a queue, process them asynchronously, and handle proper logging and error detection. ### Requirements 1. **Task Queue**: Implement a task queue using `asyncio.Queue`. 2....
import asyncio import logging import concurrent.futures logging.basicConfig(level=logging.DEBUG) async def io_task(task_data): await asyncio.sleep(1) # Simulate I/O work return f"Processed IO task with data: {task_data}" async def cpu_task(task_data): loop = asyncio.get_running_loop() with concurren...
import pytest import asyncio import logging from solution import io_task, cpu_task, process_task, main logging.basicConfig(level=logging.DEBUG) @pytest.mark.asyncio async def test_io_task(): data = "http://example.com" result = await io_task(data) assert result == f"Processed IO task with data: {data}" @...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\nasync def io_task(task_data):\n await asyncio.sleep(1) # Simulate I/O work\n return...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00031200", "row_id": 31200, "seed_ids": "[200]" }
0.528303
Docs: Python310_31200
I
[ "io_task", "cpu_task", "process_task", "main", "worker" ]
5
[ [ "process_task", "cpu_task" ], [ "process_task", "io_task" ], [ "worker", "process_task" ] ]
3
[]
false
[]
false
pytest
true
[]
true
f945e34d8e112337fc957e60a3ba76669b701479
de7a90726e0257b006ff40066f2871a953bbee4a
v1.0
instruct
Docs
Docs: Python310_31208_I
**Title:** Implement a Pseudo-Random Number Sequence Simulation and Analysis Tool **Objective:** To assess the student's ability to utilize the Python `random` module to generate and analyze pseudo-random number sequences and to simulate probability distributions. **Problem Statement:** You are tasked with creating ...
import random import math from collections import Counter def generate_random_sequence(length, distribution, params): """ Generates a sequence of random numbers based on the specified distribution and parameters. Parameters: - length (int): The number of random numbers to generate. - distribution ...
from solution import generate_random_sequence, analyze_sequence, simulate_and_analyze def test_generate_random_sequence_uniform(): length = 1000 params = {'a': 0, 'b': 1} sequence = generate_random_sequence(length, 'uniform', params) assert len(sequence) == length assert all(0 <= x <= 1 for x in se...
[ { "docstring": "Generates a sequence of random numbers based on the specified distribution and parameters.\n\nParameters:\n- length (int): The number of random numbers to generate.\n- distribution (str): The type of distribution to use. One of 'uniform', 'normal', 'exponential', or 'binary'.\n- params (dict): P...
[ 0, 1, 1, 1, 1, 1, 0, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport math\nfrom collections import Counter\n\ndef generate_random_sequence(length, distribution, params):\n \"\"\"\n Generates a sequence of rand...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00031208", "row_id": 31208, "seed_ids": "[119]" }
0.602936
Docs: Python310_31208
I
[ "generate_random_sequence", "analyze_sequence", "simulate_and_analyze" ]
3
[ [ "simulate_and_analyze", "analyze_sequence" ], [ "simulate_and_analyze", "generate_random_sequence" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5efe007cac14df4aec3a31d1ceac0a286abc0108
943071de7761eff85f61ab29a85131a9299b4123
v1.0
instruct
Docs
Docs: Python310_31221_I
You are tasked with building a secure file integrity verification system using the `hashlib` module in Python. Your system should be able to create hash digests for files using different algorithms, save these digests for later comparison, and verify the integrity of files by checking if they have been tampered with. ...
import hashlib def create_hash(filepath: str, algorithm: str = 'sha256') -> str: """ Creates a hash digest for a given file using the specified algorithm. Parameters: filepath (str): The path to the file to be hashed. algorithm (str): The hash algorithm to use (default is 'sha256'). Returns: ...
import os from solution import create_hash, save_hash, load_hash, verify_file def test_create_hash(tmp_path): test_file = tmp_path / "test.txt" test_file.write_text("hello world") hash_digest = create_hash(test_file, 'sha256') assert hash_digest == hashlib.sha256(b"hello world").hexdigest() def t...
[ { "docstring": "Creates a hash digest for a given file using the specified algorithm.\n\nParameters:\nfilepath (str): The path to the file to be hashed.\nalgorithm (str): The hash algorithm to use (default is 'sha256').\n\nReturns:\nstr: The hex digest of the file content.", "function_declaration": "def cre...
[ 0, 1, 1, 1, 0, 1, 1, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\n\ndef create_hash(filepath: str, algorithm: str = 'sha256') -> str:\n \"\"\"\n Creates a hash digest for a given file using the specified algorith...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00031221", "row_id": 31221, "seed_ids": "[225]" }
0.66925
Docs: Python310_31221
I
[ "create_hash", "save_hash", "load_hash", "verify_file" ]
4
[ [ "verify_file", "create_hash" ], [ "verify_file", "load_hash" ] ]
2
[]
false
[]
false
pytest
true
[]
true
6519bd4834df63dadff7233f900e9a519c0aae27
bb36a6c3cee50cda01f50a5ba52152a47f4361cc
v1.0
instruct
Docs
Docs: Python310_31259_I
### Secure Log Verifier You are tasked with creating a secure log verifier for a system that logs user activities. The verifier ensures that logged data has not been tampered with. You will use the hashlib library in Python to accomplish this. ### Requirements: 1. **Function Implementation:** Implement a functio...
import hashlib def secure_log_verifier(log_entries, secret_key, salt): """ Generates a BLAKE2b hexadecimal digest for the given log entries using the provided secret key and salt. """ hasher = hashlib.blake2b(key=secret_key, salt=salt) for entry in log_entries: hasher.update(entry.encode())...
from solution import secure_log_verifier, validate_log def test_secure_log_verifier_single_entry(): log_entries = ["Login: User A"] secret_key = b'supersecretkey' salt = b'unique_salt' expected_digest = hashlib.blake2b(b'Login: User A', key=secret_key, salt=salt).hexdigest() assert secure_log_verif...
[ { "docstring": "Generates a BLAKE2b hexadecimal digest for the given log entries using the provided secret key and salt.", "function_declaration": "def secure_log_verifier(log_entries, secret_key, salt):", "function_name": "secure_log_verifier", "parameter_list": "(log_entries, secret_key, salt)" ...
[ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\n\ndef secure_log_verifier(log_entries, secret_key, salt):\n \"\"\"\n Computes a secure hash digest for the log entries using blake2b with a secret...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00031259", "row_id": 31259, "seed_ids": "[225]" }
0.54024
Docs: Python310_31259
I
[ "secure_log_verifier", "validate_log" ]
2
[ [ "validate_log", "secure_log_verifier" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2ded302e17b6a59bc029b14b77cb51b5b0ee5ea3
1044c693084e85a4ce9adc430dd9411e4a51a935
v1.0
instruct
Docs
Docs: Python310_31350_I
**Problem Statement: Implementing a Secure File Integrity Checker** You are required to implement a secure file integrity checker using the `hashlib` module. The solution should handle the following requirements: 1. **Compute Hashes:** - Compute the SHA256 hash of the file content. - Compute a BLAKE2b hash us...
import hashlib import os def compute_hashes(file_path: str, blake2b_digest_size: int, salt: bytes) -> tuple: """ Computes SHA256, BLAKE2b, and salted BLAKE2b hashes of the file content. :param file_path: Path to the input file. :param blake2b_digest_size: Digest size for the BLAKE2b hash. :par...
import pytest from solution import compute_hashes, secure_password_hash, verify_file_integrity def create_test_file(content: str) -> str: file_path = 'testfile.txt' with open(file_path, 'w') as f: f.write(content) return file_path def test_compute_hashes(): content = "This is a test file." ...
[ { "docstring": "Computes SHA256, BLAKE2b, and salted BLAKE2b hashes of the file content.\n\n:param file_path: Path to the input file.\n:param blake2b_digest_size: Digest size for the BLAKE2b hash.\n:param salt: The salt to use for the BLAKE2b hash.\n:return: A tuple of hashes in hexadecimal format (SHA256, BLAK...
[ 1, 1, 0, 0, 1, 0, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\nfrom typing import Tuple\n\ndef compute_hashes(file_path: str, blake2b_digest_size: int, salt: bytes) -> Tuple[str, str, str]:\n \"\"\"\n Computes...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00031350", "row_id": 31350, "seed_ids": "[225]" }
0.595926
Docs: Python310_31350
I
[ "compute_hashes", "secure_password_hash", "verify_file_integrity" ]
3
[ [ "verify_file_integrity", "compute_hashes" ] ]
1
[]
false
[]
false
pytest
true
[]
true
470984fa7bddb856cfa3a66ad56c833d42246489
6dc71da00057c49d0efaf86b4c35daf61aa36ce7
v1.0
instruct
Docs
Docs: Seaborn_31357_I
### Question Using the seaborn library, write a function named `customized_plot` that generates a series of sine wave plots with different aesthetic customizations. Your function should: 1. Accept the following parameters: - `n` (int): The number of sine waves to plot. Default is 10. - `theme` (str): The seabor...
import seaborn as sns import numpy as np import matplotlib.pyplot as plt def sinplot(n=10, flip=1): x = np.linspace(0, 14, 100) for i in range(1, n + 1): plt.plot(x, np.sin(x + i * 0.5) * (n + 2 - i) * flip) def customized_plot(n=10, theme='darkgrid', style='darkgrid', context='notebook', remove_spine...
import pytest import matplotlib.pyplot as plt from solution import customized_plot def test_customized_plot_default_params(): customized_plot() # Here we test the plot creation; in real test environments, we would capture the plot object plt.close() def test_customized_plot_custom_params(): customized...
[ { "docstring": null, "function_declaration": "def sinplot(n=10, flip=1):", "function_name": "sinplot", "parameter_list": "(n=10, flip=1)" }, { "docstring": null, "function_declaration": "def customized_plot(n=10, theme='darkgrid', style='darkgrid', context='notebook', remove_spines=False...
[ 0, 0, 1, 0, 0, 1, 1, 1, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nimport matplotlib.pyplot as plt\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):...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00031357", "row_id": 31357, "seed_ids": "[2]" }
0.67868
Docs: Seaborn_31357
I
[ "sinplot", "customized_plot" ]
2
[ [ "customized_plot", "sinplot" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "seaborn" ]
false
dc238517dd57486649b3d9507c331c2b9f987488
0d60383a432572444c4365837d3f85e830593163
v1.0
instruct
Docs
Docs: Python310_31390_I
#### **Objective** You are required to implement a function using the `asyncio` subprocess APIs provided. This function should execute multiple commands concurrently, handle their outputs, errors, and manage potential timeouts. #### **Function Signature** ```python import asyncio from typing import List, Tuple async...
import asyncio from typing import List, Tuple async def run_command(command: str, timeout: int) -> Tuple[str, int, str, str]: try: proc = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) try...
import asyncio from solution import run_commands async def test_run_commands_success(): commands = ["echo Hello", "echo World"] results = await run_commands(commands, timeout=5) assert len(results) == 2 assert results[0][1] == 0 assert results[0][2].strip() == "Hello" assert results[1][1] == 0 ...
[]
[ 1, 1, 1, 1, 0, 0, 1, 0, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def run_commands(commands: List[str], timeout: int) -> List[Tuple[str, int, str, str]]:\n async def run_comma...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00031390", "row_id": 31390, "seed_ids": "[264]" }
0.702774
Docs: Python310_31390
I
[ "run_command", "run_commands" ]
2
[ [ "run_commands", "run_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d3009a012d83d38ea0de07db14a36952abb49f83
2288b30b8849effe42f11e42ed7a056a471bf6f8
v1.0
instruct
Docs
Docs: Python310_31434_I
**Async Subprocess Management** ### Problem Statement You are required to implement a function that takes a list of shell commands, executes them concurrently using asynchronous I/O operations, and collects their output. Each command may optionally have an input string that should be sent to its standard input. Your ...
import asyncio from typing import List, Dict, Tuple async def run_command(command: str, input_data: str) -> Tuple[str, str]: """ Executes a single shell command asynchronously and returns the output and error. """ proc = await asyncio.create_subprocess_shell( command, stdin=asyncio.subp...
import asyncio from solution import execute_commands def test_commands_successful_execution(): commands = [ ('echo "Hello, World!"', ''), ('ls /tmp', ''), # Assuming /tmp exists on the system ] result = asyncio.run(execute_commands(commands)) assert result['echo "Hello, World!"'] == ('...
[]
[ 0, 1, 1, 1, 1, 1, 0, 1, 1 ]
7
easy
0.778
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Dict, Tuple\n\nasync def run_command(command: str, input: str) -> Tuple[str, str]:\n process = await asyncio.create_subproce...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00031434", "row_id": 31434, "seed_ids": "[264]" }
0.768349
Docs: Python310_31434
I
[ "run_command", "execute_commands" ]
2
[ [ "execute_commands", "run_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
461781a183fe420182215f9637a72cbde5f9cbb5
9a31d4e090067b5eed8e9ff33b92515a8ff43c44
v1.0
instruct
Docs
Docs: Pytorch_31488_I
**Pipeline Parallelism with PyTorch**: You are tasked with implementing a model training using Pipeline Parallelism in PyTorch to understand its functionality and efficiency. You will demonstrate both creating pipeline stages manually and using them in a pipeline schedule. ### Part 1: Implementing and Using a Manual ...
import torch import torch.nn as nn class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.fc1 = nn.Linear(10, 20) self.fc2 = nn.Linear(20, 30) self.fc3 = nn.Linear(30, 10) def forward(self, x): x = torch.relu(self.fc1(x)) ...
def test_create_pipeline_stages(): stage_obj1, stage_obj2 = create_pipeline_stages() assert isinstance(stage_obj1.model, nn.Sequential) assert isinstance(stage_obj2.model, nn.Sequential) assert stage_obj1.stage_index == 0 assert stage_obj2.stage_index == 1 def test_execute_pipeline_output_shape(): ...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nfrom torch.distributed.pipelining import PipelineStage, ScheduleGPipe\n\nclass SimpleModel(nn.Module):\n def __init__(self):\n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00031488", "row_id": 31488, "seed_ids": "[82]" }
0.499753
Docs: Pytorch_31488
I
[ "create_pipeline_stages", "execute_pipeline" ]
2
[ [ "execute_pipeline", "create_pipeline_stages" ] ]
1
[]
false
[ "SimpleModel" ]
true
pytest
false
[ "torch" ]
false
06a27fcc213ebc2d088c22537592bfb60cbf5f1e
8a08e5ee94ae506aeff12c91f957394094b50b97
v1.0
instruct
Docs
Docs: Python310_31497_I
### Asynchronous Subprocess Management In this task, you are required to write an asynchronous Python function that demonstrates your understanding of creating and managing subprocesses using the `asyncio` library in Python 3.10. #### Objective: Write a function called `run_multiple_commands(commands: List[str], tim...
import asyncio from typing import List, Tuple async def run_command(command: str, timeout: int) -> Tuple[str, int, str]: try: proc = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) try: ...
import pytest import asyncio from solution import run_multiple_commands, run_command @pytest.mark.asyncio async def test_run_command_success(): result = await run_command('echo hello', 2) assert result == ('echo hello', 0, 'hello') @pytest.mark.asyncio async def test_run_command_timeout(): result = await ...
[]
[ 0, 1 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def run_command(command: str, timeout: int) -> Tuple[str, int, str]:\n process = awa...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00031497", "row_id": 31497, "seed_ids": "[264]" }
0.706867
Docs: Python310_31497
I
[ "run_command", "run_multiple_commands" ]
2
[ [ "run_multiple_commands", "run_command" ] ]
1
[]
false
[]
false
pytest
true
[]
true
51bdfc62a6942d598b7782283773dcef3326cbca
aaf7ed6de40f34a735014acb5e6f4813fd59b8da
v1.0
instruct
Docs
Docs: Python310_31518_I
**Managing Context-Sensitive State with Context Variables** ### Objective Your task is to implement a state management system that demonstrates the use of the `contextvars` module to manage context-sensitive variables in an asynchronous environment. ### Problem Statement Create an asynchronous simulation where multip...
import asyncio import contextvars # Initialize context variable task_counter = contextvars.ContextVar('task_counter', default=0) async def task_incrementer(task_id: int, increments: int): for _ in range(increments): counter = task_counter.get() task_counter.set(counter + 1) print(f"Task {task_...
import pytest import asyncio from solution import task_incrementer, run_simulation @pytest.mark.asyncio async def test_task_incrementer(): initial_value = task_counter.get() await task_incrementer(1, 5) assert task_counter.get() == initial_value + 5 @pytest.mark.parametrize("task_configs,expected_results"...
[ { "docstring": null, "function_declaration": "def run_simulation(task_configs):", "function_name": "run_simulation", "parameter_list": "(task_configs)" } ]
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\n\n# Initialize context variable\ntask_counter = contextvars.ContextVar('task_counter', default=0)\n\nasync def task_incrementer(task...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00031518", "row_id": 31518, "seed_ids": "[392]" }
0.457197
Docs: Python310_31518
I
[ "task_incrementer", "run_simulation" ]
2
[ [ "run_simulation", "task_incrementer" ] ]
1
[]
false
[]
false
pytest
true
[]
true
bd8a5034f633287f88393dfc8eb6b36603164800
a5068e2dfc100f146a4f0036e3d47b108b390ddb
v1.0
instruct
Docs
Docs: Python310_31527_I
### Asynchronous Network Server **Problem**: You are required to implement an asynchronous echo server using the `asyncio` event loop functionalities. The server should be able to handle multiple client connections concurrently and echo back any message received from a client. The server should log incoming connecti...
import asyncio import logging logging.basicConfig(level=logging.INFO) async def handle_client(reader, writer): addr = writer.get_extra_info('peername') logging.info(f"Connection from {addr}") try: while True: data = await reader.read(100) if not data: loggi...
import asyncio from solution import start_server async def test_server(): server = asyncio.create_task(start_server('127.0.0.1', 8888)) await asyncio.sleep(1) # Allow server to start reader, writer = await asyncio.open_connection('127.0.0.1', 8888) message = "Hello, World!" writer.write(message.e...
[]
[ 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
8
easy
0.889
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):\n addr = writer.get_extra_info('peername')\n print(f\"Conne...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00031527", "row_id": 31527, "seed_ids": "[267]" }
0.69073
Docs: Python310_31527
I
[ "handle_client", "start_server" ]
2
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9fa092abf9139cd42e318ed099f62d2dfab2210d
6de3d575319cb182f0aaf0d5e57ca32feaea40a1
v1.0
instruct
Docs
Docs: Python310_31535_I
### Asyncio Platform-Specific Implementation Challenge #### Objective: You are tasked with creating a function that utilizes the `asyncio` module to set up a simple server and client communication system. However, due to platform-specific limitations described in the documentation, you should ensure that your code can...
import asyncio import sys async def handle_client(reader, writer): data = await reader.read(100) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received from {addr}: {message}") writer.close() await writer.wait_closed() async def run_server(): server = await asy...
import asyncio import pytest import sys from solution import run_server, run_client, choose_event_loop @pytest.mark.asyncio async def test_server_client_communication(capfd): server_task = asyncio.create_task(run_server()) await asyncio.sleep(1) # Give the server a moment to start up client_messages = [...
[ { "docstring": null, "function_declaration": "def choose_event_loop():", "function_name": "choose_event_loop", "parameter_list": "()" } ]
[ 0, 1, 1, 1, 1, 0, 1, 0, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\n\nasync def handle_client(reader, writer):\n while True:\n data = await reader.read(100)\n message = data.decode()\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00031535", "row_id": 31535, "seed_ids": "[370]" }
0.568153
Docs: Python310_31535
I
[ "handle_client", "run_server", "run_client", "choose_event_loop" ]
4
[ [ "run_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
74c6081d66f1f101b69c26565e535b4fb7154fdb
2358d4d5108a99853289dc87eae6b80108ef2049
v1.0
instruct
Docs
Docs: Scikit_31537_I
Out-of-Core Learning for Text Classification #### Objective You need to design an out-of-core learning algorithm to classify a large dataset of text documents that cannot fit into the main memory at once. Your task involves streaming the data, extracting features, and applying an incremental learning algorithm that up...
from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score import os import numpy as np def data_stream(directory): """ Generator function to stream text data and their labels from a directory """ for filename in os.li...
import os import pytest from solution import data_stream, out_of_core_text_classification def test_data_stream(): # Setup: Create a temporary directory and populate it with sample data files os.makedirs('test_dir', exist_ok=True) with open('test_dir/sports_1.txt', 'w') as f: f.write('This is a spor...
[ { "docstring": "Generator function to stream text data and their labels from a directory ", "function_declaration": "def data_stream(directory):", "function_name": "data_stream", "parameter_list": "(directory)" }, { "docstring": null, "function_declaration": "def out_of_core_text_classif...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\nim...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00031537", "row_id": 31537, "seed_ids": "[63]" }
0.498501
Docs: Scikit_31537
I
[ "data_stream", "out_of_core_text_classification" ]
2
[ [ "out_of_core_text_classification", "data_stream" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
e56d59583ca4f41b34f468028f549761bf9f4508
e8aa2e8c662458c74d258d2db82c29432c4e1794
v1.0
instruct
Docs
Docs: Pytorch_31554_I
### Asynchronous Programming in PyTorch using torch.futures In this coding assessment, you will demonstrate your understanding of asynchronous programming with PyTorch's `torch.futures` package. You will need to implement a function that performs a series of asynchronous operations and subsequently gather their result...
import time import random import torch from concurrent.futures import ThreadPoolExecutor def async_operation(index): """Simulate an asynchronous operation that takes a random time to complete.""" time.sleep(random.random()) return index def perform_async_operations(): """ Perform 10 asynchronous o...
def test_perform_async_operations(): result = perform_async_operations() assert result == 45 # Sum of numbers from 0 to 9 is 45 def test_multiple_calls(): results = [perform_async_operations() for _ in range(5)] for result in results: assert result == 45 # Each call should produce the sum of ...
[ { "docstring": "Simulate an asynchronous operation that takes a random time to complete.", "function_declaration": "def async_operation(index):", "function_name": "async_operation", "parameter_list": "(index)" }, { "docstring": "Perform 10 asynchronous operations using torch.futures.Future a...
[ 1, 0, 1, 0, 0, 0, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport time\nimport random\n\ndef async_operation(index):\n \"\"\"Simulate an asynchronous operation that takes a random time to complete.\"\"\"\n t...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00031554", "row_id": 31554, "seed_ids": "[53]" }
0.505889
Docs: Pytorch_31554
I
[ "async_operation", "perform_async_operations" ]
2
[ [ "perform_async_operations", "async_operation" ] ]
1
[]
false
[]
false
pytest
false
[ "torch" ]
false
0cccb9023bd6e17e0414ebbb2096e94165fe01ac
f66ef51f27ab7e9d1a84b13a815b912456c0b8ce
v1.0
instruct
Docs
Docs: Python310_31556_I
**Background:** You are tasked with designing a simple file downloader using the `asyncio` library in Python. This should involve fetching multiple files concurrently from a list of URLs and storing them on the disk. You need to ensure that your program handles the concurrency properly and downloads all files efficien...
import asyncio import aiohttp import os from aiohttp import ClientSession from typing import List async def download_file(session: ClientSession, url: str, save_dir: str) -> str: try: async with session.get(url) as response: # Extract file name from URL filename = os.path.basename(u...
import os import tempfile import asyncio import aiohttp from solution import download_files # Sample URLs for testing URLS = [ "https://example.com/file1.txt", # Replace with real URLs for actual tests "https://example.com/file2.txt" ] async def mock_download_file(session, url, save_dir): """A mock funct...
[]
[ 0, 0, 0, 1, 1, 0, 1, 0, 0 ]
3
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nimport os\nfrom typing import List\n\nasync def download_file(session, url, save_path):\n try:\n async with session.get(url) a...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00031556", "row_id": 31556, "seed_ids": "[270]" }
0.588633
Docs: Python310_31556
I
[ "download_file", "download_files" ]
2
[ [ "download_files", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
89423488279e997f5ba6741ca5c1f890a5394bab
8a2b1d48b13a9c7ed4217f0a92f444d1501cecb8
v1.0
instruct
Docs
Docs: Python310_31580_I
**Question: Implement a Custom Interactive Python Prompt** Using the "readline" module in Python, write a custom interactive prompt that includes the following features: 1. **Initialization from a Custom Configuration**: The prompt should read an initialization file (named `.myreadlineconfig` in the user's home direc...
import os import readline def initialize_readline_config(): """Reads and applies configuration from ~/.myreadlineconfig if it exists.""" config_file = os.path.expanduser("~/.myreadlineconfig") if os.path.exists(config_file): with open(config_file, 'r') as f: for line in f: ...
import os import readline from solution import initialize_readline_config, load_command_history, save_command_history, setup_autocompletion, start_custom_prompt def test_initialize_readline_config(monkeypatch, tmp_path): config_path = tmp_path / ".myreadlineconfig" config_path.write_text("tab: complete\nset ed...
[ { "docstring": "Reads and applies configuration from ~/.myreadlineconfig if it exists.", "function_declaration": "def initialize_readline_config():", "function_name": "initialize_readline_config", "parameter_list": "()" }, { "docstring": "Loads the command history from the specified file and...
[ 0, 0, 0, 1, 0, 0, 0, 0, 1 ]
2
hard
0.222
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import readline\nimport os\n\ndef initialize_readline_config():\n \"\"\"Reads and applies configuration from ~/.myreadlineconfig if it exists.\"\"\"\n config_file...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00031580", "row_id": 31580, "seed_ids": "[362]" }
0.41348
Docs: Python310_31580
I
[ "initialize_readline_config", "load_command_history", "save_command_history", "setup_autocompletion", "start_custom_prompt" ]
5
[ [ "start_custom_prompt", "initialize_readline_config" ], [ "start_custom_prompt", "load_command_history" ], [ "start_custom_prompt", "save_command_history" ], [ "start_custom_prompt", "setup_autocompletion" ] ]
4
[]
false
[]
false
pytest
true
[]
true
acae1bb2ab4470166e76254d0f0055ab94f1a4f1
583522ae0f734d89659c8f69aa55604a2fb0a08f
v1.0
instruct
Docs
Docs: Python310_31653_I
### Hashing Challenge with Python's hashlib #### Problem Statement You are tasked with implementing a secure data integrity check system using Python's hashlib module. Your functions will handle hashing for different data inputs and include features like updating the hash iteratively, utilizing salt for randomized has...
import hashlib import os from typing import Optional, List def hash_data(data: bytes, algorithm: str) -> str: """ Returns the hexadecimal digest of the hashed data using the specified algorithm. """ if algorithm not in hashlib.algorithms_available: raise ValueError(f"Algorithm {algorithm} is no...
import pytest import hashlib from solution import hash_data, iterative_hash, secure_hash_with_salt, verify_secure_hash def test_hash_data_valid_algorithm(): data = b'example data' expected = hashlib.sha256(data).hexdigest() assert hash_data(data, 'sha256') == expected def test_hash_data_invalid_algorithm(...
[ { "docstring": "Returns the hexadecimal digest of the hashed data using the specified algorithm.", "function_declaration": "def hash_data(data, algorithm):", "function_name": "hash_data", "parameter_list": "(data, algorithm)" }, { "docstring": "Returns the hexadecimal digest of the concatena...
[ 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 hashlib\nimport os\nfrom typing import Optional\n\ndef hash_data(data: bytes, algorithm: str) -> str:\n \"\"\"\n Returns the hexadecimal digest of the hash...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00031653", "row_id": 31653, "seed_ids": "[225]" }
0.75277
Docs: Python310_31653
I
[ "hash_data", "iterative_hash", "secure_hash_with_salt", "verify_secure_hash" ]
4
[ [ "verify_secure_hash", "secure_hash_with_salt" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fcac27bbd351cf59944e45a6de103b16c0067fdf
ac4b3b95684769b318604525186479954d19ba96
v1.0
instruct
Docs
Docs: Python310_31788_I
**Question: Implement a Command-Line Tool Using getopt** --- ### Description You are required to implement a Python command-line tool that processes a series of arguments using the `getopt` module. The tool will support both short and long options for displaying help, verbosity, specifying the output file, and setti...
import sys import getopt def parse_arguments(args): shortopts = "hvo:" longopts = ["help", "output=", "condition="] try: opts, remaining_args = getopt.getopt(args, shortopts, longopts) except getopt.GetoptError as err: print(str(err)) display_help() sys.exit(2) opti...
import pytest from solution import parse_arguments, display_help def test_parse_help_option(capsys): with pytest.raises(SystemExit): # Since help option will exit the script parse_arguments(["-h"]) captured = capsys.readouterr() assert "Usage: script.py [options]" in captured.out with pyt...
[ { "docstring": null, "function_declaration": "def parse_arguments(args):", "function_name": "parse_arguments", "parameter_list": "(args)" }, { "docstring": null, "function_declaration": "def display_help():", "function_name": "display_help", "parameter_list": "()" } ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\nimport getopt\n\ndef parse_arguments(args):\n shortopts = \"hvo:\"\n longopts = [\"help\", \"output=\", \"condition=\"]\n try:\n opts, remai...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00031788", "row_id": 31788, "seed_ids": "[386]" }
0.460717
Docs: Python310_31788
I
[ "parse_arguments", "display_help" ]
2
[ [ "parse_arguments", "display_help" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d940963b6f5305a7186f1c19d1e8e67e96586df9
b6c710b9b65e0cd323ac62f7889d9d748e3ba8dc
v1.0
instruct
Docs
Docs: Python310_31843_I
### Python Coding Assessment Question **Objective**: Demonstrate your understanding of Python's `contextlib` module, particularly `contextmanager` decorator and `ExitStack`. #### Problem Statement You are required to implement a custom context manager using the `contextlib.contextmanager` decorator to manage the res...
from contextlib import contextmanager, ExitStack @contextmanager def database_connection_manager(): """ Simulate a database connection context manager. Acquires and releases a mock database connection. """ print("Connection Acquired") connection = "connection" try: yield connection ...
import pytest from solution import database_connection_manager, manage_multiple_connections def test_database_connection_manager(capsys): try: with database_connection_manager() as conn: print(f"Using {conn}") raise Exception("Test exception") except Exception as e: asse...
[ { "docstring": "Simulate a database connection context manager.\nAcquires and releases a mock database connection.", "function_declaration": "def database_connection_manager():", "function_name": "database_connection_manager", "parameter_list": "()" }, { "docstring": "Manages multiple databa...
[ 1, 0, 0, 1, 1, 1, 1, 1, 0 ]
6
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from contextlib import contextmanager, ExitStack\n\n@contextmanager\ndef database_connection_manager():\n try:\n # Simulate acquiring the database connection\...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00031843", "row_id": 31843, "seed_ids": "[177]" }
0.359961
Docs: Python310_31843
I
[ "database_connection_manager", "manage_multiple_connections" ]
2
[ [ "manage_multiple_connections", "database_connection_manager" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3fa5b1c81c8b72a283ec0c67ec595bb5dc59a216
cacb462f73f44217d39c78ad90c5bdb4358ddc60
v1.0
instruct
Docs
Docs: Pytorch_31864_I
You are required to implement a function utilizing the block mask operations provided by the `torch.nn.attention.flex_attention` module. Specifically, your task is to create a complex mask using nested block masks and perform logical operations on these masks. #### Function Signature ```python def complex_mask_operat...
import torch def create_nested_block_mask(size: int, value: bool = True) -> torch.Tensor: """ Creates a nested block mask of given size. For simplicity, let's assume it creates a block mask with a specified value (True/False). """ return torch.full((size, size), value, dtype=torch.bool) def and_m...
import torch from solution import create_nested_block_mask, and_masks, or_masks, complex_mask_operations def test_create_nested_block_mask(): size = 4 mask = create_nested_block_mask(size) assert mask.shape == (4, 4) assert torch.all(mask == True) def test_create_nested_block_mask_false(): size = ...
[ { "docstring": "Creates a nested block mask of given size. For simplicity, let's assume it creates a \nblock mask with a specified value (True/False).", "function_declaration": "def create_nested_block_mask(size, value=True):", "function_name": "create_nested_block_mask", "parameter_list": "(size, v...
[ 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.attention.flex_attention import create_nested_block_mask, and_masks, or_masks\n\ndef complex_mask_operations(size: int) -> torch.Tensor:\n ...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00031864", "row_id": 31864, "seed_ids": "[0]" }
0.452544
Docs: Pytorch_31864
I
[ "create_nested_block_mask", "and_masks", "or_masks", "complex_mask_operations" ]
4
[ [ "complex_mask_operations", "and_masks" ], [ "complex_mask_operations", "create_nested_block_mask" ], [ "complex_mask_operations", "or_masks" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
67752b2cb4276331b3a7ca10028e887dc55738ee
8c7b68d4c42e40eae506b8f69e639b7d2a8683af
v1.0
instruct
Docs
Docs: Python310_31972_I
### Asynchronous Web Scraping Simulation **Objective**: Utilize the asyncio library to simulate an asynchronous web scraping task. This task will test your ability to handle concurrent execution, manage asyncio tasks, and synchronize the output. **Problem Statement**: You are tasked with creating an asynchronous web ...
import asyncio import random async def fetch_content(url: str) -> str: await asyncio.sleep(random.randint(1, 3)) # Simulate network delay return f"<html>Content from {url}</html>" async def fetch_html(urls: list[str]) -> dict[str, str]: async def _fetch_and_store(url): content = await fetch_conte...
import pytest import asyncio from solution import fetch_html @pytest.mark.asyncio async def test_fetch_html_single_url(): urls = ["http://example.com"] content = await fetch_html(urls) assert len(content) == 1 assert "http://example.com" in content assert content["http://example.com"].startswith("<...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\n\nasync def fetch_content(url: str) -> str:\n await asyncio.sleep(random.randint(1, 3)) # Simulate network delay\n return f\"<html...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00031972", "row_id": 31972, "seed_ids": "[270]" }
0.588617
Docs: Python310_31972
I
[ "fetch_content", "fetch_html" ]
2
[ [ "fetch_html", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[]
true
68594a48264a218ad3ef046ee5c220cffdfa1b3e
54a53a047c946f964f023b8bec6948e3e993ce63
v1.0
instruct
Docs
Docs: Python310_32052_I
**Objective**: Write an asynchronous program that demonstrates your understanding of the `asyncio` event loop and its various methods for handling callbacks, tasks, and network connections. **Problem**: Create a Python script using the `asyncio` library to implement a simple chat server. The server should handle mult...
import asyncio clients = {} async def broadcast_message(message: str, writer: asyncio.StreamWriter) -> None: for client_writer in clients.values(): if client_writer != writer: client_writer.write(message.encode()) await client_writer.drain() async def handle_client(reader: asyncio...
import pytest import asyncio from solution import start_server, handle_client, broadcast_message @pytest.mark.asyncio async def test_server_start(): host = '127.0.0.1' port = 12345 server = await start_server(host, port) assert server.sockets, "Server failed to start" @pytest.mark.asyncio async de...
[]
[ 1, 1, 1, 1, 0, 0, 1, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nclients = {}\n\nasync def broadcast_message(message: str, writer: asyncio.StreamWriter) -> None:\n for client_writer in clients.values():\n ...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00032052", "row_id": 32052, "seed_ids": "[267]" }
0.616428
Docs: Python310_32052
I
[ "broadcast_message", "handle_client", "start_server", "main" ]
4
[ [ "handle_client", "broadcast_message" ], [ "start_server", "handle_client" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2c02ce44a0506215165a435e75f536760a25dedf
4eec993c62f84667dfdfa323205be6ebbb601b7a
v1.0
instruct
Docs
Docs: Python310_32077_I
## Question: Implement a Task Scheduling System using Python's Multiprocessing ### Objective: You will develop a task scheduling system that will distribute tasks to worker processes using Python's `multiprocessing` package. The system will read a list of tasks, execute them concurrently using worker processes, keep t...
from multiprocessing import Pool def execute_task(task): func, args = task return func(*args) def task_scheduler(tasks, num_workers): with Pool(processes=num_workers) as pool: task_indices = list(range(len(tasks))) results = pool.starmap(execute_task, [(tasks[i],) for i in task_indices]) ...
from solution import task_scheduler def add(a, b): return a + b def multiply(a, b): return a * b def test_task_scheduler(): tasks = [ (add, (1, 2)), (multiply, (2, 3)), (add, (5, 3)), (multiply, (8, 7)) ] num_workers = 2 results = task_scheduler(tasks, num...
[ { "docstring": null, "function_declaration": "def execute_task(task):", "function_name": "execute_task", "parameter_list": "(task)" }, { "docstring": null, "function_declaration": "def task_scheduler(tasks, num_workers):", "function_name": "task_scheduler", "parameter_list": "(ta...
[ 1, 1, 0, 1, 1, 0, 1, 0, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from multiprocessing import Pool\n\ndef task_worker(task):\n func, args = task\n return func(*args)\n\ndef task_scheduler(tasks, num_workers):\n with Pool(num_...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00032077", "row_id": 32077, "seed_ids": "[338]" }
0.716873
Docs: Python310_32077
I
[ "execute_task", "task_scheduler" ]
2
[ [ "task_scheduler", "execute_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5ca7fccd09c7f6b6d5bc550e4df76b47761335e5
6620c47a149f01d79f469cccd77d171da7779419
v1.0
instruct
Docs
Docs: Python310_32086_I
### Persistent Storage with Shelve **Objective:** You are tasked with creating a small application that manages a collection of user contacts using the `shelve` module. Each contact should have the attributes: `name`, `email`, and `phone`. The program should support adding new contacts, retrieving contacts by name, ...
import shelve import re def init_storage(filename): """ Initializes and returns a shelve storage. :param filename: The name of the file to store the shelve data. :return: A shelve storage. """ return shelve.open(filename) def is_valid_email(email): """ Validates the email format. ...
import pytest import os from solution import ( init_storage, add_contact, get_contact, update_contact, delete_contact, list_contacts ) import shelve # Test file name TEST_DB = 'test_contacts.db' # Helper function to clean up test database to avoid data persistence across tests def cleanup_db(): if os.path...
[ { "docstring": "Initializes and returns a shelve storage.\n\n:param filename: The name of the file to store the shelve data.\n:return: A shelve storage.", "function_declaration": "def init_storage(filename):", "function_name": "init_storage", "parameter_list": "(filename)" }, { "docstring": ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import shelve\nimport re\n\ndef init_storage(filename):\n \"\"\"\n Initializes and returns a shelf using the given filename.\n \"\"\"\n return shelve.open(f...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00032086", "row_id": 32086, "seed_ids": "[376]" }
0.325702
Docs: Python310_32086
I
[ "init_storage", "is_valid_email", "is_valid_phone", "add_contact", "get_contact", "update_contact", "delete_contact", "list_contacts" ]
8
[ [ "add_contact", "is_valid_email" ], [ "add_contact", "is_valid_phone" ], [ "update_contact", "is_valid_email" ], [ "update_contact", "is_valid_phone" ] ]
4
[]
false
[]
false
pytest
true
[]
true
a3062979d5cc59c6a331eb9607740ee68ab2e947
9dad5efe669964de72a8c8dc35b47a485c1dd71f
v1.0
instruct
Docs
Docs: Python310_32112_I
#### Objective This question assesses your understanding of Python's `asyncio` library, particularly in writing and managing asynchronous tasks and using synchronization primitives. #### Problem Statement You are tasked with implementing an asynchronous task manager for a simple distribution system. You will write a f...
import asyncio async def fetch_data(server_id: int) -> str: """ Simulates fetching data from a server. It takes `server_id` as input and returns a string indicating which server the data came from. The function uses asyncio.sleep to simulate network delay. :param server_id: The ID of the server t...
import asyncio from solution import fetch_data, manage_tasks def test_fetch_data(): async def wrapper(): result = await fetch_data(1) assert result == "Data from server 1" asyncio.run(wrapper()) def test_manage_tasks_single_server(): async def wrapper(): server_ids = [1] re...
[]
[ 1, 1, 1, 1, 0, 1, 0, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def fetch_data(server_id: int) -> str:\n \"\"\"\n Simulates fetching data from a server. It takes `server_id` as input\n and returns a ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00032112", "row_id": 32112, "seed_ids": "[270]" }
0.547567
Docs: Python310_32112
I
[ "fetch_data", "manage_tasks" ]
2
[ [ "manage_tasks", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e6ac9835ce9fb4f7bece1b9ecbeafddde47a6d0a
29b889f5904323f04dd83223da7918a278eeff81
v1.0
instruct
Docs
Docs: Python310_32146_I
**Python Coding Assessment Question: Unix Group Membership Analysis** You are given access to the Unix group database through Python's `grp` module. Your task is to implement a set of functions to analyze group memberships based on this data. Your functions should: 1. **Get All Member Names:** - Function: `get_all...
import grp def get_all_member_names(): """ Returns a set of unique user names that are members of any group. """ all_members = set() for group in grp.getgrall(): all_members.update(group.gr_mem) return all_members def find_groups_by_member(user_name): """ Returns a list of grou...
from solution import get_all_member_names, find_groups_by_member, find_common_groups import grp import pytest # Mock data for testing mock_grp_data = [ grp.struct_group(('group1', 'x', 1001, ['user1', 'user2'])), grp.struct_group(('group2', 'x', 1002, ['user2', 'user3'])), grp.struct_group(('group3', 'x', ...
[ { "docstring": "Returns a set of unique user names that are members of any group.", "function_declaration": "def get_all_member_names():", "function_name": "get_all_member_names", "parameter_list": "()" }, { "docstring": "Returns a list of group names that the specified user is a member of.\...
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import grp\n\ndef get_all_member_names():\n \"\"\"\n Returns a set of unique user names that are members of any group.\n \"\"\"\n all_members = set()\n f...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00032146", "row_id": 32146, "seed_ids": "[268]" }
0.436357
Docs: Python310_32146
I
[ "get_all_member_names", "find_groups_by_member", "find_common_groups" ]
3
[ [ "find_common_groups", "find_groups_by_member" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1adf7714ce317a37c6ebf5f9e2e592831fd2f0a2
0e319a7ef121fa5f5e290fef026ced759d90a5f8
v1.0
instruct
Docs
Docs: Python310_32159_I
You have been assigned a task to design a multi-process system to perform a computationally intensive operation. You are required to write a Python program using the `multiprocessing` package that performs the following: **Task**: Implement a function `parallel_compute_square_sum` which computes the sum of the squares...
from typing import List import multiprocessing def compute_squares(numbers: List[int]) -> int: """ Helper function to compute the sum of squares of a list of numbers. """ return sum(number * number for number in numbers) def parallel_compute_square_sum(numbers: List[int], num_workers: int) -> int: ...
from solution import parallel_compute_square_sum def test_empty_list(): assert parallel_compute_square_sum([], 4) == 0 def test_single_element_list(): assert parallel_compute_square_sum([2], 2) == 4 def test_small_list(): assert parallel_compute_square_sum([1, 2, 3, 4], 2) == 30 # 1^2 + 2^2 + 3^2 + 4^2 ...
[ { "docstring": "Helper function to compute the sum of squares of a list of numbers.", "function_declaration": "def compute_squares(numbers):", "function_name": "compute_squares", "parameter_list": "(numbers)" }, { "docstring": "Computes the sum of squares of a list of numbers using parallel ...
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport multiprocessing\n\ndef compute_square_sum(numbers: List[int]) -> int:\n return sum(x * x for x in numbers)\n\ndef parallel_compute_sq...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00032159", "row_id": 32159, "seed_ids": "[338]" }
0.661194
Docs: Python310_32159
I
[ "compute_squares", "parallel_compute_square_sum" ]
2
[ [ "parallel_compute_square_sum", "compute_squares" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ffa3f94cb567f877dde2fec6a35f11ced88241ef
627b063050b64f963803b22ab2626107fd81217e
v1.0
instruct
Docs
Docs: Python310_32200_I
### Problem: Statistical Distribution Calculations In this task, you are required to implement a few helper functions that utilize the `math` module functions to perform calculations related to statistical distributions. You will need to implement the following functions: 1. **normal_cdf(x)** 2. **inverse_normal_cdf(...
import math def normal_cdf(x): """ Calculates the Cumulative Distribution Function (CDF) for a standard normal distribution at point x. """ return (1 + math.erf(x / math.sqrt(2))) / 2 def inverse_normal_cdf(p, tolerance=1e-5): """ Calculates the inverse CDF (quantile function) for a standard n...
from solution import normal_cdf, inverse_normal_cdf, binomial_pmf, binomial_cdf def test_normal_cdf(): assert math.isclose(normal_cdf(0), 0.5) assert math.isclose(normal_cdf(1.96), 0.975, abs_tol=1e-3) assert math.isclose(normal_cdf(-1.96), 0.025, abs_tol=1e-3) assert math.isclose(normal_cdf(3), 0.9986...
[ { "docstring": "Calculates the Cumulative Distribution Function (CDF) for a standard normal distribution at point x.", "function_declaration": "def normal_cdf(x):", "function_name": "normal_cdf", "parameter_list": "(x)" }, { "docstring": "Calculates the inverse CDF (quantile function) for a ...
[ 0, 0, 1, 1, 0, 0, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\n\ndef normal_cdf(x):\n return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0\n\ndef inverse_normal_cdf(p, tolerance=1e-5):\n if p <= 0 or p >= 1:\n ...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00032200", "row_id": 32200, "seed_ids": "[274]" }
0.550532
Docs: Python310_32200
I
[ "normal_cdf", "inverse_normal_cdf", "binomial_pmf", "binomial_cdf" ]
4
[ [ "binomial_cdf", "binomial_pmf" ], [ "inverse_normal_cdf", "normal_cdf" ] ]
2
[]
false
[]
false
pytest
true
[]
true
707e1aa4d066b37ee42ed1b533c2fba1f9acaad2
1fe7e4a92cdf1b359dcfe736c64b2d04f87a71d2
v1.0
instruct
Docs
Docs: Python310_32214_I
### Asynchronous Task Scheduler: Platform-Specific I/O Handlers #### Objective Create an asynchronous Python function that schedules a task to perform non-blocking I/O operations based on the platform-specific capabilities and limitations. The function should read data from a file and write it to another file using th...
import asyncio import platform import selectors async def read_file_async(file_path): loop = asyncio.get_running_loop() with open(file_path, 'rb') as f: return await loop.run_in_executor(None, f.read) async def write_file_async(file_path, data): loop = asyncio.get_running_loop() with open(file...
import asyncio import tempfile import os from solution import platform_specific_io_handler def create_temp_file(content): tmp_file = tempfile.NamedTemporaryFile(delete=False) tmp_file.write(content) tmp_file.close() return tmp_file.name def test_io_handler_success(): src_content = b"Hello, World!"...
[]
[ 1, 0, 0, 1, 1, 0, 0, 1, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport platform\nimport selectors\nimport os\nfrom asyncio import StreamReader, StreamWriter\n\nasync def platform_specific_io_handler(source_file_path:...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00032214", "row_id": 32214, "seed_ids": "[370]" }
0.551873
Docs: Python310_32214
I
[ "read_file_async", "write_file_async", "platform_specific_io_handler" ]
3
[ [ "platform_specific_io_handler", "read_file_async" ], [ "platform_specific_io_handler", "write_file_async" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5280326e573f9ab5782f30bc78a9c79587ec3265
cd096bf0745af1fd9542275ff6ffb8d92ddbd23a
v1.0
instruct
Docs
Docs: Python310_32306_I
**Problem Statement:** You are tasked with creating an interactive drawing program using the `turtle` graphics module. In this task, you will implement a program that allows a user to draw various geometric shapes on the canvas by responding to keyboard events. Your program should support drawing lines, squares, circl...
import turtle def draw_line(): turtle.forward(100) def draw_square(): for _ in range(4): turtle.forward(50) turtle.right(90) def draw_circle(): turtle.circle(30) def clear_screen(): turtle.clear() def quit_program(): turtle.bye() def setup_drawing_program(): # Set up turtle...
# Note: Testing GUI and interactive programs like turtle is challenging with standard unit tests. # Here, we define mock functions to ensure drawing functions are called correctly. # These tests need to be run in an interactive Python environment where turtle graphics can be displayed. from solution import draw_line, ...
[ { "docstring": null, "function_declaration": "def draw_line():", "function_name": "draw_line", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def draw_square():", "function_name": "draw_square", "parameter_list": "()" }, { "docstring": null, "...
[ 0, 0, 0, 1, 0, 0, 1, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import turtle\n\ndef draw_line():\n turtle.forward(100)\n\ndef draw_square():\n for _ in range(4):\n turtle.forward(50)\n turtle.right(90)\n\ndef dr...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00032306", "row_id": 32306, "seed_ids": "[296]" }
0.702948
Docs: Python310_32306
I
[ "draw_line", "draw_square", "draw_circle", "clear_screen", "quit_program", "setup_drawing_program" ]
6
[ [ "setup_drawing_program", "clear_screen" ], [ "setup_drawing_program", "draw_circle" ], [ "setup_drawing_program", "draw_line" ], [ "setup_drawing_program", "draw_square" ], [ "setup_drawing_program", "quit_program" ] ]
5
[]
false
[]
false
pytest
true
[]
true
2498abc810074050d36335798bc37154e73af533
bfdffa8515a297d46d649cc132b6cbc59897bda7
v1.0
instruct
Docs
Docs: Python310_32404_I
#### Objective: Demonstrate understanding of the `imghdr` module and the ability to extend its functionality by implementing custom image type detection logic. #### Problem Statement: You are tasked with developing a utility to process a list of image files, determine their types, and categorize them based on their f...
from typing import List, Dict, Optional import imghdr def detect_custom_format(h: bytes) -> Optional[str]: """ Detects the custom image format by checking for a specific header signature. Parameters: h (bytes): Byte stream to check. Returns: Optional[str]: 'custom' if the ...
import os import pytest import imghdr from solution import detect_custom_format, categorize_images # Create test image files for testing def create_test_image_files(): files = { 'image1.png': b'\x00\x00\x00\x00', 'image2.jpeg': b'\x00\x00\x00\x00', 'custom_image': b'\x89PNGsomething' } ...
[ { "docstring": "Detects the custom image format by checking for a specific header signature.\n\nParameters:\n h (bytes): Byte stream to check.\n \nReturns:\n Optional[str]: 'custom' if the signature matches, otherwise None.", "function_declaration": "def detect_custom_format(h):", "function_nam...
[ 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, Optional\nimport imghdr\n\ndef detect_custom_format(h: bytes) -> Optional[str]:\n \"\"\"\n Detects if the byte stream corresponds t...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00032404", "row_id": 32404, "seed_ids": "[410]" }
0.559714
Docs: Python310_32404
I
[ "detect_custom_format", "categorize_images" ]
2
[ [ "categorize_images", "detect_custom_format" ] ]
1
[]
false
[]
false
pytest
true
[]
true
82cc9436388d32c95d164740c4a32e8a46f2d75c
42061c2f39bf88aeef0987493343f6fbdcd3cd91
v1.0
instruct
Docs
Docs: Python310_32450_I
You need to design a Python script that packages a directory containing Python modules into a distributable format. You will use the `distutils` library to achieve this. #### Task Write a Python script that: 1. Reads the metadata of a Python package from a configuration file. 2. Packages the Python module directory in...
import json import os import sys from distutils.core import setup def read_config(file_path): with open(file_path, 'r') as file: return json.load(file) def package_directory(config_path='package_config.json'): try: config = read_config(config_path) # Validating config fields r...
import os import pytest import json from unittest.mock import patch from solution import package_directory, read_config def test_read_config(tmpdir): config_content = { "name": "sample_package", "version": "0.1", "description": "A sample Python package", "author": "Jane Doe", ...
[ { "docstring": null, "function_declaration": "def read_config(file_path):", "function_name": "read_config", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def package_directory(config_path='package_config.json'):", "function_name": "package_directory...
[ 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 json\nimport os\nfrom distutils.core import setup\n\ndef read_config(file_path):\n \"\"\"\n Read and parse the configuration file.\n \"\"\"\n with op...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00032450", "row_id": 32450, "seed_ids": "[432]" }
0.597627
Docs: Python310_32450
I
[ "read_config", "package_directory" ]
2
[ [ "package_directory", "read_config" ] ]
1
[]
false
[]
false
pytest
true
[]
true
0206e716357528deb9a6656698ed98faf8a1f84d
59589f699a18a94ec7be91ed328e49ba44fe7bb1
v1.0
instruct
Docs
Docs: Python310_32489_I
### Advanced Python Networking with asyncio **Objective:** Demonstrate your ability to use the asyncio library to handle multiple asynchronous tasks, manage network connections, and schedule callbacks efficiently. **Question:** You are tasked with implementing a simple echo server and client using Python's asyncio...
import asyncio import signal async def handle_client(reader, writer): addr = writer.get_extra_info('peername') print(f"Connected to {addr}") try: while True: data = await reader.read(100) if not data: break message = data.decode() pri...
import asyncio import pytest from solution import handle_client, start_server, client @pytest.mark.asyncio async def test_echo_server(): server = await asyncio.start_server(handle_client, '127.0.0.1', 8888) addr = server.sockets[0].getsockname() async with server: message = "Hello, Asyncio!" ...
[ { "docstring": null, "function_declaration": "def ask_exit(signame, loop):", "function_name": "ask_exit", "parameter_list": "(signame, loop)" } ]
[ 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\nimport signal\nimport sys\n\nasync def handle_client(reader, writer):\n try:\n addr = writer.get_extra_info('peername')\n print(f\"Conn...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00032489", "row_id": 32489, "seed_ids": "[267]" }
0.675602
Docs: Python310_32489
I
[ "handle_client", "start_server", "ask_exit", "client", "main" ]
5
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
eb9343deada2fdc39dd83c6f225a7defb75cab44
e18dcc654a550133871ed3f131c4aa8d194d7662
v1.0
instruct
Docs
Docs: Python310_32513_I
### Coding Assessment: Secure Message Transmission #### Objective: Implement a secure message transmission module in Python using the cryptographic services provided by `hashlib`, `hmac`, and `secrets`. Your task is to write functions that: 1. **Generate Secure Hash**: Create a secure hash of a given message using th...
import hashlib import hmac import secrets import base64 def generate_secure_hash(message: str, algorithm: str = 'sha256') -> str: """ Returns a secure hash of the given message using the specified hashing algorithm. :param message: The message to hash. :param algorithm: The hashing algorithm to us...
import pytest from solution import generate_secure_hash, create_hmac, verify_hmac, generate_secure_token def test_generate_secure_hash(): message = "This is a test message." hash_sha256 = generate_secure_hash(message, 'sha256') assert hash_sha256 == hashlib.sha256(message.encode('utf-8')).hexdigest() ...
[ { "docstring": "Returns a secure hash of the given message using the specified hashing algorithm.\n\n:param message: The message to hash.\n:param algorithm: The hashing algorithm to use (default 'sha256').\n:return: Hexadecimal digest of the hashed message.", "function_declaration": "def generate_secure_has...
[ 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 hashlib\nimport hmac\nimport secrets\nimport base64\n\ndef generate_secure_hash(message: str, algorithm: str = 'sha256') -> str:\n \"\"\"\n Generates a sec...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00032513", "row_id": 32513, "seed_ids": "[394]" }
0.829124
Docs: Python310_32513
I
[ "generate_secure_hash", "create_hmac", "verify_hmac", "generate_secure_token" ]
4
[ [ "verify_hmac", "create_hmac" ] ]
1
[]
false
[]
false
pytest
true
[]
true
fb0d893429b3be4a4a83c7b0b352e40c696c6bad
0821582a78416112a7f2ad7898324f28264e03c8
v1.0
instruct
Docs
Docs: Python310_32529_I
### SQLite Database Management with Custom Types and Transactions In this task, you will create and manage an SQLite database using Python's `sqlite3` module. You need to demonstrate advanced understanding including transaction control, error handling, and custom type adapters. #### Task 1. **Create a database and e...
import sqlite3 import re class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"{self.x},{self.y}" @classmethod def from_string(cls, string): x, y = map(float, string.split(',')) return cls(x, y) def adapt_point(point): re...
import os import pytest import sqlite3 from solution import manage_employee_database, Point def setup_module(module): """Module setup/teardown for testing the database.""" # Remove the database file if it exists to ensure a clean state for tests. try: os.remove('company.db') except OSError: ...
[]
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 1 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sqlite3\n\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __repr__(self):\n return f\"Point({self.x}, {sel...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00032529", "row_id": 32529, "seed_ids": "[103]" }
0.546172
Docs: Python310_32529
I
[ "adapt_point", "convert_point", "manage_employee_database" ]
3
[ [ "manage_employee_database", "adapt_point" ], [ "manage_employee_database", "convert_point" ] ]
2
[]
false
[ "Point" ]
true
pytest
true
[]
true
99d8c447822a65f7a1f6192c813c270fbffcaf84
5dab87d5413510af3d7094f6ba0589adf0bf8e5b
v1.0
instruct
Docs
Docs: Python310_32581_I
### Coding Challenge: Custom Codec Registration and Usage #### Objective: Create a custom encoding/decoding mechanism in Python 3.10 and demonstrate its registration and usage with error handling. #### Task: 1. Implement a custom encoder and decoder using Python classes. 2. Register these custom codecs using the func...
import codecs class CustomCodec: def __init__(self): pass def custom_encoder(self, input_string): encoded = ' '.join(str(ord(char)) for char in input_string) return encoded, len(encoded) def custom_decoder(self, encoded_string): decoded = ''.join(chr(int(code)) for code in...
from solution import encode_decode_test def test_encode_decode_basic(): encoded, decoded = encode_decode_test("Hello") assert encoded == "72 101 108 108 111" assert decoded == "Hello" def test_encode_decode_empty(): encoded, decoded = encode_decode_test("") assert encoded == "" assert decoded ...
[]
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import codecs\n\nclass CustomCodec:\n def __init__(self):\n pass\n\n def custom_encoder(self, input_string):\n encoded = ' '.join(str(ord(char)) for...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00032581", "row_id": 32581, "seed_ids": "[47]" }
0.626241
Docs: Python310_32581
I
[ "lookup_custom", "register_custom_codecs", "encode_decode_test" ]
3
[ [ "encode_decode_test", "register_custom_codecs" ], [ "register_custom_codecs", "lookup_custom" ] ]
2
[]
false
[ "CustomCodec" ]
true
pytest
true
[]
true
20e40ec627e26816a2d0d277715d6adef574b272
3026ada84157a35e5a8bcfd866219344d35f1336
v1.0
instruct
Docs
Docs: Pytorch_32600_I
### Distributed Training with Uneven Inputs **Objective:** Implement a simple distributed training setup using PyTorch, where the dataset is not evenly divisible among the processors. You are required to manage these uneven inputs using the provided classes `Join`, `Joinable`, and `JoinHook`. **Task:** 1. Create a si...
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import DataLoader, Dataset, Subset import numpy as np # Define a simple neural network model class SimpleModel(nn.Module): def __init__(...
import torch from solution import SimpleModel, CustomDataset, split_dataset def test_model_structure(): model = SimpleModel() x = torch.randn(2, 10) y = model(x) assert y.shape == (2, 1), "Model output shape is incorrect." def test_custom_dataset(): dataset = CustomDataset(size=10) assert len...
[]
[ 1, 1, 0, 1, 0, 0, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom t...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00032600", "row_id": 32600, "seed_ids": "[135]" }
0.391106
Docs: Pytorch_32600
I
[ "split_dataset", "train" ]
2
[ [ "train", "split_dataset" ] ]
1
[]
false
[ "SimpleModel", "CustomDataset" ]
true
pytest
true
[ "numpy", "torch" ]
false
8a954370bb49fcffd5ae3dbe51a44813037c8126
a124186a20de05c3bb9aeba19e4c5c756ae56415
v1.0
instruct
Docs
Docs: Pytorch_32651_I
### PyTorch Reproducibility Challenge **Objective:** The goal of this task is to create a small PyTorch pipeline that includes both deterministic and nondeterministic operations. You will then configure the pipeline to ensure reproducible results following the provided guidelines. **Task:** 1. **Setup:** - Import ...
import torch import random import numpy as np # Step 1: Setting up reproducibility def set_reproducibility(seed=0): torch.manual_seed(seed) random.seed(seed) np.random.seed(seed) torch.backends.cudnn.benchmark = False torch.use_deterministic_algorithms(True) set_reproducibility(42) # Step 2: Defi...
def test_reproducible_pipeline(): output1 = run_pipeline() output2 = run_pipeline() assert torch.equal(output1, output2), "Outputs are not reproducible!"
[]
[ 0, 0, 1, 1, 1, 1, 1, 1, 1 ]
7
easy
0.778
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport random\nimport numpy as np\n\n# Step 1: Setting up reproducibility\ndef set_reproducibility(seed=0):\n torch.manual_seed(seed)\n random.seed(...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00032651", "row_id": 32651, "seed_ids": "[174]" }
0.553217
Docs: Pytorch_32651
I
[ "set_reproducibility", "run_pipeline" ]
2
[ [ "run_pipeline", "set_reproducibility" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
false
[ "numpy", "torch" ]
false
ee58e12468ee2e70b572bba673821a36fe90204f
a78b9965f2c80fa2918a9e68be47862a328e8e2c
v1.0
instruct
Docs
Docs: Python310_32673_I
### Command-Line Calculator #### Objective Design and implement a command-line calculator using the `argparse` module. The calculator should support basic arithmetic operations, advanced mathematical functions, and batch processing through input files. #### Task 1. Design an argument parser that handles the following...
import argparse import math def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y == 0: raise ValueError("Cannot divide by zero") return x / y def exp(x, y): return x ** y def sqrt(x): if x < 0: raise ValueE...
import pytest from solution import add, subtract, multiply, divide, exp, sqrt, process_operation def test_add(): assert add(5, 3) == 8 assert add(-1, 1) == 0 def test_subtract(): assert subtract(5, 3) == 2 assert subtract(-1, 1) == -2 def test_multiply(): assert multiply(5, 3) == 15 assert mu...
[ { "docstring": null, "function_declaration": "def add(x, y):", "function_name": "add", "parameter_list": "(x, y)" }, { "docstring": null, "function_declaration": "def subtract(x, y):", "function_name": "subtract", "parameter_list": "(x, y)" }, { "docstring": null, "fu...
[ 0, 1, 1, 1, 0, 0, 1, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import argparse\nimport math\nimport sys\n\ndef add(x, y):\n return x + y\n\ndef subtract(x, y):\n return x - y\n\ndef multiply(x, y):\n return x * y\n\ndef di...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00032673", "row_id": 32673, "seed_ids": "[139]" }
0.554664
Docs: Python310_32673
I
[ "add", "subtract", "multiply", "divide", "exp", "sqrt", "process_operation", "main" ]
8
[ [ "process_operation", "add" ], [ "process_operation", "divide" ], [ "process_operation", "exp" ], [ "process_operation", "multiply" ], [ "process_operation", "sqrt" ], [ "process_operation", "subtract" ] ]
6
[]
false
[]
false
pytest
true
[]
true
2dadaceda41b7cba9eeb488bc390d35f59d253a3
436b7e6eb2968cfa756aa529ba545dcd39f2084d
v1.0
instruct
Docs
Docs: Python310_32730_I
#### Objective: You are asked to create a simple text-based GUI interface using the Python `curses` module. This interface should allow a user to navigate through a menu using the arrow keys, select an option, and display corresponding information. #### Task: Implement a Python program using the `curses` module that p...
import curses def display_menu(stdscr): curses.curs_set(0) # Hide the cursor stdscr.clear() k = 0 current_row = 0 menu = ['Option 1', 'Option 2', 'Option 3', 'Exit'] while True: stdscr.clear() h, w = stdscr.getmaxyx() for idx, row in enumerate(menu): x = ...
# It's challenging to write automated tests for curses applications since they interact with the terminal. # Usually, such applications are tested manually or with end-to-end testing tools designed for terminal applications. # However, we can test some logic components without relying on curses. from solution import d...
[ { "docstring": null, "function_declaration": "def display_menu(stdscr):", "function_name": "display_menu", "parameter_list": "(stdscr)" }, { "docstring": null, "function_declaration": "def option_selected(stdscr, option):", "function_name": "option_selected", "parameter_list": "(...
[ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import curses\n\ndef draw_menu(stdscr, current_row_idx):\n \"\"\"Draws the menu and highlights the current selected row.\"\"\"\n stdscr.clear()\n h, w = stdscr...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00032730", "row_id": 32730, "seed_ids": "[74]" }
0.385364
Docs: Python310_32730
I
[ "display_menu", "option_selected", "main" ]
3
[ [ "display_menu", "option_selected" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a35f3246165d13b09b766bcfc54bd1c8f2f508e6
c9654774ce4de5c51af77408c333a5ba5de2dea6
v1.0
instruct
Docs
Docs: Scikit_32821_I
**Question**: You are given a dataset `spam.csv` that contains two columns: `text` (the message content) and `label` (either "spam" or "ham"). Your task is to implement a text classification pipeline using the Naive Bayes classifiers from the scikit-learn library to classify whether a given message is spam or not. *...
import pandas as pd import string from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB, BernoulliNB from sklearn.metrics import accuracy_score, confusion_matrix def load_data(file_path): """ Load dataset f...
from solution import load_data, preprocess_text, prepare_data, vectorize_data, train_and_evaluate_model import pandas as pd from sklearn.naive_bayes import MultinomialNB, BernoulliNB from sklearn.feature_extraction.text import TfidfVectorizer # Sample data to simulate spam.csv data = { 'text': ["Free entry in 2 a ...
[ { "docstring": "Load dataset from a CSV file.", "function_declaration": "def load_data(file_path):", "function_name": "load_data", "parameter_list": "(file_path)" }, { "docstring": "Preprocess the text by removing punctuation and converting to lowercase.", "function_declaration": "def pr...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00032821", "row_id": 32821, "seed_ids": "[61]" }
0.575087
Docs: Scikit_32821
I
[ "load_data", "preprocess_text", "prepare_data", "vectorize_data", "train_and_evaluate_model", "main" ]
6
[ [ "prepare_data", "preprocess_text" ] ]
1
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
8cdc30cc41e27c5742e4774d7eb265579b677b57
cfdedd1f91d738c888bb9222e2ad0838ddb50ba6
v1.0
instruct
Docs
Docs: Python310_32853_I
As part of improving error handling in your Python application, you need to manage different types of errors gracefully. Your task is to implement a function that processes a list of operations and appropriately handles any errors that might occur using built-in Python exceptions. Additionally, you will create a custom...
class CustomError(Exception): pass def raise_custom_error(message: str) -> None: raise CustomError(message) def process_operations(operations: list) -> list: sample_list = [1, 2, 3] results = [] for operation in operations: op_type = operation[0] try: if op_type =...
from solution import CustomError, raise_custom_error, process_operations def test_divide(): assert process_operations([("divide", 6, 3)]) == [2] assert process_operations([("divide", 6, 0)]) == ["Error: Division by zero."] def test_concat(): assert process_operations([("concat", "hello", 3)]) == ["Error: ...
[]
[ 0, 0, 0, 1, 1, 0, 1, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class CustomError(Exception):\n pass\n\ndef raise_custom_error(message: str) -> None:\n raise CustomError(message)\n\ndef process_operations(operations: list) -> ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00032853", "row_id": 32853, "seed_ids": "[256]" }
0.59495
Docs: Python310_32853
I
[ "raise_custom_error", "process_operations" ]
2
[ [ "process_operations", "raise_custom_error" ] ]
1
[]
false
[ "CustomError" ]
true
pytest
true
[]
true
1423267c2bd841c1b34cb3025208c2cb359b7c02
58603c0b1410d8d2af0a371afec09f04f62e5cdd
v1.0
instruct
Docs
Docs: Python310_32944_I
## Coding Assessment Question ### Objective Write a Python program that simulates a simple task management system using asyncio. Your program should create multiple tasks, manage their execution with timeouts, and use a FIFO queue to distribute tasks among workers. ### Requirements 1. **Task Creation**: Implement a f...
import asyncio import random async def create_task(task_id: int) -> None: """ Creates a task that prints a start message, waits for a random duration, and then prints a completion message. """ print(f"Task {task_id} started.") await asyncio.sleep(random.randint(1, 5)) print(f"Task {task_id}...
import asyncio from solution import create_task, task_manager, distribute_tasks async def test_create_task(): await create_task(1) async def test_task_manager(): await task_manager(5, 10) async def test_worker(): queue = asyncio.Queue() await queue.put(1) task = asyncio.create_task(worker(queue))...
[ { "docstring": null, "function_declaration": "def main():", "function_name": "main", "parameter_list": "()" } ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\n\nasync def create_task(task_id: int) -> None:\n \"\"\"\n Simulates a task by printing a start message, sleeping for a random durat...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00032944", "row_id": 32944, "seed_ids": "[360]" }
0.627718
Docs: Python310_32944
I
[ "create_task", "task_manager", "worker", "distribute_tasks", "main" ]
5
[ [ "distribute_tasks", "worker" ], [ "task_manager", "create_task" ], [ "worker", "create_task" ] ]
3
[]
false
[]
false
pytest
true
[]
true
72c16d8ee9cb69364b491b9f6e42308311d09f59
e1fc6c0aed1480a9b367ca0c247520ec040e9e3f
v1.0
instruct
Docs
Docs: Python310_32957_I
### Python Coding Assessment: `threading` Module **Objective**: Assess the ability to leverage the `threading` module in Python to implement a multi-threaded producer-consumer scenario while ensuring proper synchronization. #### Problem Statement You are required to implement a multi-threaded program using Python's ...
import threading import queue import time import logging # Configure logging logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s') def fetch_data(): # Simulate data fetching logic fetch_data.counter += 1 return fetch_data.counter fetch_data.counter = 0 def producer(buffer, stop_e...
import threading import queue import time import logging from solution import fetch_data, producer, consumer, main # Set logging to only show errors to keep test output clean. logging.basicConfig(level=logging.ERROR, format='%(threadName)s: %(message)s') def test_fetch_data(): count1 = fetch_data() count2 = f...
[ { "docstring": null, "function_declaration": "def fetch_data():", "function_name": "fetch_data", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def producer(buffer, stop_event):", "function_name": "producer", "parameter_list": "(buffer, stop_event)" }, ...
[ 1, 0, 0, 1, 0, 0, 1, 0, 1, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import threading\nimport queue\nimport time\nimport logging\n\n# Configure logging\nlogging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s')\n\nde...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00032957", "row_id": 32957, "seed_ids": "[120]" }
0.540381
Docs: Python310_32957
I
[ "fetch_data", "producer", "consumer", "main" ]
4
[ [ "producer", "fetch_data" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c0aa05a8a55b3c96eb9a85b8a2d78cb5773d89cf
61e0b1b9bdb91c18b1efaaa1f7689bd1596b1cfd
v1.0
instruct
Docs
Docs: Python310_33017_I
**Coding Assessment Question:** ### URL Validation and IP Address Categorization Your task is to implement a Python function that validates a list of URLs and categorizes them based on their IP addresses. You must use Python's `urllib.parse` for URL components parsing and `ipaddress` for IP address manipulation. Foll...
import urllib.parse import ipaddress def hostname_to_ip(hostname): # This is a stub function, the real implementation will be provided during evaluation. # Here we return some hardcoded values for the sake of example. if hostname == "example.com": return "93.184.216.34" # Public IP elif hostna...
from solution import categorize_urls def test_categorize_urls(): urls = [ "http://example.com", "http://192.168.1.1", "ftp://10.0.0.5/resource", "http://invalidhostname" ] result = categorize_urls(urls) assert result == { "Private": ["http://192.168.1.1", "ftp://...
[ { "docstring": null, "function_declaration": "def hostname_to_ip(hostname):", "function_name": "hostname_to_ip", "parameter_list": "(hostname)" }, { "docstring": null, "function_declaration": "def categorize_urls(urls):", "function_name": "categorize_urls", "parameter_list": "(ur...
[ 1, 0, 1, 0, 1, 1, 1, 1, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import urllib.parse\nimport ipaddress\n\ndef hostname_to_ip(hostname):\n # Placeholder function\n # This function should resolve the hostname to an IP address.\n ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00033017", "row_id": 33017, "seed_ids": "[160]" }
0.722657
Docs: Python310_33017
I
[ "hostname_to_ip", "categorize_urls" ]
2
[ [ "categorize_urls", "hostname_to_ip" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2b4062f5606313b4fe9e6ba07d09cd604e49cf6f
75c8247b24fd59375febbefadc5ebf0723236247
v1.0
instruct
Docs
Docs: Scikit_33028_I
**Objective**: Evaluate the understanding of scikit-learn metrics and their application in model evaluation for classification and regression. #### Question: You are provided with two datasets: one for a classification task and another for a regression task. Your task is to: 1. Train suitable models on these datasets....
import pandas as pd from sklearn.ensemble import RandomForestClassifier, GradientBoostingRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import ( accuracy_score, f1_score, roc_auc_score, mean_absolute_error, mean_squared_error, r2_score, precision_recall_c...
import pytest import pandas as pd from tempfile import NamedTemporaryFile from solution import classification_task, regression_task @pytest.fixture def classification_data(): data = { 'feature1': [0.1, 0.2, 0.3, 0.4, 0.5], 'feature2': [1, 2, 3, 4, 5], 'target': [0, 1, 0, 1, 0] } df ...
[ { "docstring": null, "function_declaration": "def custom_precision_recall_auc(y_true, y_pred):", "function_name": "custom_precision_recall_auc", "parameter_list": "(y_true, y_pred)" }, { "docstring": null, "function_declaration": "def custom_pinball_loss(y_true, y_pred, alpha=0.95):", ...
[ 0, 1, 0, 0, 0, 1, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingRegressor\nfrom sklearn.model_selection import train_test_...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033028", "row_id": 33028, "seed_ids": "[25]" }
0.565195
Docs: Scikit_33028
I
[ "custom_precision_recall_auc", "custom_pinball_loss", "classification_task", "regression_task" ]
4
[ [ "classification_task", "custom_precision_recall_auc" ], [ "regression_task", "custom_pinball_loss" ] ]
2
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
6a6f368eda206e858a2b8ec5ed7b7de1b3493ae7
54a4528ee9b7f23055c905962289a8360ea78cea
v1.0
instruct
Docs
Docs: Python310_33037_I
#### Objective The purpose of this exercise is to assess your understanding and ability to use various Python standard libraries to solve a comprehensive problem. You will demonstrate your skills by building a small utility script. #### Problem Statement You are tasked with creating a command-line utility that archive...
import os import shutil import glob import argparse import datetime import zipfile import sys def log_message(directory, message): with open(os.path.join(directory, 'backup.log'), 'a') as log_file: timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') log_file.write(f'[{timestamp}] {mes...
import os import shutil import zipfile from solution import backup_python_files, log_message def setup_test_environment(test_dir): if not os.path.exists(test_dir): os.makedirs(test_dir) project1_path = os.path.join(test_dir, 'project1') project2_path = os.path.join(test_dir, 'project2') os.make...
[ { "docstring": null, "function_declaration": "def log_message(directory, message):", "function_name": "log_message", "parameter_list": "(directory, message)" }, { "docstring": null, "function_declaration": "def backup_python_files(directory):", "function_name": "backup_python_files",...
[ 1, 0, 0, 1, 0, 0, 1, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport shutil\nimport glob\nimport argparse\nimport datetime\nimport zipfile\nimport sys\n\ndef log_msg(log_file, msg):\n timestamp = datetime.datetime.no...
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00033037", "row_id": 33037, "seed_ids": "[422]" }
0.689597
Docs: Python310_33037
I
[ "log_message", "backup_python_files", "main" ]
3
[ [ "backup_python_files", "log_message" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3b270a2b0d9654d77c1b51f159e5f62652eea299
f70f96bb5760e076dac40302cae6cd2ceeed1e21
v1.0
instruct
Docs
Docs: Python310_33167_I
**Title: Implement a Concurrent Prime Number Finder** **Objective:** To assess your understanding of threading and multiprocessing in Python, you will implement a concurrent program to find prime numbers within a specified range. Your task is to use both thread-based and process-based parallelism to achieve this. Addi...
from threading import Thread, Lock from multiprocessing import Process, Manager from typing import List import math def is_prime(n: int) -> bool: 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...
import pytest from solution import find_primes_concurrently def test_find_primes_small_range(): assert find_primes_concurrently(10, 20) == [11, 13, 17, 19] def test_find_primes_large_range(): assert find_primes_concurrently(1, 100) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71...
[ { "docstring": null, "function_declaration": "def is_prime(n):", "function_name": "is_prime", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def find_primes_in_range(start, end, primes):", "function_name": "find_primes_in_range", "parameter_list": "(star...
[ 0, 0, 1, 0, 0, 0, 0, 0, 1, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List, Tuple\nimport threading\nimport multiprocessing\n\n# Helper function to check if a number is prime\ndef is_prime(n: int) -> bool:\n if n < 2...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00033167", "row_id": 33167, "seed_ids": "[206]" }
0.562892
Docs: Python310_33167
I
[ "is_prime", "find_primes_in_range", "find_primes_concurrently" ]
3
[ [ "find_primes_concurrently", "find_primes_in_range" ], [ "find_primes_in_range", "is_prime" ] ]
2
[]
false
[]
false
pytest
true
[]
true
59549f6a349266f044b82bff50c95dbf5ba43493
e0c0865b98219e0499280c48c7e5f2cc627a4d77
v1.0
instruct
Docs
Docs: Python310_33209_I
**Question: Implementing an Asynchronous Data Logger** You are required to create an asynchronous data logger using Python's `asyncio` module. This logger should listen for incoming data on a specified network socket and log the data to a file. The logger needs to support the following functionalities: 1. **Network S...
import asyncio import signal import datetime async def handle_client(reader, writer, log_file): with open(log_file, 'a') as f: while True: data = await reader.read(100) if not data: break timestamp = datetime.datetime.now().isoformat() f.write...
import asyncio import os import pytest import signal from solution import run_data_logger @pytest.fixture def log_file(): log_file_path = 'test_data.log' yield log_file_path if os.path.exists(log_file_path): os.remove(log_file_path) async def send_data(host, port, data): reader, writer = awai...
[ { "docstring": null, "function_declaration": "def shutdown():", "function_name": "shutdown", "parameter_list": "()" } ]
[ 0, 1, 1, 0, 1, 1, 0, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport signal\nfrom datetime import datetime\n\nasync def handle_client(reader, writer, log_file):\n addr = writer.get_extra_info('peername')\n\n ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033209", "row_id": 33209, "seed_ids": "[267]" }
0.600431
Docs: Python310_33209
I
[ "handle_client", "run_data_logger" ]
2
[ [ "run_data_logger", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a63d032adc11b1b91f892df88d0ea701ef2fda69
e449570d6c0ebc065b83878a9beb501053e886d2
v1.0
instruct
Docs
Docs: Seaborn_33270_I
### Question **Plotting with Seaborn: Scatter Plot Customization and Faceting** #### Objective Create a series of scatter plots using the Seaborn library to visualize relationships between variables in a dataset. The plots should utilize various Seaborn functionalities such as color (`hue`), marker style (`style`), a...
import seaborn as sns import pandas as pd import matplotlib.pyplot as plt def load_and_display_tips(): # Load the dataset tips = sns.load_dataset("tips") # Display first 5 rows of the dataset print(tips.head()) return tips def basic_scatter_plot(tips): # Basic scatter plot with hue and style ...
from solution import load_and_display_tips, basic_scatter_plot, enhanced_scatter_plot, faceted_scatter_plot import seaborn as sns def test_load_and_display_tips(): tips = load_and_display_tips() assert isinstance(tips, pd.DataFrame), "Output should be a pandas DataFrame" assert not tips.empty, "DataFrame s...
[ { "docstring": null, "function_declaration": "def load_and_display_tips():", "function_name": "load_and_display_tips", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def basic_scatter_plot(tips):", "function_name": "basic_scatter_plot", "parameter_list": ...
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Load the dataset\ntips = sns.load_dataset(\"tips\")\n\n# Task 1: Display first 5 rows o...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00033270", "row_id": 33270, "seed_ids": "[69]" }
0.664398
Docs: Seaborn_33270
I
[ "load_and_display_tips", "basic_scatter_plot", "enhanced_scatter_plot", "faceted_scatter_plot", "generate_plots" ]
5
[ [ "generate_plots", "basic_scatter_plot" ], [ "generate_plots", "enhanced_scatter_plot" ], [ "generate_plots", "faceted_scatter_plot" ], [ "generate_plots", "load_and_display_tips" ] ]
4
[]
false
[]
false
pytest
true
[ "matplotlib", "pandas", "seaborn" ]
false
086a75ad102e439542a4a750426d025b09e0f502
2a78ebbec4d93f9118c0feff49dfda031becfa04
v1.0
instruct
Docs
Docs: Python310_33296_I
**Title:** Implementing Robust Debugging with `faulthandler` **Objective:** You are tasked with creating a Python script that robustly handles unexpected terminations by utilizing the `faulthandler` module. Your implementation should demonstrate comprehensive use of the functionalities provided by this module. **Pro...
import faulthandler import signal import time def setup_fault_handler(): """ Sets up the fault handler to dump tracebacks to a file. """ with open("traceback.log", "w") as f: faulthandler.enable(file=f) with open("traceback.log", "a") as f: # Register SIGUSR1 to dump traceback ...
# To test this script manually, execute it and: # 1. Verify that `traceback.log` contains tracebacks as expected. # 2. Send SIGUSR1 to the process and observe the behavior. # 3. Optional: Interrupt the script with KeyboardInterrupt and see if it handles it gracefully. # Automated testing code is limited for this scena...
[ { "docstring": "Sets up the fault handler to dump tracebacks to a file.", "function_declaration": "def setup_fault_handler():", "function_name": "setup_fault_handler", "parameter_list": "()" }, { "docstring": "Disables the fault handler.", "function_declaration": "def disable_fault_handl...
[ 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 faulthandler\nimport signal\nimport time\nimport sys\n\ndef enable_faulthandler():\n # Open the file in append mode to log tracebacks\n log_file = open(\"t...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00033296", "row_id": 33296, "seed_ids": "[407]" }
0.497537
Docs: Python310_33296
I
[ "setup_fault_handler", "disable_fault_handler", "run_process" ]
3
[ [ "run_process", "disable_fault_handler" ] ]
1
[]
false
[]
false
pytest
true
[]
true
9419f7c7bc7be6020b4e9077c431530e6521a44f
faa9fe9d3fe8eabea2eef5cada289684691df450
v1.0
instruct
Docs
Docs: Pytorch_33310_I
**Advanced PyTorch Distributed RPC Task** ### Objective: You are tasked with implementing functionality related to the Remote Reference (RRef) protocol in PyTorch's distributed RPC framework. The goal is to create a function that demonstrates the life cycle of an RRef, including its creation, usage, and deletion acros...
import os import torch import torch.distributed.rpc as rpc from torch.distributed.rpc import RRef # Function to create and return a RRef def create_rref_worker(): return RRef(torch.tensor([1, 2, 3])) # Function to use an RRef def use_rref_worker(rref): tensor = rref.to_here() print(f"Worker {rpc.get_worke...
import pytest import torch import torch.multiprocessing as mp import torch.distributed.rpc as rpc from solution import create_rref_worker, pass_rref_worker, use_rref_worker def rpc_worker(rank, world_size): rpc.init_rpc(f"worker{rank}", rank=rank, world_size=world_size) if rank == 0: rref = create_rre...
[ { "docstring": null, "function_declaration": "def create_rref_worker():", "function_name": "create_rref_worker", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def use_rref_worker(rref):", "function_name": "use_rref_worker", "parameter_list": "(rref)" }...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.distributed.rpc as rpc\n\n# Functions to demonstrate RRef life cycle\n\ndef create_tensor():\n \"\"\"\n Creates a tensor to be shared a...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033310", "row_id": 33310, "seed_ids": "[158]" }
0.392411
Docs: Pytorch_33310
I
[ "create_rref_worker", "use_rref_worker", "pass_rref_worker" ]
3
[ [ "pass_rref_worker", "use_rref_worker" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
fad88c30caf4224f756b588bfab843d28fce458b
6b00dc51d2e1aa79a100d8e500f0e7702c682582
v1.0
instruct
Docs
Docs: Python310_33381_I
### XMLRPC Server and Client Implementation You are tasked with implementing an XML-RPC server and a client that interacts with it. **Server Requirements:** 1. Implement an XML-RPC server that listens on `localhost` and port `8000`. 2. The server should provide a single method `add(a, b)` which takes two integers and...
# Server code from xmlrpc.server import SimpleXMLRPCServer import logging # Set up logging logging.basicConfig(level=logging.INFO) def add(a, b): result = a + b logging.info(f"add({a}, {b}) = {result}") return result def start_server(): server = SimpleXMLRPCServer(('localhost', 8000)) logging.inf...
import threading import time from solution import start_server, client_add def test_server_and_client(): # Start the server in a separate thread server_thread = threading.Thread(target=start_server) server_thread.daemon = True server_thread.start() # Give server some time to start time.sleep(1...
[ { "docstring": null, "function_declaration": "def add(a, b):", "function_name": "add", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def start_server():", "function_name": "start_server", "parameter_list": "()" }, { "docstring": null, "fu...
[ 0, 1, 1, 0, 0, 1, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "# server.py\nfrom xmlrpc.server import SimpleXMLRPCServer\nimport logging\n\n# Set up logging\nlogging.basicConfig(level=logging.INFO)\n\ndef add(a, b):\n result = a...
trial_gpt4o_5
{ "original_instruction": "", "prompt_id": "00033381", "row_id": 33381, "seed_ids": "[280]" }
0.495502
Docs: Python310_33381
I
[ "add", "start_server", "client_add" ]
3
[ [ "start_server", "add" ] ]
1
[]
false
[]
false
pytest
true
[]
true
e2e50a23acbb62c970e365c808d8184ccccf716f
995e6fd09bc1a28d775b20ca0276322422ee6b1c
v1.0
instruct
Docs
Docs: Python310_33444_I
## Coding Assessment Question ### Objective Design a Python program to demonstrate your understanding of Unix-specific system interactions using Python 3.10. You are required to implement functions that utilize Unix system calls and database modules to perform various tasks. ### Problem Statement You need to implemen...
import pwd import grp import syslog def get_user_info(username): """ Returns user information from the Unix password database. """ try: user_info = pwd.getpwnam(username) return { "userID": user_info.pw_uid, "userName": user_info.pw_name, "homeDirecto...
import pytest from solution import get_user_info, get_group_info, add_user_to_group, log_event def test_get_user_info(monkeypatch): # Mocking pwd.getpwnam class MockUser: pw_uid = 1001 pw_name = "john" pw_dir = "/home/john" pw_shell = "/bin/bash" def mock_getpwnam(usern...
[ { "docstring": "Returns user information from the Unix password database.", "function_declaration": "def get_user_info(username):", "function_name": "get_user_info", "parameter_list": "(username)" }, { "docstring": "Returns group information from the Unix group database.", "function_decl...
[ 0, 1, 0, 1, 1, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pwd\nimport grp\nimport syslog\n\ndef get_user_info(username):\n try:\n user_info = pwd.getpwnam(username)\n return {\n \"userID\": u...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00033444", "row_id": 33444, "seed_ids": "[149]" }
0.466458
Docs: Python310_33444
I
[ "get_user_info", "get_group_info", "add_user_to_group", "log_event" ]
4
[ [ "add_user_to_group", "log_event" ], [ "get_group_info", "log_event" ], [ "get_user_info", "log_event" ] ]
3
[]
false
[]
false
pytest
true
[]
true
a910bf2bdefae0e913f763f2a4f3f819532064ff
6af01e8e4ed0fab72f975dcb8a1379201ab3b9b7
v1.0
instruct
Docs
Docs: Python310_33484_I
### Question: Implementing Custom Serialization using Pickle and copyreg #### Objective You are required to implement a custom serialization mechanism for a Python class using the `pickle` module, with support functions registered via `copyreg`. This will include handling a complex object that contains non-trivial sta...
import pickle import copyreg import shelve class Config: def __init__(self, name, version, settings): self.name = name self.version = version self.settings = settings def update_setting(self, key, value): self.settings[key] = value def __str__(self): return f"Confi...
from solution import Config, serialize_config, deserialize_config, save_configs, load_configs, process_operations def test_config_creation(): config = Config("config1", 1, {"theme": "dark"}) assert config.name == "config1" assert config.version == 1 assert config.settings == {"theme": "dark"} def test...
[]
[ 1, 1, 0, 0, 1, 1, 1, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pickle\nimport copyreg\nimport shelve\n\nclass Config:\n def __init__(self, name, version, settings):\n self.name = name\n self.version = versio...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00033484", "row_id": 33484, "seed_ids": "[140]" }
0.599217
Docs: Python310_33484
I
[ "serialize_config", "deserialize_config", "save_configs", "load_configs", "process_operations" ]
5
[ [ "process_operations", "load_configs" ], [ "process_operations", "save_configs" ] ]
2
[]
false
[ "Config" ]
true
pytest
true
[]
true
636cb521e5641589b3b3c49be897eba80b993d6a
073b7aaf6dafba6cb621b77f1f0ac441dc76f751
v1.0
instruct
Docs
Docs: Seaborn_33491_I
You are tasked with analyzing the color distribution of a dataset and presenting it using a custom color palette created with seaborn's `dark_palette` function. ### Problem Statement 1. **Input**: You will be provided with a CSV file named `data.csv` containing a dataset with numerical and categorical columns. 2. **O...
import seaborn as sns import pandas as pd import matplotlib.pyplot as plt def create_color_palette(base_color: str, num_colors: int, as_cmap: bool) -> sns.palettes._ColorPalette: """ Create a color palette using seaborn's dark_palette function. Args: - base_color (str): The base color for the palette....
import pytest from tempfile import NamedTemporaryFile import pandas as pd import seaborn as sns from solution import create_color_palette, plot_data def test_create_color_palette_discrete(): palette = create_color_palette("seagreen", 5, False) assert isinstance(palette, sns.palettes._ColorPalette) assert l...
[ { "docstring": "Create a color palette using seaborn's dark_palette function.\n\nArgs:\n- base_color (str): The base color for the palette.\n- num_colors (int): The number of discrete colors in the palette.\n- as_cmap (bool): Whether to return a continuous colormap (True) or a discrete palette (False).\n\nRetur...
[ 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 pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndef create_color_palette(base_color: str, num_colors: int, as_cmap: bool):\n \"\"\"\n ...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033491", "row_id": 33491, "seed_ids": "[18]" }
0.652606
Docs: Seaborn_33491
I
[ "create_color_palette", "plot_data" ]
2
[ [ "plot_data", "create_color_palette" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "pandas", "seaborn" ]
false
10c6fb831bc01eb5fa69cbffc41071a9116d1222
af83ea6ef9fb77ef734320e05fba75a3d77ae373
v1.0
instruct
Docs
Docs: Python310_33538_I
#### Title: Concurrent Web Scraper with asyncio #### Objective Implement a concurrent web scraper using Python's `asyncio` library. Your scraper should fetch web pages concurrently and extract data from them. #### Problem Statement You are required to implement a concurrent web scraper that downloads and processes mu...
import asyncio import random from typing import List async def fetch_page(url: str) -> str: """ Simulates fetching a web page by sleeping for a random amount of time between 1 and 3 seconds. """ await asyncio.sleep(random.uniform(1, 3)) return f"<html><head><title>{url}</title></head><body>{'Hello ...
import pytest from solution import fetch_page, process_page, scrape import asyncio @pytest.mark.asyncio async def test_fetch_page(): url = "http://example.com" content = await fetch_page(url) assert content.startswith(f"<html><head><title>{url}</title></head><body>") assert content.endswith("</body></h...
[]
[ 0, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\nfrom typing import List\n\nasync def fetch_page(url: str) -> str:\n await asyncio.sleep(random.uniform(1, 3)) # Simulated network del...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00033538", "row_id": 33538, "seed_ids": "[270]" }
0.599551
Docs: Python310_33538
I
[ "fetch_page", "process_page", "fetch_and_process", "scrape" ]
4
[ [ "fetch_and_process", "fetch_page" ], [ "fetch_and_process", "process_page" ], [ "scrape", "fetch_and_process" ] ]
3
[]
false
[]
false
pytest
true
[]
true
f168762057750569feba95c899f1a631080ce403
1dc4dbc5ef5b224dc17ef68f407877c5ed36b021
v1.0
instruct
Docs
Docs: Python310_33553_I
### Python Networking and Asynchronous I/O Challenge You are to implement a simple secure chat server and client using the `asyncio` and `ssl` modules in Python. Your task is to create both the server and client program, with the server listening for incoming client connections and each client able to send and receive...
import asyncio import ssl import signal from datetime import datetime clients = [] async def broadcast(message: str): for client in clients: try: client.write(f"{message}\n".encode()) await client.drain() except: clients.remove(client) async def handle_client(r...
import asyncio import pytest from solution import handle_client, main, broadcast @pytest.fixture async def mock_server(): server = await asyncio.start_server(handle_client, '127.0.0.1', 8888) async with server: yield server.sockets[0].getsockname() async def test_handle_client(mock_server): reader...
[ { "docstring": null, "function_declaration": "def handle_sigint(signal, frame):", "function_name": "handle_sigint", "parameter_list": "(signal, frame)" } ]
[ 0, 1, 0, 1, 0, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport ssl\nimport signal\n\nclients = set()\n\nasync def handle_client(reader, writer):\n global clients\n client_address = writer.get_extra_info...
trial_gpt4o_1
{ "original_instruction": "", "prompt_id": "00033553", "row_id": 33553, "seed_ids": "[151]" }
0.640563
Docs: Python310_33553
I
[ "broadcast", "handle_client", "main", "handle_sigint" ]
4
[ [ "handle_client", "broadcast" ] ]
1
[]
false
[]
false
pytest
true
[]
true
b994fedde1a7050326571ff8cd28657b5eb92f35
b5a6f8b7db8eb356be6b7477990b492f469a613b
v1.0
instruct
Docs
Docs: Pytorch_33587_I
### PyTorch Coding Assessment Question: Custom Tracer with Dynamic Shape Handling #### Objective Implement a custom PyTorch function decorator to trace tensor operations, handling both constant and dynamic shapes while utilizing the Dynamo tracer capabilities described. #### Task Description Write a Python function d...
import torch import torch.fx as fx def custom_compile(fn): def wrapper(*args, **kwargs): class CustomTracer(fx.Tracer): def is_leaf_module(self, m, name): # Everything is a leaf module, including nn.Modules return False def create_proxy(self, kind, t...
from solution import custom_compile, test_custom_compile import torch def test_decorator_with_even_shape(): x = torch.randn(4) y = torch.randn(4) result = dynamic_mse(x, y) assert isinstance(result, torch.Tensor) assert result.shape == torch.Size([]) def test_decorator_with_odd_shape(): x = to...
[]
[ 0, 0, 0, 0, 1, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.fx import symbolic_trace\nimport torch.fx.experimental.symbolic_shapes as symbolic_shapes\n\n# Custom decorator to dynamically compile and trac...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00033587", "row_id": 33587, "seed_ids": "[122]" }
0.444229
Docs: Pytorch_33587
I
[ "custom_compile", "dynamic_mse", "test_custom_compile" ]
3
[ [ "test_custom_compile", "dynamic_mse" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
88360ac7a34aebd3ad7a27c1ef31099d5713e87c
973c130c6c72549a49e315add8c0672dc1cde420
v1.0
instruct
Docs
Docs: Scikit_33605_I
### Out-of-Core Learning with scikit-learn **Objective**: Implement an out-of-core learning system using scikit-learn that processes data too large to fit into memory, by performing incremental learning with streaming instances and feature extraction. **Problem Statement**: You are provided with a large dataset cons...
import numpy as np from sklearn.linear_model import SGDClassifier from sklearn.feature_extraction.text import HashingVectorizer def stream_documents(file_path): """ Generator function to stream documents from a file. Parameters: - file_path (str): Path to the file containing the dataset. ...
import pytest from solution import stream_documents, incremental_learning import os def test_stream_documents(tmp_path): test_file = tmp_path / "test_file.txt" test_content = "document1\tclass1\ndocument2\tclass2\ndocument3\tclass1" test_file.write_text(test_content) streamed_docs = list(stream_docume...
[ { "docstring": "Generator function to stream documents from a file.\n\nParameters:\n- file_path (str): Path to the file containing the dataset.\n\nYields:\n- document (str), category (str): A single document and its category from the file.", "function_declaration": "def stream_documents(file_path):", "f...
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.feature_extraction.text import HashingVectorizer\n\ndef stream_documents(file_path):\n ...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00033605", "row_id": 33605, "seed_ids": "[63]" }
0.478852
Docs: Scikit_33605
I
[ "stream_documents", "incremental_learning" ]
2
[ [ "incremental_learning", "stream_documents" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
dc89d2cf3f8d48b59f79435e0e54f84703db4ca2
5f2bd5db58c4d76c5db5ccf560f00ed0699cbbe4
v1.0
instruct
Docs
Docs: Python310_33674_I
### Question: Custom Python Initialization You are tasked with creating a custom Python environment that initializes Python in isolated mode, sets specific configuration parameters, and runs a Python command. Write a Python program that achieves the following: 1. **Initializes Python in isolated mode** using the `PyC...
class PyStatus: def __init__(self, ok=True, exit_code=0, err_msg=None): self.ok = ok self.exit_code = exit_code self.err_msg = err_msg class PyConfig: def __init__(self): self.isolated = 0 self.use_environment = 1 self.site_import = 1 self.utf8_mode = 0 ...
from solution import PyConfig, Py_InitializeFromConfig, PyConfig_InitIsolatedConfig, run_custom_python def test_pyconfig_initialization(): config = PyConfig() PyConfig_InitIsolatedConfig(config) config.utf8_mode = 1 config.allocator = "PYMEM_ALLOCATOR_MALLOC" status = Py_InitializeFromConfig(c...
[]
[ 0, 0, 1, 1, 0, 1, 0, 0, 0, 1 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "# Simulated PyStatus class to represent the status of Python initialization\nclass PyStatus:\n def __init__(self, ok=True, exit_code=0, err_msg=None):\n self....
trial_gpt4o_3
{ "original_instruction": "", "prompt_id": "00033674", "row_id": 33674, "seed_ids": "[15]" }
0.474728
Docs: Python310_33674
I
[ "PyConfig_InitIsolatedConfig", "Py_InitializeFromConfig", "run_custom_python" ]
3
[ [ "run_custom_python", "PyConfig_InitIsolatedConfig" ], [ "run_custom_python", "Py_InitializeFromConfig" ] ]
2
[]
false
[ "PyStatus", "PyConfig" ]
true
pytest
true
[]
true
df7def4e100a2227b66434ca4beb17e8b0a0671c
22c5be3dc35fe3364d80c59f8794c83165ebed0b
v1.0
instruct
Docs
Docs: Python310_33676_I
**Title**: Implement a Custom Iterator Function in Python **Objective**: Create a Python function that uses the iterator-related C-API functionalities from the provided documentation. This exercise will test your proficiency in handling Python's iterator protocols and error management. **Description**: You are provi...
import asyncio def process_iterator(lst: list, async_flag: bool) -> int: """ Processes a list of integers using synchronous or asynchronous iteration. Parameters: lst (list): The list of integers to be iterated over. async_flag (bool): A flag indicating whether to use asynchronous iter...
from solution import process_iterator def test_process_iterator_sync(): assert process_iterator([1, 2, 3, 4, 5], False) == 15 def test_process_iterator_async(): assert process_iterator([1, 2, 3, 4, 5], True) == 15 def test_process_iterator_empty_sync(): assert process_iterator([], False) == 0 def test_p...
[ { "docstring": "Processes a list of integers using synchronous or asynchronous iteration.\n\nParameters:\n lst (list): The list of integers to be iterated over.\n async_flag (bool): A flag indicating whether to use asynchronous iteration.\n\nReturns:\n int: The sum of the integers in the list.", "f...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "def process_iterator(lst: list, async_flag: bool) -> int:\n \"\"\"\n Sums up all integers in the given list `lst`.\n Handles both synchronous and asynchronous ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00033676", "row_id": 33676, "seed_ids": "[58]" }
0.590172
Docs: Python310_33676
I
[ "process_iterator", "_sync_sum", "_async_sum" ]
3
[ [ "process_iterator", "_async_sum" ], [ "process_iterator", "_sync_sum" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e0ea1ea9232f1e7d3edfa5e8886852ab64e32dfa
16e5851eafe161bff12b688bae39a36251d2a92e
v1.0
instruct
Docs
Docs: Python310_33686_I
#### Title: Advanced Usage of Python's io Module for Text and Binary I/O Operations #### Problem Statement: You are tasked with developing a utility for reading, manipulating, and writing data from and to text and binary files using Python's `io` module. #### Requirements: 1. **Functionality 1: Read Text File** -...
import os import io def read_text_file(file_path: str) -> str: try: with io.open(file_path, 'r', encoding='utf-8') as file: return file.read() except FileNotFoundError: raise FileNotFoundError(f"File at {file_path} does not exist.") except Exception as e: raise IOError(f...
import pytest import io import os from solution import read_text_file, write_text_file, read_binary_file, write_binary_file, combine_and_save_files # Helper functions to set up and tear down test files def setup_text_file(path, content): with open(path, 'w', encoding='utf-8') as f: f.write(content) def s...
[ { "docstring": null, "function_declaration": "def read_text_file(file_path):", "function_name": "read_text_file", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def write_text_file(file_path, content):", "function_name": "write_text_file", "param...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport io\n\ndef read_text_file(file_path: str) -> str:\n try:\n with io.open(file_path, 'r', encoding='utf-8') as file:\n return file.r...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00033686", "row_id": 33686, "seed_ids": "[155]" }
0.540946
Docs: Python310_33686
I
[ "read_text_file", "write_text_file", "read_binary_file", "write_binary_file", "combine_and_save_files" ]
5
[ [ "combine_and_save_files", "read_binary_file" ], [ "combine_and_save_files", "read_text_file" ], [ "combine_and_save_files", "write_binary_file" ] ]
3
[]
false
[]
false
pytest
true
[]
true
89f51b48fbefcba84c47ef85f03f68e9012ca517
846e312418feb368b18da0cfcb93a09f71e96a11
v1.0
instruct
Docs
Docs: Python310_33688_I
You are required to implement a simple WSGI application using the `wsgiref` module that serves static files from a specified directory. The application should meet the following requirements: 1. **Directory Listing and File Serving:** - The application should serve files from a specified directory. - If the re...
import os from wsgiref.simple_server import make_server from wsgiref.util import setup_testing_defaults, FileWrapper from wsgiref.headers import Headers import mimetypes def simple_file_server_application(environ, start_response): setup_testing_defaults(environ) path = environ.get('PATH_INFO', '').lstrip(...
import os import tempfile import shutil import pytest from wsgiref.util import setup_testing_defaults from io import BytesIO from solution import simple_file_server_application @pytest.fixture(scope='module') def test_dir(): base_dir = tempfile.mkdtemp() subdir = os.path.join(base_dir, 'subdir') os.makedir...
[ { "docstring": null, "function_declaration": "def simple_file_server_application(environ, start_response):", "function_name": "simple_file_server_application", "parameter_list": "(environ, start_response)" }, { "docstring": null, "function_declaration": "def run_server(directory, port=80...
[ 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\nfrom wsgiref.util import setup_testing_defaults, FileWrapper\nfrom wsgiref.headers import Headers\nfrom wsgiref.simple_server import make_server\nimport mime...
trial_gpt4o_4
{ "original_instruction": "", "prompt_id": "00033688", "row_id": 33688, "seed_ids": "[210]" }
0.549463
Docs: Python310_33688
I
[ "simple_file_server_application", "run_server" ]
2
[ [ "run_server", "simple_file_server_application" ] ]
1
[]
false
[]
false
pytest
true
[]
true
03b2a9833ddeecb82c03f1d35bda66424a4f28a0
45e259e6586f35b36d16b1e2295fa4863284530a
v1.0
instruct
Docs
Docs: Python310_33723_I
Handling MIME Type Command Execution #### Problem Statement You are given a deprecated module called `mailcap` which provides functionality for handling MIME type configurations often used in email clients and web browsers. Your task is to use this module to retrieve the mailcap entries from the system and to implemen...
import mailcap import re def get_mailcap_entries(): """ Retrieves the mailcap entries from the system Returns: dict: A dictionary mapping MIME types to their mailcap entries. """ return mailcap.getcaps() def execute_mime_viewer(mime_type, filename): """ Finds and returns the viewer...
import mailcap import pytest from solution import get_mailcap_entries, execute_mime_viewer def test_get_mailcap_entries(): # This only checks that a dictionary is returned and is non-empty if possible result = get_mailcap_entries() assert isinstance(result, dict) assert bool(result) # The dictionary s...
[ { "docstring": "Retrieves the mailcap entries from the system\nReturns:\n dict: A dictionary mapping MIME types to their mailcap entries.", "function_declaration": "def get_mailcap_entries():", "function_name": "get_mailcap_entries", "parameter_list": "()" }, { "docstring": "Finds and ret...
[ 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import mailcap\nimport re\n\ndef get_mailcap_entries():\n \"\"\"\n Retrieve mailcap entries from the system.\n \n Returns:\n dict: Dictionary mapping...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033723", "row_id": 33723, "seed_ids": "[399]" }
0.493711
Docs: Python310_33723
I
[ "get_mailcap_entries", "execute_mime_viewer" ]
2
[ [ "execute_mime_viewer", "get_mailcap_entries" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6cad1512bb4fecbd13ebc6280910e06d172ba7b9
4e5bf256a868822dd89132d82be919f8a0eab2e2
v1.0
instruct
Docs
Docs: Scikit_33747_I
### Question: ### Prediction Latency and Sparse Data Handling in Scikit-learn You are tasked with analyzing and optimizing the prediction latency and throughput of different scikit-learn models using both dense and sparse input data representations. This involves conducting benchmarks to measure the impact of various...
import numpy as np from scipy.sparse import csr_matrix from sklearn.datasets import make_classification from time import perf_counter from sklearn.metrics import accuracy_score def convert_to_sparse(X): """ Converts a dense dataset to a sparse CSR format. Parameters: - X (np.ndarray): Dense input data...
from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from solution import benchmark_models, convert_to_sparse def test_convert_to_sparse(): X_dense = np.array([[1, 0, 3], [0, 0, 6], [7, 0, 9]]) X_sparse = convert_to_sparse(X_dense) assert X_sparse.shape ==...
[ { "docstring": "Converts a dense dataset to a sparse CSR format.\n\nParameters:\n- X (np.ndarray): Dense input dataset.\n\nReturns:\n- X_sparse (scipy.sparse.csr_matrix): Sparse CSR representation of the input dataset.", "function_declaration": "def convert_to_sparse(X):", "function_name": "convert_to_s...
[ 1, 1, 1, 1, 1, 1, 0, 0, 0 ]
6
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 scipy.sparse import csr_matrix\nfrom time import perf_counter\nfrom sklearn.datasets import make_classification\n\ndef benchmark_models(models,...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00033747", "row_id": 33747, "seed_ids": "[64]" }
0.460994
Docs: Scikit_33747
I
[ "convert_to_sparse", "benchmark_models" ]
2
[ [ "benchmark_models", "convert_to_sparse" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "scipy", "sklearn" ]
false
3dd60c2d31fddce56daee98ed213bfb4cb78f705
404f0cdbc1fd2fdec62ce3de5ae9c71b1ee93b2d
v1.0
instruct
Docs
Docs: Scikit_33769_I
**Title: Implement and Evaluate Different Naive Bayes Classifiers** **Background:** You are provided with a dataset in CSV format containing textual data and associated labels. Your task is to implement and evaluate different Naive Bayes classifiers from the scikit-learn library on this dataset. The classifiers to be ...
import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB, ComplementNB, BernoulliNB from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score def load_data(file_path): ...
import pytest from sklearn.datasets import fetch_20newsgroups import pandas as pd # Assuming the above code is saved in a file named solution.py from solution import naive_bayes_classifiers # Create a temporary dataset for testing def create_temp_csv(): data = fetch_20newsgroups(subset='train') df = pd.DataFr...
[ { "docstring": null, "function_declaration": "def load_data(file_path):", "function_name": "load_data", "parameter_list": "(file_path)" }, { "docstring": null, "function_declaration": "def preprocess_data(text_data):", "function_name": "preprocess_data", "parameter_list": "(text_...
[ 0, 0, 1, 1, 1, 1, 1, 1, 0, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import ...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00033769", "row_id": 33769, "seed_ids": "[61]" }
0.526288
Docs: Scikit_33769
I
[ "load_data", "preprocess_data", "evaluate_model", "naive_bayes_classifiers" ]
4
[ [ "naive_bayes_classifiers", "evaluate_model" ], [ "naive_bayes_classifiers", "load_data" ], [ "naive_bayes_classifiers", "preprocess_data" ] ]
3
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
1992f872230d677389c86fb4aae5c371c6a8c4f3
f2f767914234bc2357f81be941d9eaac124d06ec
v1.0
instruct
Docs
Docs: Python310_33783_I
**Question: Context Management with Context Variables** In this problem, you will implement a simplified version of a context management system using the `contextvars` module in Python. You are required to demonstrate your understanding of creating, setting, and getting context variables, as well as managing contexts ...
import contextvars # Context variables context_user = contextvars.ContextVar("user") context_request_id = contextvars.ContextVar("request_id") def initialize_context(): """ Initializes the context and sets initial values for context variables. """ context_user.set(None) context_request_id.set(None...
from solution import initialize_context, set_context_var, get_context_var, save_current_context, switch_context, restore_context def test_initialize_context(): initialize_context() assert get_context_var("user") is None assert get_context_var("request_id") is None def test_set_context_var(): initializ...
[ { "docstring": "Initializes the context and sets initial values for context variables.", "function_declaration": "def initialize_context():", "function_name": "initialize_context", "parameter_list": "()" }, { "docstring": "Sets the value of a specified context variable.", "function_decla...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import contextvars\n\n# Create two context variables: \"user\" and \"request_id\"\nuser = contextvars.ContextVar(\"user\", default=None)\nrequest_id = contextvars.Conte...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00033783", "row_id": 33783, "seed_ids": "[60]" }
0.390546
Docs: Python310_33783
I
[ "initialize_context", "set_context_var", "get_context_var", "save_current_context", "switch_context", "restore_context" ]
6
[ [ "restore_context", "switch_context" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3b5ba4956fc59e8ce322cecb404c12d45fa44878
f0242a7ef8a95b3e05fed380e4a57662db875a9f
v1.0
instruct
Docs
Docs: Pytorch_33784_I
#### Objective: Implement a distributed training setup using PyTorch's `torch.distributed` package. Your implementation should initialize the distributed process group, parallelize a simple neural network model training across multiple GPUs, and ensure synchronization of gradients between devices. ### Task: 1. **Initi...
import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim from torch.nn.parallel import DistributedDataParallel as DDP import os def setup(rank, world_size): os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = '12355' dist.init_process_group("nccl", ran...
from solution import Net import torch def test_net_structure(): model = Net() assert isinstance(model.fc1, torch.nn.Linear) assert isinstance(model.fc2, torch.nn.Linear) assert isinstance(model.relu, torch.nn.ReLU) x = torch.randn(10, 10) output = model(x) assert output.shape == (10, ...
[]
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.nn.parallel import DistributedDataParallel as ...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033784", "row_id": 33784, "seed_ids": "[145]" }
0.473146
Docs: Pytorch_33784
I
[ "setup", "cleanup", "train" ]
3
[ [ "train", "cleanup" ], [ "train", "setup" ] ]
2
[]
false
[ "Net" ]
true
pytest
true
[ "torch" ]
false
52f62506cf647f0c264f66156bd5c38c1a255e95
9c828a6a18815d7bc9a967e6aaedb4903ef1e252
v1.0
instruct
Docs
Docs: Python310_33809_I
**Coding Challenge: Parallel Matrix Multiplication Using Multiprocessing** **Objective:** Implement a function to perform matrix multiplication using Python's `multiprocessing` module. This task aims to assess your understanding of creating processes, using pools, and inter-process communication. **Problem Statement...
from multiprocessing import Pool def matrix_element(A, B, row, col): """ Compute a single element of the resulting matrix """ return sum(A[row][i] * B[i][col] for i in range(len(B))) def parallel_matrix_multiply(A, B): """ Multiply two matrices A and B using multiprocessing """ num_row...
from solution import parallel_matrix_multiply def test_parallel_matrix_multiply_small(): A = [ [1, 2], [3, 4] ] B = [ [5, 6], [7, 8] ] assert parallel_matrix_multiply(A, B) == [[19, 22], [43, 50]] def test_parallel_matrix_multiply_identity(): A = [ [1, 2...
[ { "docstring": "Compute a single element of the resulting matrix", "function_declaration": "def matrix_element(A, B, row, col):", "function_name": "matrix_element", "parameter_list": "(A, B, row, col)" }, { "docstring": "Multiply two matrices A and B using multiprocessing", "function_dec...
[ 1, 1, 1, 1, 1, 0, 1, 0, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from multiprocessing import Pool\n\ndef single_element_multiply(row, column):\n return sum(x * y for x, y in zip(row, column))\n\ndef get_column(matrix, col_index):\...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00033809", "row_id": 33809, "seed_ids": "[338]" }
0.611996
Docs: Python310_33809
I
[ "matrix_element", "parallel_matrix_multiply" ]
2
[ [ "parallel_matrix_multiply", "matrix_element" ] ]
1
[]
false
[]
false
pytest
true
[]
true
289decd78e251607f04e0e0e624152e99fc0fcc4
8fad15d34cd6765a9ea5927851a1fad0e56be0ec
v1.0
instruct
Docs
Docs: Python310_33812_I
**Async Task and Network Programming with asyncio** ### Problem Statement You are to implement an asynchronous solution that fulfills the following requirements: 1. **Subprocess Management**: - Create an asynchronous function that runs a subprocess to execute a shell command ("ping -c 1 google.com" to ping Google...
import asyncio import subprocess from asyncio import Queue from typing import List async def ping_url(url: str) -> str: """ Run a subprocess to ping the URL and return the result. """ try: proc = await asyncio.create_subprocess_shell( f"ping -c 1 {url}", stdout=asyncio.s...
import pytest import asyncio from solution import ping_url, process_queue, tcp_server, main @pytest.mark.asyncio async def test_ping_url_success(): result = await ping_url("google.com") assert "1 packets transmitted" in result @pytest.mark.asyncio async def test_ping_url_failure(): result = await ping_url...
[]
[ 0, 1, 1, 0, 0, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport subprocess\nfrom typing import List\n\nasync def ping_url(url: str) -> str:\n \"\"\"\n Runs a subprocess to ping the URL and return the res...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00033812", "row_id": 33812, "seed_ids": "[360]" }
0.576887
Docs: Python310_33812
I
[ "ping_url", "process_queue", "tcp_server", "main" ]
4
[ [ "process_queue", "ping_url" ], [ "tcp_server", "ping_url" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a435c829508918a0149a96ee4a13762c7fc79e13
660d674123e4cfde6741ef152bfe3409a11fbbd3
v1.0
instruct
Docs
Docs: Python310_33860_I
#### Context You are developing a secure file verification system using Python. This system should be able to: 1. Calculate a hash of a given file to ensure its integrity. 2. Use salting to protect against collision attacks. 3. Allow verification of the file’s hash. #### Task Implement a Python function `generate_sec...
import hashlib def generate_secure_hash(file_path: str, salt: bytes, algorithm: str) -> str: """ Generate a secure hash of a file with the specified algorithm and salt. Parameters: - file_path (str): Path to the file. - salt (bytes): Salt value to be used. - algorithm (str): Hashing algorithm ...
import os import pytest @pytest.fixture def create_test_file(tmp_path): """ Fixture to create a temporary test file with some content. """ file_content = b"Sample content for hashing" file_path = tmp_path / "test_file.txt" with open(file_path, "wb") as f: f.write(file_content) retur...
[ { "docstring": "Generate a secure hash of a file with the specified algorithm and salt.\n\nParameters:\n- file_path (str): Path to the file.\n- salt (bytes): Salt value to be used.\n- algorithm (str): Hashing algorithm to be used (e.g., 'sha256', 'blake2b').\n\nReturns:\n- str: The hexadecimal hash string.", ...
[ 1, 0, 0, 1, 1, 1, 1, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import hashlib\n\ndef generate_secure_hash(file_path: str, salt: bytes, algorithm: str) -> str:\n \"\"\"\n Generate a secure hash for a given file using the speci...
trial_gpt4o_8
{ "original_instruction": "", "prompt_id": "00033860", "row_id": 33860, "seed_ids": "[225]" }
0.69215
Docs: Python310_33860
I
[ "generate_secure_hash", "verify_file_hash" ]
2
[ [ "verify_file_hash", "generate_secure_hash" ] ]
1
[]
false
[]
false
pytest
false
[]
true
b716aa5eef0a094bbd94cea4f5acfcfaa8e96aa8
19cd89fd4692ed587c70247acf63ef6d8705125b
v1.0
instruct
Docs
Docs: Python310_33910_I
### **Random Walk Simulation** **Objective:** Develop a simulation of a random walk using the Python `random` module. **Problem Statement:** A random walk is a mathematical formalization to describe a path that consists of a series of random steps. Consider a simple 1-dimensional random walk starting at position `0`....
import random def random_walk(steps): if steps < 0: raise ValueError("Number of steps cannot be negative") position = 0 walk = [position] for _ in range(steps): step = random.choice([-1, 1]) position += step walk.append(position) return walk def simulate_walks(num_w...
import pytest from solution import random_walk, simulate_walks, analyze_walks def test_random_walk_negative_steps(): with pytest.raises(ValueError): random_walk(-1) def test_random_walk(): random.seed(0) # To make the test deterministic walk = random_walk(10) assert walk[0] == 0 assert le...
[ { "docstring": null, "function_declaration": "def random_walk(steps):", "function_name": "random_walk", "parameter_list": "(steps)" }, { "docstring": null, "function_declaration": "def simulate_walks(num_walks, steps):", "function_name": "simulate_walks", "parameter_list": "(num_...
[ 0, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\n\ndef random_walk(steps):\n if steps < 0:\n raise ValueError(\"Number of steps cannot be negative\")\n position = 0\n walk = [position]\n...
trial_gpt4o_7
{ "original_instruction": "", "prompt_id": "00033910", "row_id": 33910, "seed_ids": "[119]" }
0.780545
Docs: Python310_33910
I
[ "random_walk", "simulate_walks", "analyze_walks" ]
3
[ [ "simulate_walks", "random_walk" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ff8ac63c7b64dc6a238fd786a445e4ec2e24ce65
4066b7eb2756908d0c82e4dafe7441aa8ad89c97
v1.0
instruct
Docs
Docs: Pytorch_34051_I
### PyTorch dtype Properties Assessment #### Objective Your task is to demonstrate your understanding of PyTorch's numerical properties of dtypes using the `torch.finfo` and `torch.iinfo` classes. You will write functions to extract and compare these properties for given dtypes. #### Problem 1. **Function `get_floa...
import torch def get_floating_point_info(dtype): """ Returns a dictionary with properties of the floating-point dtype. """ finfo = torch.finfo(dtype) return { "bits": finfo.bits, "eps": finfo.eps, "max": finfo.max, "min": finfo.min, "tiny": finfo.tiny, ...
from solution import get_floating_point_info, get_integer_info, compare_dtypes import torch def test_get_floating_point_info(): info = get_floating_point_info(torch.float64) assert info["bits"] == 64 assert info["eps"] > 0 assert info["max"] > 0 assert info["min"] < 0 assert info["tiny"] > 0 ...
[ { "docstring": "Returns a dictionary with properties of the floating-point dtype.", "function_declaration": "def get_floating_point_info(dtype):", "function_name": "get_floating_point_info", "parameter_list": "(dtype)" }, { "docstring": "Returns a dictionary with properties of the integer dt...
[ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\n\ndef get_floating_point_info(dtype):\n \"\"\"\n Returns the properties of a floating-point dtype in PyTorch.\n \n Parameters:\n dtype (tor...
trial_gpt4o_2
{ "original_instruction": "", "prompt_id": "00034051", "row_id": 34051, "seed_ids": "[52]" }
0.406303
Docs: Pytorch_34051
I
[ "get_floating_point_info", "get_integer_info", "compare_dtypes" ]
3
[ [ "compare_dtypes", "get_floating_point_info" ], [ "compare_dtypes", "get_integer_info" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
3be72d2fed23ab7d9f4a3ce70fc6274adc6e9068
f99d7f96116386c891abac293722861ba5eb00c1
v1.0
instruct
Docs
Docs: Python310_34113_I
### Type Object Manipulation and Creation In this assessment, you will demonstrate your understanding of Python's type objects and their manipulation by creating and interacting with custom heap-allocated types based on the provided documentation. #### Task 1. **Type Checking Function** - Implement a function in ...
import ctypes def is_type_object(obj): """ Checks if the given object is a type object. Args: obj (Any): The object to check. Returns: bool: True if the object is a type object, False otherwise. """ return isinstance(obj, type) def create_custom_type(name, base=object): """ C...
from solution import is_type_object, create_custom_type, interact_with_custom_type def test_is_type_object(): assert is_type_object(int) == True assert is_type_object(str) == True assert is_type_object(123) == False assert is_type_object('abc') == False assert is_type_object(None) == False def tes...
[]
[ 1, 1, 0, 1, 0, 1, 0, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import types\n\ndef is_type_object(obj):\n \"\"\"\n Checks if the given object is a type object.\n \n Args:\n obj (Any): The object to check.\n \n ...
trial_gpt4o_9
{ "original_instruction": "", "prompt_id": "00034113", "row_id": 34113, "seed_ids": "[48]" }
0.487811
Docs: Python310_34113
I
[ "is_type_object", "create_custom_type", "interact_with_custom_type" ]
3
[ [ "interact_with_custom_type", "create_custom_type" ] ]
1
[]
false
[]
false
pytest
true
[]
true
23ae13a8f1a561d1b4c1242cede62a7488675146
c5a8d8e9b98760a56846104b5832fd114ea223b3
v1.0
instruct
Docs
Docs: Python310_34118_I
#### Objective Demonstrate your understanding of Python's asyncio library by creating a concurrent file download manager using `asyncio` that downloads files from the internet and stores them locally. #### Problem Statement Write a Python function `download_files(urls: List[str]) -> None` that asynchronously downloads...
import asyncio import aiohttp import os from typing import List async def download_file(session, url, path): try: async with session.get(url) as response: response.raise_for_status() total_size = int(response.headers.get('content-length', 0)) downloaded_size = 0 ...
import asyncio from unittest.mock import patch, mock_open from solution import download_files def test_download_files(monkeypatch): async def mock_response(url, path='tempfile'): class MockResponse: def __init__(self): self.headers = {'content-length': '1024'} se...
[]
[ 1, 1, 1, 0, 0, 0, 0, 0, 1, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\nimport os\nfrom typing import List\n\nasync def download_file(session, url, path):\n try:\n async with session.get(url) as res...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00034118", "row_id": 34118, "seed_ids": "[270]" }
0.586053
Docs: Python310_34118
I
[ "download_file", "download_files" ]
2
[ [ "download_files", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
0f75ddbdb65b8931bf637f01c0aeaf2058c33f9b
ea8c57faafc5a779a0ccb1823bfe749a93f6ff1d
v1.0
instruct
Docs
Docs: Python310_34139_I
**Problem Statement:** Design and implement a Python program that enhances the Python interactive shell experience by implementing a command history management feature using the "readline" module. The program should support loading command history from a file, allowing the user to interactively input commands, and sa...
import atexit import os import readline def load_command_history(histfile: str) -> None: try: readline.read_history_file(histfile) print("History loaded successfully.") except FileNotFoundError: open(histfile, 'wb').close() print("History file not found. Created a new history fi...
import pytest import os import readline from solution import load_command_history, save_command_history, interactive_shell @pytest.fixture def mock_histfile(tmp_path): return os.path.join(tmp_path, "history_file") def test_load_command_history_file_not_found(mock_histfile): load_command_history(mock_histfile)...
[ { "docstring": null, "function_declaration": "def load_command_history(histfile):", "function_name": "load_command_history", "parameter_list": "(histfile)" }, { "docstring": null, "function_declaration": "def save_command_history(prev_h_len, histfile):", "function_name": "save_comman...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import atexit\nimport os\nimport readline\n\ndef load_command_history(histfile: str) -> None:\n try:\n readline.read_history_file(histfile)\n print(\"H...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00034139", "row_id": 34139, "seed_ids": "[362]" }
0.427416
Docs: Python310_34139
I
[ "load_command_history", "save_command_history", "interactive_shell" ]
3
[ [ "interactive_shell", "load_command_history" ], [ "interactive_shell", "save_command_history" ] ]
2
[]
false
[]
false
pytest
true
[]
true
d25eb550bb214ec8c9d03c6befdf3998dfc97fd5
3be713070ba0612e4e90270abca5c7c0682075a4
v1.0
instruct
Docs
Docs: Pytorch_34150_I
**Question: Implement Distributed Data Parallel Training with PyTorch** Given the PyTorch DDP documentation, your task is to implement a distributed data parallel training script using PyTorch's `torch.nn.parallel.DistributedDataParallel` (DDP) module. You will use a simple neural network model and distribute the trai...
import os import torch import torch.distributed as dist import torch.multiprocessing as mp import torch.nn as nn import torch.optim as optim from torch.nn.parallel import DistributedDataParallel as DDP # Provided SimpleNN model class SimpleNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): ...
from solution import SimpleNN def test_simple_nn_initialization(): model = SimpleNN(10, 50, 10) assert isinstance(model.hidden, nn.Linear), "Hidden layer should be an instance of nn.Linear" assert isinstance(model.relu, nn.ReLU), "ReLU layer should be an instance of nn.ReLU" assert isinstance(model.out...
[]
[ 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.nn.paralle...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00034150", "row_id": 34150, "seed_ids": "[181]" }
0.465948
Docs: Pytorch_34150
I
[ "setup", "cleanup", "train", "main" ]
4
[ [ "train", "cleanup" ], [ "train", "setup" ] ]
2
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
d028352ad3eb29c31a0a201125add08220d4d97e
a3ec8196a179daba15fe8cda6d0e16107f276bbc
v1.0
instruct
Docs
Docs: Python310_34155_I
**Concurrent Web Scraper with Thread Pool** You are required to implement a web scraper that fetches the content from a list of URLs concurrently using the `concurrent.futures` module's `ThreadPoolExecutor`. Your task is to ensure efficient and thread-safe handling of the fetched data. ### Problem Statement Write a f...
import requests from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List, Dict def fetch_content(url: str) -> (str, str): try: response = requests.get(url, timeout=10) response.raise_for_status() return url, response.text except (requests.ConnectionError, ...
from solution import concurrent_scraper from unittest.mock import patch def mock_requests_get(url, timeout=10): class MockResponse: def __init__(self, url): self.url = url if "fail" in url: self.status_code = 404 self.text = None else: ...
[ { "docstring": null, "function_declaration": "def fetch_content(url):", "function_name": "fetch_content", "parameter_list": "(url)" }, { "docstring": null, "function_declaration": "def concurrent_scraper(urls):", "function_name": "concurrent_scraper", "parameter_list": "(urls)" ...
[ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import requests\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List, Dict\n\ndef fetch_content(url: str) -> (str, str):\n try:\...
trial_gpt4o_0
{ "original_instruction": "", "prompt_id": "00034155", "row_id": 34155, "seed_ids": "[206]" }
0.575446
Docs: Python310_34155
I
[ "fetch_content", "concurrent_scraper" ]
2
[ [ "concurrent_scraper", "fetch_content" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
43636cc41edf55d3f03a7066bf04d78b1e9f8110
0ebacbb2e00fe114588792bb09fa21335e5a20a0
v1.0
instruct
Docs
Docs: Pytorch_34171_I
### Question: Working with Named Tensors in PyTorch #### Objective In this assignment, you will work with named tensors in PyTorch to ensure the correct propagation of names through various tensor operations. Named tensors provide additional runtime correctness checks and improve code readability. #### Part 1: Creati...
import torch from typing import List, Tuple def create_named_tensor(shape: List[int], names: List[str]) -> torch.Tensor: """ Create a PyTorch tensor with specified shape and named dimensions. Args: shape (List[int]): A list of integers representing the shape of the tensor. names (List[str]): A...
import pytest import torch from solution import create_named_tensor, named_tensor_operations def test_create_named_tensor(): tensor = create_named_tensor([2, 3, 4], ['N', 'C', 'H']) assert tensor.shape == torch.Size([2, 3, 4]) assert tensor.names == ('N', 'C', 'H') def test_named_tensor_operations_broadca...
[ { "docstring": "Create a PyTorch tensor with specified shape and named dimensions.\n\nArgs:\nshape (List[int]): A list of integers representing the shape of the tensor.\nnames (List[str]): A list of strings representing the names of the tensor's dimensions.\n\nReturns:\ntorch.Tensor: A PyTorch tensor with the s...
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom typing import List\n\ndef create_named_tensor(shape: List[int], names: List[str]) -> torch.Tensor:\n if len(shape) != len(names):\n raise V...
trial_gpt4o_6
{ "original_instruction": "", "prompt_id": "00034171", "row_id": 34171, "seed_ids": "[72]" }
0.574324
Docs: Pytorch_34171
I
[ "create_named_tensor", "named_tensor_operations" ]
2
[ [ "named_tensor_operations", "create_named_tensor" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
82606ee9cd24e300dcf9ff6b277a1e435a3a8334
b801765133e9baeab005b1eaf2e32546fe20fce8