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_37487_I | **Question: Implement an Asynchronous File Reader with Platform Constraints**
You are required to implement an asynchronous file reader using Python's `asyncio` module. The file reader should be capable of reading from a file and processing each line asynchronously. Your solution should account for platform-specific c... | import asyncio
import platform
async def process_line(line):
print(line.strip())
await asyncio.sleep(0.1)
async def async_file_reader(file_path: str) -> None:
system = platform.system()
if system == "Windows":
# Use ProactorEventLoop for Windows
asyncio.set_event_loop_policy(asyncio.Wi... | import asyncio
from solution import async_file_reader
import pytest
@pytest.mark.asyncio
async def test_async_file_reader(tmp_path):
test_file_path = tmp_path / "test.txt"
content = "Line 1\nLine 2\nLine 3\n"
test_file_path.write_text(content)
# Capture print output
from io import StringIO
imp... | [] | [
1,
0,
1,
1,
1,
0,
1,
1,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport platform\n\nasync def async_file_reader(file_path: str) -> None:\n \"\"\"\n Asynchronously reads and processes each line of the given file.... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00037487",
"row_id": 37487,
"seed_ids": "[370]"
} | 0.422116 | Docs: Python310_37487 | I | [
"process_line",
"async_file_reader"
] | 2 | [
[
"async_file_reader",
"process_line"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a91c86826a0fbee820bbe91257f4c455b6cd6d3f | 1df7c5382eb78dd3fb6252ff9a7eb6d0bb4ea52e | |||
v1.0 | instruct | Docs | Docs: Pytorch_37505_I | ### Distributed Checkpoint in PyTorch
You are tasked with simulating a distributed training environment using PyTorch's `torch.distributed.checkpoint` module for saving and loading checkpoints. Your goal is to manage the state dictionaries of a model and optimizer across multiple devices.
### Objective
Implement a s... | import torch
import torch.nn as nn
import torch.optim as optim
import os
from torch.distributed import init_process_group, destroy_process_group
# Define a simple feedforward neural network
class SimpleNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(SimpleNN, self).__init__()... | import os
import torch
import torch.nn as nn
import torch.optim as optim
from solution import SimpleNN, save_checkpoint, load_checkpoint
def test_save_load_checkpoint():
model = SimpleNN(input_size=10, hidden_size=20, output_size=1)
optimizer = optim.SGD(model.parameters(), lr=0.01)
checkpoint_path = './ch... | [] | [
0,
0,
1,
0,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport os\nfrom torch.distributed.checkpoint import save, load\nimport torch.distributed.checkpoint as... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00037505",
"row_id": 37505,
"seed_ids": "[30]"
} | 0.526319 | Docs: Pytorch_37505 | I | [
"save_checkpoint",
"load_checkpoint",
"run_training",
"main"
] | 4 | [
[
"run_training",
"load_checkpoint"
],
[
"run_training",
"save_checkpoint"
]
] | 2 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"torch"
] | false | 41b0ce0afa4ce70defd26cfea181b70b0f850c36 | 8f2d61947de8edcd2519790754ac51ce5c1d5490 | |||
v1.0 | instruct | Docs | Docs: Python310_37605_I | ### Custom Asyncio Event Loop Policy with Process Watcher
**Objective**:
Implement a custom event loop policy that integrates a specialized process watcher capable of handling subprocess lifecycle events efficiently using threads.
**Problem Statement**:
You are required to create a custom event loop policy and a thre... | import asyncio
import subprocess
class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):
def get_event_loop(self):
print("Custom get_event_loop called")
return super().get_event_loop()
class MyThreadedChildWatcher(asyncio.ThreadedChildWatcher):
def add_child_handler(self, pid, callback, *args... | import asyncio
import subprocess
from solution import MyEventLoopPolicy, MyThreadedChildWatcher, run_custom_event_loop
async def test_create_subprocess():
process = await create_subprocess()
assert process.returncode == 0
stdout, stderr = await process.communicate()
assert stdout.decode().strip() == 'h... | [] | [
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport subprocess\n\nclass MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):\n def get_event_loop(self):\n print(\"Custom get_event_loop call... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00037605",
"row_id": 37605,
"seed_ids": "[359]"
} | 0.438898 | Docs: Python310_37605 | I | [
"create_subprocess",
"run_custom_event_loop"
] | 2 | [
[
"run_custom_event_loop",
"create_subprocess"
]
] | 1 | [] | false | [
"MyEventLoopPolicy",
"MyThreadedChildWatcher"
] | true | pytest | true | [] | true | f045a9599a71e0dc9d018a68be4a356b34bc3a91 | f9e1a2e62bfca045885dc69b02095b8a96b49dac | |||
v1.0 | instruct | Docs | Docs: Python310_37646_I | ### Advanced Python Function Implementation
**Problem Statement:**
You are required to implement a Python function `detect_prime_numbers` that analyzes a list of integers and identifies which of them are prime numbers. Additionally, the function should support customization for:
- Number filtering constraints (e.g., ... | def is_prime(n):
"""
Check if a number is a prime.
"""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
p = 3
while p * p <= n:
if n % p == 0:
return False
p += 2
return True
def detect_prime_numbers(numbe... | from solution import detect_prime_numbers
def test_detect_prime_numbers_no_filter():
assert detect_prime_numbers([2, 3, 4, 5, 6]) == [
'2 is a prime number',
'3 is a prime number',
'4 is not a prime number',
'5 is a prime number',
'6 is not a prime number']
def test_det... | [
{
"docstring": "Check if a number is a prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Analyze a list of integers and identify which are prime numbers with optional filtering.\n\n:param numbers: List of integers to ... | [
1,
1,
1,
1,
0,
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": "def detect_prime_numbers(numbers: list, filter_fn=None, prime_message=\"{} is a prime number\", non_prime_message=\"{} is not a prime number\") -> list:\n def is_pri... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00037646",
"row_id": 37646,
"seed_ids": "[426]"
} | 0.791406 | Docs: Python310_37646 | I | [
"is_prime",
"detect_prime_numbers"
] | 2 | [
[
"detect_prime_numbers",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 597d17c3744e43ebcf175342d51abbe9e82818ad | 252c4dd2f5eed49dffe7df9f7ba5001edeb3d43d | |||
v1.0 | instruct | Docs | Docs: Scikit_37654_I | ### Incremental Learning Pipeline with Out-of-Core Data
**Objective:** Build an incremental learning pipeline using scikit-learn to classify text data that is too large to fit into memory all at once.
**Description:**
You are given a large dataset of text documents categorized into different classes. Your task is to ... | import os
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import accuracy_score
def stream_documents(file_path: str, chunk_size: int):
"""
Generator function that yields chunks of text documents from a file.
Args:
- file... | import tempfile
import os
import pytest
from solution import stream_documents, incremental_learning_pipeline
def create_temp_file(data):
temp_file = tempfile.NamedTemporaryFile(delete=False, mode='w', encoding='utf-8')
temp_file.writelines(data)
temp_file.close()
return temp_file.name
def test_stream_... | [
{
"docstring": "Generator function that yields chunks of text documents from a file.\n\nArgs:\n- file_path: str : Path to the file containing the text documents.\n- chunk_size: int : Number of documents to yield in each chunk.\n\nYields:\n- List[str]: A list of text documents.",
"function_declaration": "def... | [
1,
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_score\n\ndef stream_... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00037654",
"row_id": 37654,
"seed_ids": "[63]"
} | 0.530109 | Docs: Scikit_37654 | I | [
"stream_documents",
"incremental_learning_pipeline"
] | 2 | [
[
"incremental_learning_pipeline",
"stream_documents"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | 7ea43ef0ebb1ebd9b4267eb1c9c95421b603e6a8 | 8267d539874df24c0bd5688f04d2e8cab70426e6 | |||
v1.0 | instruct | Docs | Docs: Python310_37677_I | ### Question: Build a Registration Form Using `tkinter`
#### Objective
Create a simple registration form using the `tkinter` package in Python. The form should accept several fields, validate the input data, and display the entered information upon submission.
#### Requirements
1. **Widgets**:
- Labels for each fi... | import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
def validate_registration_form(name, email, age, gender, country):
"""
Validates the registration form.
Returns a tuple (is_valid, message).
"""
if not name.strip():
return False, "Name cannot be empty."
if '@' ... | from solution import validate_registration_form
def test_validate_registration_form_valid():
is_valid, message = validate_registration_form("John Doe", "john.doe@example.com", "25", "Male", "USA")
assert is_valid == True
assert message == "Validation Successful."
def test_validate_registration_form_empty_... | [
{
"docstring": "Validates the registration form.\nReturns a tuple (is_valid, message).",
"function_declaration": "def validate_registration_form(name, email, age, gender, country):",
"function_name": "validate_registration_form",
"parameter_list": "(name, email, age, gender, country)"
},
{
"... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import tkinter as tk\nfrom tkinter import ttk, messagebox\n\ndef validate_and_submit():\n name = name_entry.get()\n email = email_entry.get()\n age = age_entry... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00037677",
"row_id": 37677,
"seed_ids": "[115]"
} | 0.406337 | Docs: Python310_37677 | I | [
"validate_registration_form",
"on_submit",
"create_registration_form"
] | 3 | [
[
"create_registration_form",
"on_submit"
],
[
"on_submit",
"validate_registration_form"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ee606a6a3b7c6fd8f0ce649df6126fc4884c301f | 82f92b3cb40162b41acf7164097ac13bb465c509 | |||
v1.0 | instruct | Docs | Docs: Python310_37682_I | ### Question: Implementing and Profiling a Function for Prime Number Detection
#### Background
You are required to implement a Python function that checks whether a given number is a prime number. You will then profile its performance to identify potential bottlenecks and suggest optimizations.
#### Instructions
1.... | import cProfile
import pstats
import math
def is_prime(n: int) -> bool:
"""
Check if a number is a prime number.
Parameters:
n (int): The number to be checked.
Returns:
bool: True if n is a prime number, False otherwise.
"""
if n <= 1:
return False
if n <= 3:
retur... | def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(13) == True
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert i... | [
{
"docstring": "Check if a number is a prime number.\n\nParameters:\nn (int): The number to be checked.\n\nReturns:\nbool: True if n is a prime number, False otherwise.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": null,
... | [
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": "def is_prime(n: int) -> bool:\n \"\"\"\n Checks if a number is a prime number.\n \n Args:\n n (int): The number to check.\n \n Returns:\n bool: ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00037682",
"row_id": 37682,
"seed_ids": "[364]"
} | 0.777724 | Docs: Python310_37682 | I | [
"is_prime",
"profile_is_prime",
"is_prime_optimized",
"profile_is_prime_optimized"
] | 4 | [
[
"profile_is_prime",
"is_prime"
],
[
"profile_is_prime_optimized",
"is_prime_optimized"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 70bb5cc527d692045202c56696626fff32e586aa | eb132bed019df84e7b9c568f4c544b5916c0f9c7 | |||
v1.0 | instruct | Docs | Docs: Python310_37755_I | Manipulating Audio Files with `aifc`
#### Objective:
Write a Python script using the `aifc` module to manipulate an AIFF file. Your task is to:
1. Open an AIFF file named `input.aiff` and read its properties.
2. Create a stereo (2 channels) version of the same audio with a modified frame rate and save it as `output.ai... | import aifc
def process_aiff(input_filename: str, output_filename: str):
# Open the input file and read properties
with aifc.open(input_filename, 'r') as input_file:
nchannels = input_file.getnchannels()
sampwidth = input_file.getsampwidth()
framerate = input_file.getframerate()
... | import aifc
import os
import pytest
def create_test_aiff(filename, channels, sampwidth, framerate, frames):
with aifc.open(filename, 'w') as f:
f.setnchannels(channels)
f.setsampwidth(sampwidth)
f.setframerate(framerate)
f.writeframes(frames)
def read_aiff_properties(filename):
... | [
{
"docstring": null,
"function_declaration": "def process_aiff(input_filename, output_filename):",
"function_name": "process_aiff",
"parameter_list": "(input_filename, output_filename)"
},
{
"docstring": null,
"function_declaration": "def convert_to_stereo(frames, nchannels, sampwidth, n... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import aifc\n\ndef process_aiff(input_filename: str, output_filename: str):\n # Open the input file and read properties\n with aifc.open(input_filename, 'r') as i... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00037755",
"row_id": 37755,
"seed_ids": "[365]"
} | 0.461557 | Docs: Python310_37755 | I | [
"process_aiff",
"convert_to_stereo"
] | 2 | [
[
"process_aiff",
"convert_to_stereo"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 5724d0654f700c2ff61c4bad89a06763cca139f0 | add2353dba83196244e15ee4bebf73873d3b1fbd | |||
v1.0 | instruct | Docs | Docs: Python310_37797_I | **Problem Statement:**
Implement a function to concurrently fetch the contents of multiple URLs using the `asyncio` high-level API. The function should take a list of URLs and return a dictionary where the keys are the URLs and the values are the fetched contents. If a URL cannot be fetched, the value should be `None`... | import asyncio
import aiohttp
from typing import List, Dict, Optional
async def fetch_content(session: aiohttp.ClientSession, url: str) -> Optional[str]:
"""
Fetch the content of a URL using the given session.
:param session: aiohttp ClientSession
:param url: URL to fetch content from
:return:... | import pytest
import asyncio
from solution import fetch_all_contents
@pytest.mark.asyncio
async def test_fetch_all_contents_valid_url():
urls = ['https://example.com']
result = await fetch_all_contents(urls)
assert 'https://example.com' in result
assert result['https://example.com'] is not None
@pytes... | [] | [
0,
1,
1,
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 asyncio\nimport aiohttp\nfrom typing import List, Dict, Optional\n\nasync def fetch_content(session, url):\n try:\n async with session.get(url, timeout... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00037797",
"row_id": 37797,
"seed_ids": "[270]"
} | 0.597401 | Docs: Python310_37797 | I | [
"fetch_content",
"fetch_all_contents"
] | 2 | [
[
"fetch_all_contents",
"fetch_content"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 7f04ec5b20aa58a04daee98566b7ec196b1f031c | 60870e5d42ec88bdc373154bccb57a81e6a15f8e | |||
v1.0 | instruct | Docs | Docs: Python310_37808_I | **Objective:**
You are tasked with developing a concurrent program that processes a list of URLs to fetch their HTML content. This will assess your understanding of the "multiprocessing" package in Python.
**Description:**
Write a Python program using the "multiprocessing" package to:
1. Create a pool of worker proces... | import multiprocessing
from queue import Empty
import requests
def fetch_url(url):
"""
Fetch the HTML content of the given URL.
Args:
- url (str): The URL to fetch.
Returns:
- str: HTML content of the URL.
"""
try:
response = requests.get(url)
return response.t... | from solution import fetch_url, process_urls
def test_fetch_url_success(monkeypatch):
class MockResponse:
@staticmethod
def get(*args, **kwargs):
class MockResponseInner:
text = 'HTML content of the page'
return MockResponseInner()
monkeypatch.setatt... | [
{
"docstring": "Fetch the HTML content of the given URL.\n\nArgs:\n- url (str): The URL to fetch.\n\nReturns:\n- str: HTML content of the URL.",
"function_declaration": "def fetch_url(url):",
"function_name": "fetch_url",
"parameter_list": "(url)"
},
{
"docstring": "Worker function to fetch ... | [
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 multiprocessing\nfrom queue import Empty\nimport requests\n\ndef fetch_url(url):\n \"\"\"\n Fetch the HTML content of the given URL.\n \n Args:\n ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00037808",
"row_id": 37808,
"seed_ids": "[338]"
} | 0.604279 | Docs: Python310_37808 | I | [
"fetch_url",
"worker",
"process_urls"
] | 3 | [
[
"worker",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"requests"
] | false | edeb42f5e53017266c91baa6936f6dd68d3bebf8 | b61c9e830118d96934e5483e7979539d40961809 | |||
v1.0 | instruct | Docs | Docs: Pytorch_37829_I | ### PyTorch: Profiling Model Performance with TorchInductor
#### Problem Statement
You are tasked with profiling the performance of a deep learning model using PyTorch's TorchInductor on a GPU. Specifically, you will:
1. Set relevant environment variables.
2. Run a benchmark script on a model to gather performance da... | import os
import re
import subprocess
def set_environment_variables():
os.environ['TORCHINDUCTOR_UNIQUE_KERNEL_NAMES'] = '1'
os.environ['TORCHINDUCTOR_BENCHMARK_KERNEL'] = '1'
def run_benchmark_script():
command = "python -u benchmarks/dynamo/timm_models.py --backend inductor --amp --performance --dashboa... | import os
import subprocess
from unittest.mock import patch, mock_open
def test_set_environment_variables():
set_environment_variables()
assert os.environ['TORCHINDUCTOR_UNIQUE_KERNEL_NAMES'] == '1'
assert os.environ['TORCHINDUCTOR_BENCHMARK_KERNEL'] == '1'
@patch('subprocess.run')
def test_run_benchmark_... | [
{
"docstring": null,
"function_declaration": "def set_environment_variables():",
"function_name": "set_environment_variables",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def run_benchmark_script():",
"function_name": "run_benchmark_script",
"parameter... | [
1,
1,
0,
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 os\nimport subprocess\n\ndef set_environment_variables():\n \"\"\"\n Sets the required environment variables for TorchInductor.\n \"\"\"\n os.environ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00037829",
"row_id": 37829,
"seed_ids": "[15]"
} | 0.560723 | Docs: Pytorch_37829 | I | [
"set_environment_variables",
"run_benchmark_script",
"extract_compiled_module_path",
"analyze_performance_logs",
"extract_kernel_path",
"profile_individual_kernel",
"main"
] | 7 | [
[
"analyze_performance_logs",
"extract_compiled_module_path"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 89c0af826c6ae1f88c37400f0e361363b00681a2 | c23800e40ce943e5532f86eb0f163cc5a34818d1 | |||
v1.0 | instruct | Docs | Docs: Python310_37867_I | ### Question: Binary Data and Pretty Printing with Multithreading
You have been tasked with creating a program that reads binary data from a file, processes the data to extract specific information, and prints this information in a readable format while performing these tasks in parallel using multiple threads.
#### ... | import struct
import threading
import pprint
def create_binary_user_file(file_path):
user_data = [
(1234, 'Alice'),
(5678, 'Bob'),
(91011, 'Charlie'),
(121314, 'David')
]
with open(file_path, 'wb') as f:
for user_id, username in user_data:
username_length... | from solution import create_binary_user_file, read_user_data, pretty_print_user_data, parallel_read_and_print
import os
def test_create_binary_user_file():
file_path = 'test_users.bin'
create_binary_user_file(file_path)
assert os.path.isfile(file_path)
os.remove(file_path)
def test_read_user_data():
... | [
{
"docstring": null,
"function_declaration": "def create_binary_user_file(file_path):",
"function_name": "create_binary_user_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def read_user_data(file_path):",
"function_name": "read_user_data",
... | [
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import struct\nimport threading\nimport os\nfrom pprint import pprint\n\ndef create_binary_user_file(file_path, user_data):\n with open(file_path, 'wb') as f:\n ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00037867",
"row_id": 37867,
"seed_ids": "[420]"
} | 0.386332 | Docs: Python310_37867 | I | [
"create_binary_user_file",
"read_user_data",
"pretty_print_user_data",
"parallel_read_and_print"
] | 4 | [
[
"parallel_read_and_print",
"pretty_print_user_data"
],
[
"parallel_read_and_print",
"read_user_data"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 9dfc07c7ef6b56da88f24e19f247b1ec61b2b88c | a9ffe2e6febd385cf28f7c313e2df8c042e73649 | |||
v1.0 | instruct | Docs | Docs: Python310_37947_I | ### Question: Implementing Enhanced Interactive Command History Management
You have been asked to implement a command history management system using the `readline` module. This system will enhance the default capabilities in two key areas:
1. **Persistent History Management**:
This feature requires the system to... | import os
import atexit
import readline
def initialize_history(histfile=os.path.expanduser("~/.custom_history"), hist_len=2000):
"""
Initialize command history by loading from the specified file,
and set up saving history upon exit.
Parameters:
histfile (str): Path to the history file.
hist_le... | import readline
from solution import initialize_history, custom_completer, setup_readline
def test_initialize_history(tmpdir):
histfile = tmpdir.join(".custom_history")
initialize_history(str(histfile))
readline.add_history('test_command')
assert readline.get_current_history_length() == 1
assert re... | [
{
"docstring": "Initialize command history by loading from the specified file,\nand set up saving history upon exit.\n\nParameters:\nhistfile (str): Path to the history file.\nhist_len (int): Maximum number of history entries to save.",
"function_declaration": "def initialize_history(histfile=os.path.expand... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport atexit\nimport readline\n\ndef initialize_history(histfile=os.path.expanduser(\"~/.custom_history\"), hist_len=2000):\n \"\"\"\n Initializes the... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00037947",
"row_id": 37947,
"seed_ids": "[362]"
} | 0.42078 | Docs: Python310_37947 | I | [
"initialize_history",
"custom_completer",
"setup_readline"
] | 3 | [
[
"setup_readline",
"custom_completer"
],
[
"setup_readline",
"initialize_history"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e559f4086f665f2af37767e1d8a741bc72673f6f | 0d186c269ce077e65e02a256abd7a436a0aedbb0 | |||
v1.0 | instruct | Docs | Docs: Python310_37955_I | **Question: Implement an Echo Server using the `selectors` module**
Using the `selectors` module in Python, implement an echo server that can handle multiple client connections concurrently. The server should:
1. Accept incoming client connections.
2. Read data from connected clients.
3. Echo the received data back t... | import selectors
import socket
import types
sel = selectors.DefaultSelector()
def accept(sock, mask):
conn, addr = sock.accept() # Should be ready
conn.setblocking(False)
data = types.SimpleNamespace(addr=addr, inb=b'', outb=b'')
events = selectors.EVENT_READ | selectors.EVENT_WRITE
sel.register(... | import socket
import threading
import time
# Start server in a separate thread
def run_server():
import solution
solution.start_server()
server_thread = threading.Thread(target=run_server, daemon=True)
server_thread.start()
time.sleep(1) # Ensure the server has time to start
def test_echo_single_message():
... | [
{
"docstring": null,
"function_declaration": "def accept(sock, mask):",
"function_name": "accept",
"parameter_list": "(sock, mask)"
},
{
"docstring": null,
"function_declaration": "def service_connection(key, mask):",
"function_name": "service_connection",
"parameter_list": "(key... | [
0,
1,
1,
1,
0,
1,
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 selectors\nimport socket\n\ndef accept(sock, mask):\n conn, addr = sock.accept() # Should be ready\n print('Accepted connection from', addr)\n conn.set... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00037955",
"row_id": 37955,
"seed_ids": "[288]"
} | 0.652743 | Docs: Python310_37955 | I | [
"accept",
"service_connection",
"start_server"
] | 3 | [
[
"start_server",
"accept"
],
[
"start_server",
"service_connection"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 25d88f264d8f1031cd9ea5dfe8776a696bbf7363 | 6a0c0a8deafd00c4178d711d2169350bcd455965 | |||
v1.0 | instruct | Docs | Docs: Pytorch_37968_I | <|Analysis Begin|>
The provided documentation describes two functions within the `torch.utils.dlpack` module: `from_dlpack` and `to_dlpack`. These functions facilitate data interchange between PyTorch tensors and other frameworks that support DLPack, a tensor format standard.
- `from_dlpack`: Converts a DLPack tensor... | import torch
from torch.utils.dlpack import from_dlpack, to_dlpack
def convert_to_dlpack(tensor):
"""
Convert a PyTorch tensor to a DLPack tensor.
"""
return to_dlpack(tensor)
def convert_from_dlpack(dlpack_tensor):
"""
Convert a DLPack tensor to a PyTorch tensor.
"""
return from_dlpac... | from solution import convert_to_dlpack, convert_from_dlpack, interoperability_test
import torch
def test_convert_to_dlpack():
tensor = torch.tensor([1, 2, 3], dtype=torch.float32)
dlpack_tensor = convert_to_dlpack(tensor)
assert isinstance(dlpack_tensor, object) # Check if the returned object is non-trivi... | [
{
"docstring": "Convert a PyTorch tensor to a DLPack tensor.",
"function_declaration": "def convert_to_dlpack(tensor):",
"function_name": "convert_to_dlpack",
"parameter_list": "(tensor)"
},
{
"docstring": "Convert a DLPack tensor to a PyTorch tensor.",
"function_declaration": "def conve... | [
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 torch\nfrom torch.utils.dlpack import to_dlpack, from_dlpack\n\ndef convert_to_dlpack(tensor):\n \"\"\"\n Converts a given PyTorch tensor to a DLPack tenso... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00037968",
"row_id": 37968,
"seed_ids": "[73]"
} | 0.407343 | Docs: Pytorch_37968 | I | [
"convert_to_dlpack",
"convert_from_dlpack",
"interoperability_test"
] | 3 | [
[
"interoperability_test",
"convert_from_dlpack"
],
[
"interoperability_test",
"convert_to_dlpack"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | cfe16d26554b9bf8e1b0e9e69a5a87e2fdf806d9 | ab40cef9c61ba724248f798bbd3b359c686c6e7d | |||
v1.0 | instruct | Docs | Docs: Python310_37977_I | **Concurrency and Asynchronous Execution with concurrent.futures**
You're tasked with processing a large list of integers to determine their primality and then summing the prime numbers asynchronously for efficient computation. The goal is to make use of both `ThreadPoolExecutor` and `ProcessPoolExecutor` to handle di... | from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from typing import List
def is_prime(n: int) -> bool:
"""
Returns True if n is a prime number, else False.
"""
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in ra... | from solution import is_prime, check_primes, sum_primes, main
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(10) == False
assert is_prime(17) == True
assert is_prime(1) == False
assert is_prime(0) == False
assert is_prime(29) == True
assert is... | [
{
"docstring": "Returns True if n is a prime number, else False.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Checks the primality of each number in the list using multi-threading.\n\nArgs:\n- numbers: List of integers ... | [
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": "from typing import List\nfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\nimport concurrent.futures\n\ndef is_prime(n: int) -> bool:\n \"\"\"\... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00037977",
"row_id": 37977,
"seed_ids": "[347]"
} | 0.480472 | Docs: Python310_37977 | I | [
"is_prime",
"check_primes",
"sum_primes",
"main"
] | 4 | [
[
"check_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b42d8936d07c1145e1113b0d9d3ffc8da7bbab95 | 4d48bb771cccb47b529837cfe67cc041e57d4d55 | |||
v1.0 | instruct | Docs | Docs: Python310_37988_I | **Question: Comprehensive Database Interaction Using `sqlite3`**
You're tasked with creating a mini application that manages a database of books using the `sqlite3` module. This application should allow for creating the database and table, inserting data, performing queries, editing entries, and handling potential err... | import sqlite3
class Review:
def __init__(self, text, reviewer):
self.text = text
self.reviewer = reviewer
def __repr__(self):
return f'Review({self.text}, {self.reviewer})'
def adapt_review(review):
return f"{review.text};{review.reviewer}".encode()
def convert_review(s):
te... | import sqlite3
import pytest
from solution import setup_database, insert_sample_data, fetch_books_by_author, update_book_rating, Review, setup_review_conversion
def test_setup_database():
setup_database()
con = sqlite3.connect("books.db")
cur = con.cursor()
cur.execute("SELECT name FROM sqlite_master W... | [] | [
0,
0,
1,
1,
1,
1,
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 sqlite3\n\nclass Review:\n def __init__(self, text, reviewer):\n self.text = text\n self.reviewer = reviewer\n\n def __repr__(self):\n ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00037988",
"row_id": 37988,
"seed_ids": "[103]"
} | 0.51876 | Docs: Python310_37988 | I | [
"adapt_review",
"convert_review",
"setup_database",
"insert_sample_data",
"fetch_books_by_author",
"update_book_rating",
"setup_review_conversion"
] | 7 | [
[
"setup_review_conversion",
"adapt_review"
],
[
"setup_review_conversion",
"convert_review"
]
] | 2 | [] | false | [
"Review"
] | true | pytest | true | [] | true | 99d3aa66d0f112ae654943e898b9502881897e69 | e7f606951f7b87cdd121190452d64a07e3c21623 | |||
v1.0 | instruct | Docs | Docs: Python310_38011_I | #### Objective
Demonstrate the practical application and understanding of asyncio in Python 3.10 by creating a simple concurrent task manager that includes network IO operations.
#### Problem Statement
You are required to create an asynchronous task manager that performs multiple tasks concurrently:
1. Fetch data from... | import asyncio
from typing import List
async def fetch_data(url: str) -> str:
await asyncio.sleep(2) # simulate network delay
return f"Data from {url}"
async def process_data(data: str) -> str:
await asyncio.sleep(1) # simulate processing delay
return data[::-1].upper()
async def task_manager(urls:... | import asyncio
from solution import fetch_data, process_data, task_manager
def test_fetch_data():
async def wrapper():
result = await fetch_data("http://example.com")
assert result == "Data from http://example.com"
asyncio.run(wrapper())
def test_process_data():
async def wrapper(... | [] | [
1,
1,
1,
0,
0,
1,
1,
1,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List\n\nasync def fetch_data(url: str) -> str:\n await asyncio.sleep(2) # simulate network delay\n return f\"Data from {url}\"... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00038011",
"row_id": 38011,
"seed_ids": "[360]"
} | 0.517795 | Docs: Python310_38011 | I | [
"fetch_data",
"process_data",
"task_manager"
] | 3 | [
[
"task_manager",
"fetch_data"
],
[
"task_manager",
"process_data"
]
] | 2 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 843e66edf92ff5fdb37556df8da16f76f15de146 | 1da646375e6386b860a6e6ae5dad0903e419b50d | |||
v1.0 | instruct | Docs | Docs: Python310_38013_I | ### Advanced Python Assessment Question: System Audit and Memory Management
**Objective:**
Your task is to write a Python script that demonstrates the use of audit hooks and memory management using the `sys` module.
**Problem Statement:**
1. Implement an auditing system using the functions `sys.addaudithook()` and `s... | import sys
def my_audit_hook(event, args):
print(f"Audit Event: {event}, Arguments: {args}")
def track_memory_usage(obj):
print(f"Allocated Blocks: {sys.getallocatedblocks()}")
return sys.getsizeof(obj)
def test_audit_and_memory():
sys.addaudithook(my_audit_hook)
# Allocating different objec... | from solution import my_audit_hook, track_memory_usage, test_audit_and_memory
def test_audit_hook_registration():
sys.addaudithook(my_audit_hook)
sys.audit("test.event", ("arg1",))
# This should show the audit event output
def test_track_memory_usage():
sample_list = [1, 2, 3]
assert track_memory_... | [
{
"docstring": null,
"function_declaration": "def my_audit_hook(event, args):",
"function_name": "my_audit_hook",
"parameter_list": "(event, args)"
},
{
"docstring": null,
"function_declaration": "def track_memory_usage(obj):",
"function_name": "track_memory_usage",
"parameter_li... | [
0,
0,
0,
1,
0,
0,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\n\ndef my_audit_hook(event, args):\n \"\"\"\n Audit hook that logs all audit events with their arguments.\n \"\"\"\n print(f\"Audit Event: {event... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00038013",
"row_id": 38013,
"seed_ids": "[348]"
} | 0.570953 | Docs: Python310_38013 | I | [
"my_audit_hook",
"track_memory_usage",
"test_audit_and_memory"
] | 3 | [
[
"test_audit_and_memory",
"my_audit_hook"
],
[
"test_audit_and_memory",
"track_memory_usage"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | b7319aac27bcfe1d0433fa5b4928320440ca1f4a | aa3cf49afa1ba75ceebb400acaabde614cc81628 | |||
v1.0 | instruct | Docs | Docs: Python310_38019_I | ### Asyncio Networking and Task Management with Python 3.10
#### Objective
Your task is to create an echo server and client using Python's `asyncio` module. The server will accept connections from clients, read incoming data, and echo back the same data to the client. Additionally, you should manage tasks and handle e... | import asyncio
async def handle_client(reader, writer):
try:
while True:
data = await reader.read(100)
if not data:
break
writer.write(data)
await writer.drain()
except asyncio.CancelledError:
pass
except Exception as e:
... | import asyncio
import pytest
from solution import handle_client, start_server
@pytest.mark.asyncio
async def test_server_echo():
# Start the server
server_task = asyncio.create_task(start_server())
await asyncio.sleep(1)
reader, writer = await asyncio.open_connection('localhost', 8888)
test_messag... | [
{
"docstring": null,
"function_declaration": "def main():",
"function_name": "main",
"parameter_list": "()"
}
] | [
1,
0,
0,
1,
0,
0,
0,
0,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n try:\n while True:\n data = await reader.read(100)\n if not data:\n ... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00038019",
"row_id": 38019,
"seed_ids": "[101]"
} | 0.702034 | Docs: Python310_38019 | I | [
"handle_client",
"start_server",
"main"
] | 3 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fc80e9c1e5f8b9abcaca91ccd34907577667e9ce | 01946ea88bd4392a245520ab16384b29982e3c47 | |||
v1.0 | instruct | Docs | Docs: Scikit_38027_I | You are given a high-dimensional dataset (`data.csv`), and your task is to perform unsupervised dimensionality reduction using different techniques from the scikit-learn library. You will need to apply Principal Component Analysis (PCA), Random Projections, and Feature Agglomeration, and then compare the variance ratio... | import pandas as pd
from sklearn.decomposition import PCA
from sklearn.random_projection import johnson_lindenstrauss_min_dim, SparseRandomProjection
from sklearn.cluster import FeatureAgglomeration
from sklearn.preprocessing import StandardScaler
def load_and_preprocess_data(file_path):
# Load the data
data =... | import pytest
from solution import (
load_and_preprocess_data,
apply_pca,
apply_random_projection,
apply_feature_agglomeration,
dimensionality_reduction_comparison
)
import pandas as pd
import numpy as np
# Mock data for testing
data_csv = 'data.csv'
data = pd.DataFrame({
'feature1': np.random.... | [
{
"docstring": null,
"function_declaration": "def load_and_preprocess_data(file_path):",
"function_name": "load_and_preprocess_data",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def apply_pca(data_scaled):",
"function_name": "apply_pca",
"para... | [
0,
1,
0,
0,
1,
0,
0,
1,
0
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.decomposition import PCA\nfrom sklearn.random_projection import johnson_lindenstrauss_min_dim, SparseRandomProjection\nfrom sklearn.cl... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00038027",
"row_id": 38027,
"seed_ids": "[30]"
} | 0.684528 | Docs: Scikit_38027 | I | [
"load_and_preprocess_data",
"apply_pca",
"apply_random_projection",
"apply_feature_agglomeration",
"dimensionality_reduction_comparison"
] | 5 | [
[
"dimensionality_reduction_comparison",
"apply_feature_agglomeration"
],
[
"dimensionality_reduction_comparison",
"apply_pca"
],
[
"dimensionality_reduction_comparison",
"apply_random_projection"
],
[
"dimensionality_reduction_comparison",
"load_and_preprocess_data"
]
... | 4 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 064c927ffaf25890b37a03b079e9800f5b51fef2 | 626c578235c6ce7b18669feacfd1f1fe39593d6e | |||
v1.0 | instruct | Docs | Docs: Pytorch_38047_I | ### Question: PyTorch Backend Optimization for Matrix Multiplication
#### Background
In this question, you will work with various PyTorch backend functionalities to control and optimize matrix multiplications on different hardware. Specifically, you will use `torch.backends.cuda` to toggle settings related to mixed-p... | import torch
import time
def benchmark_matmul(size=2048):
"""
Measures and returns the time taken to perform a large matrix multiplication
using PyTorch.
Parameters:
size (int): The size of the square matrices to multiply.
Returns:
float: Time taken to perform the matrix multiplication.
... | def test_benchmark_matmul_cpu():
time_taken = benchmark_matmul()
assert time_taken > 0
def test_toggle_mixed_precision():
# Ensures API changes do not raise errors.
try:
toggle_mixed_precision(tf32=True, fp16=True, bf16=True)
toggle_mixed_precision(tf32=False)
toggle_mixed_preci... | [
{
"docstring": "Measures and returns the time taken to perform a large matrix multiplication\nusing PyTorch.\n\nParameters:\nsize (int): The size of the square matrices to multiply.\n\nReturns:\nfloat: Time taken to perform the matrix multiplication.",
"function_declaration": "def benchmark_matmul(size=2048... | [
0,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport time\n\ndef benchmark_matmul(size=2048):\n \"\"\"\n Measures and returns the time taken to perform a large matrix multiplication using PyTorc... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00038047",
"row_id": 38047,
"seed_ids": "[32]"
} | 0.468354 | Docs: Pytorch_38047 | I | [
"benchmark_matmul",
"toggle_mixed_precision",
"benchmark_with_settings"
] | 3 | [
[
"benchmark_with_settings",
"benchmark_matmul"
],
[
"benchmark_with_settings",
"toggle_mixed_precision"
]
] | 2 | [] | false | [] | false | pytest | false | [
"torch"
] | false | 3e1a1eb1fc1c29594c6676b01d8a0acdbde263bf | c01d34a3b24f5ac17ca2941bd5e166d4743a21b5 | |||
v1.0 | instruct | Docs | Docs: Python310_38055_I | ### Asynchronous Web Scraping with Error Handling
You are tasked with designing a function that asynchronously fetches multiple web pages and processes the content. You will use the `concurrent.futures.ThreadPoolExecutor` for this purpose. The function should handle potential errors gracefully and keep track of both s... | import concurrent.futures
import urllib.request
from typing import List, Tuple, Dict
def fetch_url(url: str, timeout: float) -> str:
"""
Fetches the content of a URL with a specified timeout.
:param url: URL to fetch
:param timeout: Timeout in seconds
:return: Content of the fetched URL
:r... | from solution import async_web_scraper
import pytest
def test_async_web_scraper_successful():
urls = [
"http://www.example.com/",
"https://www.google.com/"
]
timeout = 5.0
success, errors = async_web_scraper(urls, timeout)
assert len(success) == 2
assert len(errors) == 0
... | [
{
"docstring": "Fetches the content of a URL with a specified timeout.\n\n:param url: URL to fetch\n:param timeout: Timeout in seconds\n:return: Content of the fetched URL\n:raises: Exception if the fetch fails",
"function_declaration": "def fetch_url(url, timeout):",
"function_name": "fetch_url",
"... | [
0,
0,
1,
0,
0,
1,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nimport urllib.request\nfrom urllib.error import URLError, HTTPError\nfrom typing import List, Tuple, Dict\n\ndef fetch_url_content(url: str, ... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00038055",
"row_id": 38055,
"seed_ids": "[347]"
} | 0.656421 | Docs: Python310_38055 | I | [
"fetch_url",
"async_web_scraper"
] | 2 | [
[
"async_web_scraper",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ba326068d14802c1af046f4a0551a4b56c628d97 | e38847d56b9d7028e9568b0858b6f35279831c58 | |||
v1.0 | instruct | Docs | Docs: Python310_38091_I | ## Coding Assessment Question
### Objective
Design and implement a Python script using the `ossaudiodev` module that records audio from a microphone, modifies the audio data, and then plays it back. The modification should involve switching stereo channels (left and right) or reversing the audio data.
### Requirement... | import ossaudiodev
import time
def switch_stereo_channels(data):
"""
Switch the stereo channels in the provided audio data.
:param data: Bytes containing stereo audio data.
:return: Bytes containing stereo audio data with switched channels.
"""
new_data = bytearray()
for i in range(0, len(d... | def test_switch_stereo_channels():
# Original stereo data; two frames of 16-bit stereo (left, right)
original_data = bytes([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08])
# Expected output after switching channels
expected_data = bytes([0x03, 0x04, 0x01, 0x02, 0x07, 0x08, 0x05, 0x06])
result_... | [
{
"docstring": "Switch the stereo channels in the provided audio data.\n:param data: Bytes containing stereo audio data.\n:return: Bytes containing stereo audio data with switched channels.",
"function_declaration": "def switch_stereo_channels(data):",
"function_name": "switch_stereo_channels",
"par... | [
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 ossaudiodev\n\ndef switch_stereo_channels(data):\n \"\"\"\n Switches stereo channels (left and right) in the given audio data.\n \n Args:\n data (... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00038091",
"row_id": 38091,
"seed_ids": "[127]"
} | 0.481418 | Docs: Python310_38091 | I | [
"switch_stereo_channels",
"record_and_play"
] | 2 | [
[
"record_and_play",
"switch_stereo_channels"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 5d55b54ba06808ed1d0bf859bac6829094e99b55 | 2172888775e989f4d925a7f6d9c91486e0aa268d | |||
v1.0 | instruct | Docs | Docs: Python310_38131_I | ### Problem: Concurrent Execution and Resource Management
You are required to implement a Python function that processes a list of tasks using both threading and multiprocessing to optimize for both CPU-bound and IO-bound operations. The task list contains tuples where each tuple has the format `(task_type, data)`. Th... | import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
# Simulate a CPU-bound task by performing a computationally intensive operation
def cpu_bound_task(data):
# Just a dummy function that performs some heavy computations
result = 0
for i in range(1, data * 10000):
resu... | from solution import cpu_bound_task, io_bound_task, process_tasks
def test_cpu_bound_task():
assert cpu_bound_task(1) == sum(i * i for i in range(1, 10000))
assert cpu_bound_task(2) == sum(i * i for i in range(1, 20000))
def test_io_bound_task():
assert io_bound_task(1) == 1
assert io_bound_task(5) ==... | [
{
"docstring": null,
"function_declaration": "def cpu_bound_task(data):",
"function_name": "cpu_bound_task",
"parameter_list": "(data)"
},
{
"docstring": null,
"function_declaration": "def io_bound_task(data):",
"function_name": "io_bound_task",
"parameter_list": "(data)"
},
... | [
1,
0,
0,
0,
1,
1,
0,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor\n\ndef simulate_io_task(complexity):\n import time\n time.sleep(complexity)\n return com... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00038131",
"row_id": 38131,
"seed_ids": "[206]"
} | 0.661183 | Docs: Python310_38131 | I | [
"cpu_bound_task",
"io_bound_task",
"process_tasks"
] | 3 | [
[
"process_tasks",
"cpu_bound_task"
],
[
"process_tasks",
"io_bound_task"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | fddfaa49eca1150089609726f0ff82bc67979f19 | 3786758c6c39cad99563c630c5fac61464776b72 | |||
v1.0 | instruct | Docs | Docs: Python310_38157_I | Secure File Integrity Check with Personalized BLAKE2 Hashing
You have been contracted to create a secure file integrity verification system that uses the BLAKE2 hashing algorithm. This system should allow users to generate personalized hash values for their files and verify the integrity of these files later on.
Impl... | import hashlib
def generate_personalized_hash(file_path: str, personalization_string: str) -> str:
"""
Generates a personalized BLAKE2b hash for the given file.
:param file_path: Path to the file
:param personalization_string: Personalization string, must be no longer than 16 bytes
:return: Hexade... | import os
import pytest
from solution import generate_personalized_hash, verify_file_integrity
# Sample file path for testing
test_file_path = 'test_file.txt'
personalization_string = 'file_check'
def setup_module(module):
# Create a test file
with open(test_file_path, 'w') as f:
f.write("Hello, world... | [
{
"docstring": "Generates a personalized BLAKE2b hash for the given file.\n\n:param file_path: Path to the file\n:param personalization_string: Personalization string, must be no longer than 16 bytes\n:return: Hexadecimal string representing the personalized hash value of the file's content",
"function_decl... | [
0,
1,
1,
0,
0,
1,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import hashlib\n\ndef generate_personalized_hash(file_path: str, personalization_string: str) -> str:\n \"\"\"\n Generates a personalized BLAKE2b hash for the giv... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00038157",
"row_id": 38157,
"seed_ids": "[394]"
} | 0.628463 | Docs: Python310_38157 | I | [
"generate_personalized_hash",
"verify_file_integrity"
] | 2 | [
[
"verify_file_integrity",
"generate_personalized_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 061b660522e62d8b045be3261e8835cbc8f051ec | 36f80ae82aa92321db9840303b93419dfc48e6cf | |||
v1.0 | instruct | Docs | Docs: Python310_38159_I | ### Python Coding Assessment Question
**Problem Statement:**
Your task is to create both a TCP echo client and a TCP echo server using asyncio streams in Python. They should communicate such that the client sends a message to the server, the server echoes it back, and the client receives the message and prints it.
#... | import asyncio
async def handle_echo(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
print(f"Send: {message!r}")
writer.write(data)
await writer.drain()
print("Close the conne... | import asyncio
import pytest
from asyncio import gather
from solution import tcp_echo_server, tcp_echo_client
@pytest.mark.asyncio
async def test_tcp_echo():
server_task = asyncio.create_task(tcp_echo_server('127.0.0.1', 8888))
await asyncio.sleep(1) # Give the server a second to start
client_message = ... | [] | [
0,
0,
1,
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 asyncio\n\nasync def handle_echo(reader, writer):\n data = await reader.read(100)\n message = data.decode()\n addr = writer.get_extra_info('peername')\n... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00038159",
"row_id": 38159,
"seed_ids": "[182]"
} | 0.664228 | Docs: Python310_38159 | I | [
"handle_echo",
"tcp_echo_server",
"tcp_echo_client",
"main"
] | 4 | [
[
"tcp_echo_server",
"handle_echo"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3b00b9467e9bb61f8a43fc327f15b9dee7b8bf2c | 4ba440e8a803d3419fbac8bfca0d25f04a523a5a | |||
v1.0 | instruct | Docs | Docs: Python310_38188_I | **Objective:**
The goal of this task is to ensure you comprehend the fundamental and advanced concepts of distributing Python modules, both through legacy tools like Distutils and modern alternatives like Setuptools.
**Task:**
Implement a Python script that emulates a simplified version of the `setup.py` script using ... | import setuptools
import os
def validate_files(data_files):
"""
Validates that all data files exist.
"""
missing_files = [file for file in data_files if not os.path.exists(file)]
if missing_files:
raise FileNotFoundError(f"Data files not found: {missing_files}")
return True
def create_... | import pytest
import os
from solution import create_setup_script, validate_files
def setup_module(module):
"""
Setup the test environment by creating temporary files and directories.
"""
os.makedirs("data", exist_ok=True)
with open("data/file1.txt", "w") as f:
f.write("This is file1.")
... | [
{
"docstring": "Validates that all data files exist.",
"function_declaration": "def validate_files(data_files):",
"function_name": "validate_files",
"parameter_list": "(data_files)"
},
{
"docstring": "Creates a setup script using setuptools with given packages, extension module, and data fil... | [
1,
0,
0,
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 setuptools\nimport os\n\ndef validate_files(data_files):\n \"\"\"\n Validates that all data files exist.\n \"\"\"\n missing_files = [file for file in... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00038188",
"row_id": 38188,
"seed_ids": "[435]"
} | 0.588941 | Docs: Python310_38188 | I | [
"validate_files",
"create_setup_script"
] | 2 | [
[
"create_setup_script",
"validate_files"
]
] | 1 | [] | false | [] | false | pytest | true | [
"setuptools"
] | false | 713d56bfab95ebab87c14f890410c78125fc6ec1 | a0ccc6df3f20b234d22f43b36aa508177b1524c8 | |||
v1.0 | instruct | Docs | Docs: Python310_38190_I | ### Asynchronous Subprocess Management
You are tasked with creating a Python script that spawns multiple subprocesses to perform various system operations concurrently. Your goal is to implement a function that accepts a list of shell commands and runs them concurrently using asyncio. The function should return the co... | import asyncio
async def run_command(command: str) -> str:
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
output = stdout.decode() + stderr.decode()
retur... | import asyncio
from solution import run_commands
async def test_run_commands_single_successful_command():
commands = ['echo "Hello, World!"']
result = await run_commands(commands)
assert result == "Hello, World!\n"
async def test_run_commands_multiple_successful_commands():
commands = ['echo "Hello, W... | [] | [
1,
1,
1,
1,
1,
1,
0,
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\n\nasync def run_command(command):\n proc = await asyncio.create_subprocess_shell(\n command,\n stdout=asyncio.subprocess.PIPE,\n ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00038190",
"row_id": 38190,
"seed_ids": "[264]"
} | 0.756221 | Docs: Python310_38190 | I | [
"run_command",
"run_commands"
] | 2 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 092e40d5f8c8aae0dff9f6774481de3ed84fc907 | d3a94a25b8672bd7059d6d68fa8106120ee19f3e | |||
v1.0 | instruct | Docs | Docs: Python310_38243_I | ### Python Coding Assessment Question
**Objective:** Implement a custom subset of the "pydoc" functionalities to demonstrate comprehension of generating and serving Python documentation.
#### Problem Statement:
You are tasked with creating a simple version of the "pydoc" tool that can generate and serve documentatio... | import inspect
import importlib
from http.server import SimpleHTTPRequestHandler, HTTPServer
from html import escape
def generate_doc(module_name: str) -> str:
"""
Generate documentation for the given module name.
Parameters:
- module_name: str
Returns:
- A string containing the documentation... | from solution import generate_doc
import pytest
def test_generate_doc_valid_module():
doc = generate_doc('sys')
assert "This module provides access to some objects used or maintained by the" in doc
def test_generate_doc_invalid_module():
doc = generate_doc('non_existent_module')
assert doc == "Module ... | [] | [
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 inspect\nimport importlib\nfrom http.server import SimpleHTTPRequestHandler, HTTPServer\nimport html\n\ndef generate_doc(module_name: str) -> str:\n \"\"\"\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00038243",
"row_id": 38243,
"seed_ids": "[240]"
} | 0.478399 | Docs: Python310_38243 | I | [
"generate_doc",
"serve_doc"
] | 2 | [
[
"serve_doc",
"generate_doc"
]
] | 1 | [] | false | [
"CustomHTTPRequestHandler"
] | true | pytest | true | [
"test_module"
] | false | 853f56cae577774fe834de03fdd9bbb7559a3301 | ca0cde7515da7f9c6ea8cc467b05295794526778 | |||
v1.0 | instruct | Docs | Docs: Python310_38274_I | ### Asynchronous Data Fetcher
**Objective**:
Implement an asynchronous data fetcher that retrieves data from multiple sources concurrently using the `asyncio` library.
**Background**:
You are tasked with creating a utility that can fetch data from multiple URLs concurrently. This utility should use the `asyncio` lib... | import aiohttp
import asyncio
async def fetch_data(url: str) -> str:
"""
Fetch data from a URL asynchronously.
Parameters:
url (str): The URL to fetch data from.
Returns:
str: The data fetched from the URL.
"""
async with aiohttp.ClientSession() as session:
async with session.... | import asyncio
from solution import fetch_data, gather_data
async def test_fetch_data_valid_url():
url = 'https://jsonplaceholder.typicode.com/posts/1'
data = await fetch_data(url)
assert isinstance(data, str) and len(data) > 0
async def test_fetch_data_invalid_url():
url = 'https://jsonplaceholder.ty... | [] | [
1,
1,
1,
0,
0,
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": "import aiohttp\nimport asyncio\n\nasync def fetch_data(url: str) -> str:\n \"\"\"\n Fetches the data from the provided URL asynchronously.\n\n :param url: The ... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00038274",
"row_id": 38274,
"seed_ids": "[270]"
} | 0.586736 | Docs: Python310_38274 | I | [
"fetch_data",
"gather_data",
"main"
] | 3 | [
[
"gather_data",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 93416dcda299cd6e2bb1aa34b68ad707df6253d4 | fc20156f0f9263f91787719c4307648a25ae8b07 | |||
v1.0 | instruct | Docs | Docs: Python310_38286_I | ### Multiprocessing-Based Web Scraper with Data Aggregation
#### Objective
You need to write a Python script using the `multiprocessing` package to create a web scraper that fetches data from multiple URLs concurrently and aggregates the results.
#### Task Description
1. **Create a Function to Fetch Data**:
- Im... | import requests
from bs4 import BeautifulSoup
from multiprocessing import Pool
from typing import List, Dict
def fetch_data(url: str) -> str:
"""
Fetch HTML content from a given URL.
Parameters:
url (str): The URL to fetch data from.
Returns:
str: HTML content of the page.
"""
... | from solution import fetch_data, concurrent_fetch, aggregate_data
def test_fetch_data():
url = 'http://example.com'
result = fetch_data(url)
assert isinstance(result, str)
assert '<html>' in result.lower() # Ensure it's an HTML document
def test_concurrent_fetch():
urls = ['http://example.com', '... | [
{
"docstring": "Fetch HTML content from a given URL.\n\nParameters:\nurl (str): The URL to fetch data from.\n\nReturns:\nstr: HTML content of the page.",
"function_declaration": "def fetch_data(url):",
"function_name": "fetch_data",
"parameter_list": "(url)"
},
{
"docstring": "Fetch all URLs... | [
0,
1,
0,
0,
1,
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 requests\nfrom multiprocessing import Pool\nfrom typing import List, Dict\nfrom bs4 import BeautifulSoup\n\ndef fetch_data(url: str) -> str:\n \"\"\"\n Fet... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00038286",
"row_id": 38286,
"seed_ids": "[338]"
} | 0.661447 | Docs: Python310_38286 | I | [
"fetch_data",
"concurrent_fetch",
"aggregate_data",
"main"
] | 4 | [
[
"concurrent_fetch",
"fetch_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"bs4",
"requests"
] | false | dbc3fa086ab3748c7615e8efd4428b2f2816dbb7 | 22daebf02f6734c1fdeefabf194eb2a2cc08cd52 | |||
v1.0 | instruct | Docs | Docs: Python310_38294_I | **Advanced Python Coding Assessment**
### Problem Statement
You are required to implement an asynchronous Python function that executes multiple shell commands in parallel, captures their standard output and error streams, and returns the results in an organized manner. This function should also handle cases where th... | import asyncio
from typing import List, Dict
async def run_command(command: str) -> Dict[str, str]:
"""
Execute a single shell command and capture its outputs and errors.
Parameters:
command (str): The shell command to be executed.
Returns:
Dict[str, str]: A dictionary contain... | import asyncio
from solution import run_commands
def test_run_commands():
asyncio.run(test_run_commands_inner())
async def test_run_commands_inner():
commands = ["echo Hello", "invalid_command"]
results = await run_commands(commands)
assert len(results) == 2
result_1 = results[0]
as... | [] | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Dict\n\nasync def run_command(command: str) -> Dict[str, str]:\n process = await asyncio.create_subprocess_shell(\n c... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00038294",
"row_id": 38294,
"seed_ids": "[264]"
} | 0.751376 | Docs: Python310_38294 | I | [
"run_command",
"run_commands",
"main"
] | 3 | [
[
"run_commands",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0fd605430d5ff50290109fa3da4d1499c2d0867d | bb7ff7a741fdb406e3c7d0dfecad31d0e76725d2 | |||
v1.0 | instruct | Docs | Docs: Python310_38302_I | ### Asynchronous Web Server Simulation
#### Objective
Implement a simple asynchronous web server that can handle multiple client connections concurrently using the `asyncio` module. The server should be able to process HTTP GET requests and respond with an appropriate message.
#### Task
1. **Create a Server**:
- ... | import asyncio
async def handle_client(reader, writer):
try:
data = await reader.readuntil(b'\r\n\r\n')
message = data.decode()
request_line = message.split("\r\n")[0]
method, path, version = request_line.split()
if method == 'GET':
response = 'HTTP/1.1 200 OK\r... | import asyncio
import socket
import pytest
@pytest.mark.asyncio
async def test_server_response():
server_task = asyncio.create_task(start_server())
await asyncio.sleep(1) # Let the server start
reader, writer = await asyncio.open_connection('localhost', 8080)
request = 'GET / HTTP/1.1\r\nHost: localh... | [] | [
0,
1,
1,
1,
1,
0,
0,
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 asyncio\n\nasync def handle_client(reader, writer):\n try:\n request = await reader.readuntil(b'\\r\\n\\r\\n')\n except asyncio.IncompleteReadError:... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00038302",
"row_id": 38302,
"seed_ids": "[151]"
} | 0.563364 | Docs: Python310_38302 | I | [
"handle_client",
"start_server"
] | 2 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 75af1caeb690107b1eccf0b5c97ed985572be19e | 85259db884ba8cd138ce913f30c131ad47ff58ba | |||
v1.0 | instruct | Docs | Docs: Python310_38330_I | ### Question: Efficient Calculation and Caching using functools
You have been assigned a task to efficiently compute the result of a mathematical function with the help of caching and function manipulation.
#### Problem:
Implement a function `cached_power(base: int, exponent: int) -> int` that calculates `base` raise... | import functools
import time
@functools.cache
def cached_power(base: int, exponent: int) -> int:
"""
Calculates base raised to the power exponent with an artificial delay.
Args:
base (int): The base number.
exponent (int): The power to raise the base to.
Returns:
int: The result o... | import time
from solution import cached_power, partial_cached_power
def test_cached_power_initial_call():
start_time = time.time()
assert cached_power(2, 10) == 1024
elapsed_time = time.time() - start_time
assert elapsed_time >= 2
def test_cached_power_cached_call():
start_time = time.time()
a... | [
{
"docstring": "Calculates base raised to the power exponent with an artificial delay.\n\nArgs:\nbase (int): The base number.\nexponent (int): The power to raise the base to.\n\nReturns:\nint: The result of base ** exponent.",
"function_declaration": "def cached_power(base, exponent):",
"function_name":... | [
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 functools\nimport time\n\n@functools.cache\ndef cached_power(base: int, exponent: int) -> int:\n \"\"\"\n Computes base raised to the power exponent with a... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00038330",
"row_id": 38330,
"seed_ids": "[236]"
} | 0.491101 | Docs: Python310_38330 | I | [
"cached_power",
"partial_cached_power"
] | 2 | [
[
"partial_cached_power",
"cached_power"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0b4714182ee02d95fbebe081b898dedff0e970aa | 60e7a32bbc5c716352bf2815d3ae512eb7d31f8a | |||
v1.0 | instruct | Docs | Docs: Python310_38346_I | **Coding Assessment Question**
Write a Python program that creates two subprocesses asynchronously. Each subprocess will perform a different task and their outputs must be captured and displayed. One subprocess should list the contents of a directory, while the other should display the current date and time. On comple... | import asyncio
import os
async def run_command(command):
"""
Run a command in a subprocess and capture its output.
"""
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proce... | import pytest
from solution import run_command, run_tasks
import os
@pytest.mark.asyncio
async def test_run_command_ls():
"""
Test the `run_command` function with the 'ls' command.
"""
# Check for directory listing
command = "ls ./"
process = await asyncio.create_subprocess_shell(
comma... | [] | [
1,
1,
1,
0,
0,
1,
1,
0,
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 os\n\nasync def run_tasks(directory):\n async def run_command(command):\n process = await asyncio.create_subprocess_shell(\n ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00038346",
"row_id": 38346,
"seed_ids": "[264]"
} | 0.643748 | Docs: Python310_38346 | I | [
"run_command",
"run_tasks",
"main"
] | 3 | [
[
"run_tasks",
"run_command"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4f7ca29a8509383a313c876df00cacc0a63f1d1f | 685e309b29b339f35346429ed6603e33b9a8fe50 | |||
v1.0 | instruct | Docs | Docs: Python310_38397_I | You are tasked with creating a Python script that demonstrates advanced logging capabilities using the `syslog` module. Your script should:
1. **Open the syslog**:
- Use `openlog` to customize the logging behavior with a custom identifier (`ident`) and log option (`logoption`).
2. **Log messages with different prio... | import syslog
def configure_logging(ident: str, logoption: int, facility: int) -> None:
"""
Configures the syslog with the given identifier, log option, and facility.
"""
print(f"Configuring syslog with ident='{ident}', logoption={logoption}, facility={facility}...")
syslog.openlog(ident, logoption... | import syslog
from unittest.mock import patch
def test_configure_logging():
with patch('syslog.openlog') as mocked_openlog:
configure_logging('test_ident', syslog.LOG_PID | syslog.LOG_CONS, syslog.LOG_USER)
mocked_openlog.assert_called_with('test_ident', syslog.LOG_PID | syslog.LOG_CONS, syslog.LOG... | [
{
"docstring": "Configures the syslog with the given identifier, log option, and facility.",
"function_declaration": "def configure_logging(ident, logoption, facility):",
"function_name": "configure_logging",
"parameter_list": "(ident, logoption, facility)"
},
{
"docstring": "Logs messages w... | [
1,
1,
0,
0,
1,
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 syslog\n\ndef configure_logging(ident: str, logoption: int, facility: int) -> None:\n \"\"\"\n Configures the syslog with the given identifier, log option,... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00038397",
"row_id": 38397,
"seed_ids": "[133]"
} | 0.639243 | Docs: Python310_38397 | I | [
"configure_logging",
"log_messages",
"set_log_mask",
"reset_logging"
] | 4 | [
[
"reset_logging",
"configure_logging"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 04a7cfea969d82a039613f9104c8bdd0b97d404a | 5114ab498564a769d7690a2145703c5a14b5f857 | |||
v1.0 | instruct | Docs | Docs: Scikit_38415_I | You are provided with a dataset of house prices and various features describing the houses. Your task is to build a robust machine learning model using the scikit-learn library to predict house prices. Specifically, you are required to:
1. **Load and preprocess the dataset:**
- Handle missing values appropriately.
... | import pandas as pd
import numpy as np
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRe... | from solution import load_and_preprocess_data, train_and_evaluate_models
import numpy as np
import pandas as pd
from sklearn.datasets import make_regression
# Create a synthetic dataset to simulate house prices
def create_synthetic_house_price_data():
X, y = make_regression(n_samples=100, n_features=10, noise=0.1)... | [
{
"docstring": null,
"function_declaration": "def load_and_preprocess_data(filepath):",
"function_name": "load_and_preprocess_data",
"parameter_list": "(filepath)"
},
{
"docstring": null,
"function_declaration": "def train_and_evaluate_models(filepath):",
"function_name": "train_and_... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncode... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00038415",
"row_id": 38415,
"seed_ids": "[1]"
} | 0.578037 | Docs: Scikit_38415 | I | [
"load_and_preprocess_data",
"train_and_evaluate_models"
] | 2 | [
[
"train_and_evaluate_models",
"load_and_preprocess_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"sklearn"
] | false | 864cd49e405197ded4346c91fbe8780622351d47 | 2b4906bff8b88870bb59aecdb7b770575180558a | |||
v1.0 | instruct | Docs | Docs: Python310_38496_I | #### Context Management with `contextvars`
**Objective:**
In this task, you will create a set of functions to manage context-local state using the `contextvars` module. Specifically, you will create functions that:
1. Initialize context variables with default values.
2. Modify the values of context variables.
3. Reset... | import contextvars
from typing import Any, Callable
# Step 1: Initialize context variable
user_id = contextvars.ContextVar('user_id', default=None)
def set_user_id(new_id: int) -> contextvars.Token:
"""
Sets the user_id context variable to new_id and returns the token representing the context state before the... | import contextvars
from solution import set_user_id, reset_user_id, run_in_custom_context, user_id
def get_current_user_id():
"""
Helper function to return the current value of the user_id context variable.
"""
return user_id.get()
def test_set_user_id():
token = set_user_id(123)
assert get_cu... | [
{
"docstring": "Sets the user_id context variable to new_id and returns the token representing the context state before the call.",
"function_declaration": "def set_user_id(new_id):",
"function_name": "set_user_id",
"parameter_list": "(new_id)"
},
{
"docstring": "Resets the user_id context v... | [
1,
1,
1
] | 3 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import contextvars\nfrom typing import Any, Callable\n\n# Step 1: Initialize context variable\nuser_id = contextvars.ContextVar('user_id', default=None)\n\ndef set_user... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038496",
"row_id": 38496,
"seed_ids": "[392]"
} | 0.325935 | Docs: Python310_38496 | I | [
"set_user_id",
"reset_user_id",
"run_in_custom_context"
] | 3 | [
[
"run_in_custom_context",
"reset_user_id"
],
[
"run_in_custom_context",
"set_user_id"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1eb36ec6f041d986f85e2c985efeeaa587df8787 | 0d9f626ee01c589ff1cfc32fc60731b5de53b9c4 | |||
v1.0 | instruct | Docs | Docs: Python310_38501_I | **Objective**: In this task, you need to demonstrate your understanding of parsing argument lists, dynamically generating documentation, and handling input constraints in Python functions by implementing a pseudo Argument Clinic-like mechanism in Python.
### Problem Description:
You are required to implement a simplif... | def argument_clinic(param_types: dict):
def decorator(f):
def wrapped_func(*args, **kwargs):
# Check positional arguments
for i, (arg_name, arg_type) in enumerate(param_types.items()):
if i < len(args):
if not isinstance(args[i], arg_type):
... | def test_example_function_valid():
assert example_function(5, "testName", True) == "n: 5, name: testName, flag: True"
def test_example_function_type_error_positional():
try:
example_function("5", "testName", True)
except TypeError as e:
assert str(e) == "Argument 'n' must be of type int"
... | [
{
"docstring": null,
"function_declaration": "def argument_clinic(param_types):",
"function_name": "argument_clinic",
"parameter_list": "(param_types)"
},
{
"docstring": "Function that demonstrates example usage of argument_clinic",
"function_declaration": "def example_function(n, name, ... | [
0,
1,
0
] | 1 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def argument_clinic(param_types: dict):\n def decorator(f):\n def wrapped_func(*args, **kwargs):\n # Check argument types\n for i, (arg_... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00038501",
"row_id": 38501,
"seed_ids": "[64]"
} | 0.641727 | Docs: Python310_38501 | I | [
"argument_clinic",
"example_function",
"another_example"
] | 3 | [
[
"another_example",
"argument_clinic"
],
[
"example_function",
"argument_clinic"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | dcfc4cee74d5c5e696d08891500059a30e4ea5eb | bd067341044a4b93f5e4db313e96812bde198b97 | |||
v1.0 | instruct | Docs | Docs: Python310_38567_I | ### Advanced SQLite Management in Python
You are given the task to manage an SQLite database using Python's `sqlite3` module. This database must handle frequent insertion of records, ensure data integrity, and make use of both custom data adapters and converters. The following coding tasks will test your understanding... | import sqlite3
from datetime import datetime
class SensorReading:
def __init__(self, date, temperature, humidity):
self.date = date
self.temperature = temperature
self.humidity = humidity
def __repr__(self):
return f"SensorReading(date={self.date}, temperature={self.temperature... | import pytest
from solution import SensorReading, adapt_sensor_reading, convert_sensor_reading, setup_database, insert_data, fetch_data
def test_adapt_sensor_reading():
reading = SensorReading("2023-10-10", 23.5, 50.0)
adapted = adapt_sensor_reading(reading)
assert adapted == ("2023-10-10", 23.5, 50.0)
de... | [] | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sqlite3\n\nclass SensorReading:\n def __init__(self, date, temperature, humidity):\n self.date = date\n self.temperature = temperature\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00038567",
"row_id": 38567,
"seed_ids": "[103]"
} | 0.582913 | Docs: Python310_38567 | I | [
"adapt_sensor_reading",
"convert_sensor_reading",
"setup_database",
"insert_data",
"fetch_data",
"main"
] | 6 | [
[
"insert_data",
"adapt_sensor_reading"
]
] | 1 | [] | false | [
"SensorReading"
] | true | pytest | true | [] | true | 75dc71373ebc5fd272b467e32a125303af6935b8 | c98a04d28cb1a81be97db9e8d369de60f1b38aa7 | |||
v1.0 | instruct | Docs | Docs: Python310_38642_I | **Question: Asynchronous Web Scraping with Timeout Handling**
**Objective:**
Implement a function that asynchronously scrapes data from a list of URLs and handles potential exceptions, including timeouts and non-existent domains. Use `ThreadPoolExecutor` to manage concurrent requests and return a dictionary containin... | import concurrent.futures
import urllib.request
import urllib.error
def fetch_url(url, timeout):
try:
with urllib.request.urlopen(url, timeout=timeout) as response:
return len(response.read())
except Exception as e:
return f"Error: {e}"
def fetch_urls(urls, timeout, max_workers):
... | from solution import fetch_urls
def test_fetch_urls_valid():
urls = [
'http://httpbin.org/get',
'https://jsonplaceholder.typicode.com/posts',
'http://www.example.com',
]
results = fetch_urls(urls, timeout=5, max_workers=3)
for url in urls:
assert isinstance(results[url],... | [
{
"docstring": null,
"function_declaration": "def fetch_url(url, timeout):",
"function_name": "fetch_url",
"parameter_list": "(url, timeout)"
},
{
"docstring": null,
"function_declaration": "def fetch_urls(urls, timeout, max_workers):",
"function_name": "fetch_urls",
"parameter_l... | [
1,
1,
0
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import concurrent.futures\nimport urllib.request\nimport urllib.error\n\ndef fetch_url(url, timeout):\n try:\n with urllib.request.urlopen(url, timeout=timeou... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00038642",
"row_id": 38642,
"seed_ids": "[347]"
} | 0.625514 | Docs: Python310_38642 | I | [
"fetch_url",
"fetch_urls"
] | 2 | [
[
"fetch_urls",
"fetch_url"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4b7ab2ff57dd0ed1db684df0a599692e9189b013 | 7b0900a9be5074fa74410ded5e7e081126db05b0 | |||
v1.0 | instruct | Docs | Docs: Python310_38717_I | ### Asynchronous File Downloader with Retry Logic
You are tasked with implementing an asynchronous file downloader that downloads multiple files concurrently with the ability to retry downloading in case of failure. This function should make use of asyncio's task management, synchronization, and exception handling fun... | import asyncio
import random
from typing import List
# Custom Exception for download errors
class DownloadError(Exception):
pass
async def download_file(url: str) -> str:
"""
Simulates downloading a file from the given URL.
It raises DownloadError with a 30% probability to simulate a download failure.... | import pytest
import asyncio
from solution import download_file, download_files, DownloadError
@pytest.mark.asyncio
async def test_download_file_success():
url = "http://example.com/success"
result = await download_file(url)
assert result == url
@pytest.mark.asyncio
async def test_download_file_failure():... | [] | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport random\nimport logging\nfrom typing import List\n\n# Set up logging\nlogging.basicConfig(level=logging.INFO)\n\nclass DownloadError(Exception):\n... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038717",
"row_id": 38717,
"seed_ids": "[360]"
} | 0.550635 | Docs: Python310_38717 | I | [
"download_file",
"download_files"
] | 2 | [
[
"download_files",
"download_file"
]
] | 1 | [] | false | [
"DownloadError"
] | true | pytest | true | [] | true | 5c29354610c56c9aac358e727842f801c3487221 | 70087a8b85f52dba00b817d742cb643493b4a2a7 | |||
v1.0 | instruct | Docs | Docs: Python310_38725_I | **Objective:**
Demonstrate your understanding of using Distutils to create various built distributions in Python.
### Problem Statement:
You need to write a Python script that automates the creation of various built distributions for a provided Python package and verifies their successful creation. The script shoul... | import os
import subprocess
import platform
def create_distribution(path, format):
"""
Creates a built distribution for a specified format.
"""
command = f'python setup.py sdist --formats={format}'
try:
subprocess.check_call(command, shell=True, cwd=path)
return True
except subp... | import os
import platform
import pytest
from solution import create_and_verify_distributions
def test_create_and_verify_distributions(monkeypatch):
test_path = '/tmp/test_package' # Use a temporary directory for testing
os.makedirs(test_path, exist_ok=True)
# Write a minimal setup.py
setup_content = ... | [
{
"docstring": "Creates a built distribution for a specified format.",
"function_declaration": "def create_distribution(path, format):",
"function_name": "create_distribution",
"parameter_list": "(path, format)"
},
{
"docstring": "Creates and verifies built distributions for the specified pa... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport subprocess\nimport platform\n\ndef create_and_verify_distributions(package_path):\n \"\"\"\n Creates various built distributions for a Python pa... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00038725",
"row_id": 38725,
"seed_ids": "[437]"
} | 0.507094 | Docs: Python310_38725 | I | [
"create_distribution",
"create_and_verify_distributions"
] | 2 | [
[
"create_and_verify_distributions",
"create_distribution"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | abaa9adef22ce2b16fba8a8519a23540c02b9ef6 | a94cecc796ed844a26f010eb27c6535ade9b69c0 | |||
v1.0 | instruct | Docs | Docs: Python310_38738_I | **Objective**: Demonstrate the ability to work with system error codes and handle exceptions using the Python `errno` module.
#### Problem Description
You are required to implement a function `retrieve_error_message` that takes an integer error code and returns either:
- A string that explains the error, or
- An appr... | import errno
def retrieve_error_message(err_code: int) -> str:
"""
Returns a string that explains the error, or
an appropriate built-in exception name if the error code maps directly to one of Python’s built-in exceptions.
"""
error_map = {
errno.EPERM: "PermissionError",
errno.ENO... | from solution import retrieve_error_message, describe_all_errors
import errno
def test_retrieve_error_message():
assert retrieve_error_message(errno.EPERM) == "PermissionError"
assert retrieve_error_message(errno.ENOENT) == "FileNotFoundError"
assert retrieve_error_message(errno.EBADF) == "Bad file descrip... | [
{
"docstring": "Returns a string that explains the error, or \nan appropriate built-in exception name if the error code maps directly to one of Python’s built-in exceptions.",
"function_declaration": "def retrieve_error_message(err_code):",
"function_name": "retrieve_error_message",
"parameter_list"... | [
0,
1,
1
] | 2 | easy | 0.667 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import errno\n\ndef retrieve_error_message(err_code: int) -> str:\n \"\"\"\n Returns the error message for a given error code, or the exception name\n if the e... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00038738",
"row_id": 38738,
"seed_ids": "[252]"
} | 0.526029 | Docs: Python310_38738 | I | [
"retrieve_error_message",
"describe_all_errors"
] | 2 | [
[
"describe_all_errors",
"retrieve_error_message"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9891646089892667f51fa52e03771e62325e69a2 | 03372d94f49aa34dbc44cb4b7400f2251a65b6f2 | |||
v1.0 | instruct | Docs | Docs: Pytorch_38767_I | ## Quantization Accuracy Improvement in PyTorch
### Objective
Your task is to implement a PyTorch function that prepares a given model for quantization by fusing Conv-BN layers and adjusting the dtype of specific layers to improve quantization accuracy.
### Description
You will implement the function `prepare_for_qua... | import torch
import torch.nn as nn
import torch.ao.quantization as quantization
def fuse_model(model):
layers_to_fuse = []
for name, module in model.named_children():
if isinstance(module, nn.Sequential):
fuse_model(module)
if isinstance(module, nn.Conv2d) or isinstance(module, nn.L... | import pytest
import torch
import torch.nn as nn
from solution import prepare_for_quantization
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.conv = nn.Conv2d(1, 20, 5, 1)
self.bn = nn.BatchNorm2d(20)
self.fc = nn.Linear(320, 10)
def ... | [
{
"docstring": null,
"function_declaration": "def fuse_model(model):",
"function_name": "fuse_model",
"parameter_list": "(model)"
},
{
"docstring": null,
"function_declaration": "def prepare_for_quantization(model, dtype_layers, dtype=torch.qint8):",
"function_name": "prepare_for_qua... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch import nn\nfrom torch.ao.quantization import fuse_modules, quantize_dynamic\nfrom typing import List\n\ndef prepare_for_quantization(model: tor... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00038767",
"row_id": 38767,
"seed_ids": "[141]"
} | 0.50949 | Docs: Pytorch_38767 | I | [
"fuse_model",
"prepare_for_quantization"
] | 2 | [
[
"prepare_for_quantization",
"fuse_model"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 9b6be62420a4ba8a9d72f171ce4f13c21190ed94 | 1b4e2a1c28db1b75fde89ad9910b93a1477cfa76 | |||
v1.0 | instruct | Docs | Docs: Python310_38795_I | **Performance Profiling Task**
Your task is to write a program that profiles the performance of the following Python function and then reports on the most time-consuming sections.
### Function to Profile
```python
def string_manipulation(input_string):
result = []
for i, char in enumerate(input_string):
... | import cProfile
import pstats
import io
def string_manipulation(input_string):
"""
Manipulates the input string by converting vowels to uppercase and consonants to lowercase.
"""
result = []
for i, char in enumerate(input_string):
if char in 'aeiouAEIOU':
result.append(char.uppe... | import subprocess
def test_profile_string_manipulation():
result = subprocess.run(["python", "solution.py"], capture_output=True, text=True)
output = result.stdout
assert "Top 10 function calls by cumulative time:" in output
assert "Function with highest total time spent:" in output
# ens... | [
{
"docstring": "Manipulates the input string by converting vowels to uppercase and consonants to lowercase.",
"function_declaration": "def string_manipulation(input_string):",
"function_name": "string_manipulation",
"parameter_list": "(input_string)"
},
{
"docstring": "Profiles the string_ma... | [
0,
0,
0,
1,
1,
1,
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 cProfile\nimport pstats\nimport io\n\ndef profile_string_manipulation():\n def string_manipulation(input_string):\n \"\"\"\n Converts each vowel... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00038795",
"row_id": 38795,
"seed_ids": "[142]"
} | 0.516129 | Docs: Python310_38795 | I | [
"string_manipulation",
"profile_string_manipulation"
] | 2 | [
[
"profile_string_manipulation",
"string_manipulation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2624201d32ed91283ce242d9a4fa1fba1d3990a6 | b9c3d8306e9526717ecc7f5aebc396b6cc16845e | |||
v1.0 | instruct | Docs | Docs: Python310_38834_I | ### Question: Implementing Custom Signal Handlers and Timer
You are required to write a Python program that performs the following tasks:
1. **Set up a signal handler** for the `SIGALRM` signal. This handler should print "Received SIGALRM. Exiting the program!" and then terminate the program using an appropriate func... | import signal
import sys
def handle_sigalrm(signum, frame):
"""
Signal handler for SIGALRM.
Prints a message and exits the program.
"""
print("Received SIGALRM. Exiting the program!")
sys.exit(0)
def setup_signal_handler():
"""
Sets up the signal handler for SIGALRM.
"""
signal... | import signal
import os
import subprocess
import pytest
# Since this functionality involves handling OS signals and involves timing,
# it's best tested through subprocess to observe the output.
def test_handle_sigalrm():
# Create a simple script as a string
script = """
import signal
import sys
def handle_s... | [
{
"docstring": "Signal handler for SIGALRM.\nPrints a message and exits the program.",
"function_declaration": "def handle_sigalrm(signum, frame):",
"function_name": "handle_sigalrm",
"parameter_list": "(signum, frame)"
},
{
"docstring": "Sets up the signal handler for SIGALRM.",
"functi... | [
0,
1,
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 signal\nimport sys\n\ndef handle_sigalrm(signum, frame):\n \"\"\"\n Signal handler for SIGALRM.\n Prints a message and terminates the program.\n \"\"... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00038834",
"row_id": 38834,
"seed_ids": "[253]"
} | 0.529805 | Docs: Python310_38834 | I | [
"handle_sigalrm",
"setup_signal_handler",
"schedule_alarm",
"long_running_task",
"main"
] | 5 | [
[
"setup_signal_handler",
"handle_sigalrm"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | bb734d1a6508b56c91bde1b500977e43210b71c7 | 624842457109471d5c3c5540e1eb2fb63ab939c4 | |||
v1.0 | instruct | Docs | Docs: Python310_38837_I | ### Python Development Mode and Resource Management
You are provided with a script that reads and processes a text file specified as a command-line argument. The current implementation, however, has some resource management issues that are only detected when Python Development Mode is enabled.
The existing script is ... | import sys
def process_file():
# Open the file using a with statement to ensure it is closed properly
with open(sys.argv[1]) as fp:
lines = fp.readlines()
process_lines(lines)
print("Processing complete")
def process_lines(lines):
# Placeholder for line processing code
pass
if __... | import os
import subprocess
import pytest
def create_temp_file(content):
filename = "temp_test_file.txt"
with open(filename, "w") as f:
f.write(content)
return filename
def test_process_file():
# Create a temporary file for the test
test_filename = create_temp_file("Line 1\nLine 2\nLine 3\... | [
{
"docstring": null,
"function_declaration": "def process_file():",
"function_name": "process_file",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def process_lines(lines):",
"function_name": "process_lines",
"parameter_list": "(lines)"
}
] | [
1,
1,
0,
1,
1,
1,
1,
0,
1,
0
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\n\ndef process_file():\n with open(sys.argv[1]) as fp:\n lines = fp.readlines()\n process_lines(lines)\n print(\"Processing complete\")\n... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00038837",
"row_id": 38837,
"seed_ids": "[249]"
} | 0.52465 | Docs: Python310_38837 | I | [
"process_file",
"process_lines"
] | 2 | [
[
"process_file",
"process_lines"
]
] | 1 | [
"process_lines"
] | false | [] | false | pytest | false | [] | true | 7466a2e5e732099db3f315e34889459126e6b5a8 | 54faf8ae2c64e94fd8ef66998e683807ea4d2f17 | |||
v1.0 | instruct | Docs | Docs: Python310_38848_I | ### ctypes Question
You are required to implement a Python function using the `ctypes` library to interact with a C standard library function. The function you need to interact with is `qsort` from the C standard library, which sorts an array.
Here’s what you need to do:
1. Implement a Python function `sort_integers... | import ctypes
from ctypes import CDLL, CFUNCTYPE, POINTER, c_int, c_void_p
from typing import List
def compare(a, b):
ai = ctypes.cast(a, ctypes.POINTER(c_int)).contents.value
bi = ctypes.cast(b, ctypes.POINTER(c_int)).contents.value
return ai - bi
def sort_integers(arr: List[int]) -> List[int]:
if no... | def test_sort_random_numbers():
assert sort_integers([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
def test_sort_already_sorted():
assert sort_integers([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_sort_reverse_order():
assert sort_integers([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
def... | [
{
"docstring": null,
"function_declaration": "def compare(a, b):",
"function_name": "compare",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def sort_integers(arr):",
"function_name": "sort_integers",
"parameter_list": "(arr)"
}
] | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport ctypes\nimport platform\n\ndef sort_integers(arr: List[int]) -> List[int]:\n if platform.system() == \"Linux\":\n libc = ctype... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00038848",
"row_id": 38848,
"seed_ids": "[400]"
} | 0.596415 | Docs: Python310_38848 | I | [
"compare",
"sort_integers"
] | 2 | [
[
"sort_integers",
"compare"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 85265717a0d704c80769f88482d6806563f1a188 | 3210b88171ccbab5bd9ce174909fa52b2b3026f2 | |||
v1.0 | instruct | Docs | Docs: Scikit_38909_I | Out-of-Core Learning Implementation
**Objective**: Implement an out-of-core learning pipeline to classify a large dataset using the scikit-learn library.
---
#### Question
You are provided with a large dataset that cannot fit into main memory at once. Your task is to implement an out-of-core learning pipeline using... | from sklearn.linear_model import SGDClassifier
from sklearn.feature_extraction.text import HashingVectorizer
import numpy as np
def stream_data(file_path, chunk_size=1000):
"""
Generator function to stream data from a file in mini-batches.
"""
with open(file_path, 'r') as file:
chunk = []
... | from solution import stream_data, process_and_train
import tempfile
import os
def test_stream_data():
# Setup
data = """0 This is a positive example.
1 This is a negative example.
0 Another positive example.
1 Another negative example."""
file_path = tempfile.mkstemp()[1]
with open(file_path, 'w')... | [
{
"docstring": "Generator function to stream data from a file in mini-batches.",
"function_declaration": "def stream_data(file_path, chunk_size=1000):",
"function_name": "stream_data",
"parameter_list": "(file_path, chunk_size=1000)"
},
{
"docstring": "Processes the data and trains the class... | [
1,
1,
1,
1,
0,
1,
1,
1,
0,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from sklearn.linear_model import SGDClassifier\nfrom sklearn.feature_extraction.text import HashingVectorizer\nimport numpy as np\n\ndef stream_data(file_path, chunk_si... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00038909",
"row_id": 38909,
"seed_ids": "[63]"
} | 0.435088 | Docs: Scikit_38909 | I | [
"stream_data",
"process_and_train"
] | 2 | [
[
"process_and_train",
"stream_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | d5d5b760ebafd635f35a66fb9dfcbc639ac6c1bc | a7c0854ce12c748a081c7d90bd4ff3521e05d382 | |||
v1.0 | instruct | Docs | Docs: Python310_38910_I | **Coding Assessment Question:**
### Debugging and Profiling in Python
#### Background
As a Python developer, you need to ensure that your code runs efficiently without errors and uses resources optimally. To achieve this, Python provides various libraries for debugging, profiling, monitoring memory usage, and measuri... | import pdb
import cProfile
import timeit
import tracemalloc
# Original inefficient Fibonacci function
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
# 1. Using pdb to debug
def debug_fib():
pdb.set_trace()
fib(10) # Example call to initialize debugging (use proper pdb commands to ... | from solution import fib, optimized_fib
def test_original_fib_base_cases():
assert fib(0) == 0
assert fib(1) == 1
def test_original_fib_small_n_values():
assert fib(2) == 1
assert fib(3) == 2
assert fib(4) == 3
assert fib(5) == 5
def test_optimized_fib_base_cases():
assert optimized_fib(0... | [
{
"docstring": null,
"function_declaration": "def fib(n):",
"function_name": "fib",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def debug_fib():",
"function_name": "debug_fib",
"parameter_list": "()"
},
{
"docstring": null,
"function_decla... | [
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 pdb\nimport cProfile\nimport timeit\nimport tracemalloc\n\n# Original inefficient Fibonacci function\ndef fib(n):\n if n <= 1:\n return n\n return f... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00038910",
"row_id": 38910,
"seed_ids": "[364]"
} | 0.669815 | Docs: Python310_38910 | I | [
"fib",
"debug_fib",
"profile_fib",
"optimized_fib",
"fib_time",
"trace_memory"
] | 6 | [
[
"debug_fib",
"fib"
],
[
"profile_fib",
"fib"
],
[
"trace_memory",
"optimized_fib"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 3105bb9c66c214fb9145789e3dd9fdc93242bee1 | 35e3ad23ed8cff70e0b13d6f980d6696055f64a9 | |||
v1.0 | instruct | Docs | Docs: Pytorch_38911_I | ### PyTorch Coding Assessment Question: Asynchronous Computation with `torch.futures`
#### Objective
In this assessment, you will demonstrate your understanding of asynchronous execution in PyTorch using `torch.futures`. You are required to write code that creates `Future` objects, performs distributed computation, an... | import torch
from torch.futures import Future, collect_all
def matrix_multiplication(matrix1, matrix2, device):
"""
Performs matrix multiplication on the specified device.
Args:
matrix1 (torch.Tensor): First matrix.
matrix2 (torch.Tensor): Second matrix.
device (torch.device): Device to ru... | import torch
from solution import matrix_multiplication, parallel_matrix_multiplication
def test_matrix_multiplication_cpu():
matrix1 = torch.randn(3, 3)
matrix2 = torch.randn(3, 3)
device = torch.device('cpu')
result = matrix_multiplication(matrix1, matrix2, device)
expected_result = torch.matmul(... | [
{
"docstring": "Performs matrix multiplication on the specified device.\n\nArgs:\nmatrix1 (torch.Tensor): First matrix.\nmatrix2 (torch.Tensor): Second matrix.\ndevice (torch.device): Device to run the computation on.\n\nReturns:\ntorch.Tensor: Resultant matrix after multiplication.",
"function_declaration"... | [
0,
1,
0,
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": "import torch\nfrom torch.futures import Future, collect_all\n\ndef matrix_multiplication(matrix1, matrix2, device):\n \"\"\"\n Performs matrix multiplication on a... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00038911",
"row_id": 38911,
"seed_ids": "[53]"
} | 0.451785 | Docs: Pytorch_38911 | I | [
"matrix_multiplication",
"parallel_matrix_multiplication"
] | 2 | [
[
"parallel_matrix_multiplication",
"matrix_multiplication"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 4ae97aa7c80970d5d70bf9b5f7532aadadd5fa98 | 197580e938cfb34c3123f4c581312834ee914be6 | |||
v1.0 | instruct | Docs | Docs: Scikit_38940_I | ### Question: Optimizing Prediction Performance with scikit-learn
You are given a dataset containing features and labels for a binary classification problem. Your task is to:
1. Implement a scikit-learn pipeline to preprocess the data and train a classifier.
2. Optimize the prediction latency and throughput according ... | import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import time
... | from solution import optimize_prediction_performance
import pandas as pd
def test_optimize_prediction_performance():
# Create a mock dataset
data = {
'feature1': [1, 2, 0, 4, 0],
'feature2': [0, 0, 3, 0, 5],
'feature3': [7, 8, 0, 0, 0],
'target': [0, 1, 0, 1, 0]
}
df = p... | [
{
"docstring": null,
"function_declaration": "def measure_latency_and_throughput(estimator, X, Y, bulk_size=1000):",
"function_name": "measure_latency_and_throughput",
"parameter_list": "(estimator, X, Y, bulk_size=1000)"
},
{
"docstring": null,
"function_declaration": "def optimize_pred... | [
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\nimport numpy as np\nfrom scipy.sparse import csr_matrix\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom skle... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00038940",
"row_id": 38940,
"seed_ids": "[64]"
} | 0.556106 | Docs: Scikit_38940 | I | [
"measure_latency_and_throughput",
"optimize_prediction_performance"
] | 2 | [
[
"optimize_prediction_performance",
"measure_latency_and_throughput"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"pandas",
"scipy",
"sklearn"
] | false | 625f3d81afc2fc7ac19bf75c9137aef01e3fe02a | dbb76083e472ae29f638935c3af14a0376222dbf | |||
v1.0 | instruct | Docs | Docs: Python310_38950_I | ### Python List Operations Module
Your task is to implement a Python module that provides functionalities similar to those described in the provided documentation for Python list objects using C-API. However, you must implement these functionalities in Python without using the list's built-in methods to demonstrate yo... | def is_list(obj):
"""
Returns True if the given object is a list, False otherwise.
"""
return isinstance(obj, list)
def create_list(length):
"""
Returns a new list of the specified length, filled with None.
"""
return [None] * length
def get_length(lst):
"""
Returns the length ... | def test_is_list():
assert is_list([1, 2, 3]) == True
assert is_list("hello") == False
assert is_list((1, 2, 3)) == False
assert is_list(None) == False
def test_create_list():
assert create_list(3) == [None, None, None]
assert create_list(0) == []
def test_get_length():
assert get_length([... | [
{
"docstring": "Returns True if the given object is a list, False otherwise.",
"function_declaration": "def is_list(obj):",
"function_name": "is_list",
"parameter_list": "(obj)"
},
{
"docstring": "Returns a new list of the specified length, filled with None.",
"function_declaration": "de... | [
0,
0,
1,
0,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_list(obj):\n \"\"\"\n Checks if the object is a list.\n \"\"\"\n return isinstance(obj, list)\n\ndef create_list(length):\n \"\"\"\n Creates a ... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00038950",
"row_id": 38950,
"seed_ids": "[12]"
} | 0.571757 | Docs: Python310_38950 | I | [
"is_list",
"create_list",
"get_length",
"get_item",
"set_item",
"insert_item",
"append_item",
"sort_list",
"reverse_list",
"to_tuple"
] | 10 | [
[
"get_item",
"get_length"
],
[
"insert_item",
"get_length"
],
[
"reverse_list",
"get_length"
],
[
"set_item",
"get_length"
],
[
"sort_list",
"get_length"
]
] | 5 | [] | false | [] | false | pytest | false | [] | true | 2cdcb99c4ef86aa050b826de88ec6b3bf69b0831 | 9b7c35f8d48b54809bfb664e4d87099fcca8e014 | |||
v1.0 | instruct | Docs | Docs: Scikit_38957_I | ### Feature Extraction and Classification Using Scikit-Learn
You are provided with a dataset of textual movie reviews and their associated ratings (positive or negative). Your task is to build a machine learning pipeline that preprocesses the text data, extracts relevant features using suitable methods from scikit-lea... | from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Example preloaded data
dataset = [
{"review": "I loved ... | from solution import load_data, build_pipeline, train_and_evaluate
def test_load_data():
X_train, X_test, y_train, y_test = load_data()
assert len(X_train) > 0
assert len(X_test) > 0
assert len(y_train) > 0
assert len(y_test) > 0
def test_build_pipeline():
pipeline = build_pipeline()
asser... | [
{
"docstring": null,
"function_declaration": "def load_data():",
"function_name": "load_data",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def build_pipeline():",
"function_name": "build_pipeline",
"parameter_list": "()"
},
{
"docstring": null,... | [
0,
0,
1,
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": "import numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.pipeline ... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00038957",
"row_id": 38957,
"seed_ids": "[40]"
} | 0.655585 | Docs: Scikit_38957 | I | [
"load_data",
"build_pipeline",
"train_and_evaluate"
] | 3 | [
[
"train_and_evaluate",
"build_pipeline"
]
] | 1 | [] | false | [] | false | pytest | true | [
"sklearn"
] | false | 800a23654aafb9b2621272425bf177a8a680618d | 0591967505e442f38e6b376fe77a7ec7252e68bc | |||
v1.0 | instruct | Docs | Docs: Python310_39043_I | **Question: Create a Custom Animation Using the Turtle Module**
**Objective:**
You are required to demonstrate your understanding of the Python turtle graphics module by creating an advanced animation. The animation will feature multiple turtles that perform synchronized and unsynchronized movements and interactions.
... | import turtle
import threading
def move_in_circle(t, radius=100, steps=120):
t.pendown()
for _ in range(steps):
t.circle(radius, extent=360/steps)
if _ == steps // 2:
t.penup()
t.pencolor("darkred")
t.pendown()
def move_in_square(t, side=150):
t.pendown(... | import pytest
import turtle
from solution import create_custom_animation
def test_create_custom_animation():
# Actual unit testing for graphical applications like turtle is complex.
# Since turtle requires GUI, automatic testing isn't feasible.
# This test is a dummy and would normally require an environm... | [
{
"docstring": null,
"function_declaration": "def move_in_circle(t, radius=100, steps=120):",
"function_name": "move_in_circle",
"parameter_list": "(t, radius=100, steps=120)"
},
{
"docstring": null,
"function_declaration": "def move_in_square(t, side=150):",
"function_name": "move_i... | [
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 turtle\nimport threading\n\ndef move_in_circle(turtle_obj, radius, pen_colors):\n turtle_obj.penup()\n turtle_obj.goto(radius, 0)\n turtle_obj.pendown()... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00039043",
"row_id": 39043,
"seed_ids": "[179]"
} | 0.651799 | Docs: Python310_39043 | I | [
"move_in_circle",
"move_in_square",
"move_in_zigzag",
"synchronize_movement",
"stop_turtles",
"create_custom_animation"
] | 6 | [
[
"create_custom_animation",
"stop_turtles"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 77709b6563f4e14e2f28f9ac4d98442776152471 | 7ea6925dfb7bb2201b43325a3e401c76056021b6 | |||
v1.0 | instruct | Docs | Docs: Python310_39048_I | In this problem, you are tasked with handling multiple signals in Python to safely manage a time-bound operation. You must use signal handling to ensure that a specific task does not run indefinitely and can be interrupted gracefully.
### Specifications
**Function**: `timed_execution`
#### Description:
Implement a ... | import signal
class TimeoutException(Exception):
pass
def handler(signum, frame):
raise TimeoutException("Function execution exceeded timeout")
def timed_execution(timeout, task):
# Set the signal handler and the alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
try:
... | import pytest
import time
from solution import timed_execution, TimeoutException
def sample_task_short():
time.sleep(1)
return "Task Completed - Short"
def sample_task_long():
time.sleep(5)
return "Task Completed - Long"
def sample_task_instant():
return "Task Completed - Instant"
def test_timed... | [] | [
0,
1,
1,
0,
0,
0,
0,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\n\nclass TimeoutException(Exception):\n pass\n\ndef handler(signum, frame):\n raise TimeoutException(\"Function execution exceeded timeout\")\n\ndef... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039048",
"row_id": 39048,
"seed_ids": "[253]"
} | 0.632424 | Docs: Python310_39048 | I | [
"handler",
"timed_execution"
] | 2 | [
[
"timed_execution",
"handler"
]
] | 1 | [] | false | [
"TimeoutException"
] | true | pytest | true | [] | true | 4849e17d3a84e9939b080c8f736a04f959220c42 | b833616d553ebbe2ae5afaf314c8a9897557a3de | |||
v1.0 | instruct | Docs | Docs: Python310_39140_I | ### Objective
To test the understanding of Python's `random` module, including its basic functions, sequence operations, and statistical distributions.
### Problem Statement
You are tasked with simulating the results of a simplified game show. The game show involves:
1. Selecting random contestants from the audience.
... | import random
def select_contestants(population, k):
"""
Returns a list of k unique contestants chosen randomly from the population list.
Raises a ValueError if k is greater than the population size.
"""
if k > len(population):
raise ValueError("Number of contestants to select cannot exceed... | from solution import select_contestants, shuffle_contestants, assign_scores, generate_reproducible_results
def test_select_contestants():
population = ["Alice", "Bob", "Carol", "Dave", "Eve"]
result = select_contestants(population, 3)
assert len(result) == 3
assert all(contestant in population for cont... | [
{
"docstring": "Returns a list of k unique contestants chosen randomly from the population list.\nRaises a ValueError if k is greater than the population size.",
"function_declaration": "def select_contestants(population, k):",
"function_name": "select_contestants",
"parameter_list": "(population, k... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\n\ndef select_contestants(population, k):\n \"\"\"\n Returns a list of k unique contestants chosen randomly from the population list.\n If k is g... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00039140",
"row_id": 39140,
"seed_ids": "[119]"
} | 0.593718 | Docs: Python310_39140 | I | [
"select_contestants",
"shuffle_contestants",
"assign_scores",
"generate_reproducible_results"
] | 4 | [
[
"generate_reproducible_results",
"assign_scores"
],
[
"generate_reproducible_results",
"select_contestants"
],
[
"generate_reproducible_results",
"shuffle_contestants"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 7162e5d3ba89c60b39e65ce490ec64247d701a27 | 9f6cf39796c014f3f57a65d72013c9d0bcd120a3 | |||
v1.0 | instruct | Docs | Docs: Python310_39147_I | ### Secure Data Transmission and Storage
In this task, you are required to implement two functions in Python to demonstrate secure data handling practices. Your implementation should consider the outlined security considerations and aim to mitigate potential vulnerabilities.
#### Function 1: `secure_data_transmission... | import base64
def secure_data_transmission(data: str) -> str:
"""
Encodes the input string data into base64 format.
Args:
data (str): The data to be encoded
Returns:
str: Base64 encoded string
"""
# Convert string data to bytes
bytes_data = data.encode('utf-8')
... | from solution import secure_data_transmission, secure_data_storage
import base64
import os
def test_secure_data_transmission():
data = "sensitive data"
encoded_data = secure_data_transmission(data)
expected_encoded_data = base64.b64encode(data.encode('utf-8')).decode('utf-8')
assert encoded_data == exp... | [
{
"docstring": "Encodes the input string data into base64 format.\n\nArgs:\n data (str): The data to be encoded\n\nReturns:\n str: Base64 encoded string",
"function_declaration": "def secure_data_transmission(data):",
"function_name": "secure_data_transmission",
"parameter_list": "(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 base64\n\ndef secure_data_transmission(data: str) -> str:\n \"\"\"\n Safely encodes a string into base64 format.\n\n Args:\n data (str): The data to ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039147",
"row_id": 39147,
"seed_ids": "[199]"
} | 0.721223 | Docs: Python310_39147 | I | [
"secure_data_transmission",
"secure_data_storage"
] | 2 | [
[
"secure_data_storage",
"secure_data_transmission"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7b741db35cb352398b0b029ec2bfe45c6a59a2d3 | e540c7635b0acf7fa31e0fceb06c61b1e39e04f6 | |||
v1.0 | instruct | Docs | Docs: Python310_39171_I | **Objective:**
Design an asyncio-based program that demonstrates the following features:
- Declaring coroutines and tasks.
- Running tasks concurrently.
- Handling task cancellations and timeouts.
- Using thread integration for IO-bound operations.
**Question:**
You are required to create a program for processing mult... | import asyncio
async def fetch_data(id, delay):
"""
Simulates fetching data by sleeping for a specified delay.
"""
await asyncio.sleep(delay)
return f"data_{id}"
async def process_data(data):
"""
Simulates processing of fetched data by converting it to uppercase.
"""
await asyncio.... | from solution import fetch_data, process_data, cancellable_task, fetch_and_process_data, main
import asyncio
def test_fetch_data():
result = asyncio.run(fetch_data(1, 1))
assert result == "data_1"
def test_process_data():
result = asyncio.run(process_data("data_1"))
assert result == "DATA_1"
def test... | [] | [
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 fetch_data(id, delay):\n await asyncio.sleep(delay)\n return f\"data_{id}\"\n\nasync def process_data(data):\n await asyncio.sleep(... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00039171",
"row_id": 39171,
"seed_ids": "[317]"
} | 0.619296 | Docs: Python310_39171 | I | [
"fetch_data",
"process_data",
"cancellable_task",
"fetch_and_process_data",
"main"
] | 5 | [
[
"fetch_and_process_data",
"cancellable_task"
],
[
"fetch_and_process_data",
"fetch_data"
],
[
"fetch_and_process_data",
"process_data"
]
] | 3 | [
"process_data"
] | false | [] | false | pytest | true | [] | true | 147db47ac307de2a55660a9fbff8fa1680cd50d3 | eb64b3fc08ea257ecfdb62ce07647a6b909629f0 | |||
v1.0 | instruct | Docs | Docs: Python310_39185_I | ### Advanced Coding Assessment: SQLite Database Operations in Python
#### Objective:
You are tasked with creating a Python script using the `sqlite3` module to manage an inventory database, perform various SQL operations, and manipulate custom data types. This will test your understanding of database connections, crea... | import sqlite3
from datetime import date
# Custom class Product
class Product:
def __init__(self, id, name, quantity, price, received_date):
self.id = id
self.name = name
self.quantity = quantity
self.price = price
self.received_date = received_date
def adapt_product(produc... | from solution import create_connection, create_table, insert_product, query_products, delete_product, backup_database, Product
import os
def test_create_connection():
conn = create_connection('test_inventory.db')
assert conn is not None
conn.close()
def test_create_table():
conn = create_connection('t... | [] | [
0,
1,
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 sqlite3\nfrom datetime import date\nimport datetime\n\nclass Product:\n def __init__(self, id, name, quantity, price, received_date):\n self.id = id\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00039185",
"row_id": 39185,
"seed_ids": "[103]"
} | 0.513405 | Docs: Python310_39185 | I | [
"adapt_product",
"convert_date",
"create_connection",
"create_table",
"insert_product",
"query_products",
"delete_product",
"backup_database"
] | 8 | [
[
"backup_database",
"create_connection"
]
] | 1 | [] | false | [
"Product"
] | true | pytest | true | [] | true | bcda590aaf877b5ba86e65283c27935141edb1f0 | 9eb7d05cc418f344997c72f20e62c99b7d92622a | |||
v1.0 | instruct | Docs | Docs: Pytorch_39220_I | #### Objective
You are given a task to analyze the performance of a PyTorch-based neural network training script using `torch.utils.bottleneck`. You will need to implement a neural network, train it on a synthetic dataset, and profile it using `torch.utils.bottleneck`. Finally, you should extract and interpret the pro... | import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
# Define the neural network
class SimpleNN(nn.Module):
def __init__(self):
super(SimpleNN, self).__init__()
self.fc1 = nn.Linear(100, 50)
self.relu = nn.ReLU()
self.... | import torch
from solution import SimpleNN, create_dataset
def test_neural_network_initialization():
model = SimpleNN()
assert isinstance(model, SimpleNN), "Model should be an instance of SimpleNN"
def test_dataset_creation():
X, Y = create_dataset()
assert X.shape == (10000, 100), "Features matrix sh... | [] | [
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 torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, TensorDataset\nimport torch.utils.bottleneck\n\nclass SimpleN... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00039220",
"row_id": 39220,
"seed_ids": "[26]"
} | 0.519988 | Docs: Pytorch_39220 | I | [
"create_dataset",
"train"
] | 2 | [
[
"train",
"create_dataset"
]
] | 1 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"torch"
] | false | 94aa084817d32cec45680cc96872c026c409ef2d | a131c376b680bebb4c385da07db8cc0029b8cdcf | |||
v1.0 | instruct | Docs | Docs: Python310_39254_I | #### Objective:
Create a Python script using the `getopt` module that will parse and validate the following command line arguments and options:
- Short options: `-u` (username), `-p` (password), `-s` (secure flag), `-h` (help)
- Long options: `--username`, `--password`, `--secure`, `--help`
#### Requirements:
1. Your... | import getopt
import sys
def usage():
print("Usage: script.py -u <username> -p <password> [-s] [-h]")
print(" or: script.py --username <username> --password <password> [--secure] [--help]")
def parse_args(argv):
username = None
password = None
secure = False
try:
opts, args = getopt... | import sys
import pytest
from solution import parse_args, usage
def test_help_message(monkeypatch, capsys):
test_args = ['script.py', '-h']
monkeypatch.setattr(sys, 'argv', test_args)
with pytest.raises(SystemExit):
parse_args(sys.argv[1:])
captured = capsys.readouterr()
assert "Usage:" in... | [
{
"docstring": null,
"function_declaration": "def usage():",
"function_name": "usage",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def parse_args(argv):",
"function_name": "parse_args",
"parameter_list": "(argv)"
}
] | [
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 getopt\nimport sys\n\ndef usage():\n \"\"\"\n Print the usage information for the script.\n \"\"\"\n print(\"Usage: script.py -u <username> -p <passw... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00039254",
"row_id": 39254,
"seed_ids": "[386]"
} | 0.464531 | Docs: Python310_39254 | I | [
"usage",
"parse_args"
] | 2 | [
[
"parse_args",
"usage"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 63fe9d3ce742c4f419f8effbc0df20e56ca8f4f0 | 61429544f106f9b72cac57a523688212e25e91cb | |||
v1.0 | instruct | Docs | Docs: Pytorch_39259_I | You are given a set of operations and data in real tensor form. Your task is to write a function that converts these real tensors into complex tensors, applies a series of transformations, and returns the resulting complex tensor.
#### Function Signature
```python
import torch
def transform_complex_tensor(real_tensor... | import torch
def apply_operations(tensor: torch.Tensor, ops: list) -> torch.Tensor:
for op in ops:
if op[0] == "add":
tensor = tensor + op[1]
elif op[0] == "mul":
tensor = tensor * op[1]
elif op[0] == "neg":
tensor = -tensor
else:
rais... | import torch
from solution import transform_complex_tensor
def test_transform_complex_tensor_basic():
real_tensor = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
real_ops = [("add", 2), ("mul", 3)]
imag_ops = [("neg",), ("mul", 0.5)]
result = transform_complex_tensor(real_tensor, real_ops, imag_ops)
... | [
{
"docstring": null,
"function_declaration": "def apply_operations(tensor, ops):",
"function_name": "apply_operations",
"parameter_list": "(tensor, ops)"
},
{
"docstring": null,
"function_declaration": "def transform_complex_tensor(real_tensor, real_ops, imag_ops):",
"function_name":... | [
0,
1,
1,
1,
0,
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 torch\n\ndef apply_operations(tensor, ops):\n for op in ops:\n if op[0] == \"add\":\n tensor = tensor + op[1]\n elif op[0] == \"mul\"... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039259",
"row_id": 39259,
"seed_ids": "[116]"
} | 0.528846 | Docs: Pytorch_39259 | I | [
"apply_operations",
"transform_complex_tensor"
] | 2 | [
[
"transform_complex_tensor",
"apply_operations"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | bf387c075c2d31792c20481840719ea854729a9c | 0763ad22679bcedd5d2bb760f8f61d6be65858a7 | |||
v1.0 | instruct | Docs | Docs: Scikit_39349_I | ### Question:
**Objective:** Implement a custom scoring function and use it to evaluate the performance of a machine learning model using scikit-learn.
**Problem Statement:**
You are provided with a dataset and asked to perform a regression task. The goal is to predict the output variable as accurately as possible. ... | import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
from sklearn.metrics import make_scorer
from sklearn.model_selection import cross_val_score
def custom_mape(y_true, y_pred):
"""
Custom Mean Absolute Percentage Error (MAPE) function.
... | import numpy as np
from solution import custom_mape, evaluate_model_with_mape
def test_custom_mape():
y_true = np.array([10, 20, 30, 40, 50])
y_pred = np.array([12, 18, 29, 41, 55])
expected_mape = np.mean(np.abs((y_true - y_pred) / y_true)) * 100
assert custom_mape(y_true, y_pred) == expected_mape
de... | [
{
"docstring": "Custom Mean Absolute Percentage Error (MAPE) function.\n\nParameters:\ny_true (array-like): True target values.\ny_pred (array-like): Predicted target values.\n\nReturns:\nfloat: MAPE value.",
"function_declaration": "def custom_mape(y_true, y_pred):",
"function_name": "custom_mape",
... | [
0,
0,
0,
0,
1,
1,
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 sklearn.datasets import fetch_california_housing\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import make_scorer\nfrom sklearn.model_se... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00039349",
"row_id": 39349,
"seed_ids": "[25]"
} | 0.677936 | Docs: Scikit_39349 | I | [
"custom_mape",
"evaluate_model_with_mape"
] | 2 | [
[
"evaluate_model_with_mape",
"custom_mape"
]
] | 1 | [] | false | [] | false | pytest | true | [
"numpy",
"sklearn"
] | false | 2926ac8ad62e41e74a5972799f53b9b2001d9e42 | d2f0c837447e4d82a100475462a1659328786b71 | |||
v1.0 | instruct | Docs | Docs: Python310_39433_I | You are required to write a Python program that mimics a simple task manager. This task manager should allow you to start a task, stop a task, and handle various signals during the task execution. Specifically, your program should be able to:
1. **Start a Task**: The task should be a loop running that increments a cou... | import signal
import time
# Global variable to control the task loop
running = True
def handle_signal(signum, frame):
global running
print(f"Signal handler called with signal {signum}")
if signum in [signal.SIGALRM, signal.SIGINT, signal.SIGTERM]:
running = False
def start_task():
global runn... | import pytest
import os
import signal
import time
import subprocess
def run_task_in_subprocess():
# Function to run the task manager in a subprocess
return subprocess.Popen(['python', 'solution.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def test_task_stops_on_alarm():
proc = run_task... | [
{
"docstring": null,
"function_declaration": "def handle_signal(signum, frame):",
"function_name": "handle_signal",
"parameter_list": "(signum, frame)"
},
{
"docstring": null,
"function_declaration": "def start_task():",
"function_name": "start_task",
"parameter_list": "()"
}
] | [
1,
0,
0,
1,
1,
1,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import signal\nimport time\n\n# Global flag for task running state\nrunning = True\n\ndef handle_signal(signum, frame):\n \"\"\"\n Signal handler function to hand... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00039433",
"row_id": 39433,
"seed_ids": "[253]"
} | 0.571305 | Docs: Python310_39433 | I | [
"handle_signal",
"start_task"
] | 2 | [
[
"start_task",
"handle_signal"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 89203cacb7c44897a45efb267bb6d2adcb374117 | b465a7dd33df1f196431d7fc27a32d992214c893 | |||
v1.0 | instruct | Docs | Docs: Python310_39452_I | **Task: Asynchronous Task Manager using `asyncio`**
**Objective:**
Implement an asynchronous task manager that can schedule and run multiple tasks concurrently, handle timeouts and cancellations, collect results, and gracefully manage task completions using Python's `asyncio` module.
**Background:**
You have been pro... | import asyncio
from typing import List, Tuple
async def task(identifier: str, delay: int) -> str:
await asyncio.sleep(delay)
return f"Task {identifier} completed after {delay} seconds."
async def task_manager(tasks: List[Tuple[str, int]], timeout: int) -> Tuple[List[str], List[asyncio.Task]]:
task_list = ... | import asyncio
import pytest
from solution import task, task_manager
@pytest.mark.asyncio
async def test_task():
assert await task("Test", 1) == "Task Test completed after 1 seconds."
@pytest.mark.asyncio
async def test_task_manager_all_complete():
tasks = [("A", 1), ("B", 2)]
timeout = 3
results, pen... | [
{
"docstring": null,
"function_declaration": "def run_task_manager(task_details, timeout):",
"function_name": "run_task_manager",
"parameter_list": "(task_details, timeout)"
}
] | [
0,
0,
1,
1,
0,
1,
1,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def task(identifier: str, delay: int) -> str:\n \"\"\"\n Simulates a task with a given delay.\n \"\"\"\... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00039452",
"row_id": 39452,
"seed_ids": "[317]"
} | 0.622532 | Docs: Python310_39452 | I | [
"task",
"task_manager",
"run_task_manager"
] | 3 | [
[
"run_task_manager",
"task_manager"
],
[
"task_manager",
"task"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 5524311ab81ae4438172ecc6bb3d8e65d61a54c7 | af94e2c1e299c92f8efe838d6c9b75e36d100ec7 | |||
v1.0 | instruct | Docs | Docs: Python310_39455_I | **Objective:** Demonstrate understanding and handling of asyncio exceptions in Python.
**Problem Statement:**
You are tasked with writing an asynchronous function `fetch_url` that fetches content from a list of URLs concurrently. The function should handle different asyncio-specific exceptions appropriately. Here are... | import asyncio
import aiohttp
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
async def fetch_content_from_url(url: str) -> str:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
asy... | import pytest
import asyncio
from unittest.mock import patch, AsyncMock
from solution import fetch_url
@pytest.fixture
def event_loop():
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
@pytest.mark.asyncio
async def test_fetch_url_timeout(event_loop):
urls = ["http://ex... | [] | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport aiohttp\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nasync def fetch_content_from_url(url:... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00039455",
"row_id": 39455,
"seed_ids": "[396]"
} | 0.546142 | Docs: Python310_39455 | I | [
"fetch_content_from_url",
"fetch_url"
] | 2 | [
[
"fetch_url",
"fetch_content_from_url"
]
] | 1 | [] | false | [] | false | pytest | true | [
"aiohttp"
] | false | 13f51b18d5a0004502fcde6d2758d46a638c1502 | 8938ae7734222b5b50d5da1c19b9f9a850268d7b | |||
v1.0 | instruct | Docs | Docs: Python310_39535_I | ### Asynchronous Programming with Platform-Specific Constraints
**Objective:**
You are tasked with writing a Python program that performs asynchronous file read and write operations, taking into consideration the platform-specific limitations of the `asyncio` library as described in the documentation.
**Requirements:... | import asyncio
import os
import platform
async def read_file_async(file_path):
"""
Asynchronously reads the content of a file.
If the platform does not support asyncio's file operations (e.g., Windows),
falls back to synchronous reading using a thread pool.
:param file_path: str - Path to... | import os
import pytest
import asyncio
from solution import read_file_async, write_file_async
@pytest.fixture(scope="module")
def event_loop():
"""Create an instance of the default event loop for each test case."""
loop = asyncio.get_event_loop()
yield loop
loop.close()
@pytest.fixture
def test_file(... | [
{
"docstring": null,
"function_declaration": "def _sync_read_file(file_path):",
"function_name": "_sync_read_file",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def _sync_write_file(file_path, data):",
"function_name": "_sync_write_file",
"para... | [
1,
0,
0,
1,
0,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import asyncio\nimport os\nimport platform\n\nasync def read_file_async(file_path):\n \"\"\"\n Asynchronously reads the content of a file.\n \n If the platf... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00039535",
"row_id": 39535,
"seed_ids": "[370]"
} | 0.51583 | Docs: Python310_39535 | I | [
"read_file_async",
"write_file_async",
"_sync_read_file",
"_sync_write_file"
] | 4 | [
[
"read_file_async",
"_sync_read_file"
],
[
"write_file_async",
"_sync_write_file"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 459c0b1e02055fffc78121d75dd52fb5c45cd8d1 | b2260437e3610fdccd045814e71c120aa6d184a1 | |||
v1.0 | instruct | Docs | Docs: Seaborn_39536_I | Titanic Data Visualization Challenge
**Objective:**
Create a Seaborn-based visualization to explore survival rates on the Titanic, segmented by different demographic groups. You will utilize advanced plotting techniques such as faceting, stacking, and histogram adjustments provided by the Seaborn library.
**Instructi... | import seaborn.objects as so
from seaborn import load_dataset
import matplotlib.pyplot as plt
def plot_titanic_data():
# Load the Titanic dataset
titanic = load_dataset("titanic")
# Faceted Bar Chart with Stacking
bar_plot = (
so.Plot(titanic, x="class", color="sex", y="alive")
.facet(... | import pytest
from solution import plot_titanic_data, generate_plots
import seaborn.objects as so
from seaborn import load_dataset
def test_titanic_data_loading():
titanic = load_dataset("titanic")
assert not titanic.empty
def test_bar_chart_creation():
titanic = load_dataset("titanic")
assert titanic... | [
{
"docstring": null,
"function_declaration": "def plot_titanic_data():",
"function_name": "plot_titanic_data",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def generate_plots():",
"function_name": "generate_plots",
"parameter_list": "()"
}
] | [
1,
0,
1,
0,
1,
1,
0,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import seaborn.objects as so\nfrom seaborn import load_dataset\nimport matplotlib.pyplot as plt\n\ndef titanic_visualization():\n # Load the Titanic dataset\n tit... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00039536",
"row_id": 39536,
"seed_ids": "[54]"
} | 0.579929 | Docs: Seaborn_39536 | I | [
"plot_titanic_data",
"generate_plots"
] | 2 | [
[
"generate_plots",
"plot_titanic_data"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"seaborn"
] | false | 5efc48e002dd620c0b3729452193ece873755e5c | 915174af18f8dcb43899bef8b2f34ad2a9d116f0 | |||
v1.0 | instruct | Docs | Docs: Pytorch_39538_I | #### Objective:
In this task, you will implement a custom neural network training loop in PyTorch utilizing the `torch.compile` feature for optimization. Additionally, you will demonstrate the integration of NumPy operations within the PyTorch computation graph and handle potential debugging scenarios.
#### Problem S... | import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
# Step 1: Define Neural Network model
class SimpleNN(nn.Module):
def __init__(self):
super(SimpleNN, self).__init__()
self.hidden = nn.Linear(2, 10)
self.activation = nn.ReLU()
self.output = nn.Linear(... | import pytest
from solution import SimpleNN, generate_dataset, normalize_data
def test_model_forward():
model = SimpleNN()
sample_data = torch.tensor([[0.5, -0.5]], dtype=torch.float32)
output = model(sample_data)
assert output.shape == (1, 1), "Output shape should be (1, 1)"
assert 0.0 <= output.i... | [] | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\n\n# Step 1: Define Neural Network model\nclass SimpleNN(nn.Module):\n def __ini... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00039538",
"row_id": 39538,
"seed_ids": "[121]"
} | 0.538314 | Docs: Pytorch_39538 | I | [
"generate_dataset",
"normalize_data",
"train_model"
] | 3 | [
[
"train_model",
"generate_dataset"
],
[
"train_model",
"normalize_data"
]
] | 2 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"numpy",
"torch"
] | false | ccaa36128454c15f2a621501f5f615995e965f4f | 2c082b7b6194179ee9b266b8439f159dc3d29201 | |||
v1.0 | instruct | Docs | Docs: Python310_39539_I | ### Task: Dynamic Class Creation and Manipulation
You are tasked with dynamically creating classes and manipulating their types using the `types` module in Python. The objective is to create a base class and a derived class dynamically, utilizing custom metaclasses and dynamic attributes. You will also need to create ... | import types
def create_meta_class_logger():
class MetaClassLogger(type):
def __new__(cls, name, bases, dct):
print(f"Creating class: {name}")
return super().__new__(cls, name, bases, dct)
return MetaClassLogger
MetaClassLogger = create_meta_class_logger()
def create_dynamic_b... | from solution import create_dynamic_base, create_dynamic_derived, demonstrate_dynamic_classes
def test_dynamic_base_creation():
DynamicBase = create_dynamic_base()
assert DynamicBase.__name__ == "DynamicBase"
assert DynamicBase.class_attr == "Base Class"
instance = DynamicBase()
assert instanc... | [] | [
0,
0,
0,
1,
0,
0,
0,
1,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import types\n\ndef create_meta_class_logger():\n class MetaClassLogger(type):\n def __new__(mcs, name, bases, class_dict):\n print(f\"Creating cla... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00039539",
"row_id": 39539,
"seed_ids": "[372]"
} | 0.424851 | Docs: Python310_39539 | I | [
"create_meta_class_logger",
"create_dynamic_base",
"create_dynamic_derived",
"demonstrate_dynamic_classes"
] | 4 | [
[
"create_dynamic_derived",
"create_dynamic_base"
],
[
"demonstrate_dynamic_classes",
"create_dynamic_base"
],
[
"demonstrate_dynamic_classes",
"create_dynamic_derived"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 2a683c40c15df58786290a4c649ae6732d96c70c | 5917e439341990cb3b939bc23fe75eb654b115f7 | |||
v1.0 | instruct | Docs | Docs: Pytorch_39555_I | #### Objective:
Demonstrate your understanding of PyTorch's `torch.futures` package and its `Future` type by implementing an asynchronous task management system.
#### Problem Statement:
You are required to implement a function `aggregate_squares` that performs the following tasks:
1. Launches multiple asynchronous t... | import torch
import torch.futures
def compute_square_async(n: int) -> torch.futures.Future:
"""
Simulates an asynchronous operation to compute the square of a given number n.
Args:
- n (int): The number to square asynchronously.
Returns:
- torch.futures.Future: A future object holding... | from solution import compute_square_async, aggregate_squares
def test_compute_square_async():
future = compute_square_async(3)
assert future.wait() == 9
def test_aggregate_squares_with_positive_numbers():
numbers = [1, 2, 3, 4]
assert aggregate_squares(numbers) == 30
def test_aggregate_squares_with_z... | [
{
"docstring": "Simulates an asynchronous operation to compute the square of a given number n.\n\nArgs:\n- n (int): The number to square asynchronously.\n\nReturns:\n- torch.futures.Future: A future object holding the result of n squared.",
"function_declaration": "def compute_square_async(n):",
"functi... | [
1,
0,
1,
1,
1,
0,
1,
1,
0,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nimport torch.futures\nfrom typing import List\n\ndef compute_square_async(n: int) -> torch.futures.Future:\n \"\"\"\n Simulates an asynchronous oper... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00039555",
"row_id": 39555,
"seed_ids": "[53]"
} | 0.573776 | Docs: Pytorch_39555 | I | [
"compute_square_async",
"aggregate_squares"
] | 2 | [
[
"aggregate_squares",
"compute_square_async"
]
] | 1 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 4011c2aa9b5de1a437d13fa919e50f88f854377c | c6d2a0c0055e3e14f5a3b60320045114ba4f70c0 | |||
v1.0 | instruct | Docs | Docs: Python310_39560_I | ### Sorting Algorithm Implementation and Analysis
#### **Objective:**
Implement a custom sorting function in Python and analyze its performance. This task assesses your understanding of sorting algorithms and the ability to optimize and analyze code performance.
#### **Problem Statement:**
You are required to write a... | from typing import List
import time
import random
def custom_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers using the Merge Sort algorithm.
"""
if len(arr) <= 1:
return arr
def merge(left: List[int], right: List[int]) -> List[int]:
sorted_list = []
i = j = ... | from solution import custom_sort, analyze_sort
import random
def test_custom_sort_short_list():
assert custom_sort([34, 7, 23, 32, 5, 62]) == [5, 7, 23, 32, 34, 62]
def test_custom_sort_sorted_list():
assert custom_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
def test_custom_sort_reverse_sorted_list():
asser... | [
{
"docstring": "Sorts a list of integers using the Merge Sort algorithm.",
"function_declaration": "def custom_sort(arr):",
"function_name": "custom_sort",
"parameter_list": "(arr)"
},
{
"docstring": "Compares the performance of custom_sort and Python's built-in sorted() function.",
"fun... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nimport time\n\ndef merge_sort(arr):\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n left_half = merge_sort(arr[:mid])\n rig... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039560",
"row_id": 39560,
"seed_ids": "[73]"
} | 0.612673 | Docs: Python310_39560 | I | [
"custom_sort",
"analyze_sort"
] | 2 | [
[
"analyze_sort",
"custom_sort"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d43b6ea4a68a17a5cfb106cf6a8590fede74c076 | 477b53662a039b5fc9aca34f5254b66fb09db7a6 | |||
v1.0 | instruct | Docs | Docs: Python310_39576_I | ## Coding Assessment Question
### Objective
Your task is to create a function that processes data in a performance-efficient manner using the functionalities available in the `functools` module of Python. Your function will read a list of numbers, apply a transformation, and return the results. You must utilize cachin... | from functools import lru_cache, partial
from typing import List
# Step 1: Implement cached Fibonacci function
@lru_cache(maxsize=None)
def fib(n: int) -> int:
"""
Returns the nth Fibonacci number.
"""
if n < 2:
return n
return fib(n-1) + fib(n-2)
# Step 2: Implement the scaling function a... | from solution import fib, scale, process_numbers
def test_fib():
assert fib(0) == 0
assert fib(1) == 1
assert fib(2) == 1
assert fib(3) == 2
assert fib(10) == 55
assert fib(20) == 6765
def test_scale():
assert scale(10, 5) == 50
assert scale(2, 3) == 6
def test_process_numbers():
... | [
{
"docstring": "Returns the nth Fibonacci number.",
"function_declaration": "def fib(n):",
"function_name": "fib",
"parameter_list": "(n)"
},
{
"docstring": "Scales the value by the given factor.",
"function_declaration": "def scale(factor, value):",
"function_name": "scale",
"pa... | [
1,
0,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import lru_cache, partial\nfrom typing import List\n\n# Step 1: Implement cached Fibonacci function\n@lru_cache(maxsize=None)\ndef fib(n: int) -> int:\n ... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039576",
"row_id": 39576,
"seed_ids": "[236]"
} | 0.677176 | Docs: Python310_39576 | I | [
"fib",
"scale",
"process_numbers"
] | 3 | [
[
"process_numbers",
"fib"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9450c2c50adf42e52b30ce60768f7ff1bcd7abe2 | 0123759d1b747d9319669d7e1312b6779dc0d6c0 | |||
v1.0 | instruct | Docs | Docs: Scikit_39604_I | ### Gaussian Process Regression with Custom Kernels
#### Objective:
Implement a Gaussian Process Regressor using scikit-learn. Your task is to:
1. Train the model with multiple kernels.
2. Optimize the hyperparameters of the kernels.
3. Evaluate the performance on a test dataset.
#### Problem Statement:
You are provi... | import numpy as np
import matplotlib.pyplot as plt
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, Matern
from sklearn.metrics import mean_squared_error
# Function to train and evaluate GPR with given kernel
def train_evaluate_gpr(X_train, y_train, X_test... | from solution import train_evaluate_gpr, execute_workflow
import numpy as np
from sklearn.gaussian_process.kernels import RBF, Matern
def test_gpr_rbf_kernel():
np.random.seed(42)
X_train = np.random.rand(10, 1) * 10
y_train = np.sin(X_train).ravel() + np.random.normal(0, 0.1, X_train.shape[0])
X_test ... | [
{
"docstring": "Train and evaluate Gaussian Process Regressor with the provided kernel.\n\nParameters:\n- X_train: Training feature dataset\n- y_train: Training target values\n- X_test: Testing feature dataset\n- y_test: Testing target values\n- kernel: Kernel to be used in the Gaussian Process Regressor\n\nRet... | [
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 numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import RBF, Ma... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039604",
"row_id": 39604,
"seed_ids": "[41]"
} | 0.546376 | Docs: Scikit_39604 | I | [
"train_evaluate_gpr",
"execute_workflow"
] | 2 | [
[
"execute_workflow",
"train_evaluate_gpr"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"sklearn"
] | false | a54ef422405bec4e8bb557decbef275550ad8ff9 | 203ca9b24c350d5b256aac1d0fb50ec0e367785f | |||
v1.0 | instruct | Docs | Docs: Python310_39624_I | ### Question: Memory Leak Detection Using `tracemalloc`
You are given a Python application that seems to leak memory in some of its functions. Your task is to write a script using the `tracemalloc` module to identify the source of the memory leak.
#### Requirements:
1. Write a function `identify_memory_leak(app_funct... | import tracemalloc
import linecache
def display_top(snapshot, key_type='lineno', limit=10):
snapshot = snapshot.filter_traces((
tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
tracemalloc.Filter(False, "<unknown>"),
))
top_stats = snapshot.statistics(key_type)
print("Top %s... | from solution import identify_memory_leak
def test_no_memory_leak():
def noop():
pass
identify_memory_leak(noop, num_top_stats=5)
def test_memory_leak():
def leaking_function():
a = []
for _ in range(10000):
a.append("x" * 10000)
identify_memory_leak(leaking_funct... | [
{
"docstring": null,
"function_declaration": "def display_top(snapshot, key_type='lineno', limit=10):",
"function_name": "display_top",
"parameter_list": "(snapshot, key_type='lineno', limit=10)"
},
{
"docstring": null,
"function_declaration": "def identify_memory_leak(app_function, num_... | [
1,
1,
0,
0,
1,
1,
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 tracemalloc\nimport linecache\n\ndef display_top(snapshot, key_type='lineno', limit=10):\n snapshot = snapshot.filter_traces((\n tracemalloc.Filter(Fal... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039624",
"row_id": 39624,
"seed_ids": "[404]"
} | 0.533681 | Docs: Python310_39624 | I | [
"display_top",
"identify_memory_leak"
] | 2 | [
[
"identify_memory_leak",
"display_top"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dbc90a41c580abd4994f8eb95d5f080168c2e1f0 | 7cdeed1e307ce00964f2388a4d90592a406695cd | |||
v1.0 | instruct | Docs | Docs: Python310_39639_I | ### Question: Interactive Web Browser Opener
You are tasked with developing a Python script that provides an interactive way for users to open multiple URLs in either new tabs or new windows of their default web browser.
#### Function Requirements:
1. Write a function `choose_mode_and_open(urls, mode="tab")` that:
... | import webbrowser
def choose_mode_and_open(urls, mode="tab"):
"""
Opens the given URLs in the specified mode ("tab" or "window").
Parameters:
urls (list): List of URLs to open.
mode (str): Mode to open URLs in, either "tab" or "window".
Raises:
ValueError: If mode is not "tab" or "window"... | import pytest
from unittest.mock import patch
from solution import choose_mode_and_open, interactive_browser_opener
def test_choose_mode_and_open_tab():
with patch('webbrowser.open_new_tab') as mock_open_new_tab:
choose_mode_and_open(["https://www.google.com", "https://www.github.com"], mode="tab")
... | [
{
"docstring": "Opens the given URLs in the specified mode (\"tab\" or \"window\").\n\nParameters:\nurls (list): List of URLs to open.\nmode (str): Mode to open URLs in, either \"tab\" or \"window\".\n\nRaises:\nValueError: If mode is not \"tab\" or \"window\".",
"function_declaration": "def choose_mode_and... | [
0,
0,
0,
1,
1,
0,
0,
0,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import webbrowser\n\ndef choose_mode_and_open(urls, mode=\"tab\"):\n \"\"\"\n Opens URLs in the specified mode using the default web browser.\n \n :param ur... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00039639",
"row_id": 39639,
"seed_ids": "[290]"
} | 0.630396 | Docs: Python310_39639 | I | [
"choose_mode_and_open",
"interactive_browser_opener"
] | 2 | [
[
"interactive_browser_opener",
"choose_mode_and_open"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f47f7b374140bf80ddda5576b5e07dd2a3af3377 | 518b1443c0ccbd7280cee60c2a3a86f7e05a0e46 | |||
v1.0 | instruct | Docs | Docs: Seaborn_39665_I | ### Question: Advanced Visualization of Error Bars using Seaborn
**Objective:**
Your task is to visualize various types of error bars using the Seaborn package. This will assess your understanding of Seaborn's error bar functionality and your ability to customize and organize plots efficiently.
**Requirements:**
1. ... | import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# Function to generate a dataset
def generate_data(seed=0, size=200):
np.random.seed(seed)
data = np.random.normal(loc=0, scale=1, size=size)
return data
# Function to create individual plots
def create_plot(ax, data, errorbar_type):... | import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from solution import generate_data, create_plot, plot_errorbars
def test_generate_data_length():
data = generate_data()
assert len(data) == 200
def test_generate_data_mean_std():
data = generate_data()
mean = np.mean(data)
st... | [
{
"docstring": null,
"function_declaration": "def generate_data(seed=0, size=200):",
"function_name": "generate_data",
"parameter_list": "(seed=0, size=200)"
},
{
"docstring": null,
"function_declaration": "def create_plot(ax, data, errorbar_type):",
"function_name": "create_plot",
... | [
1,
0,
0,
0,
0,
0,
1,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# Function to generate a dataset\ndef generate_data(seed=0, size=200):\n \"\"\"\n Ge... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00039665",
"row_id": 39665,
"seed_ids": "[0]"
} | 0.634058 | Docs: Seaborn_39665 | I | [
"generate_data",
"create_plot",
"plot_errorbars"
] | 3 | [
[
"plot_errorbars",
"create_plot"
],
[
"plot_errorbars",
"generate_data"
]
] | 2 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"seaborn"
] | false | 0b5fdaf54570c27fcfa3cde0874bea34f4762755 | 23def575a22e44b2a7727fac9a3d105481af0f63 | |||
v1.0 | instruct | Docs | Docs: Python310_39740_I | ### Question: HMAC Implementation and Verification
You are tasked with implementing a secure message authentication system that uses the HMAC library in Python for ensuring the integrity and authenticity of messages.
**Your Task:**
1. Implement the function `create_hmac(key, message, algorithm)` which:
- Takes a ... | import hmac
import hashlib
def create_hmac(key, message, algorithm):
"""
Creates an HMAC hexdigest for a given message using the provided key and hashing algorithm.
Args:
key (bytes or bytearray): The key for HMAC generation.
message (str): The message to authenticate.
algorithm (s... | from solution import create_hmac, verify_hmac
def test_create_hmac_sha256():
key = b"supersecretkey"
message = "This is a secure message."
algorithm = "sha256"
hexdigest = create_hmac(key, message, algorithm)
assert isinstance(hexdigest, str)
assert len(hexdigest) == 64 # SHA-256 produces a 64... | [
{
"docstring": "Creates an HMAC hexdigest for a given message using the provided key and hashing algorithm.\n\nArgs:\n key (bytes or bytearray): The key for HMAC generation.\n message (str): The message to authenticate.\n algorithm (str): The hashing algorithm (e.g., 'sha256').\n\nReturns:\n str: Th... | [
0,
1,
1,
1,
0,
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 hmac\nimport hashlib\n\ndef create_hmac(key, message, algorithm):\n \"\"\"\n Creates an HMAC digest for the given message using the specified algorithm.\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00039740",
"row_id": 39740,
"seed_ids": "[298]"
} | 0.830715 | Docs: Python310_39740 | I | [
"create_hmac",
"verify_hmac"
] | 2 | [
[
"verify_hmac",
"create_hmac"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3bdede849b5d2ba7e48f75a31526eb6d0857afb3 | f24fae1bb1ebec9a0dbe4ccf35c06fb4109fb10e | |||
v1.0 | instruct | Docs | Docs: Python310_39773_I | ### Question: Implement a Hash-Based File Integrity Verification System
You are required to implement a system that verifies the integrity of files using secure hash functions provided by the `hashlib` module.
The system should be able to:
1. Generate a hash of a file using a specified hashing algorithm.
2. Compare ... | import hashlib
def hash_file(file_path, algorithm):
"""
Generates the hash of a file using the specified hashing algorithm.
Parameters:
- file_path (str): The path to the file.
- algorithm (str): The name of the hashing algorithm ('sha256', 'blake2b').
Returns:
- str: The hexadecimal dige... | import pytest
from solution import hash_file, verify_file
def test_hash_file_sha256():
with open("test_file.txt", "w") as f:
f.write("This is a test file.")
expected_hash = hashlib.sha256(b"This is a test file.").hexdigest()
assert hash_file("test_file.txt", "sha256") == expected_hash
def test_ha... | [
{
"docstring": "Generates the hash of a file using the specified hashing algorithm.\n\nParameters:\n- file_path (str): The path to the file.\n- algorithm (str): The name of the hashing algorithm ('sha256', 'blake2b').\n\nReturns:\n- str: The hexadecimal digest string representing the hash of the file.",
"fu... | [
1,
0,
1,
1,
0,
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 hash_file(file_path: str, algorithm: str) -> str:\n \"\"\"\n Generate the hash of a file using specified algorithm.\n \n :param file_p... | trial_gpt4o_5 | {
"original_instruction": "",
"prompt_id": "00039773",
"row_id": 39773,
"seed_ids": "[225]"
} | 0.665698 | Docs: Python310_39773 | I | [
"hash_file",
"verify_file"
] | 2 | [
[
"verify_file",
"hash_file"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4d38c347f495f3c284f4eb192994fade1e070139 | 4992c280f6f0a370f78b7e6d1efa873bfaade73c | |||
v1.0 | instruct | Docs | Docs: Python310_39787_I | ### Exception Handling and Custom Exception Class Implementation
#### Background:
In Python, robust error handling and custom exception creation are fundamental skills. Being able to raise meaningful exceptions and handle exceptions correctly ensures that your code is both resilient and maintainable. This task will as... | class ProcessingError(Exception):
pass
def process_data(data):
if not isinstance(data, list):
raise ProcessingError("An unexpected error occurred - Input should be a list")
if not data:
raise ValueError("List is empty")
sum_data = 0
for item in data:
if not isinstance(item... | import pytest
from solution import process_data, safe_process, ProcessingError
def test_process_data_valid_input():
assert process_data([10, 20, 30]) == 60
def test_process_data_type_error():
with pytest.raises(TypeError):
process_data([10, '20', 30])
def test_process_data_value_error():
... | [] | [
1,
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class ProcessingError(Exception):\n pass\n\ndef process_data(data):\n if not isinstance(data, list):\n raise ProcessingError(\"An unexpected error occurred... | trial_gpt4o_0 | {
"original_instruction": "",
"prompt_id": "00039787",
"row_id": 39787,
"seed_ids": "[256]"
} | 0.551309 | Docs: Python310_39787 | I | [
"process_data",
"safe_process"
] | 2 | [
[
"safe_process",
"process_data"
]
] | 1 | [
"process_data"
] | false | [
"ProcessingError"
] | true | pytest | true | [] | true | 9ff4120d35597c7cfe144f8f4aa874cdc1a5106e | 9a908c98fcfa2439eec2c23519919a4a770d5fc9 | |||
v1.0 | instruct | Docs | Docs: Python310_39798_I | ### Question: Implement a Custom Asynchronous Echo Server with Additional Logging
As an exercise, you will implement a custom TCP echo server that logs each received message with a timestamp to a file and echoes the message back to the client. This will help you understand the use of `asyncio` streams for handling net... | import asyncio
import datetime
async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
data = await reader.read(100) # Read up to 100 bytes from the client
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
... | import asyncio
import os
from solution import handle_client, start_server
async def mock_client(message, port):
reader, writer = await asyncio.open_connection('127.0.0.1', port)
print(f'Send: {message}')
writer.write(message.encode())
await writer.drain()
data = await reader.read(100)
print(... | [] | [
0,
1,
0,
1,
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 asyncio\nimport datetime\n\nasync def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):\n addr = writer.get_extra_info('peername')\n ... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00039798",
"row_id": 39798,
"seed_ids": "[182]"
} | 0.689515 | Docs: Python310_39798 | I | [
"handle_client",
"start_server"
] | 2 | [
[
"start_server",
"handle_client"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a5667679ddf7c31b01abeb1df136307be26386ec | 50e88098231541bf5ace5681f1e1ed7f86f14d8d | |||
v1.0 | instruct | Docs | Docs: Python310_39811_I | ### Question:
You are developing a secure file verification system that ensures the integrity and authenticity of files transferred over an insecure network. Your solution should use Python's `hashlib` module to achieve this.
#### Requirements:
1. Implement a function `generate_file_hash(filepath: str, algorithm: st... | import hashlib
def generate_file_hash(filepath: str, algorithm: str) -> str:
"""
Generate the hash for a file using the specified algorithm.
:param filepath: Path to the file whose hash is to be computed.
:param algorithm: Name of the hash algorithm to use.
:return: Hexadecimal string of the c... | import pytest
from tempfile import NamedTemporaryFile
from solution import generate_file_hash, verify_file_hash
def test_generate_file_hash_md5():
with NamedTemporaryFile(delete=True) as temp_file:
temp_file.write(b"hello world")
temp_file.flush()
expected_hash = hashlib.md5(b"hello world"... | [
{
"docstring": "Generate the hash for a file using the specified algorithm.\n\n:param filepath: Path to the file whose hash is to be computed.\n:param algorithm: Name of the hash algorithm to use.\n:return: Hexadecimal string of the computed hash value.",
"function_declaration": "def generate_file_hash(file... | [
1,
1,
0,
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 hashlib\n\ndef generate_file_hash(filepath: str, algorithm: str) -> str:\n \"\"\"\n Computes the hash of a file using the specified algorithm.\n \n A... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039811",
"row_id": 39811,
"seed_ids": "[225]"
} | 0.708722 | Docs: Python310_39811 | I | [
"generate_file_hash",
"verify_file_hash"
] | 2 | [
[
"verify_file_hash",
"generate_file_hash"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1d42f297c56396250004f123cd090f457ba39542 | 1260b2d3c83f7e0090676c3e1f620564eb11049f | |||
v1.0 | instruct | Docs | Docs: Pytorch_39822_I | **PyTorch Distributed Training with NCCL Debugging**
You are tasked to simulate a distributed machine learning training setup using PyTorch's `torch.distributed` package with the NCCL backend. You need to demonstrate your understanding of how to configure various NCCL-related environment variables to handle error case... | import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def setup_nccl_environment():
os.environ['TORCH_NCCL_ASYNC_ERROR_HANDLING'] = '1'
os.environ['TORCH_NCCL_ENABLE_TIMING'] = '1'
os.environ['TORCH_NCCL_ENABLE_MONITORING'] = '1'
os.environ['TORCH_NCCL_HEARTBEAT_TIM... | from solution import setup_nccl_environment, initialize_process_group
import os
def test_setup_nccl_environment():
setup_nccl_environment()
assert os.environ['TORCH_NCCL_ASYNC_ERROR_HANDLING'] == '1'
assert os.environ['TORCH_NCCL_ENABLE_TIMING'] == '1'
assert os.environ['TORCH_NCCL_ENABLE_MONITORING'] ... | [
{
"docstring": null,
"function_declaration": "def setup_nccl_environment():",
"function_name": "setup_nccl_environment",
"parameter_list": "()"
},
{
"docstring": null,
"function_declaration": "def initialize_process_group(rank, world_size):",
"function_name": "initialize_process_grou... | [
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 os\nimport torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\n\ndef setup_nccl_environment():\n os.environ['TORCH_NCCL_ASYNC_ERROR_H... | trial_gpt4o_6 | {
"original_instruction": "",
"prompt_id": "00039822",
"row_id": 39822,
"seed_ids": "[5]"
} | 0.445266 | Docs: Pytorch_39822 | I | [
"setup_nccl_environment",
"initialize_process_group",
"train"
] | 3 | [
[
"train",
"initialize_process_group"
],
[
"train",
"setup_nccl_environment"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | c85497f4ddb4b9c98ded509ef8a5979f732eb89c | e1bd23fb8a1da76aafd30ab568c07e53fd1f58c7 | |||
v1.0 | instruct | Docs | Docs: Python310_39957_I | **Objective:**
You are required to write a Python program that demonstrates understanding of multiple Python runtime services, including handling system parameters, usage of data classes, and effective resource management through context managers. This will include:
1. Retrieving system-specific information.
2. Impleme... | import sys
import platform
from dataclasses import dataclass
from contextlib import contextmanager
import traceback
def get_system_info() -> dict:
"""
Retrieves system-specific information using sys and platform modules.
"""
return {
"python_version": sys.version,
"platform_name": platf... | from solution import get_system_info, Book, log_file, faulty_function, safe_function
import os
def test_get_system_info():
info = get_system_info()
assert 'python_version' in info
assert 'platform_name' in info
assert 'command_line_args' in info
def test_book_class():
book = Book(title="Python 101... | [] | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import sys\nfrom dataclasses import dataclass\nfrom contextlib import contextmanager\nimport traceback\n\ndef get_system_info() -> dict:\n \"\"\"\n Retrieves syst... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00039957",
"row_id": 39957,
"seed_ids": "[146]"
} | 0.552376 | Docs: Python310_39957 | I | [
"get_system_info",
"log_file",
"faulty_function",
"safe_function"
] | 4 | [
[
"safe_function",
"faulty_function"
],
[
"safe_function",
"log_file"
]
] | 2 | [] | false | [
"Book"
] | true | pytest | true | [] | true | 1296b9f370f6e4657f7356c67e44d8e8047a95d1 | 7df7cbb12a8ff5e890d93a991e5678d34ffc4804 | |||
v1.0 | instruct | Docs | Docs: Python310_40028_I | ### Question: Implementing and Managing Python Threads in an Embedded Application
#### Objective:
Demonstrate your understanding of thread management, GIL handling, and initialization/finalization of the Python interpreter by creating a C extension that incorporates embedding Python and managing threads.
#### Task:
Y... | import threading
import time
def read_file_simulated(filename):
"""
Simulated Python function that performs a blocking I/O operation.
"""
try:
with open(filename, 'r') as file:
time.sleep(2) # Simulate a blocking read operation
content = file.read()
return conte... | import threading
import time
from pytest import raises
from solution import read_file_simulated, run_thread
def test_read_file_simulated_existing_file(tmp_path):
# Create a temporary file
temp_file = tmp_path / "example.txt"
temp_file.write_text("Hello, World!")
content = read_file_simulated(str(t... | [
{
"docstring": "Simulated Python function that performs a blocking I/O operation.",
"function_declaration": "def read_file_simulated(filename):",
"function_name": "read_file_simulated",
"parameter_list": "(filename)"
},
{
"docstring": null,
"function_declaration": "def run_thread():",
... | [
1,
0,
0,
1,
1,
0,
1,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import threading\nimport time\n\ndef read_file():\n \"\"\"\n Dummy function to simulate blocking I/O operation\n \"\"\"\n time.sleep(2) # Simulate a delay\... | trial_gpt4o_4 | {
"original_instruction": "",
"prompt_id": "00040028",
"row_id": 40028,
"seed_ids": "[55]"
} | 0.53487 | Docs: Python310_40028 | I | [
"read_file_simulated",
"run_thread"
] | 2 | [
[
"run_thread",
"read_file_simulated"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aff7423aba79c7583dcb9acb3a66576f803fa918 | 12196d495994084dff8ec6544f0b95f121470e90 | |||
v1.0 | instruct | Docs | Docs: Pytorch_40069_I | ## Coding Assessment Question
You are tasked with implementing and analyzing a neural network model using the new `torch.func` API in PyTorch 2.0. The specific focus will be on using function transforms to compute gradients and jacobians of the model parameters.
### Objective
1. Implement a neural network model for ... | import torch
from torch.func import grad, jacrev, functional_call
# Define model
class SimpleNN(torch.nn.Module):
def __init__(self, input_features, hidden_features, output_features):
super(SimpleNN, self).__init__()
self.fc1 = torch.nn.Linear(input_features, hidden_features)
self.fc2 = tor... | import torch
from solution import SimpleNN, compute_loss, compute_gradients, compute_jacobians
def test_compute_loss():
input_features = 10
hidden_features = 20
output_features = 1
batch_size = 64
model = SimpleNN(input_features, hidden_features, output_features)
params = dict(model.named_param... | [] | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import torch\nfrom torch.func import grad, jacrev, functional_call\n\n# Define a simple neural network model\nclass SimpleNN(torch.nn.Module):\n def __init__(self, i... | trial_gpt4o_3 | {
"original_instruction": "",
"prompt_id": "00040069",
"row_id": 40069,
"seed_ids": "[23]"
} | 0.535584 | Docs: Pytorch_40069 | I | [
"compute_loss",
"compute_gradients",
"compute_jacobians"
] | 3 | [
[
"compute_gradients",
"compute_loss"
]
] | 1 | [] | false | [
"SimpleNN"
] | true | pytest | true | [
"torch"
] | false | 4715238ea3b09f26195439c174e769b0c68febc5 | 13e22b815a6ab951c2a94b5e2418598f81253281 | |||
v1.0 | instruct | Docs | Docs: Python310_40106_I | **Question: Automating File Operations with Python Standard Library**
You are tasked with writing a Python script that automates the following operations:
1. **Create a new directory**: Use the `os` module to create a new directory named "example_dir" in the current working directory.
2. **Generate a File with Random... | import os
import random
import statistics
import zipfile
import datetime
def create_directory(directory_name):
if not os.path.exists(directory_name):
os.makedirs(directory_name)
log_event(f"Created directory: {directory_name}")
else:
log_event(f"Directory already exists: {directory_name... | import os
import zipfile
import pytest
# Assuming the solution is placed into a file named solution.py
from solution import create_directory, generate_random_numbers_file, read_numbers_from_file, compute_statistics, compress_file
def setup_module(module):
if not os.path.exists("example_dir"):
os.makedirs(... | [
{
"docstring": null,
"function_declaration": "def create_directory(directory_name):",
"function_name": "create_directory",
"parameter_list": "(directory_name)"
},
{
"docstring": null,
"function_declaration": "def generate_random_numbers_file(file_path):",
"function_name": "generate_r... | [
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": "import os\nimport random\nimport statistics\nimport zipfile\nfrom datetime import datetime\n\ndef create_directory(directory_name):\n if not os.path.exists(directory... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00040106",
"row_id": 40106,
"seed_ids": "[422]"
} | 0.664036 | Docs: Python310_40106 | I | [
"create_directory",
"generate_random_numbers_file",
"read_numbers_from_file",
"compute_statistics",
"compress_file",
"log_event",
"main"
] | 7 | [
[
"compress_file",
"log_event"
],
[
"compute_statistics",
"log_event"
],
[
"create_directory",
"log_event"
],
[
"generate_random_numbers_file",
"log_event"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | 36e4ccc169153c9d38a2789331136f6f613cae0e | 64c6edc16cdebf62c5519d5310c09b7c0ef9848e | |||
v1.0 | instruct | Docs | Docs: Python310_40183_I | ### Secure Message Authentication using HMAC
Implement a secure messaging system where multiple messages are sent and received. The system should verify the integrity and authenticity of these messages using the HMAC (Keyed-Hash Message Authentication Code) algorithm.
#### Requirements:
1. **Function `generate_hmac_k... | import hmac
import hashlib
import os
def generate_hmac_keys(n):
"""
Generates a list of n random secret keys, each 16 bytes long.
"""
return [os.urandom(16) for _ in range(n)]
def send_message(key, message, digestmod):
"""
Generates HMAC digest for the given message using the provided key an... | import pytest
from solution import generate_hmac_keys, send_message, receive_message, secure_communication
def test_generate_hmac_keys_length():
keys = generate_hmac_keys(3)
assert len(keys) == 3
assert all(len(key) == 16 for key in keys)
def test_send_message():
key = os.urandom(16)
message = "He... | [
{
"docstring": "Generates a list of n random secret keys, each 16 bytes long.",
"function_declaration": "def generate_hmac_keys(n):",
"function_name": "generate_hmac_keys",
"parameter_list": "(n)"
},
{
"docstring": "Generates HMAC digest for the given message using the provided key and diges... | [
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 hmac\nimport hashlib\n\ndef generate_hmac_keys(n):\n \"\"\"\n Generates n random secret keys, each 16 bytes long.\n \"\"\"\n return [os.ur... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00040183",
"row_id": 40183,
"seed_ids": "[298]"
} | 0.781524 | Docs: Python310_40183 | I | [
"generate_hmac_keys",
"send_message",
"receive_message",
"secure_communication"
] | 4 | [
[
"secure_communication",
"generate_hmac_keys"
],
[
"secure_communication",
"receive_message"
],
[
"secure_communication",
"send_message"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 0469a4ec17654b1aebdd12c74a564eafed0a270b | f17f3cb18706c3c349b2e1209cd209ed6a959d9e | |||
v1.0 | instruct | Docs | Docs: Python310_40216_I | You are tasked with implementing a set of utility functions that leverage the `quopri` module to encode and decode text data. The following functions need to be implemented:
1. **Function name:** `encode_text`
- **Input:**
- `text` (str): A string containing the text to be encoded.
- `quotetabs` (bool): A... | import quopri
def encode_text(text, quotetabs, header=False):
"""
Returns the quoted-printable encoded string.
:param text: str
:param quotetabs: bool
:param header: bool
:return: str
"""
encoded_bytes = quopri.encodestring(text.encode('utf-8'), quotetabs, header=header)
return... | import os
import pytest
from solution import encode_text, decode_text, encode_file, decode_file
def test_encode_text():
assert encode_text("Hello World! This is a test.", quotetabs=True) == (
"Hello=20World!=20This=20is=20a=20test."
)
assert encode_text("A test with\ttab", quotetabs=True) == "A=20t... | [
{
"docstring": "Returns the quoted-printable encoded string.\n\n:param text: str\n:param quotetabs: bool\n:param header: bool\n:return: str",
"function_declaration": "def encode_text(text, quotetabs, header=False):",
"function_name": "encode_text",
"parameter_list": "(text, quotetabs, header=False)"... | [
0,
1,
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": "import quopri\n\ndef encode_text(text, quotetabs=False, header=False):\n \"\"\"\n Encodes a given text using quoted-printable encoding.\n \n Parameters:\n ... | trial_gpt4o_1 | {
"original_instruction": "",
"prompt_id": "00040216",
"row_id": 40216,
"seed_ids": "[390]"
} | 0.522252 | Docs: Python310_40216 | I | [
"encode_text",
"decode_text",
"encode_file",
"decode_file"
] | 4 | [
[
"decode_file",
"decode_text"
],
[
"encode_file",
"encode_text"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | d0c41f9db4ff1b80357c118ef6d46c8c44d16d13 | abaec34af158fb00b4205dcf81886ae041c120ca | |||
v1.0 | instruct | Docs | Docs: Scikit_40218_I | ### Covariance Estimation with scikit-learn
#### Background
Covariance estimation is crucial in statistics and machine learning, often required for analyzing the relationships between various features of a dataset. The `sklearn.covariance` module in scikit-learn provides several methods for covariance estimation under... | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.covariance import (EmpiricalCovariance, ShrunkCovariance,
LedoitWolf, OAS, GraphicalLasso, MinCovDet)
def load_data(file_path):
"""
Loads the dataset from a given CSV file p... | import numpy as np
import pandas as pd
from solution import load_data, compute_covariances, mean_squared_error, compare_covariances, visualize_covariances
def test_load_data(tmp_path):
data_csv = tmp_path / 'data.csv'
data_csv.write_text("A,B,C,D,E\n1,2,3,4,5\n6,7,8,9,10\n11,12,13,14,15\n16,17,18,19,20\n21,22,... | [
{
"docstring": "Loads the dataset from a given CSV file path.\n\nParameters:\n- file_path: str, path to the CSV file\n\nReturns:\n- DataFrame containing the loaded data",
"function_declaration": "def load_data(file_path):",
"function_name": "load_data",
"parameter_list": "(file_path)"
},
{
"... | [
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 pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.covariance import (EmpiricalCovariance, ShrunkCovariance,\... | trial_gpt4o_2 | {
"original_instruction": "",
"prompt_id": "00040218",
"row_id": 40218,
"seed_ids": "[54]"
} | 0.571682 | Docs: Scikit_40218 | I | [
"load_data",
"compute_covariances",
"mean_squared_error",
"compare_covariances",
"visualize_covariances",
"main"
] | 6 | [
[
"compare_covariances",
"mean_squared_error"
]
] | 1 | [] | false | [] | false | pytest | true | [
"matplotlib",
"numpy",
"pandas",
"seaborn",
"sklearn"
] | false | 4302c5f7b1cbe6e21c16ac4da76db51140e770d5 | c3a9c3595f0c133e87238d31e140a3e966428491 | |||
v1.0 | instruct | Docs | Docs: Pandas_40239_I | ### Pandas Coding Assessment Question: Stylish Data Aggregator
**Objective:** Design a code snippet that reads a dataset, processes it to extract meaningful metrics, and then uses pandas' `Styler` to apply customized styling for a presentable output.
**Problem Description:**
1. **Data Input:** You are given a CSV fi... | import pandas as pd
def process_and_style_sales_data(file_path):
# Load data
df = pd.read_csv(file_path)
# Process data
df['TotalSales'] = df['Quantity'] * df['UnitPrice']
summary_df = df.groupby(['Region', 'Product']).agg(
TotalSales=pd.NamedAgg(column='TotalSales', aggfunc='sum'),
... | import pytest
import pandas as pd
from pandas._testing import assert_frame_equal
from io import StringIO
from solution import process_and_style_sales_data, highlight_max_min_sales
# Sample data to be used for tests
sample_data = """Date,Region,Product,Quantity,UnitPrice
2023-01-01,North,ProductA,10,15.0
2023-01-01,Nor... | [
{
"docstring": null,
"function_declaration": "def process_and_style_sales_data(file_path):",
"function_name": "process_and_style_sales_data",
"parameter_list": "(file_path)"
},
{
"docstring": null,
"function_declaration": "def highlight_max_min_sales(series):",
"function_name": "high... | [
1,
0,
0,
1,
0,
0,
1,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import pandas as pd\n\ndef process_and_style_sales_data(file_path):\n # Load data\n df = pd.read_csv(file_path)\n\n # Process data\n df['TotalSales'] = df['... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00040239",
"row_id": 40239,
"seed_ids": "[30]"
} | 0.647727 | Docs: Pandas_40239 | I | [
"process_and_style_sales_data",
"highlight_max_min_sales"
] | 2 | [
[
"process_and_style_sales_data",
"highlight_max_min_sales"
]
] | 1 | [] | false | [] | false | pytest | true | [
"pandas"
] | false | 7ab6bfbec2365e2492023d8e214cb8c4a51b318f | c03f36fe597ad0f2c468a746984b661ae9894aca | |||
v1.0 | instruct | Docs | Docs: Pytorch_40240_I | Your task is to create and register a custom communication hook with the DistributedDataParallel (DDP) model in PyTorch. Your custom hook will modify the gradients by applying a specific operation before they are allreduced across workers.
### Requirements
1. Implement a custom communication hook that:
- Multipli... | import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.futures import collect_all
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__... | def test_custom_hook():
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
from pytest import approx
class SimpleModel(nn.Module):
def __i... | [] | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import os\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.multiprocessing as mp\nfrom torch.nn.paralle... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00040240",
"row_id": 40240,
"seed_ids": "[92]"
} | 0.397843 | Docs: Pytorch_40240 | I | [
"custom_hook",
"setup",
"cleanup",
"demo"
] | 4 | [
[
"demo",
"cleanup"
],
[
"demo",
"setup"
]
] | 2 | [] | false | [
"SimpleModel"
] | true | pytest | false | [
"torch"
] | false | c5cb5fe7fcc758d0c388279086942d2ec7740cf5 | 140b7e27f1768625cae285b32ae0a508377a8944 | |||
v1.0 | instruct | Docs | Docs: Python310_40290_I | ### Problem: Efficient Fibonacci Sequence Generator
In this task, you are required to create an efficient Fibonacci number generator that employs multiple utilities provided by the `functools` module.
#### Requirements:
1. **Partial Function Application**:
- Create a `partial` function that calculates the sum of... | from functools import partial, lru_cache
def add(x, y):
"""
Returns the sum of x and y.
"""
return x + y
def partial_sum(n):
"""
Returns a partial function that adds a given value n.
"""
return partial(add, n)
@lru_cache(maxsize=None)
def fibonacci(n):
"""
Returns the nth Fibo... | from solution import partial_sum, fibonacci, cache_info
def test_partial_sum():
add_5 = partial_sum(5)
assert add_5(10) == 15 # 5 + 10 = 15
assert add_5(0) == 5 # 5 + 0 = 5
assert add_5(-5) == 0 # 5 + (-5) = 0
def test_fibonacci_base_cases():
assert fibonacci(0) == 0
assert fibonacci(1) ... | [
{
"docstring": "Returns the sum of x and y.",
"function_declaration": "def add(x, y):",
"function_name": "add",
"parameter_list": "(x, y)"
},
{
"docstring": "Returns a partial function that adds a given value n.",
"function_declaration": "def partial_sum(n):",
"function_name": "parti... | [
0,
0,
1,
0,
0,
0,
0,
1,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import partial, lru_cache\n\ndef add(x, y):\n return x + y\n\ndef partial_sum(n):\n return partial(add, n)\n\n@lru_cache(maxsize=None)\ndef fibonac... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00040290",
"row_id": 40290,
"seed_ids": "[236]"
} | 0.629241 | Docs: Python310_40290 | I | [
"add",
"partial_sum",
"fibonacci",
"cache_info"
] | 4 | [
[
"partial_sum",
"add"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 16d9763afe91d871ae711855ddb28c44ac352c81 | 3069568773d2fd878b046d3fd73696866e087ee7 | |||
v1.0 | instruct | Docs | Docs: Python310_40291_I | **Coding Assessment Question**
### Context
The `codecs` module in Python provides a flexible framework for converting data between different encoding formats. It supports text encodings, byte encodings, error handling mechanisms, and stream-based processing.
### Problem
Create a custom codec for encoding and decoding... | import codecs
class SubstitutionCipherCodec(codecs.Codec):
def __init__(self, shift):
self.shift = shift
def encode(self, input, errors='strict'):
return self._transform(input, self.shift), len(input)
def decode(self, input, errors='strict'):
return self._transform(input, -self.s... | import codecs
import pytest
# To avoid cyclic imports in the test, let's redefine part of the solution logic here.
class SubstitutionCipherCodec(codecs.Codec):
def __init__(self, shift):
self.shift = shift
def encode(self, input, errors='strict'):
return self._transform(input, self.shift), len... | [] | [
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 codecs\n\nclass SubstitutionCipherCodec(codecs.Codec):\n def __init__(self, shift):\n self.shift = shift\n \n def encode(self, input, errors='str... | trial_gpt4o_7 | {
"original_instruction": "",
"prompt_id": "00040291",
"row_id": 40291,
"seed_ids": "[211]"
} | 0.6834 | Docs: Python310_40291 | I | [
"substitution_cipher_search",
"substitution_cipher_encode",
"substitution_cipher_decode",
"register_substitution_cipher_codec"
] | 4 | [
[
"register_substitution_cipher_codec",
"substitution_cipher_search"
],
[
"substitution_cipher_search",
"substitution_cipher_decode"
],
[
"substitution_cipher_search",
"substitution_cipher_encode"
]
] | 3 | [] | false | [
"SubstitutionCipherCodec"
] | true | pytest | false | [] | true | 4729f8a8e973d7bcea23bd44f9c0b4b8116d5f34 | 1d175ccca7af4cabb2ac0d3c53bf419337014803 | |||
v1.0 | instruct | Docs | Docs: Pytorch_40353_I | #### Objective:
Implement a function that processes multiple independent tasks asynchronously using PyTorch `Future` objects and the utility functions `collect_all` and `wait_all`. The goal is to demonstrate comprehension of asynchronous programming and the use of futures in PyTorch.
#### Problem Statement:
You are ta... | import torch
import asyncio
import random
async def execute_task(task_id):
delay = random.uniform(0.1, 1.0)
await asyncio.sleep(delay)
return task_id
async def execute_tasks_async(n):
tasks = []
for task_id in range(n):
tasks.append(asyncio.ensure_future(execute_task(task_id)))
co... | from solution import execute_tasks
import pytest
def test_execute_tasks():
result = execute_tasks(5)
assert len(result) == 5
for value in result:
assert value in range(5)
def test_single_task():
result = execute_tasks(1)
assert len(result) == 1
assert result[0] == 0
def test_max_t... | [
{
"docstring": "This function initializes 'n' tasks asynchronously and returns the results of\nthose tasks once they are completed.",
"function_declaration": "def execute_tasks(n):",
"function_name": "execute_tasks",
"parameter_list": "(n)"
}
] | [
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": "import time\nimport random\nimport torch\nfrom torch.futures import collect_all, wait_all\n\ndef execute_task(task_id):\n delay = random.uniform(0.1, 1.0)\n time.... | trial_gpt4o_8 | {
"original_instruction": "",
"prompt_id": "00040353",
"row_id": 40353,
"seed_ids": "[53]"
} | 0.546796 | Docs: Pytorch_40353 | I | [
"execute_task",
"execute_tasks_async",
"execute_tasks"
] | 3 | [
[
"execute_tasks",
"execute_tasks_async"
],
[
"execute_tasks_async",
"execute_task"
]
] | 2 | [] | false | [] | false | pytest | true | [
"torch"
] | false | 2ba0550dfb18f5486929d457d5d90dfc05998482 | d5514e7ae2849548cb34fd772bea3c1a02e51f36 | |||
v1.0 | instruct | Docs | Docs: Python310_40369_I | ### Coding Challenge: Custom Generator Implementation and Validation
You are tasked with creating a custom generator in Python and implementing functions to dynamically create and validate generator objects. Use Python's native capabilities to implement the following functionalities as described below.
#### Part 1: C... | def custom_sequence_generator(start, stop, step):
"""
Yields an arithmetic sequence of numbers starting from `start`,
incrementing by `step`, and stopping before `stop`.
"""
current = start
while current < stop:
yield current
current += step
def create_generator_object(frame_da... | from solution import custom_sequence_generator, create_generator_object, is_generator_object
def test_custom_sequence_generator():
gen = custom_sequence_generator(1, 10, 2)
assert list(gen) == [1, 3, 5, 7, 9]
def test_create_generator_object():
gen = create_generator_object((1, 10, 2))
assert list(gen... | [
{
"docstring": "Yields an arithmetic sequence of numbers starting from `start`, \nincrementing by `step`, and stopping before `stop`.",
"function_declaration": "def custom_sequence_generator(start, stop, step):",
"function_name": "custom_sequence_generator",
"parameter_list": "(start, stop, step)"
... | [
1,
1,
1,
0,
1,
1,
1,
0,
0,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import inspect\n\ndef custom_sequence_generator(start, stop, step):\n \"\"\"\n Generates an arithmetic sequence of numbers starting from start, incrementing by st... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00040369",
"row_id": 40369,
"seed_ids": "[27]"
} | 0.587719 | Docs: Python310_40369 | I | [
"custom_sequence_generator",
"create_generator_object",
"is_generator_object"
] | 3 | [
[
"create_generator_object",
"custom_sequence_generator"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 67e7f365830a51fef5e7873c55aaf5fb80076d6c | 195042eb6484b7958185db8390f54557e59b04d2 | |||
v1.0 | instruct | Docs | Docs: Python310_40403_I | ### Functional Programming HOWTO
**Problem Statement: Fibonacci Sequence Generator**
You are required to implement a Python function that generates a sequence of Fibonacci numbers using functional programming principles. The implementation must use higher-order functions such as `map`, `reduce`, and `filter`.
**Func... | from typing import List
from itertools import islice
from functools import reduce
def fibonacci_generator():
"""
Generator to yield Fibonacci sequence indefinitely.
"""
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def fibonacci_sequence(n: int) -> List[int]:
"""
Generate... | from solution import fibonacci_sequence
def test_fibonacci_sequence_1():
assert fibonacci_sequence(1) == [0]
def test_fibonacci_sequence_2():
assert fibonacci_sequence(2) == [0, 1]
def test_fibonacci_sequence_5():
assert fibonacci_sequence(5) == [0, 1, 1, 2, 3]
def test_fibonacci_sequence_10():
asse... | [
{
"docstring": "Generator to yield Fibonacci sequence indefinitely.",
"function_declaration": "def fibonacci_generator():",
"function_name": "fibonacci_generator",
"parameter_list": "()"
},
{
"docstring": "Generates the first n Fibonacci numbers using functional programming principles.",
... | [
1,
0,
0,
0,
0,
0,
0,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\nimport itertools\n\ndef fibonacci_sequence(n: int) -> List[int]:\n \"\"\"\n Generates the first n Fibonacci numbers using functional prog... | trial_gpt4o_9 | {
"original_instruction": "",
"prompt_id": "00040403",
"row_id": 40403,
"seed_ids": "[73]"
} | 0.795961 | Docs: Python310_40403 | I | [
"fibonacci_generator",
"fibonacci_sequence"
] | 2 | [
[
"fibonacci_sequence",
"fibonacci_generator"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f09ddb417345e4f87138d24ba979f44dab02322b | 4bb8903e0881f0dfb3ddee58108f0d9e98dc2380 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.