version
stringclasses
1 value
style
stringclasses
2 values
subset
stringclasses
12 values
question_id
stringlengths
9
23
question
stringlengths
27
8.13k
solution
stringlengths
99
5.97k
test
stringlengths
105
4.45k
test_info
listlengths
0
13
gpt_pass_sequence
listlengths
1
10
gpt_pass_trial_num
int64
1
10
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
trials
dict
chosen_trial
stringclasses
10 values
metadata
dict
benchmark_similarity
float64
0.16
0.93
benchmark_instruction
stringclasses
1 value
benchmark_task_id
stringclasses
1 value
filter_reason
stringclasses
1 value
base_id
stringlengths
7
21
variant
stringclasses
2 values
top_function_names
listlengths
2
13
n_top_functions
int64
2
13
helper_call_edges
listlengths
1
16
n_helper_call_edges
int64
1
16
harness_functions
listlengths
0
3
structural_wrapper
bool
1 class
class_names
listlengths
0
5
has_class
bool
2 classes
test_kind
stringclasses
1 value
test_has_solution_import
bool
2 classes
third_party_imports
listlengths
0
5
stdlib_only
bool
2 classes
question_norm_sha1
stringlengths
40
40
solution_ast_sha1
stringlengths
40
40
v1.0
complete
Docs
Docs: Pytorch_39220_C
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 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": "#### Objective\n\nYou 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 shoul...
0.695515
Docs: Pytorch_39220
C
[ "create_dataset", "train" ]
2
[ [ "train", "create_dataset" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
82533b6c114ffbdec262e775e01c22b35c78044a
a131c376b680bebb4c385da07db8cc0029b8cdcf
v1.0
complete
Docs
Docs: Python310_37977_C
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. Args: - n: The number to be checked for primality. Returns: - Boolean indicating if n is prime. """ ...
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": "**Concurrency and Asynchronous Execution with concurrent.futures**\n\nYou'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 `Pr...
0.577408
Docs: Python310_37977
C
[ "is_prime", "check_primes", "sum_primes", "main" ]
4
[ [ "check_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
1f0b7c02e3a84f548bd2f642d303e87e2dea4c78
4d48bb771cccb47b529837cfe67cc041e57d4d55
v1.0
complete
Docs
Docs: Python310_39185_C
import sqlite3 from datetime import date 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(product): return (product...
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": "### Advanced Coding Assessment: SQLite Database Operations in Python\n\n#### Objective:\nYou 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 understandi...
0.503197
Docs: Python310_39185
C
[ "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
14028686e154e36c275bfa4888591ff0c0b856b5
9eb7d05cc418f344997c72f20e62c99b7d92622a
v1.0
complete
Docs
Docs: Seaborn_39536_C
import seaborn.objects as so from seaborn import load_dataset import matplotlib.pyplot as plt def plot_titanic_data(): """ Create Seaborn-based visualizations to explore survival rates on the Titanic, segmented by different demographic groups. - Faceted bar chart comparing the number of survivors and ...
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": "Titanic Data Visualization Challenge\n\n**Objective:**\nCreate 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 t...
0.768852
Docs: Seaborn_39536
C
[ "plot_titanic_data", "generate_plots" ]
2
[ [ "generate_plots", "plot_titanic_data" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "seaborn" ]
false
a1f82113a259bc0384e939c6e582691d00c05c03
915174af18f8dcb43899bef8b2f34ad2a9d116f0
v1.0
complete
Docs
Docs: Python310_39433_C
import signal import time # Define the signal handler function def handle_signal(signum, frame): """ Handle signals to stop the task execution gracefully. """ global running print(f"Signal handler called with signal {signum}") if signum == signal.SIGALRM or signum == signal.SIGINT: running = Fa...
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": "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:\n\n1. **Start a Task**: The task should be a loo...
0.632148
Docs: Python310_39433
C
[ "handle_signal", "start_task" ]
2
[ [ "start_task", "handle_signal" ] ]
1
[]
false
[]
false
pytest
false
[]
true
a1ce8efc144ee750753a521d1c7631fbd3575069
b465a7dd33df1f196431d7fc27a32d992214c893
v1.0
complete
Docs
Docs: Python310_39560_C
from typing import List def custom_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers using the Merge Sort algorithm. >>> custom_sort([34, 7, 23, 32, 5, 62]) [5, 7, 23, 32, 34, 62] >>> custom_sort([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> custom_sort([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5]...
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": "### Sorting Algorithm Implementation and Analysis\n\n#### **Objective:**\nImplement 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.\n\n#### **Problem Statem...
0.676286
Docs: Python310_39560
C
[ "custom_sort", "analyze_sort" ]
2
[ [ "analyze_sort", "custom_sort" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cbd339b02fb067934b20320b8e9270dc84d64eb1
477b53662a039b5fc9aca34f5254b66fb09db7a6
v1.0
complete
Docs
Docs: Python310_39452_C
import asyncio from typing import List, Tuple async def task(identifier: str, delay: int) -> str: """ Simulates a task by sleeping for a given delay and then returning a message indicating the completion of the task. >>> await task("Test", 1) 'Task Test completed after 1 seconds.' """ pass async d...
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": "**Task: Asynchronous Task Manager using `asyncio`**\n\n**Objective:**\nImplement 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.\n\...
0.716191
Docs: Python310_39452
C
[ "task", "task_manager", "run_task_manager" ]
3
[ [ "run_task_manager", "task_manager" ], [ "task_manager", "task" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a40ec9ed5a86ef98ff54e022572238097ec0a6e5
af94e2c1e299c92f8efe838d6c9b75e36d100ec7
v1.0
complete
Docs
Docs: Python310_39140_C
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. """ def shuffle_contestants(contestants): """ Shuffles the order of contestants in-place. ...
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": "### Objective\nTo test the understanding of Python's `random` module, including its basic functions, sequence operations, and statistical distributions.\n\n### Problem Statement\nYou are tasked with simulating the results of a simplified game show. The game show involves:\n1. Selecting rand...
0.571367
Docs: Python310_39140
C
[ "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
2d35012eb17e14457f9224794f654dfe5c86098c
9f6cf39796c014f3f57a65d72013c9d0bcd120a3
v1.0
complete
Docs
Docs: Python310_39535_C
import asyncio import platform from typing import Optional async def read_file_async(file_path: str) -> str: """ 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_p...
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": "### Asynchronous Programming with Platform-Specific Constraints\n\n**Objective:**\nYou 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...
0.500636
Docs: Python310_39535
C
[ "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
04297adfdf589f7fc2df87b491963cea45c254b0
b2260437e3610fdccd045814e71c120aa6d184a1
v1.0
complete
Docs
Docs: Python310_39639_C
import webbrowser def choose_mode_and_open(urls: list, mode: str = "tab") -> None: """ 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 ...
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": "### Question: Interactive Web Browser Opener\n\nYou 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.\n\n#### Function Requirements:\n1. Write a function `choose_mode_an...
0.656444
Docs: Python310_39639
C
[ "choose_mode_and_open", "interactive_browser_opener" ]
2
[ [ "interactive_browser_opener", "choose_mode_and_open" ] ]
1
[]
false
[]
false
pytest
true
[]
true
57b8fe01d24555a1c11e2771c36d8be202eb7e02
518b1443c0ccbd7280cee60c2a3a86f7e05a0e46
v1.0
complete
Docs
Docs: Python310_39539_C
import types def create_meta_class_logger(): """Create a custom metaclass MetaClassLogger. It should print "Creating class: <class-name>" when a class is created. Returns: Type: The metaclass MetaClassLogger. """ # [Implement function here] def create_dynamic_base(): """Creat...
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": "### Task: Dynamic Class Creation and Manipulation\n\nYou 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...
0.3918
Docs: Python310_39539
C
[ "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
40abd09eee2827643b1464ea62d6be036c56dec6
5917e439341990cb3b939bc23fe75eb654b115f7
v1.0
complete
Docs
Docs: Python310_39798_C
import asyncio import datetime async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): """Handle a client by reading their message, logging it with a timestamp, and echoing it back. """ # Implement the client handling logic async def start_server(host: str, port: int): """...
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": "### Question: Implement a Custom Asynchronous Echo Server with Additional Logging\n\nAs 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 `as...
0.749179
Docs: Python310_39798
C
[ "handle_client", "start_server" ]
2
[ [ "start_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
024fecdd9d19dca608cb1da3fa4e60b3ebb63d81
50e88098231541bf5ace5681f1e1ed7f86f14d8d
v1.0
complete
Docs
Docs: Pytorch_39555_C
import torch import torch.futures from typing import List 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:...
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": "#### Objective:\nDemonstrate your understanding of PyTorch's `torch.futures` package and its `Future` type by implementing an asynchronous task management system.\n\n#### Problem Statement:\n\nYou are required to implement a function `aggregate_squares` that performs the following tasks:\n\...
0.577409
Docs: Pytorch_39555
C
[ "compute_square_async", "aggregate_squares" ]
2
[ [ "aggregate_squares", "compute_square_async" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
6e668eb725ace1cb1a71e31400ad1af05e2d20f8
c6d2a0c0055e3e14f5a3b60320045114ba4f70c0
v1.0
complete
Docs
Docs: Python310_39811_C
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 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": "### Question:\n\nYou 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.\n\n#### Requirements:\n\n1. Implement a function `generate_fil...
0.744528
Docs: Python310_39811
C
[ "generate_file_hash", "verify_file_hash" ]
2
[ [ "verify_file_hash", "generate_file_hash" ] ]
1
[]
false
[]
false
pytest
true
[]
true
dcd7aa418c0ca319e215ba8983dc9c124cc5f6ff
1260b2d3c83f7e0090676c3e1f620564eb11049f
v1.0
complete
Docs
Docs: Python310_39576_C
from typing import List from functools import lru_cache, partial @lru_cache(maxsize=None) def fib(n: int) -> int: """ Calculates the nth Fibonacci number. >>> fib(0) == 0 >>> fib(1) == 1 >>> fib(2) == 1 >>> fib(10) == 55 """ pass def scale(factor: int, value: int) -> int: """ M...
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": "## Coding Assessment Question\n\n### Objective\nYour 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 ...
0.740976
Docs: Python310_39576
C
[ "fib", "scale", "process_numbers" ]
3
[ [ "process_numbers", "fib" ] ]
1
[]
false
[]
false
pytest
true
[]
true
16597559f14013dc078c486985ec7d3065bf1878
0123759d1b747d9319669d7e1312b6779dc0d6c0
v1.0
complete
Docs
Docs: Python310_39787_C
class ProcessingError(Exception): """ Custom exception for processing errors. """ pass def process_data(data: list) -> int: """ Processes a list of integers. - Ensures the data contains only integers. - Raises a ValueError if the list is empty. - Calculates the sum of the integers in the list....
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": "### Exception Handling and Custom Exception Class Implementation\n\n#### Background:\nIn 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...
0.534624
Docs: Python310_39787
C
[ "process_data", "safe_process" ]
2
[ [ "safe_process", "process_data" ] ]
1
[ "process_data" ]
false
[ "ProcessingError" ]
true
pytest
true
[]
true
ba3a7f9249d481bf08a7be26f748efef23d0097e
9a908c98fcfa2439eec2c23519919a4a770d5fc9
v1.0
complete
Docs
Docs: Scikit_39604_C
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 def train_evaluate_gpr(X_train, y_train, X_test, y_test, kernel): """ Train and evaluate Gauss...
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": "### Gaussian Process Regression with Custom Kernels\n\n#### Objective:\nImplement a Gaussian Process Regressor using scikit-learn. Your task is to:\n1. Train the model with multiple kernels.\n2. Optimize the hyperparameters of the kernels.\n3. Evaluate the performance on a test dataset.\n\n...
0.588953
Docs: Scikit_39604
C
[ "train_evaluate_gpr", "execute_workflow" ]
2
[ [ "execute_workflow", "train_evaluate_gpr" ] ]
1
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "sklearn" ]
false
6bf151fd2a27d5d0f2be8cfbd99c6b7cac383d32
203ca9b24c350d5b256aac1d0fb50ec0e367785f
v1.0
complete
Docs
Docs: Python310_39740_C
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...
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": "### Question: HMAC Implementation and Verification\n\nYou are tasked with implementing a secure message authentication system that uses the HMAC library in Python for ensuring the integrity and authenticity of messages.\n\n**Your Task:**\n1. Implement the function `create_hmac(key, message,...
0.860146
Docs: Python310_39740
C
[ "create_hmac", "verify_hmac" ]
2
[ [ "verify_hmac", "create_hmac" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d12eead1170c7ec1cf0c8ae12a6400c1b4a67c53
f24fae1bb1ebec9a0dbe4ccf35c06fb4109fb10e
v1.0
complete
Docs
Docs: Python310_39624_C
import tracemalloc import linecache def display_top(snapshot, key_type='lineno', limit=10): """ Display the top memory-consuming lines of code from a snapshot. Filters out the traces from '<frozen importlib._bootstrap>' and '<unknown>'. Args: snapshot: A tracemalloc snapshot object. key_ty...
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": "### Question: Memory Leak Detection Using `tracemalloc`\n\nYou 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.\n\n#### Requirements:\n1. Write a functi...
0.462379
Docs: Python310_39624
C
[ "display_top", "identify_memory_leak" ]
2
[ [ "identify_memory_leak", "display_top" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a46ce8b59c16aca72e82c1d06589aa6e7fbcd3ca
7cdeed1e307ce00964f2388a4d90592a406695cd
v1.0
complete
Docs
Docs: Seaborn_39665_C
import numpy as np import seaborn as sns import matplotlib.pyplot as plt def generate_data(seed=0, size=200): """Generate a dataset of random values from a normal distribution. """ np.random.seed(seed) data = np.random.normal(loc=0, scale=1, size=size) return data def create_plot(ax, data, errorba...
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": "### Question: Advanced Visualization of Error Bars using Seaborn\n\n**Objective:**\nYour 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 effi...
0.696836
Docs: Seaborn_39665
C
[ "generate_data", "create_plot", "plot_errorbars" ]
3
[ [ "plot_errorbars", "create_plot" ], [ "plot_errorbars", "generate_data" ] ]
2
[]
false
[]
false
pytest
true
[ "matplotlib", "numpy", "seaborn" ]
false
ace74332c36f0df9dc7a6d2974cd189634813810
23def575a22e44b2a7727fac9a3d105481af0f63
v1.0
complete
Docs
Docs: Pytorch_39259_C
import torch def transform_complex_tensor(real_tensor: torch.Tensor, real_ops: list, imag_ops: list) -> torch.Tensor: """ Convert a real tensor to complex tensor, apply a series of transformations, and return the resulting complex tensor. Parameters: real_tensor (torch.Tensor): A real tensor of shape (......
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": "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.\n\n#### Function Signature\n```python\nimport torch\n\ndef t...
0.539529
Docs: Pytorch_39259
C
[ "apply_operations", "transform_complex_tensor" ]
2
[ [ "transform_complex_tensor", "apply_operations" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
99cd1baf7e2bf42afd710b678f6b1b27b0ca0a13
0763ad22679bcedd5d2bb760f8f61d6be65858a7
v1.0
complete
Docs
Docs: Python310_39455_C
import asyncio async def fetch_url(urls: list, timeout: int) -> None: """ Fetches content from a list of URLs using asyncio. Handles asyncio-specific exceptions appropriately. Parameters: urls (list): A list of URLs to fetch content from. timeout (int): The maximum time (in seconds) to wait for e...
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": "**Objective:** Demonstrate understanding and handling of asyncio exceptions in Python.\n\n**Problem Statement:**\n\nYou 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 e...
0.646773
Docs: Python310_39455
C
[ "fetch_content_from_url", "fetch_url" ]
2
[ [ "fetch_url", "fetch_content_from_url" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
1afbd9a05d33fe0ceb61cd39bdff15f152683aad
8938ae7734222b5b50d5da1c19b9f9a850268d7b
v1.0
complete
Docs
Docs: Pytorch_39538_C
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 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": "#### Objective:\n\nIn 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 debug...
0.721007
Docs: Pytorch_39538
C
[ "generate_dataset", "normalize_data", "train_model" ]
3
[ [ "train_model", "generate_dataset" ], [ "train_model", "normalize_data" ] ]
2
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "numpy", "torch" ]
false
b9ffdeca709bf1fc7a42eb23e7694a6f30b01637
2c082b7b6194179ee9b266b8439f159dc3d29201
v1.0
complete
Docs
Docs: Python310_39773_C
import hashlib def hash_file(file_path: str, algorithm: str) -> str: """ 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 (e.g., 'sha256', 'blake2b'). Returns: - st...
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": "### Question: Implement a Hash-Based File Integrity Verification System\n\nYou are required to implement a system that verifies the integrity of files using secure hash functions provided by the `hashlib` module. \n\nThe system should be able to:\n1. Generate a hash of a file using a specif...
0.7258
Docs: Python310_39773
C
[ "hash_file", "verify_file" ]
2
[ [ "verify_file", "hash_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6e915667486f32dda783caf8ccb7f9edbc147ce4
4992c280f6f0a370f78b7e6d1efa873bfaade73c
v1.0
complete
Docs
Docs: Python310_39957_C
import sys import platform from dataclasses import dataclass from contextlib import contextmanager def get_system_info() -> dict: """ Retrieves system-specific information using sys and platform modules. >>> isinstance(get_system_info(), dict) True """ @dataclass class Book: """ Data class represe...
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": "**Objective:**\nYou 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:\n1. Retrieving system-s...
0.535852
Docs: Python310_39957
C
[ "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
c900f2625f62a568bd866720711fa75911363385
7df7cbb12a8ff5e890d93a991e5678d34ffc4804
v1.0
complete
Docs
Docs: Python310_40403_C
from typing import List def fibonacci_sequence(n: int) -> List[int]: """ Generates the first n Fibonacci numbers using functional programming principles. >>> fibonacci_sequence(1) [0] >>> fibonacci_sequence(2) [0, 1] >>> fibonacci_sequence(5) [0, 1, 1, 2, 3] >>> fibonacci_sequence(10) [0, 1, 1, 2, ...
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": "### Functional Programming HOWTO\n\n**Problem Statement: Fibonacci Sequence Generator**\n\nYou 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`...
0.864432
Docs: Python310_40403
C
[ "fibonacci_generator", "fibonacci_sequence" ]
2
[ [ "fibonacci_sequence", "fibonacci_generator" ] ]
1
[]
false
[]
false
pytest
true
[]
true
41f97eebf55d15f41d6852a54737a9fa12270379
4bb8903e0881f0dfb3ddee58108f0d9e98dc2380
v1.0
complete
Docs
Docs: Pytorch_39822_C
import os import torch import torch.distributed as dist import torch.multiprocessing as mp def setup_nccl_environment(): """ Configure NCCL environment variables for debugging and monitoring. >>> setup_nccl_environment() """ os.environ['TORCH_NCCL_ASYNC_ERROR_HANDLING'] = '1' os.environ['TORCH_NCCL...
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": "**PyTorch Distributed Training with NCCL Debugging**\n\nYou 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...
0.504392
Docs: Pytorch_39822
C
[ "setup_nccl_environment", "initialize_process_group", "train" ]
3
[ [ "train", "initialize_process_group" ], [ "train", "setup_nccl_environment" ] ]
2
[]
false
[]
false
pytest
true
[ "torch" ]
false
0db22ff158a07bf8ef5cc680b7163600a97cc86c
e1bd23fb8a1da76aafd30ab568c07e53fd1f58c7
v1.0
complete
Docs
Docs: Python310_40290_C
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. >>> add_5 = partial_sum(5) >>> print(add_5(10)) # 15 >>> print(add_5(0)) # 5 >>> print(add_5(-...
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": "### Problem: Efficient Fibonacci Sequence Generator\n\nIn this task, you are required to create an efficient Fibonacci number generator that employs multiple utilities provided by the `functools` module.\n\n#### Requirements:\n\n1. **Partial Function Application**:\n - Create a `partial`...
0.701789
Docs: Python310_40290
C
[ "add", "partial_sum", "fibonacci", "cache_info" ]
4
[ [ "partial_sum", "add" ] ]
1
[]
false
[]
false
pytest
true
[]
true
05a0325974f639ede26177a6626bf478a95a9f7c
3069568773d2fd878b046d3fd73696866e087ee7
v1.0
complete
Docs
Docs: Python310_40183_C
import hmac import hashlib import os def generate_hmac_keys(n): """Generates a list of n random secret keys, each 16 bytes long. >>> len(generate_hmac_keys(3)) == 3 True >>> all(len(key) == 16 for key in generate_hmac_keys(3)) True """ pass def send_message(key, message, digestmod): ...
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": "### Secure Message Authentication using HMAC\n\nImplement 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.\n\n#### Requirement...
0.850172
Docs: Python310_40183
C
[ "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
5bb37f285ae0e3f08af5e094886438f5dd9b0fbd
f17f3cb18706c3c349b2e1209cd209ed6a959d9e
v1.0
complete
Docs
Docs: Python310_40028_C
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 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": "### Question: Implementing and Managing Python Threads in an Embedded Application\n\n#### Objective:\nDemonstrate your understanding of thread management, GIL handling, and initialization/finalization of the Python interpreter by creating a C extension that incorporates embedding Python and...
0.567255
Docs: Python310_40028
C
[ "read_file_simulated", "run_thread" ]
2
[ [ "run_thread", "read_file_simulated" ] ]
1
[]
false
[]
false
pytest
true
[]
true
34a6145402e626889e8b88980d068b08096c587f
12196d495994084dff8ec6544f0b95f121470e90
v1.0
complete
Docs
Docs: Pytorch_40353_C
import torch import asyncio import random async def execute_task(task_id): """" This function simulates a random delay for a given task and returns the task ID. """ delay = random.uniform(0.1, 1.0) await asyncio.sleep(delay) return task_id async def execute_tasks_async(n): """ This fun...
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": "#### Objective:\nImplement 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.\n\n##...
0.596544
Docs: Pytorch_40353
C
[ "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
bcdd5edf08788d98c429063b5eeae32ab92040fa
d5514e7ae2849548cb34fd772bea3c1a02e51f36
v1.0
complete
Docs
Docs: Python310_40535_C
import traceback import datetime import sys import os def detailed_traceback(info, context_lines=5, output_format='text', logdir=None): """ Generate a detailed traceback report. Args: info (tuple): A 3-tuple containing the result from sys.exc_info(). context_lines (int): Number of context ...
import traceback import datetime import sys import os def detailed_traceback(info, context_lines=5, output_format='text', logdir=None): exc_type, exc_value, exc_tb = info tb_lines = traceback.format_tb(exc_tb, limit=None) context_str = "" for tb in tb_lines: tb_parts = tb.split("\n") f...
import sys import os import tempfile from solution import detailed_traceback def test_detailed_traceback_text_format(): try: 1 / 0 except ZeroDivisionError: info = sys.exc_info() result = detailed_traceback(info, context_lines=3, output_format='text', logdir=None) assert 'ZeroDi...
[ { "docstring": null, "function_declaration": "def detailed_traceback(info, context_lines=5, output_format='text', logdir=None):", "function_name": "detailed_traceback", "parameter_list": "(info, context_lines=5, output_format='text', logdir=None)" }, { "docstring": "Fetch the context lines a...
[ 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import traceback\nimport datetime\nimport sys\nimport os\n\ndef detailed_traceback(info, context_lines=5, output_format='text', logdir=None):\n \"\"\"\n Generate ...
trial_gpt4o_8
{ "original_instruction": "### Advanced Python Coding Assessment\n\n**Objective:**\nYou are required to implement a custom traceback handler that mimics some functionalities of the deprecated `cgitb` module. This will assess your understanding of Python's exception handling, traceback management, and string formattin...
0.590331
Docs: Python310_40535
C
[ "detailed_traceback", "format_context" ]
2
[ [ "detailed_traceback", "format_context" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a0b051917a0e515af7f03ff4d3a492362af9744e
3e40c50130caadd68474630d3d390cf69725625a
v1.0
complete
Docs
Docs: Python310_40473_C
from typing import List def parallel_sum_of_squares(numbers: List[int], chunk_size: int) -> int: """ Computes the total sum of squares of all numbers in the given list in parallel. The list is split into chunks of the specified size and processed concurrently. >>> parallel_sum_of_squares([1, 2, 3, 4, 5], ...
from typing import List from concurrent.futures import ThreadPoolExecutor def sum_of_squares_chunk(numbers: List[int]) -> int: """ Helper function to compute the sum of squares of a given list of numbers. """ return sum(x ** 2 for x in numbers) def parallel_sum_of_squares(numbers: List[int], chunk_siz...
from solution import parallel_sum_of_squares def test_small_list(): assert parallel_sum_of_squares([1, 2, 3, 4, 5], 2) == 55 def test_single_chunk(): assert parallel_sum_of_squares([1, 3, 5, 7, 9], 5) == 165 def test_multiple_full_chunks(): assert parallel_sum_of_squares([1, 2, 3, 4, 5, 6, 7, 8, 9, 1...
[ { "docstring": "Helper function to compute the sum of squares of a given list of numbers.", "function_declaration": "def sum_of_squares_chunk(numbers):", "function_name": "sum_of_squares_chunk", "parameter_list": "(numbers)" }, { "docstring": "Computes the total sum of squares of all numbers...
[ 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": "from concurrent.futures import ThreadPoolExecutor\nfrom typing import List\n\ndef parallel_sum_of_squares(numbers: List[int], chunk_size: int) -> int:\n def sum_of_s...
trial_gpt4o_9
{ "original_instruction": "### Parallel Computation with \"concurrent.futures\"\n\nYou are required to write a Python program that uses the \"concurrent.futures\" module to execute parallel tasks. The task involves calculating the sum of squares for a list of numbers. To achieve this, you must split the list into chu...
0.745446
Docs: Python310_40473
C
[ "sum_of_squares_chunk", "parallel_sum_of_squares" ]
2
[ [ "parallel_sum_of_squares", "sum_of_squares_chunk" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cac7f38f73f1763095b3eadfc3871d73af1cd547
52f66e636f154d9cef46724ae83dc63d565437ec
v1.0
complete
Docs
Docs: Pytorch_40240_C
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).__...
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": "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. \n\n### Requirements\n\n1. Implement a custom commu...
0.540103
Docs: Pytorch_40240
C
[ "custom_hook", "setup", "cleanup", "demo" ]
4
[ [ "demo", "cleanup" ], [ "demo", "setup" ] ]
2
[]
false
[ "SimpleModel" ]
true
pytest
false
[ "torch" ]
false
8c3adbf7292b8b45d8196e1d34162989aa3a2f11
140b7e27f1768625cae285b32ae0a508377a8944
v1.0
complete
Docs
Docs: Python310_40369_C
def custom_sequence_generator(start, stop, step): """ Yields an arithmetic sequence of numbers starting from `start`, incrementing by `step`, and stopping before `stop`. Parameters: - start (int): The starting value of the sequence. - stop (int): The sequence will stop before this value. ...
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": "### Coding Challenge: Custom Generator Implementation and Validation\n\nYou 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 d...
0.573352
Docs: Python310_40369
C
[ "custom_sequence_generator", "create_generator_object", "is_generator_object" ]
3
[ [ "create_generator_object", "custom_sequence_generator" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6fb1ee5186d56893def50f24712dd618344025ca
195042eb6484b7958185db8390f54557e59b04d2
v1.0
complete
Docs
Docs: Scikit_40560_C
import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.model_selection import TunedThresholdClassifierCV from sklearn.metrics import make_scorer, recall_score, confusion_matrix def tune_and_evaluate_threshold(X_train, y_train, X_test, y_test): """ Train a classifier to predict the like...
import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_predict, KFold from sklearn.metrics import make_scorer, recall_score, confusion_matrix, precision_recall_curve def tune_threshold_for_recall(y_true, y_proba, pos_label=1): precision, recall, thresho...
import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from solution import tune_and_evaluate_threshold def generate_synthetic_data(): X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, n_informativ...
[ { "docstring": null, "function_declaration": "def tune_threshold_for_recall(y_true, y_proba, pos_label=1):", "function_name": "tune_threshold_for_recall", "parameter_list": "(y_true, y_proba, pos_label=1)" }, { "docstring": null, "function_declaration": "def tune_and_evaluate_threshold(X...
[ 0, 0, 0, 1, 0, 1, 1, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import StratifiedKFold, cross_val_predict\nfrom sklearn.metrics im...
trial_gpt4o_6
{ "original_instruction": "### Question:\n\nYou are developing a classifier to help medical practitioners identify patients who might have cancer. Given the critical nature of this application, your primary goal is to maximize recall, ensuring that fewer actual cases of cancer are missed, which justifies higher false...
0.672917
Docs: Scikit_40560
C
[ "tune_threshold_for_recall", "tune_and_evaluate_threshold" ]
2
[ [ "tune_and_evaluate_threshold", "tune_threshold_for_recall" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
2c8d8815a579cec7f940eca6e699feda3d810d55
56d34b9e65c9f0ca329c7e5491f8bd21172a63e7
v1.0
complete
Docs
Docs: Pandas_40239_C
import pandas as pd def process_and_style_sales_data(file_path): """ Process sales data from a CSV file and apply pandas Styler for customized styling. The function reads data from the provided CSV file, processes it to calculate the total sales and number of transactions for each Region and Product, and ...
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": "### Pandas Coding Assessment Question: Stylish Data Aggregator\n\n**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.\n\n**Problem Description:**\n\n1. **D...
0.70018
Docs: Pandas_40239
C
[ "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
603054dc86807b2b017bf9b415b33d1178557cd5
c03f36fe597ad0f2c468a746984b661ae9894aca
v1.0
complete
Docs
Docs: Python310_41051_C
import contextvars import asyncio # Define the context variable to store the user ID user_id_var = contextvars.ContextVar('user_id') def log_event(event: str) -> None: """ Logs the event message along with the current user ID retrieved from the context variable. :param event: str: The event message ...
import contextvars import asyncio # Define the context variable to store the user ID user_id_var = contextvars.ContextVar('user_id') def log_event(event: str) -> None: """ Logs the event message along with the current user ID retrieved from the context variable. """ user_id = user_id_var.get() pri...
import asyncio from io import StringIO import sys from solution import log_event, handle_user_interaction, main def test_log_event(): user_id_var.set(99) old_stdout = sys.stdout sys.stdout = mystdout = StringIO() log_event("Test Event") assert mystdout.getvalue() == "User 99: Test Event\n" sys...
[ { "docstring": "Logs the event message along with the current user ID retrieved from the context variable.", "function_declaration": "def log_event(event):", "function_name": "log_event", "parameter_list": "(event)" } ]
[ 1, 0, 1, 0, 1, 0, 1, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport contextvars\n\n# Define a context variable to store the user ID\nuser_id_var = contextvars.ContextVar('user_id', default=None)\n\ndef log_event(e...
trial_gpt4o_4
{ "original_instruction": "**Objective**: To evaluate your understanding of the `contextvars` module and its integration with asynchronous programming in Python.\n\n**Problem Statement**:\n\nYou are required to implement an asynchronous logging system that keeps track of user-specific events. Each user interaction sh...
0.452898
Docs: Python310_41051
C
[ "log_event", "handle_user_interaction", "main" ]
3
[ [ "handle_user_interaction", "log_event" ] ]
1
[]
false
[]
false
pytest
true
[]
true
5cbc0d5fa3022d8b791eef82d797c502638135c2
05e742ddc1ac0e39770b06fc62b52dcabc83fb5d
v1.0
complete
Docs
Docs: Python310_40741_C
import asyncio import random import logging async def process_task(task_id): """ Simulates processing a task by sleeping for a random duration and printing a completion message. :param task_id: the ID of the task """ await asyncio.sleep(random.uniform(0.1, 1.0)) print(f"Task {task_id} comp...
import asyncio import random import logging async def process_task(task_id): """ Simulates processing a task by sleeping for a random duration and printing a completion message. """ await asyncio.sleep(random.uniform(0.1, 1.0)) print(f"Task {task_id} completed") async def main(tasks): """ ...
import pytest import asyncio from solution import process_task, main def test_process_task(): """ Test that process_task runs without raising exceptions. """ async def run_task(): await process_task(1) asyncio.run(run_task()) assert True # If no exception is raised, the test passes de...
[ { "docstring": "Top-level code to run the asyncio application with proper\nexception handling and debug mode activated.", "function_declaration": "def run_application():", "function_name": "run_application", "parameter_list": "()" } ]
[ 1, 1, 0, 1, 1, 1, 0, 0, 1, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\nimport logging\n\nasync def process_task(task_id):\n \"\"\"\n Simulates processing a task by sleeping for a random duration\n an...
trial_gpt4o_0
{ "original_instruction": "#### Objective\n\nTo assess the students' understanding of asynchronous programming with the `asyncio` module in Python, evaluating their ability to create and handle coroutines, manage concurrency, and address common pitfalls.\n\n#### Problem Statement\n\nYou are tasked with designing a co...
0.535261
Docs: Python310_40741
C
[ "process_task", "main", "run_application" ]
3
[ [ "run_application", "main" ] ]
1
[]
false
[]
false
pytest
true
[]
true
14a77220196f19d3beb8400914a4e90eabb15ef2
b5463a8509df177c6c83baca2771ae73fe058da0
v1.0
complete
Docs
Docs: Pytorch_40069_C
import torch def compute_loss(params, inputs, targets): """Compute the mean squared error (MSE) loss given the model parameters, inputs, and targets.""" pass def compute_gradients(params, inputs, targets): """Compute the gradients of the model parameters with respect to the loss using `torch.func.grad`.""...
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": "## Coding Assessment Question\n\nYou 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.\n\n### Objective\n\n1. Im...
0.679486
Docs: Pytorch_40069
C
[ "compute_loss", "compute_gradients", "compute_jacobians" ]
3
[ [ "compute_gradients", "compute_loss" ] ]
1
[]
false
[ "SimpleNN" ]
true
pytest
true
[ "torch" ]
false
292e2b869c4a661f4f4d753a3ee4ba01dc93ec02
13e22b815a6ab951c2a94b5e2418598f81253281
v1.0
complete
Docs
Docs: Python310_41188_C
import asyncio from typing import List async def download_file(url: str) -> None: """ Simulate downloading a file from the given URL by sleeping asynchronously for a random number of seconds between 1 and 5. Print messages indicating the start, completion, and cancellation of the download. Args: -...
import asyncio import random from typing import List async def download_file(url: str) -> None: try: print(f"Starting download from {url}") await asyncio.sleep(random.randint(1, 5)) print(f"Completed download from {url}") except asyncio.CancelledError: print(f"Download from {url...
import asyncio import pytest from unittest.mock import patch from solution import download_file, manage_downloads @pytest.mark.asyncio async def test_download_file(): url = "http://example.com/file" with patch("random.randint", return_value=2): await download_file(url) @pytest.mark.asyncio async def ...
[]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 0 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\nfrom typing import List\n\nasync def download_file(url: str) -> None:\n try:\n print(f\"Starting download from {url}\")\n ...
trial_gpt4o_0
{ "original_instruction": "#### Objective\n\nYour task is to build a simple file download manager using `asyncio`. The file download manager should be able to handle multiple downloads concurrently, manage the download queue, and handle timeouts and cancellations.\n\n#### Requirements\n\n1. **Function: `download_file...
0.55378
Docs: Python310_41188
C
[ "download_file", "manage_downloads" ]
2
[ [ "manage_downloads", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
f899b270b398240732f86526bdac80165fcb9481
7c23a01e4356325cdc9e9a2c8b683275ba23254c
v1.0
complete
Docs
Docs: Python310_40291_C
import codecs class SubstitutionCipherCodec(codecs.Codec): def __init__(self, shift): self.shift = shift def encode(self, input, errors='strict'): """Encode the given input by shifting each alphabetical char. Args: - input (str): The string to encode. - errors (str): E...
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": "**Coding Assessment Question**\n\n### Context\nThe `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.\n\n### Problem\nCreate a cus...
0.712735
Docs: Python310_40291
C
[ "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
da784a6b79b87ac94b394af63c71caaf7c31b7ef
1d175ccca7af4cabb2ac0d3c53bf419337014803
v1.0
complete
Docs
Docs: Python310_41002_C
import traceback def log_exception_to_file(exc: Exception, file_path: str) -> None: """ Captures the exception details and writes them to a specified log file. Args: exc (Exception): The caught exception. file_path (str): The path to the log file where exception details should be written. """ ...
import traceback def log_exception_to_file(exc: Exception, file_path: str) -> None: """ Captures the exception details and writes them to a specified log file. Args: exc (Exception): The caught exception. file_path (str): The path to the log file where exception details should be written. ...
import os from solution import log_exception_to_file, raise_and_log_exception, forced_error def test_log_exception_to_file(): try: forced_error() except Exception as exc: log_exception_to_file(exc, 'test_error_log.txt') with open('test_error_log.txt', 'r') as f: contents = f.read()...
[ { "docstring": "Captures the exception details and writes them to a specified log file.\n\nArgs:\nexc (Exception): The caught exception.\nfile_path (str): The path to the log file where exception details should be written.", "function_declaration": "def log_exception_to_file(exc, file_path):", "function...
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import traceback\n\ndef log_exception_to_file(exc: Exception, file_path: str) -> None:\n \"\"\"\n Logs the details of an exception to a file.\n \n :param ex...
trial_gpt4o_9
{ "original_instruction": "<|Analysis Begin|>\n\nThe provided documentation is for Python's `traceback` module, which facilitates handling and manipulating stack tracebacks. Here's a summary of the significant features and functions covered in this documentation:\n\n1. **Printing and Formatting**:\n - `traceback.pr...
0.538023
Docs: Python310_41002
C
[ "log_exception_to_file", "raise_and_log_exception", "forced_error" ]
3
[ [ "raise_and_log_exception", "forced_error" ], [ "raise_and_log_exception", "log_exception_to_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
5f6261f2ea419a7e918ba29db94cbcd806a4db8c
5db7d01b87b8a526e66471feb364c3a879921ec1
v1.0
complete
Docs
Docs: Python310_40820_C
import asyncio async def read_write_async(files: list, data: bytes, timeout: float) -> dict: """ Reads from and writes to a list of files asynchronously while handling specific asyncio exceptions. Parameters: files (list): A list of file paths (strings) to be read from and written to. data (bytes)...
import asyncio async def read_file(file_path, timeout): try: with open(file_path, "rb") as file: return await asyncio.wait_for(file.read(), timeout=timeout) except asyncio.TimeoutError: return None, "Read operation timed out" except asyncio.CancelledError as e: return No...
import asyncio import pytest from solution import read_write_async @pytest.mark.asyncio async def test_read_write_async_success(): files = ["test_file1.txt", "test_file2.txt"] for file in files: with open(file, "wb") as f: f.write(b"Initial data") data = b"Example data" timeout = 5....
[]
[ 1, 1, 1, 0, 0, 1, 0, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def read_write_async(files: list, data: bytes, timeout: float) -> dict:\n results = {}\n\n async def read(file_path):\n await async...
trial_gpt4o_8
{ "original_instruction": "### Question: Handling Special Exceptions in Asynchronous Programming\n\nYou are tasked with writing an asynchronous function that performs read and write operations on multiple files. This function should handle various exceptions from the `asyncio` module that may be raised during these o...
0.601908
Docs: Python310_40820
C
[ "read_file", "write_file", "read_write_async" ]
3
[ [ "read_write_async", "read_file" ], [ "read_write_async", "write_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
16b51c3b5d0179d6d4de5b6156abb624406f9377
a802934c8f80341bde06a9267a1ae9c611d68911
v1.0
complete
Docs
Docs: Python310_40875_C
import asyncio import contextvars from typing import List, Dict # Define context variable to store the current dictionary context = contextvars.ContextVar('context', default={}) async def process_numbers(numbers: List[int]) -> List[int]: """ Process a list of integers asynchronously, doubling each number and stor...
import asyncio import contextvars from typing import List, Dict # Define context variable to store the current dictionary context = contextvars.ContextVar('context', default={}) async def process_number(number: int) -> int: # Get the current context state ctx = context.get() # Double the number double...
import pytest import asyncio from solution import process_numbers, get_context_summary @pytest.mark.asyncio async def test_process_numbers(): numbers = [1, 2, 3] expected_doubled = [2, 4, 6] result = await process_numbers(numbers) assert result == expected_doubled context_summary = get_context_summ...
[ { "docstring": null, "function_declaration": "def get_context_summary():", "function_name": "get_context_summary", "parameter_list": "()" } ]
[ 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 contextvars\nimport asyncio\nfrom typing import List, Dict\n\n# Define the context variable at the module level\ncontext_data = contextvars.ContextVar('context_d...
trial_gpt4o_1
{ "original_instruction": "### Question: Context Management with `contextvars` in Python\n\n#### Objective:\nYour task is to demonstrate your understanding of the `contextvars` module by implementing a function that manages context-local state and performs a specific computation asynchronously.\n\n#### Problem Statem...
0.583192
Docs: Python310_40875
C
[ "process_number", "process_numbers", "get_context_summary" ]
3
[ [ "process_numbers", "process_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a1425d6e39e7d4e43b2740075828b821c386d217
2dfe529b91e4a35d3fbc442ff36945f7473e9a13
v1.0
complete
Docs
Docs: Python310_41295_C
from typing import List, Dict, Tuple import threading import multiprocessing def cpu_bound_task(n: int) -> int: """ Computes the sum of the first n natural numbers. >>> cpu_bound_task(5) == 15 >>> cpu_bound_task(100) == 5050 >>> cpu_bound_task(0) == 0 """ pass def io_bound_task(filename: str) ...
import threading import multiprocessing from typing import List, Dict, Tuple def cpu_bound_task(n: int) -> int: """ Computes the sum of the first n natural numbers. """ return n * (n + 1) // 2 def io_bound_task(filename: str) -> int: """ Reads a file and returns the number of lines in the file...
import os import pytest from solution import cpu_bound_task, io_bound_task, scheduler def test_cpu_bound_task(): assert cpu_bound_task(5) == 15 assert cpu_bound_task(100) == 5050 assert cpu_bound_task(0) == 0 def test_io_bound_task(tmpdir): file_path = tmpdir.join("testfile.txt") file_path.write("...
[ { "docstring": "Computes the sum of the first n natural numbers.", "function_declaration": "def cpu_bound_task(n):", "function_name": "cpu_bound_task", "parameter_list": "(n)" }, { "docstring": "Reads a file and returns the number of lines in the file.", "function_declaration": "def io_b...
[ 0, 0, 0, 0, 0, 1, 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": "import threading\nfrom multiprocessing import Process, Pipe\nimport os\n\ndef cpu_bound_task(n: int) -> int:\n \"\"\"\n CPU-bound task that computes the sum of th...
trial_gpt4o_5
{ "original_instruction": "**Question Title**: Implementing and Managing Concurrent Execution in Python\n\n**Objective**: Write a Python program that demonstrates the use of threading and multiprocessing for concurrent execution. Your solution must include the creation and management of threads and processes, as well...
0.643721
Docs: Python310_41295
C
[ "cpu_bound_task", "io_bound_task", "execute_task", "scheduler" ]
4
[ [ "execute_task", "cpu_bound_task" ], [ "execute_task", "io_bound_task" ] ]
2
[]
false
[]
false
pytest
true
[]
true
531bb66fb6a7b11b86849d1d436b1e47162c1411
6a7558887807fc8c8e3dcd7753690538d21815ea
v1.0
complete
Docs
Docs: Pytorch_40800_C
import torch import torch.distributed.rpc as rpc from torch.distributed.rpc import RRef import torch.multiprocessing as mp def initialize_workers(rank, world_size): """ This function initializes the RPC framework on each worker. """ options = rpc.TensorPipeRpcBackendOptions(num_worker_threads=16) r...
import torch import torch.distributed.rpc as rpc from torch.distributed.rpc import RRef import torch.multiprocessing as mp def initialize_workers(rank, world_size): """ This function initializes the RPC framework on each worker. """ options = rpc.TensorPipeRpcBackendOptions(num_worker_threads=16) r...
import pytest import torch import torch.distributed.rpc as rpc from torch.multiprocessing import Process from solution import main def run_main(world_size): """ Helper function to run the main function in a multi-process environment. """ rpc.init_rpc("tester", rank=0, world_size=world_size, rpc_backend...
[ { "docstring": "This function initializes the RPC framework on each worker.", "function_declaration": "def initialize_workers(rank, world_size):", "function_name": "initialize_workers", "parameter_list": "(rank, world_size)" }, { "docstring": "Creates a tensor on worker0.", "function_dec...
[ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.distributed.rpc as rpc\nfrom torch.distributed.rpc import RRef\n\ndef initialize_workers():\n \"\"\"\n Initialize the RPC framework for...
trial_gpt4o_7
{ "original_instruction": "You are tasked with implementing a distributed system using the PyTorch distributed RPC framework. Your system needs to coordinate computations across multiple workers while correctly managing remote references (RRef) to avoid premature deletion of shared objects.\n\n### Instructions\n\n1. ...
0.490789
Docs: Pytorch_40800
C
[ "initialize_workers", "worker0_tensor", "worker1_addition", "worker2_multiplication", "distribute_computation", "final_result", "main" ]
7
[ [ "distribute_computation", "worker0_tensor" ], [ "distribute_computation", "worker1_addition" ], [ "distribute_computation", "worker2_multiplication" ], [ "final_result", "distribute_computation" ] ]
4
[]
false
[]
false
pytest
true
[ "torch" ]
false
10555496d01cebcd23c3627c655e0a2b8754be13
e4a751dcc9a07f251594ffa3ad4fab7d2106d28c
v1.0
complete
Docs
Docs: Python310_41004_C
import timeit from typing import List, Dict import copy def compare_sorting_algorithms(data: List[int]) -> Dict[str, float]: """ Compare the execution time of sorting a list using three different methods: built-in `sorted()`, custom Bubble Sort, and custom Quick Sort. Parameters: data (List[int]...
import timeit from typing import List, Dict import copy def bubble_sort(data: List[int]) -> List[int]: n = len(data) for i in range(n): for j in range(0, n-i-1): if data[j] > data[j+1]: data[j], data[j+1] = data[j+1], data[j] return data def quick_sort(data: List[int]) ...
from solution import compare_sorting_algorithms def test_compare_sorting_algorithms_basic(): data = [5, 3, 8, 6, 2, 7, 4, 1] results = compare_sorting_algorithms(data) assert set(results.keys()) == {'built-in', 'bubble_sort', 'quick_sort'} assert all(isinstance(value, float) for value in results.values...
[ { "docstring": null, "function_declaration": "def bubble_sort(data):", "function_name": "bubble_sort", "parameter_list": "(data)" }, { "docstring": null, "function_declaration": "def quick_sort(data):", "function_name": "quick_sort", "parameter_list": "(data)" }, { "docst...
[ 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 timeit\nfrom typing import List, Dict\n\ndef bubble_sort(data: List[int]) -> List[int]:\n arr = data[:]\n n = len(arr)\n for i in range(n):\n for...
trial_gpt4o_9
{ "original_instruction": "#### Objective\nDemonstrate your understanding of the `timeit` module in Python by writing a function that compares the performance of different implementations of a particular task.\n\n#### Task\nImplement the function `compare_sorting_algorithms` which:\n1. Accepts a list of integers.\n2....
0.636449
Docs: Python310_41004
C
[ "bubble_sort", "quick_sort", "compare_sorting_algorithms" ]
3
[ [ "compare_sorting_algorithms", "bubble_sort" ], [ "compare_sorting_algorithms", "quick_sort" ] ]
2
[]
false
[]
false
pytest
true
[]
true
b338fa643ef3a8eadce2bd47ee7d0f6e7f0509a0
f6f2e4d68ff66840a0eaf67f9ae3d64b0c89c203
v1.0
complete
Docs
Docs: Python310_41378_C
import aiohttp import asyncio import os from typing import List async def download_file(url: str, destination: str) -> None: """Download a single file asynchronously from the given URL to the specified destination. Args: url (str): The URL of the file to download. destination (str): The pa...
import aiohttp import asyncio import os from typing import List async def download_file(url: str, destination: str) -> None: async with aiohttp.ClientSession() as session: async with session.get(url) as response: response.raise_for_status() total_size = int(response.headers.get('con...
import aiohttp import asyncio import os import pytest from unittest.mock import patch, mock_open from solution import download_file, download_files @pytest.mark.asyncio async def test_download_file_success(): url = "http://example.com/file1.txt" destination = "./downloads/file1.txt" # Mock the aiohtt...
[]
[ 1, 1, 1, 1, 0, 0, 0, 0, 1, 0 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import aiohttp\nimport asyncio\nimport os\nfrom typing import List\n\nasync def download_file(url: str, destination: str) -> None:\n \"\"\"\n Downloads a file fro...
trial_gpt4o_2
{ "original_instruction": "**Question:**\n\n### Asynchronous File Downloader using `asyncio`\n\nYou are required to implement an asynchronous file downloader using Python's `asyncio` module. Your downloader should be capable of downloading multiple files concurrently and reporting the progress of each download.\n\n##...
0.636413
Docs: Python310_41378
C
[ "download_file", "download_files" ]
2
[ [ "download_files", "download_file" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
0e637e95e18ae2d33c9f95a5bcb3dc01c96b42b2
12000c0f94ed927b90304be029cfa564332ae18c
v1.0
complete
Docs
Docs: Pytorch_41147_C
import torch from torch.utils.data import DataLoader, Dataset, IterableDataset class CustomMapDataset(Dataset): def __init__(self, data): """ Initialize the custom map-style dataset with the given data. """ self.data = data def __getitem__(self, index): """ Fetch the item at the given ...
import torch from torch.utils.data import DataLoader, Dataset, IterableDataset import random import numpy as np class CustomMapDataset(Dataset): def __init__(self, data): self.data = data def __getitem__(self, index): image, label = self.data[index] image_tensor = torch.tensor(image, d...
import pytest import torch from solution import CustomMapDataset, CustomIterableDataset, custom_collate_fn from torch.utils.data import DataLoader def test_custom_map_dataset(): data = [([1, 2, 3], 1), ([4, 5, 6, 7], 0)] dataset = CustomMapDataset(data) assert len(dataset) == 2 image, label = dataset[0...
[]
[ 0, 0, 0, 1, 0, 0, 0, 0, 0 ]
1
hard
0.111
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import torch\nfrom torch.utils.data import DataLoader, Dataset, IterableDataset\nimport torch.nn.functional as F\nimport numpy as np\n\nclass C...
trial_gpt4o_4
{ "original_instruction": "### Advanced PyTorch DataLoader Implementation\n\n#### Objective:\nCreate an efficient custom data loading pipeline using `torch.utils.data.DataLoader`, demonstrating mastery of:\n1. Custom collate functions.\n2. Handling both map-style and iterable-style datasets.\n3. Optimizing data loadi...
0.434395
Docs: Pytorch_41147
C
[ "pad_sequence", "custom_collate_fn", "main" ]
3
[ [ "custom_collate_fn", "pad_sequence" ] ]
1
[]
false
[ "CustomMapDataset", "CustomIterableDataset" ]
true
pytest
true
[ "numpy", "torch" ]
false
eb398c256bf6b1f57be1c3977788c5cec3a874a8
cb0301fdb89abcd61d6d99ef14fa5f7fac981b6a
v1.0
complete
Docs
Docs: Python310_40869_C
import re from typing import List def transform_code(code: str, fixers: List[str]) -> str: """ Transform a piece of Python 2.x code to Python 3.x code by applying specific fixers. The function supports the following fixers: 1. "print": Converts print statements to print function calls. 2. "raw_inp...
import re from typing import List def print_fixer(code: str) -> str: """ Convert Python 2 print statements to Python 3 print function. """ return re.sub(r'print (.*)', r'print(\1)', code) def raw_input_fixer(code: str) -> str: """ Convert Python 2 raw_input() to Python 3 input(). """ r...
from solution import transform_code def test_print_fixer(): code = '''print "Hello, World!"''' expected = '''print("Hello, World!")''' assert transform_code(code, ["print"]) == expected def test_raw_input_fixer(): code = '''name = raw_input()''' expected = '''name = input()''' assert transform...
[ { "docstring": "Convert Python 2 print statements to Python 3 print function.", "function_declaration": "def print_fixer(code):", "function_name": "print_fixer", "parameter_list": "(code)" }, { "docstring": "Convert Python 2 raw_input() to Python 3 input().", "function_declaration": "def...
[ 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 re\nfrom typing import List\n\ndef fix_print(code: str) -> str:\n \"\"\"\n Fix the print statements from Python 2 style to Python 3 style.\n \"\"\"\n ...
trial_gpt4o_5
{ "original_instruction": "**Title: Implementing a Custom Python 2 to Python 3 Transformation**\n\n**Objective:**\nYou are required to manually implement a function that transforms a piece of Python 2.x code to Python 3.x code by applying specific fixers. This exercise will test your understanding of common compatibi...
0.540914
Docs: Python310_40869
C
[ "print_fixer", "raw_input_fixer", "except_fixer", "transform_code" ]
4
[ [ "transform_code", "except_fixer" ], [ "transform_code", "print_fixer" ], [ "transform_code", "raw_input_fixer" ] ]
3
[]
false
[]
false
pytest
true
[]
true
7d01d20bf931b20bc179cba2f50962d4653692df
f156900cf3dfe8215026825638ade1b96a7ff025
v1.0
complete
Docs
Docs: Python310_41117_C
def complex_operation(complex1: tuple, complex2: tuple, operation: str) -> tuple: """ Perform operations on complex numbers using provided Py_complex functions. complex1: A tuple of two floats representing the first complex number (real, imaginary). complex2: A tuple of two floats representing the seco...
class Py_complex: def __init__(self, real, imag): self.real = real self.imag = imag def _Py_c_sum(left, right): return Py_complex(left.real + right.real, left.imag + right.imag) def _Py_c_diff(left, right): return Py_complex(left.real - right.real, left.imag - right.imag) def _Py_c_neg(nu...
from solution import complex_operation def test_add(): assert complex_operation((1.0, 2.0), (3.0, 4.0), "add") == (4.0, 6.0) def test_subtract(): assert complex_operation((1.0, 2.0), (3.0, 4.0), "subtract") == (-2.0, -2.0) def test_negate(): assert complex_operation((1.0, 2.0), (0.0, 0.0), "negate") == (...
[]
[ 1, 0, 0, 1, 1, 0, 1, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Py_complex:\n def __init__(self, real, imag):\n self.real = real\n self.imag = imag\n\ndef _Py_c_sum(left, right):\n return Py_complex(left.re...
trial_gpt4o_6
{ "original_instruction": "### Complex Number Operations using Py_complex Struct\n\nYour task is to implement a function that takes four parameters: two complex numbers, each represented by a tuple of two floats (real and imaginary parts), and a string specifying the operation to perform. The function should return t...
0.632217
Docs: Python310_41117
C
[ "_Py_c_sum", "_Py_c_diff", "_Py_c_neg", "_Py_c_prod", "_Py_c_quot", "_Py_c_pow", "complex_operation" ]
7
[ [ "complex_operation", "_Py_c_diff" ], [ "complex_operation", "_Py_c_neg" ], [ "complex_operation", "_Py_c_pow" ], [ "complex_operation", "_Py_c_prod" ], [ "complex_operation", "_Py_c_quot" ], [ "complex_operation", "_Py_c_sum" ] ]
6
[]
false
[ "Py_complex" ]
true
pytest
true
[]
true
7c84d8a138ddb66dc9c21b0a5a09b0287e7bdc7e
a0b4519f6356d70b52352d186cc85630c2303b98
v1.0
complete
Docs
Docs: Python310_40106_C
import os import random import statistics import zipfile import datetime def create_directory(directory_name): """Create a new directory named directory_name.""" if not os.path.exists(directory_name): os.makedirs(directory_name) log_event(f"Created directory: {directory_name}") else: ...
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": "**Question: Automating File Operations with Python Standard Library**\n\nYou are tasked with writing a Python script that automates the following operations:\n\n1. **Create a new directory**: Use the `os` module to create a new directory named \"example_dir\" in the current working director...
0.713486
Docs: Python310_40106
C
[ "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
c7f9539270e86807ccb5c0065838f8df1a55fb34
64c6edc16cdebf62c5519d5310c09b7c0ef9848e
v1.0
complete
Docs
Docs: Python310_41359_C
from typing import Iterator import itertools def fibonacci_seq(n: int) -> Iterator[int]: """ Generates the first n numbers of the Fibonacci sequence. :param n: Number of Fibonacci numbers to generate :return: Iterator of the first n Fibonacci numbers >>> list(fibonacci_seq(1)) [0] ...
from typing import Iterator import itertools def fibonacci_seq(n: int) -> Iterator[int]: """ Generates the first n numbers of the Fibonacci sequence. :param n: Number of Fibonacci numbers to generate :return: Iterator of the first n Fibonacci numbers """ def fibonacci_gen(): a, b = 0, 1...
import pytest from solution import ( fibonacci_seq, filter_primes, sum_of_combinations ) def test_fibonacci_seq(): assert list(fibonacci_seq(1)) == [0] assert list(fibonacci_seq(2)) == [0, 1] assert list(fibonacci_seq(5)) == [0, 1, 1, 2, 3] assert list(fibonacci_seq(10)) == [0, 1, 1, 2, 3, ...
[ { "docstring": "Generates the first n numbers of the Fibonacci sequence.\n:param n: Number of Fibonacci numbers to generate\n:return: Iterator of the first n Fibonacci numbers", "function_declaration": "def fibonacci_seq(n):", "function_name": "fibonacci_seq", "parameter_list": "(n)" }, { "d...
[ 0, 1, 0, 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": "from typing import Iterator\nimport itertools\nimport math\n\ndef fibonacci_seq(n: int) -> Iterator[int]:\n \"\"\"\n Generates the first `n` numbers of the Fibona...
trial_gpt4o_9
{ "original_instruction": "**Problem Statement**\n\nYou are required to implement a set of functions to process and manipulate sequences of data efficiently using functional programming techniques. Specifically, you will need to create generators, use iterators, and employ modules like `itertools` and `functools`.\n\...
0.736183
Docs: Python310_41359
C
[ "fibonacci_seq", "is_prime", "filter_primes", "sum_of_combinations" ]
4
[ [ "filter_primes", "is_prime" ] ]
1
[]
false
[]
false
pytest
true
[]
true
93e146c4aab94921ad37075407cbf3a4a0c9593c
c05d4165d128a0952b3071464082b671f1ec3924
v1.0
complete
Docs
Docs: Scikit_40554_C
import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split def stream_data(file_path, batch_size): """ A generator function to simulate streaming ...
import numpy as np from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split def stream_data(file_path, batch_size): """ A generator function to simulate streaming ...
from solution import stream_data, train_incremental_model, evaluate_model from sklearn.feature_extraction.text import HashingVectorizer from sklearn.linear_model import SGDClassifier from sklearn.metrics import accuracy_score import tempfile import os def test_stream_data(): # Create a temporary file with sample d...
[ { "docstring": "A generator function to simulate streaming of data in batches.\n\nArgs:\nfile_path (str): The path to the large text file.\nbatch_size (int): Number of samples per batch.\n\nYields:\nX_batch (list): List of text samples.\ny_batch (list): List of labels for the text samples.", "function_decla...
[ 1, 0, 1, 0, 1, 0, 1, 0, 1, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import accuracy_...
trial_gpt4o_8
{ "original_instruction": "#### Objective\nYou are tasked with training a text classification model on a dataset that is too large to fit into the memory using scikit-learn. You will use out-of-core learning techniques with an incremental classifier.\n\n#### Task\n1. **Data Streaming:** Write a function `stream_data`...
0.665859
Docs: Scikit_40554
C
[ "stream_data", "train_incremental_model", "evaluate_model" ]
3
[ [ "train_incremental_model", "stream_data" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
05e53a3a5821549614f1356bbe7c32166f115b73
f52b9142356341d5d72af5756d86a062917405c4
v1.0
complete
Docs
Docs: Python310_41374_C
import os import gzip import shutil import logging def compress_and_decompress_files(input_dir: str, compressed_dir: str, decompressed_dir: str) -> None: """ Compress all files in the input_dir directory and store the compressed files in the compressed_dir directory. Decompress the compressed files from th...
import os import gzip import shutil import logging def compress_file(input_path, output_path): try: with open(input_path, 'rb') as f_in, gzip.open(output_path, 'wb', compresslevel=9) as f_out: shutil.copyfileobj(f_in, f_out) except Exception as e: logging.error(f"Failed to compress ...
import os import shutil import pytest from solution import compress_and_decompress_files # Set up test directories input_dir = 'test_input_dir' compressed_dir = 'test_compressed_dir' decompressed_dir = 'test_decompressed_dir' @pytest.fixture(scope="module", autouse=True) def setup_and_teardown(): # Setup: Create ...
[ { "docstring": null, "function_declaration": "def compress_file(input_path, output_path):", "function_name": "compress_file", "parameter_list": "(input_path, output_path)" }, { "docstring": null, "function_declaration": "def decompress_file(input_path, output_path):", "function_name"...
[ 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import os\nimport gzip\nimport shutil\n\ndef compress_and_decompress_files(input_dir: str, compressed_dir: str, decompressed_dir: str) -> None:\n if not os.path.exis...
trial_gpt4o_1
{ "original_instruction": "**Objective:**\nDesign and implement a Python function using the `gzip` module to compress files in a given directory and then decompress them into another specified directory, while handling possible exceptions.\n\n**Problem Statement:**\nWrite a Python function `compress_and_decompress_fi...
0.722209
Docs: Python310_41374
C
[ "compress_file", "decompress_file", "compress_and_decompress_files" ]
3
[ [ "compress_and_decompress_files", "compress_file" ], [ "compress_and_decompress_files", "decompress_file" ] ]
2
[]
false
[]
false
pytest
true
[]
true
e701fb104049d4838df796274ef02eb6900b2246
5635492b2719d09259bc3f3d30086e8328c74238
v1.0
complete
Docs
Docs: Python310_40845_C
c #include <Python.h> typedef struct { PyObject_HEAD int value; int ref_count; } MyObject; static PyObject* my_incref(PyObject *self, PyObject *args) { // Simulate the behavior of Py_INCREF } static PyObject* my_decref(PyObject *self, PyObject *args) { // Simulate the behavior of Py_DECREF } sta...
# Emulating the creation of a Python extension module in C within Python itself for educational purposes. class MyObject: def __init__(self, value): self.value = value self.ref_count = 1 def my_incref(obj): if obj is not None: obj.ref_count += 1 print(f"Object reference count i...
def test_my_incref(): obj = MyObject(10) initial_ref_count = obj.ref_count my_incref(obj) assert obj.ref_count == initial_ref_count + 1 def test_my_decref(): obj = MyObject(10) initial_ref_count = obj.ref_count my_incref(obj) my_decref(obj) assert obj.ref_count == initial_ref_count ...
[]
[ 1, 0, 1, 0, 0, 0, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "# solution.py\n\nfrom ctypes import c_int, c_void_p\n\nclass PyObject:\n def __init__(self, value=0):\n self.value = value\n self.refcount = c_int(1) ...
trial_gpt4o_8
{ "original_instruction": "As a Python developer, you are required to manage the lifecycle of Python objects using reference counting. Write a Python extension module in C that simulates the behavior of `Py_INCREF`, `Py_DECREF`, `Py_XINCREF`, and `Py_XDECREF` functions described in the documentation.\n\n### Requireme...
0.40432
Docs: Python310_40845
C
[ "my_incref", "my_decref", "my_xincref", "my_xdecref" ]
4
[ [ "my_xdecref", "my_decref" ], [ "my_xincref", "my_incref" ] ]
2
[]
false
[ "MyObject" ]
true
pytest
false
[]
true
68ef0d1154c0a7817829a56b527330802df44eeb
ccad5445331b0953b6c2ccdd34c0f79c8a7fddb5
v1.0
complete
Docs
Docs: Python310_41376_C
import timeit from typing import List, Dict def square_using_loop(nums: List[int]) -> List[int]: """ Square numbers using a loop. >>> square_using_loop([1, 2, 3, 4, 5]) [1, 4, 9, 16, 25] """ result = [] for num in nums: result.append(num ** 2) return result def square_using_lis...
import timeit def square_using_loop(nums): result = [] for num in nums: result.append(num ** 2) return result def square_using_list_comprehension(nums): return [num ** 2 for num in nums] def square_using_map(nums): return list(map(lambda x: x ** 2, nums)) def benchmark_square_functions(n...
from solution import ( square_using_loop, square_using_list_comprehension, square_using_map, benchmark_square_functions ) def test_square_using_loop(): nums = [1, 2, 3, 4, 5] assert square_using_loop(nums) == [1, 4, 9, 16, 25] def test_square_using_list_comprehension(): nums = [1, 2, 3, 4,...
[ { "docstring": null, "function_declaration": "def square_using_loop(nums):", "function_name": "square_using_loop", "parameter_list": "(nums)" }, { "docstring": null, "function_declaration": "def square_using_list_comprehension(nums):", "function_name": "square_using_list_comprehensio...
[ 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import timeit\n\ndef square_using_loop(nums):\n result = []\n for num in nums:\n result.append(num ** 2)\n return result\n\ndef square_using_list_compre...
trial_gpt4o_4
{ "original_instruction": "**Question: Performance Benchmarking Using the `timeit` Module**\n\nThe purpose of this exercise is to assess your understanding of the Python `timeit` module and your ability to benchmark the performance of different code snippets.\n\n### Problem Statement:\nYou are tasked with benchmarkin...
0.612836
Docs: Python310_41376
C
[ "square_using_loop", "square_using_list_comprehension", "square_using_map", "benchmark_square_functions" ]
4
[ [ "benchmark_square_functions", "square_using_list_comprehension" ], [ "benchmark_square_functions", "square_using_loop" ], [ "benchmark_square_functions", "square_using_map" ] ]
3
[]
false
[]
false
pytest
true
[]
true
d6e36636a0cab8ef3e868d7b872c263cc057fbfc
dc758284c5d0dbb575d3a68a78d1fc54f1591448
v1.0
complete
Docs
Docs: Pytorch_41095_C
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist import torch.multiprocessing as mp from torch.distributed.elastic.multiprocessing.errors import ( record, ChildFailedError, ErrorHandler, ProcessFailure ) import random import logging logging.basicConfig(lev...
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist import torch.multiprocessing as mp from torch.distributed.elastic.multiprocessing.errors import ( record, ChildFailedError, ErrorHandler, ProcessFailure ) import random import logging logging.basicConfig(lev...
from solution import distributed_training_loop def test_distributed_training_loop(): try: distributed_training_loop() except ChildFailedError as e: assert isinstance(e, ChildFailedError) except ProcessFailure as e: assert isinstance(e, ProcessFailure) else: assert True ...
[]
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom torch.distributed.elastic.multiprocessing.errors import record,...
trial_gpt4o_9
{ "original_instruction": "You are tasked with implementing a fault-tolerant distributed training loop using PyTorch. The goal is to demonstrate your understanding of distributed multiprocessing and how to handle errors that occur within a distributed setting. You must utilize the provided `torch.distributed.elastic....
0.592691
Docs: Pytorch_41095
C
[ "train", "distributed_training_loop" ]
2
[ [ "distributed_training_loop", "train" ] ]
1
[]
false
[ "SimpleModel" ]
true
pytest
true
[ "torch" ]
false
312fc80944a0dfa799cfe17f22cb0ca5e1bd9c7a
8589c789dfc518793a158e42042f1267565aed75
v1.0
complete
Docs
Docs: Python310_41891_C
import asyncio from typing import List, Tuple async def worker(name: str, queue: asyncio.PriorityQueue, output_list: List[str]): # Your implementation here pass async def schedule_tasks(tasks: List[Tuple[int, str]]) -> None: """ Design a task scheduling system that processes tasks concurrently based on th...
import asyncio from typing import List, Tuple async def worker(name: str, queue: asyncio.PriorityQueue, output_list: List[str]): while True: priority, task = await queue.get() if priority is None: # Break out of the loop if we encounter the stop signal break await as...
import asyncio from solution import schedule_tasks def test_schedule_tasks(capsys): tasks = [ (1, 'Clean the house'), (3, 'Buy groceries'), (2, 'Pay bills'), (0, 'Emergency meeting') ] asyncio.run(schedule_tasks(tasks)) expected_output = [ 'Emergency me...
[]
[ 1, 0, 1, 1, 1, 1, 1, 0, 0, 1 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List, Tuple\n\nasync def worker(name: str, queue: asyncio.PriorityQueue, output_list: List[str]):\n while True:\n priority,...
trial_gpt4o_5
{ "original_instruction": "**Question: Implement and Utilize Asyncio Queues for a Task Scheduler**\n\n### Problem Statement\n\nYou are to design a task scheduling system that concurrently processes tasks with varying priorities. Use the `asyncio.PriorityQueue` to schedule tasks based on their priorities. Each task mu...
0.590937
Docs: Python310_41891
C
[ "worker", "schedule_tasks" ]
2
[ [ "schedule_tasks", "worker" ] ]
1
[]
false
[]
false
pytest
true
[]
true
97163ca02b9a2fe7f7ba4d085fa1f792a80b5bc3
41e1c5c03c22e64a0826921a03829b1a3e2aeece
v1.0
complete
Docs
Docs: Pytorch_41899_C
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torch.distributed.algorithms import Join, Joinable, JoinHook class SimpleNet(nn.Module): """ A simple fully connected neural network """ def __init__(self): super(SimpleNet, self).__init__() sel...
import torch import torch.nn as nn import torch.optim as optim import torch.distributed as dist from torch.distributed.algorithms.join import Join, Joinable # Define your neural network model class SimpleNet(nn.Module): def __init__(self): super(SimpleNet, self).__init__() self.fc1 = nn.Linear(10, ...
def test_distributed_training(): rank = 0 world_size = 2 num_epochs = 5 # Simulate the function call for each rank from multiprocessing import Process processes = [] for rank in range(world_size): p = Process(target=distributed_training, args=(rank, world_size, num_epochs)) ...
[]
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
1
hard
0.1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributed as dist\nfrom torch.distributed.algorithms.join import Join, Joinable, JoinHo...
trial_gpt4o_1
{ "original_instruction": "## Coding Assessment Question\n\n### Objective\nYou are required to demonstrate your understanding of PyTorch's Generic Join Context Manager for handling distributed training with uneven input sizes. You will implement a distributed training loop using PyTorch, ensuring correct synchronizat...
0.564196
Docs: Pytorch_41899
C
[ "setup", "cleanup", "distributed_training" ]
3
[ [ "distributed_training", "cleanup" ], [ "distributed_training", "setup" ] ]
2
[]
false
[ "SimpleNet" ]
true
pytest
false
[ "torch" ]
false
b80dfea3383f1aabc461c8534bf0f3199016892b
7b120cb278ded6648ff132ca320fc8d6bf453039
v1.0
complete
Docs
Docs: Python310_41559_C
import sys def audit_hook(event, args): """ Audit hook function that logs the event name and arguments. Parameters: event (str): The event name. args (tuple): The event arguments. Example usage: >>> audit_hook("test_event", ("arg1", "arg2")) Audit Event: test_event, Arguments: ('a...
import sys # Part 1: Add Audit Hook def audit_hook(event, args): print(f"Audit Event: {event}, Arguments: {args}") sys.addaudithook(audit_hook) # Part 2: Memory Tracing Decorator def memory_tracer(func): def wrapper(*args, **kwargs): before = sys.getallocatedblocks() result = func(*args, **kw...
from solution import memory_tracer, example_function, monitor_events, audit_hook import sys def test_audit_hook(capsys): audit_hook("test_event", ("arg1", "arg2")) captured = capsys.readouterr() assert "Audit Event: test_event, Arguments: ('arg1', 'arg2')" in captured.out def test_memory_tracer(capsys): ...
[ { "docstring": null, "function_declaration": "def audit_hook(event, args):", "function_name": "audit_hook", "parameter_list": "(event, args)" }, { "docstring": null, "function_declaration": "def memory_tracer(func):", "function_name": "memory_tracer", "parameter_list": "(func)" ...
[ 0, 0, 0, 0, 0, 0, 1, 0, 1, 1 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sys\n\n# Part 1: Add Audit Hook\ndef audit_hook(event, args):\n print(f\"Audit Event: {event}, Arguments: {args}\")\n\nsys.addaudithook(audit_hook)\n\n# Part ...
trial_gpt4o_8
{ "original_instruction": "#### Objective:\nWrite a Python program where you will:\n1. Use the `sys` module to add an audit hook.\n2. Implement a memory tracing function to track and print the memory allocation of a specific function.\n3. Monitor and record the number of times specific events (e.g., function calls) a...
0.517544
Docs: Python310_41559
C
[ "audit_hook", "memory_tracer", "example_function", "trace_function", "monitor_events" ]
5
[ [ "monitor_events", "example_function" ], [ "monitor_events", "trace_function" ] ]
2
[]
false
[]
false
pytest
true
[]
true
47e6d60008ac62fcfc5e94c1673c0bb3e52bd903
3a8620b401c776dfa50656b1a84c1fb00126a728
v1.0
complete
Docs
Docs: Python310_41458_C
import asyncio import random from typing import List async def fetch_conversion_rate(source: str) -> float: """ Simulates fetching a conversion rate from a given source. Args: - source: str: The name of the source. Returns: - float: A mock conversion rate between 0.8 and 1.2. Exa...
import asyncio import random from typing import List async def fetch_conversion_rate(source: str) -> float: """ Simulates fetching a conversion rate from a given source. Args: - source: str: The name of the source. Returns: - float: A mock conversion rate between 0.8 and 1.2. """ ...
import asyncio import pytest from solution import fetch_conversion_rate, get_average_conversion_rate # Helper coroutine to run async tests def run(coro): return asyncio.run(coro) # Test for fetch_conversion_rate function to check return type and value range def test_fetch_conversion_rate(): rate = run(fetch_c...
[]
[ 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 asyncio\nimport random\nfrom typing import List\n\nasync def fetch_conversion_rate(source: str) -> float:\n \"\"\" Simulate fetching a conversion rate from a ...
trial_gpt4o_6
{ "original_instruction": "### Asyncio Currency Conversion Tasks\n\nYou are required to build a small asyncio program that concurrently fetches and processes currency conversion rates from multiple sources.\n\n#### Problem Statement\n\nImplement a function `fetch_conversion_rate(source: str) -> float` which simulates...
0.514605
Docs: Python310_41458
C
[ "fetch_conversion_rate", "get_average_conversion_rate" ]
2
[ [ "get_average_conversion_rate", "fetch_conversion_rate" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6783249c1e0860a064bf20fe2d1fe69fecf740e5
d89b3c42602fa259ddd2b9b93e021437486589e5
v1.0
complete
Docs
Docs: Python310_42040_C
import concurrent.futures def process_numbers_concurrently(numbers: list, use_threads: bool = True) -> list: """ Processes a list of integers, where each integer is squared. Uses either ThreadPoolExecutor or ProcessPoolExecutor from concurrent.futures. Args: - numbers: list of integers to be squar...
import concurrent.futures def square_number(n): return n * n def process_numbers_concurrently(numbers: list, use_threads: bool = True) -> list: """ Processes a list of integers, where each integer is squared. Uses either ThreadPoolExecutor or ProcessPoolExecutor from concurrent.futures. Args: ...
from solution import process_numbers_concurrently def test_process_numbers_concurrently_with_threads(): numbers = [1, 2, 3, 4, 5] result = process_numbers_concurrently(numbers, use_threads=True) assert result == [1, 4, 9, 16, 25] def test_process_numbers_concurrently_with_processes(): numbers = [1, 2,...
[ { "docstring": null, "function_declaration": "def square_number(n):", "function_name": "square_number", "parameter_list": "(n)" }, { "docstring": "Processes a list of integers, where each integer is squared.\nUses either ThreadPoolExecutor or ProcessPoolExecutor from concurrent.futures.\n\nA...
[ 1, 0, 0, 0, 0, 0, 1, 0, 1, 1 ]
4
medium
0.4
{ "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 square_number(n):\n return n * n\n\ndef process_numbers_concurrently(numbers: list, use...
trial_gpt4o_9
{ "original_instruction": "## Coding Assessment Question\n\n### Objective\nImplement a Python function that uses the `concurrent.futures` module to perform concurrent execution of multiple tasks. The function will process a list of integers, where each integer will be squared. The task involves ensuring that the resu...
0.62405
Docs: Python310_42040
C
[ "square_number", "process_numbers_concurrently" ]
2
[ [ "process_numbers_concurrently", "square_number" ] ]
1
[]
false
[]
false
pytest
true
[]
true
d1f1c3db8ac41a41d1504e45b0996c17f218b432
7e1e17a2ccb029812d77fcd689b719fe0fc54c83
v1.0
complete
Docs
Docs: Python310_41653_C
import heapq import itertools REMOVED = '<removed-task>' counter = itertools.count() def add_task(pq, entry_finder, task, priority): """ Adds a new task to the priority queue or updates the priority of an existing task. Parameters: - pq: List representing the heap-based priority queue. - entr...
import heapq import itertools REMOVED = '<removed-task>' counter = itertools.count() def add_task(pq, entry_finder, task, priority): """ Adds a new task to the priority queue or updates the priority of an existing task. Parameters: - pq: List representing the heap-based priority queue. - entr...
from solution import add_task, remove_task, pop_task def test_add_and_pop_task(): pq = [] entry_finder = {} add_task(pq, entry_finder, 'task1', 5) add_task(pq, entry_finder, 'task2', 9) add_task(pq, entry_finder, 'task3', 3) assert pop_task(pq, entry_finder) == 'task3' assert pop_task(...
[ { "docstring": "Adds a new task to the priority queue or updates the priority of an existing task.\n\nParameters:\n- pq: List representing the heap-based priority queue.\n- entry_finder: Dictionary mapping tasks to their heap entries.\n- task: The name of the task being added or updated.\n- priority: The new pr...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import heapq\nimport itertools\n\nREMOVED = '<removed-task>' # Placeholder for a removed task\ncounter = itertools.count() # Unique sequence count\n\ndef add_task(pq,...
trial_gpt4o_2
{ "original_instruction": "### Priority Queue Management with Dynamic Tasks\n\n**Objective:**\nImplement a priority queue system using the `heapq` module, accommodating dynamic task priorities. This exercise will test your understanding of heap operations, dynamic updates, and efficient algorithms.\n\n**Scenario:**\n...
0.560198
Docs: Python310_41653
C
[ "add_task", "remove_task", "pop_task" ]
3
[ [ "add_task", "remove_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
098869b620bd43707d5e688a0c872a57965c9e76
03284bc9fa885a6cb1207efe1349ec29ca67a8b5
v1.0
complete
Docs
Docs: Python310_41751_C
import asyncio import signal import functools async def handle_client(reader, writer): """A coroutine that handles communication with a single client. It reads data from the client, logs the received message, sends the same message back to the client, and closes the connection when the client discon...
import asyncio import signal import functools async def handle_client(reader, writer): address = writer.get_extra_info('peername') print(f"Connection from {address}") try: while True: data = await reader.read(100) if not data: break message = dat...
import asyncio import pytest from solution import handle_client, start_echo_server @pytest.mark.asyncio async def test_handle_client_echo(): server = await asyncio.start_server(handle_client, '127.0.0.1', 0) addr = server.sockets[0].getsockname() reader, writer = await asyncio.open_connection(*addr) t...
[ { "docstring": null, "function_declaration": "def ask_exit(signame, loop):", "function_name": "ask_exit", "parameter_list": "(signame, loop)" } ]
[ 1, 0 ]
1
medium
0.5
{ "trial_gpt4o_0": null, "trial_gpt4o_1": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared1_results_combined.jsonl", "solution_code": "import asyncio\nimport signal\nimport functools\n\nasync def handle_client(reader, writer):\n address = writer.get_extra_info('peername')\n ...
trial_gpt4o_1
{ "original_instruction": "### Asyncio Event Loop and Network Operations\n\n#### Problem Statement:\nYou are provided with a task to build an asynchronous TCP echo server using Python's `asyncio` library. The server should accept incoming client connections, read messages sent by the clients, and echo the same messag...
0.678709
Docs: Python310_41751
C
[ "handle_client", "start_echo_server", "ask_exit", "main" ]
4
[ [ "start_echo_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
72b1ca5c39a909c0e837fe5699c2d9943807a9f0
cb109013569cb5a9e72ea4ba1f3bf02b1c8412dd
v1.0
complete
Docs
Docs: Python310_40968_C
import curses import random def start_curses_app(stdscr): """Start the curses application and initialize the game.""" curses.curs_set(0) # Hide cursor stdscr.keypad(True) # Enable special keys curses.start_color() height, width = 20, 20 treasures_collected = 0 game_over = False ...
import curses import random def start_curses_app(stdscr): curses.curs_set(0) # Hide cursor stdscr.keypad(True) # Enable special keys curses.start_color() height, width = 20, 20 treasures_collected = 0 game_over = False # Create dungeon and place elements dungeon, player_pos = cr...
import pytest from solution import create_dungeon, handle_movement def test_initial_dungeon(): height, width = 20, 20 dungeon, player_pos = create_dungeon(height, width) assert len(dungeon) == height assert len(dungeon[0]) == width assert dungeon[1][1] == '@' walls = [dungeon[i][0] == '#' and...
[ { "docstring": null, "function_declaration": "def start_curses_app(stdscr):", "function_name": "start_curses_app", "parameter_list": "(stdscr)" }, { "docstring": null, "function_declaration": "def create_dungeon(height, width):", "function_name": "create_dungeon", "parameter_list...
[ 1, 1, 0, 0, 1, 0, 1, 1, 0, 1 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import curses\nimport random\n\ndef start_curses_app(stdscr):\n curses.curs_set(0) # Hide cursor\n stdscr.keypad(True) # Enable special keys\n curses.start_c...
trial_gpt4o_0
{ "original_instruction": "### Question: Create a Text Adventure Game Using Python `curses` Module\n\nAs a programming challenge, you will create a simple text adventure game using the `curses` module. In this game, the player explores a grid-based dungeon, moving their character '@' around and avoiding or interactin...
0.533965
Docs: Python310_40968
C
[ "start_curses_app", "create_dungeon", "place_randomly", "render_dungeon", "handle_movement", "main" ]
6
[ [ "create_dungeon", "place_randomly" ], [ "start_curses_app", "create_dungeon" ], [ "start_curses_app", "handle_movement" ], [ "start_curses_app", "render_dungeon" ] ]
4
[]
false
[]
false
pytest
true
[]
true
c409ecaef1def425d9bbfcf6a3f6403c8d767ecd
7f83a6923f5faecadef4dd224234b58b2099d46e
v1.0
complete
Docs
Docs: Python310_41730_C
import types def is_cell(obj): """ Returns True if the object is a cell object, False otherwise. """ pass def create_cell(value): """ Creates a new cell object containing the given value. """ pass def get_cell_value(cell): """ Returns the value contained in the cell object. ...
import types def is_cell(obj): """ Returns True if the object is a cell object, False otherwise. """ return isinstance(obj, types.CellType) def create_cell(value): """ Creates a new cell object containing the given value. """ # Using a closure to create a cell object def closure():...
from solution import is_cell, create_cell, get_cell_value, set_cell_value import types import pytest def test_is_cell(): # Create a cell and non-cell object cell = create_cell(10) non_cell = 10 assert is_cell(cell) == True assert is_cell(non_cell) == False def test_create_cell(): cell...
[ { "docstring": "Returns True if the object is a cell object, False otherwise.", "function_declaration": "def is_cell(obj):", "function_name": "is_cell", "parameter_list": "(obj)" }, { "docstring": "Creates a new cell object containing the given value.", "function_declaration": "def creat...
[ 1, 0, 0 ]
1
medium
0.333
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import types\n\ndef is_cell(obj):\n \"\"\"\n Returns True if the object is a cell object, False otherwise.\n \"\"\"\n return isinstance(obj, types.CellType)...
trial_gpt4o_0
{ "original_instruction": "#### Objective\nDemonstrate your understanding of handling cell objects in Python by implementing a set of wrappers around some of the core functions provided in the Python C API documentation.\n\n#### Task\nYou need to write a Python module that provides functions for creating, accessing, ...
0.445706
Docs: Python310_41730
C
[ "is_cell", "create_cell", "get_cell_value", "set_cell_value" ]
4
[ [ "get_cell_value", "is_cell" ], [ "set_cell_value", "is_cell" ] ]
2
[]
false
[]
false
pytest
true
[]
true
cb9a7cee855043373774b770d2e7c742115349b1
eb61f3e3c69371509a52416713cca9dadc9f4da8
v1.0
complete
Docs
Docs: Python310_42143_C
import time from concurrent.futures import ThreadPoolExecutor, as_completed def process_task(task_id, duration): """ Simulates task processing by sleeping for `duration` seconds. Returns a message indicating the task completion. """ pass # Implement the sleeping and message return functionality d...
import time from concurrent.futures import ThreadPoolExecutor, as_completed def process_task(task_id, duration): """ Simulates task processing by sleeping for `duration` seconds. Returns a message indicating the task completion. """ time.sleep(duration) return f"Task {task_id} completed in {dur...
from solution import process_task, manage_tasks def test_process_task(): # Test process_task with various durations assert process_task(1, 1) == "Task 1 completed in 1 seconds" assert process_task(2, 3) == "Task 2 completed in 3 seconds" assert process_task(3, 2) == "Task 3 completed in 2 seconds" def...
[ { "docstring": "Simulates task processing by sleeping for `duration` seconds.\nReturns a message indicating the task completion.", "function_declaration": "def process_task(task_id, duration):", "function_name": "process_task", "parameter_list": "(task_id, duration)" }, { "docstring": "Manag...
[ 1, 1, 1, 1, 1, 0, 0, 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 time\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\ndef process_task(task_id, duration):\n \"\"\"\n Simulates task processing by sleep...
trial_gpt4o_7
{ "original_instruction": "### Advanced Asynchronous Execution With `concurrent.futures`\n\nYou are tasked with designing a multi-threaded job processing system using the `concurrent.futures` module in Python. The system will process a list of tasks and return the results once all tasks are completed.\n\n#### Require...
0.751277
Docs: Python310_42143
C
[ "process_task", "manage_tasks" ]
2
[ [ "manage_tasks", "process_task" ] ]
1
[]
false
[]
false
pytest
true
[]
true
818dbf45bd2ae02a6f0e2423d3cb389845d5ae80
f793114fe1b2951f34491032478383d1d00aa4cb
v1.0
complete
Docs
Docs: Python310_42047_C
import codecs class ReverseCodec(codecs.Codec): def encode(self, input, errors='strict'): return input[::-1], len(input) def decode(self, input, errors='strict'): return input[::-1], len(input) def reverse_search_function(encoding): if encoding == 'reverse_codec': return codecs.Co...
import codecs class ReverseCodec(codecs.Codec): def encode(self, input, errors='strict'): return input[::-1], len(input) def decode(self, input, errors='strict'): return input[::-1], len(input) def reverse_search_function(encoding): if encoding == 'reverse_codec': return codecs.Co...
from solution import register_custom_codec, encode_text, decode_text def test_register_custom_codec(): register_custom_codec() assert codecs.lookup('reverse_codec') is not None def test_encode_text(): register_custom_codec() assert encode_text("hello") == "olleh" assert encode_text("world") == "dl...
[]
[ 0, 1, 1, 0, 1, 0, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import codecs\n\ndef reverse_encode(input, errors='strict'):\n return (input[::-1], len(input))\n\ndef reverse_decode(input, errors='strict'):\n return (input[::-...
trial_gpt4o_1
{ "original_instruction": "### Custom Codec Implementation and Utilization\n\n**Objective:**\n\nYou are tasked with implementing a custom codec and using it to encode and decode text, demonstrating your understanding of the codec-related functions in Python.\n\n**Instructions:**\n\n1. **Implement a Custom Codec:**\n ...
0.612777
Docs: Python310_42047
C
[ "reverse_search_function", "register_custom_codec", "encode_text", "decode_text" ]
4
[ [ "register_custom_codec", "reverse_search_function" ] ]
1
[]
false
[ "ReverseCodec" ]
true
pytest
true
[]
true
edf8212aee3df65c0a11b9ba0549fb611b7b662a
4dccb458a03ad4f2d169a66ffef3cfdf89fc5af3
v1.0
complete
Docs
Docs: Python310_42327_C
from concurrent.futures import ProcessPoolExecutor from typing import List def square(n: int) -> int: return n * n def sum_of_squares(numbers: List[int]) -> int: """ Calculate the sum of squares of a list of numbers using asynchronous execution with ProcessPoolExecutor. >>> sum_of_squares([]) 0 >>...
from concurrent.futures import ProcessPoolExecutor from typing import List def square(n: int) -> int: return n * n def sum_of_squares(numbers: List[int]) -> int: if not numbers: return 0 with ProcessPoolExecutor() as executor: results = executor.map(square, numbers) return su...
from solution import sum_of_squares def test_sum_of_squares_empty_list(): assert sum_of_squares([]) == 0 def test_sum_of_squares_single_element(): assert sum_of_squares([5]) == 25 def test_sum_of_squares_positive_elements(): assert sum_of_squares([1, 2, 3, 4, 5]) == 55 def test_sum_of_squares_negative_e...
[ { "docstring": null, "function_declaration": "def square(n):", "function_name": "square", "parameter_list": "(n)" }, { "docstring": null, "function_declaration": "def sum_of_squares(numbers):", "function_name": "sum_of_squares", "parameter_list": "(numbers)" } ]
[ 1, 0, 0, 0, 1, 1, 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": "from concurrent.futures import ProcessPoolExecutor\nfrom typing import List\n\ndef square(n: int) -> int:\n return n * n\n\ndef sum_of_squares(numbers: List[int]) ->...
trial_gpt4o_0
{ "original_instruction": "## Coding Assessment Question\n\n### Objective\nImplement a Python program to efficiently calculate the sum of squares of a list of numbers using asynchronous execution with `ProcessPoolExecutor` from the \"concurrent.futures\" module. The solution should demonstrate the student's ability t...
0.600807
Docs: Python310_42327
C
[ "square", "sum_of_squares" ]
2
[ [ "sum_of_squares", "square" ] ]
1
[]
false
[]
false
pytest
true
[]
true
78a4f95c429df9e684be32e5678840549bfd4799
15652006bee0a9284828c1f38e78d2d250b01345
v1.0
complete
Docs
Docs: Python310_41789_C
def process_tasks(tasks: List[Dict[str, Any]]) -> Tuple[List[Any], List[str]]: """ Processes a list of tasks and returns the results and errors. >>> tasks = [ ... {"operation": "divide", "args": [10, 2]}, ... {"operation": "sqrt", "args": [16]}, ... {"operation": "concat", "args": ["Hell...
import math import warnings def divide(a, b): try: return a / b except ZeroDivisionError as e: raise ZeroDivisionError(f"ZeroDivisionError: Cannot divide {a} by zero.") def sqrt(x): try: if x < 0: raise ValueError(f"ValueError: Cannot calculate square root of negative n...
import pytest from solution import process_tasks, factorial def test_process_tasks(): tasks = [ {"operation": "divide", "args": [10, 2]}, {"operation": "sqrt", "args": [16]}, {"operation": "concat", "args": ["Hello", " ", "world"]}, {"operation": "add", "args": [1, 2, 3]}, {...
[ { "docstring": null, "function_declaration": "def divide(a, b):", "function_name": "divide", "parameter_list": "(a, b)" }, { "docstring": null, "function_declaration": "def sqrt(x):", "function_name": "sqrt", "parameter_list": "(x)" }, { "docstring": null, "function_d...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import math\nimport warnings\n\ndef divide(a, b):\n try:\n return a / b\n except ZeroDivisionError as e:\n raise ZeroDivisionError(f\"ZeroDivisionEr...
trial_gpt4o_0
{ "original_instruction": "#### Objective:\nYour task is to implement a robust Python module that can handle multiple operations and exceptions from a given set of tasks. You are required to demonstrate your understanding of advanced exception handling and recursion control in Python.\n\n#### Requirements:\n1. **Func...
0.683411
Docs: Python310_41789
C
[ "divide", "sqrt", "concat", "sum_args", "factorial", "process_tasks" ]
6
[ [ "process_tasks", "concat" ], [ "process_tasks", "divide" ], [ "process_tasks", "sqrt" ], [ "process_tasks", "sum_args" ] ]
4
[]
false
[]
false
pytest
true
[]
true
0248ae1735ef3f925494932f7ff7fb9a7ebf9649
fdc71e563b23d4d907a40d811212e8ab9195b29d
v1.0
complete
Docs
Docs: Pytorch_42103_C
import torch from torch.futures import Future from typing import List def process_pipeline(data: List[int]) -> List[int]: """ Given a list of integers, apply a series of asynchronous transformations to the data and return the final aggregated results. The transformations should occur in different ...
import torch from torch.futures import Future from typing import List def add_one(x: int) -> Future: future = Future() future.set_result(x + 1) return future def square(x: int) -> Future: future = Future() future.set_result(x * x) return future def sqrt(x: int) -> Future: future = Future(...
import pytest from solution import process_pipeline def test_process_pipeline_basic(): data = [1, 2, 3, 4] result = process_pipeline(data) expected = [torch.sqrt(torch.tensor(4)), torch.sqrt(torch.tensor(9)), torch.sqrt(torch.tensor(16)), torch.sqrt(torch.tensor(25))] assert result == [e.item() for e i...
[ { "docstring": null, "function_declaration": "def add_one(x):", "function_name": "add_one", "parameter_list": "(x)" }, { "docstring": null, "function_declaration": "def square(x):", "function_name": "square", "parameter_list": "(x)" }, { "docstring": null, "function_d...
[ 1, 0, 0, 0, 0, 1, 0, 0, 1, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch\nfrom torch.futures import Future\nfrom typing import List\nimport math\n\ndef async_transform_stage1(data: List[int]) -> List[Future]:\n futures = []\n...
trial_gpt4o_8
{ "original_instruction": "You are tasked with designing an asynchronous pipeline using PyTorch's `torch.futures.Future` to process a batch of data in parallel. Your pipeline consists of several stages, each performing a different computation asynchronously. You will need to collect the results from all stages and re...
0.562372
Docs: Pytorch_42103
C
[ "add_one", "square", "sqrt", "process_pipeline" ]
4
[ [ "process_pipeline", "add_one" ], [ "process_pipeline", "sqrt" ], [ "process_pipeline", "square" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
61f4dd618095c78257a1c4c6156b110559a5d47c
0fc92b000895084c46928a79530d42e3a1d03d0a
v1.0
complete
Docs
Docs: Python310_42244_C
class FileFormatError(Exception): """Raised when a file has an incorrect format.""" pass class ProcessingError(Exception): """Raised for general processing errors.""" pass class CriticalError(ProcessingError): """Raised when a critical error occurs.""" pass def process_file(file_name: str) ->...
class FileFormatError(Exception): """Raised when a file has an incorrect format.""" pass class ProcessingError(Exception): """Raised for general processing errors.""" pass class CriticalError(ProcessingError): """Raised when a critical error occurs.""" pass def process_file(file_name: str) ->...
import pytest from solution import FileFormatError, ProcessingError, CriticalError, process_file, safe_process def test_process_file_bad_format(): with pytest.raises(FileFormatError): process_file("bad_format.txt") def test_process_file_critical_issue(): with pytest.raises(CriticalError): proc...
[]
[ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 ]
2
hard
0.2
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class FileFormatError(Exception):\n \"\"\"Exception raised for errors in the file format.\"\"\"\n pass\n\nclass ProcessingError(Exception):\n \"\"\"Exception r...
trial_gpt4o_5
{ "original_instruction": "### Advanced Python Exception Handling\n\nYou are tasked with implementing a small module that simulates a file processing system with several potential error conditions. This will test your ability to handle a variety of exceptions properly and ensure your code is robust and informative in...
0.51272
Docs: Python310_42244
C
[ "process_file", "safe_process" ]
2
[ [ "safe_process", "process_file" ] ]
1
[]
false
[ "FileFormatError", "ProcessingError", "CriticalError" ]
true
pytest
true
[]
true
574141ebf38b0579dfdce2365e55af7bd283c18f
10ec489195e6dc12294d9ba6e2cbd29eba45c5e8
v1.0
complete
Docs
Docs: Python310_42309_C
import asyncio from typing import List async def fetch_page_content(url: str) -> str: """ Simulates fetching the content of a web page. Args: url (str): The URL of the web page. Returns: str: Simulated content of the web page. """ pass async def fetch_all_contents(urls: List[str]) -> L...
import asyncio from typing import List async def fetch_page_content(url: str) -> str: """ Simulates fetching the content of a web page. Args: url (str): The URL of the web page. Returns: str: Simulated content of the web page. """ await asyncio.sleep(1) return f"Content of...
import asyncio from solution import fetch_page_content, fetch_all_contents def test_fetch_page_content(): result = asyncio.run(fetch_page_content("http://example.com/page1")) assert result == "Content of http://example.com/page1" def test_fetch_all_contents(): urls = [ "http://example.com/page1", ...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nfrom typing import List\n\nasync def fetch_page_content(url: str) -> str:\n \"\"\"\n Simulates fetching the content of a web page.\n :param url...
trial_gpt4o_9
{ "original_instruction": "### Asynchronous Programming with Coroutines\n\nIn this assessment, you are required to demonstrate your understanding of Python's async and await functionality by creating an asynchronous function and handling coroutines.\n\n#### Problem Statement\n\nYou are tasked to implement a simplifie...
0.547979
Docs: Python310_42309
C
[ "fetch_page_content", "fetch_all_contents" ]
2
[ [ "fetch_all_contents", "fetch_page_content" ] ]
1
[]
false
[]
false
pytest
true
[]
true
cd3b8b53efd05c0ee3aaf602d061278f2dacef6b
7799b2c9b93abec024c62d7b9494cc60a0abde45
v1.0
complete
Docs
Docs: Python310_41725_C
import marshal SUPPORTED_TYPES = (bool, int, float, str, bytes, list, tuple, set, dict, type(None), type(...), StopIteration) def replace_unsupported(v): """ Helper function to replace unsupported types with None. """ if isinstance(v, SUPPORTED_TYPES): if isinstance(v, (list, tuple, set)): ...
import marshal SUPPORTED_TYPES = (bool, int, float, str, bytes, list, tuple, set, dict, type(None), type(...), StopIteration) def replace_unsupported(v): if isinstance(v, SUPPORTED_TYPES): if isinstance(v, (list, tuple, set)): return type(v)(replace_unsupported(i) for i in v) elif isin...
from solution import custom_serialize, custom_deserialize import os def test_serialize_deserialize_file(): obj = {"key1": 123, "key2": [1, 2, 3]} file_path = "test.marshal" custom_serialize(obj, file_path=file_path) deserialized_obj = custom_deserialize(file_path=file_path) assert deserialize...
[ { "docstring": null, "function_declaration": "def replace_unsupported(v):", "function_name": "replace_unsupported", "parameter_list": "(v)" }, { "docstring": null, "function_declaration": "def custom_serialize(obj, file_path=None, to_bytes=False):", "function_name": "custom_serialize...
[ 1, 1, 1 ]
3
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import marshal\nimport os\n\ndef filter_supported_types(obj):\n if isinstance(obj, (bool, int, float, str, bytes, type(None), type(Ellipsis), StopIteration)):\n ...
trial_gpt4o_2
{ "original_instruction": "**Question: Custom Object Serialization and Deserialization**\n\nIn this challenge, you are required to implement a pair of functions `custom_serialize` and `custom_deserialize` that utilize the `marshal` module to serialize and deserialize specific Python objects. Your implementation shoul...
0.600665
Docs: Python310_41725
C
[ "replace_unsupported", "custom_serialize", "custom_deserialize" ]
3
[ [ "custom_serialize", "replace_unsupported" ] ]
1
[]
false
[]
false
pytest
true
[]
true
998aa5c2d7e7fa8da17de291c8c5c0c59735c4f2
5a8595aab7e40a809db3dd3dfe2bbc48cdaea477
v1.0
complete
Docs
Docs: Python310_42491_C
import asyncio async def process_and_send(file_paths: list, server_host: str, server_port: int): """ Asynchronous function to read data from multiple files concurrently, process the data, and send the processed data to a server over a TCP connection. Args: file_paths (list of str): List cont...
import asyncio from asyncio import Lock async def read_file(file_path, file_lock, queue): async with file_lock: try: async with aiofiles.open(file_path, mode='r') as f: async for line in f: num = int(line.strip()) await queue.put(num + 1) ...
import pytest import asyncio from solution import process_and_send # Dummy server to receive incoming data async def dummy_server(reader, writer): received_data = [] while True: data = await reader.readline() if not data: break received_data.append(int(data.decode().strip())...
[]
[ 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 asyncio\n\nasync def read_file(file_path):\n async with aiofiles.open(file_path, 'r') as file:\n lines = await file.readlines()\n return [int(li...
trial_gpt4o_9
{ "original_instruction": "### Asynchronous File Processing and Network Communication\n\n**Objective:**\n\nImplement an asynchronous system that reads data from multiple files concurrently, processes the data, and sends the processed data to a server over a network.\n\n**Requirements:**\n\n1. **Reading Files:**\n ...
0.509759
Docs: Python310_42491
C
[ "read_file", "send_to_server", "process_and_send" ]
3
[ [ "process_and_send", "read_file" ], [ "process_and_send", "send_to_server" ] ]
2
[]
false
[]
false
pytest
true
[]
true
2130482cc46392036c8de513c79796cdd662244d
05d76c8dcecaa38a88e61df070907d5c3d716cd2
v1.0
complete
Docs
Docs: Python310_42396_C
import asyncio import requests from concurrent.futures import ThreadPoolExecutor from bs4 import BeautifulSoup import logging logging.basicConfig(level=logging.DEBUG) # Enable asyncio debug mode asyncio.get_event_loop().set_debug(True) async def fetch_title(url): """ Asynchronously fetch the title from a sin...
import asyncio import requests from concurrent.futures import ThreadPoolExecutor from bs4 import BeautifulSoup import logging logging.basicConfig(level=logging.DEBUG) # Enable asyncio debug mode asyncio.get_event_loop().set_debug(True) def fetch_title_sync(url): """ Synchronous function to fetch the title fr...
import asyncio from solution import fetch_title, fetch_all_titles def test_fetch_title(monkeypatch): class MockResponse: def __init__(self, text): self.text = text self.status_code = 200 def raise_for_status(self): pass def mock_get(url): if url...
[ { "docstring": "Synchronous function to fetch the title from a single URL.", "function_declaration": "def fetch_title_sync(url):", "function_name": "fetch_title_sync", "parameter_list": "(url)" } ]
[ 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": "import asyncio\nimport requests\nfrom concurrent.futures import ThreadPoolExecutor\nfrom bs4 import BeautifulSoup\nimport logging\n\nlogging.basicConfig(level=logging.D...
trial_gpt4o_3
{ "original_instruction": "**Question:**\n\nYou have been hired by a company to develop a simplified web scraper using `asyncio`. This web scraper needs to fetch data from multiple URLs concurrently and process each webpage to extract the title. You are required to implement this web scraper efficiently, ensuring tha...
0.702934
Docs: Python310_42396
C
[ "fetch_title_sync", "fetch_title", "fetch_all_titles", "main" ]
4
[ [ "fetch_all_titles", "fetch_title" ], [ "fetch_title", "fetch_title_sync" ] ]
2
[]
false
[]
false
pytest
true
[ "bs4", "requests" ]
false
92f82b3d30b4de0e91a5f8a94b90ed994ae6fa22
2962686a14a44cfbbe0611a6a5f359d479ce61c5
v1.0
complete
Docs
Docs: Python310_42168_C
import asyncio async def handler(name: str, queue: asyncio.Queue): """ Asynchronous function to handle ticket bookings from the queue. Continuously processes ticket booking requests from the queue, simulating a delay between 0.1 and 0.5 seconds for each request. Args: name (str): The name of the h...
import asyncio import random async def handler(name: str, queue: asyncio.Queue): while True: try: ticket_number = await queue.get() await asyncio.sleep(random.uniform(0.1, 0.5)) queue.task_done() print(f'{name} processed ticket #{ticket_number}') exce...
import asyncio from solution import handler, booking_simulator async def test_handler(): queue = asyncio.Queue() for i in range(5): await queue.put(i+1) handler_task = asyncio.create_task(handler('test-handler', queue)) await queue.join() handler_task.cancel() await asyncio.gather(...
[]
[ 1, 1, 1, 0, 1, 1, 0, 0, 1 ]
6
easy
0.667
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport random\n\nasync def handler(name: str, queue: asyncio.Queue):\n while True:\n ticket_number = await queue.get()\n await asyncio....
trial_gpt4o_9
{ "original_instruction": "<|Analysis Begin|>\n\nThe given documentation is about `asyncio.queues` from the Python standard library.\n\n- **Classes Provided:**\n - `asyncio.Queue`: A first-in, first-out (FIFO) queue.\n - Methods: `empty()`, `full()`, `get()`, `get_nowait()`, `join()`, `put()`, `put_nowait()`, `qs...
0.5331
Docs: Python310_42168
C
[ "handler", "booking_simulator" ]
2
[ [ "booking_simulator", "handler" ] ]
1
[]
false
[]
false
pytest
true
[]
true
945ca479b7901f36681734b09ba4b4b810448c06
1bb90b4b4bfa2e5ae15b29b6bfc66767af130ccc
v1.0
complete
Docs
Docs: Python310_41922_C
import threading from typing import List, Dict def read_and_process_file(file_name: str, results_dict: Dict[str, int], lock: threading.Lock) -> None: """ This function reads the file, processes the numbers, and updates the shared dictionary. Args: file_name (str): The name of the file to be proces...
import threading from typing import List, Dict import os def read_and_process_file(file_name: str, results_dict: Dict[str, int], lock: threading.Lock) -> None: """ This function reads the file, processes the numbers, and updates the shared dictionary. """ try: with open(file_name, 'r') as file:...
import os import threading from solution import read_and_process_file, process_files_concurrently def create_file(file_name, contents): with open(file_name, 'w') as f: f.write(contents) def test_read_and_process_file(): try: create_file('test1.txt', '1\n2\n3\n') results = {} lo...
[ { "docstring": "This function reads the file, processes the numbers, and updates the shared dictionary.", "function_declaration": "def read_and_process_file(file_name, results_dict, lock):", "function_name": "read_and_process_file", "parameter_list": "(file_name, results_dict, lock)" }, { "d...
[ 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 threading\nfrom typing import List, Dict\n\ndef read_and_process_file(file_name: str, results_dict: Dict[str, int], lock: threading.Lock) -> None:\n \"\"\"\n ...
trial_gpt4o_9
{ "original_instruction": "### Multi-threaded File Processing with Thread Pool and Synchronization\n\n**Objective:**\nImplement a multi-threaded file processing system where multiple threads read data from different files, process the data, and store the results in a shared resource. Use synchronization primitives to...
0.559746
Docs: Python310_41922
C
[ "read_and_process_file", "process_files_concurrently" ]
2
[ [ "process_files_concurrently", "read_and_process_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
a7fb3239b491748f297054c0ba28534a3a78dbfc
ff4a0ac196b71f9785c89e5b51442a135505cc2e
v1.0
complete
Docs
Docs: Python310_42492_C
from typing import List, Dict import aiohttp import asyncio async def async_web_scraper(urls: List[str]) -> Dict[str, int]: """ Asynchronous Web Scraper to fetch data concurrently from multiple URLs, process the content, and store the results. Args: urls (List[str]): A list of URLs to be fetched. Each...
from typing import List, Dict import aiohttp import asyncio from collections import defaultdict async def fetch_content(url: str, session: aiohttp.ClientSession) -> str: try: async with session.get(url) as response: return await response.text() except Exception as e: print(f'Error f...
import pytest import asyncio from solution import async_web_scraper # Mock aiohttp for testing purposes class MockResponse: def __init__(self, text): self._text = text async def text(self): return self._text def release(self): pass class MockSession: def __init__(self...
[]
[ 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 aiohttp\nimport asyncio\nfrom typing import List, Dict\n\nasync def fetch(url: str, session: aiohttp.ClientSession) -> str:\n \"\"\"\n Fetch the content of...
trial_gpt4o_1
{ "original_instruction": "### Asynchronous Web Scraper with asyncio\n\n#### Objective\nDesign a Python function using the `asyncio` library to fetch data concurrently from multiple URLs, process the content, and store the results.\n\n#### Problem Statement\nYou need to implement a function `async_web_scraper(urls: L...
0.65861
Docs: Python310_42492
C
[ "fetch_content", "process_url", "async_web_scraper" ]
3
[ [ "async_web_scraper", "process_url" ], [ "process_url", "fetch_content" ] ]
2
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
992dc8cbb5db099ba75e68a98e90cad71ddc6115
54173da7d8848f8349dbb4c61dcb9c3ab72d054d
v1.0
complete
Docs
Docs: Python310_42320_C
import sys import traceback def initialize_profiler(profile_data): """ Initialize the system profiler to count function calls. """ pass # Your code here def exception_handler(exc_type, exc_value, exc_traceback): """ Log unhandled exceptions detailing type, value, and traceback. """ pass # Yo...
import sys import traceback def initialize_profiler(profile_data): """ Initialize the system profiler to count function calls. """ def profiler(frame, event, arg): if event == 'call': function_name = frame.f_code.co_name if function_name in profile_data: ...
import sys import os from solution import initialize_profiler, exception_handler, setup_system_hooks, run_script def test_initialize_profiler(): profile_data = {} initialize_profiler(profile_data) def sample_function(): return "Called" sample_function() sample_function() assert profil...
[ { "docstring": "Initialize the system profiler to count function calls.", "function_declaration": "def initialize_profiler(profile_data):", "function_name": "initialize_profiler", "parameter_list": "(profile_data)" }, { "docstring": "Log unhandled exceptions detailing type, value, and traceb...
[ 0, 0, 0, 0, 1, 1, 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 sys\nimport traceback\n\ndef initialize_profiler(profile_data):\n def profiler(frame, event, arg):\n if event == 'call':\n function_name = f...
trial_gpt4o_9
{ "original_instruction": "**Objective:** Demonstrate understanding of advanced usage of the `sys` module for profiling and debugging a Python program.\n\n---\n\n#### Problem Statement\n\nYou are tasked with implementing a Python function that uses the `sys` module to profile the execution of a script and collect deb...
0.523185
Docs: Python310_42320
C
[ "initialize_profiler", "exception_handler", "setup_system_hooks", "run_script" ]
4
[ [ "setup_system_hooks", "initialize_profiler" ] ]
1
[]
false
[]
false
pytest
true
[]
true
de8d00719d5b763e3dd21877342a434603432c82
f4cce017511f5e961a04baa1f1c8b3ca4a95cea6
v1.0
complete
Docs
Docs: Python310_41996_C
import sched import time def display_event(message: str): """ This function prints the current time and the provided message. Args: message (str): Message to be displayed. """ pass def schedule_tasks(scheduler: sched.scheduler, tasks: list): """ Schedules multiple tasks using ...
import sched import time def display_event(message: str): """ This function prints the current time and the provided message. Args: message (str): Message to be displayed. """ print(f"{time.time()}: {message}") def schedule_tasks(scheduler: sched.scheduler, tasks: list): """ S...
import sched import time from io import StringIO import sys from solution import display_event, schedule_tasks def test_display_event(): original_stdout = sys.stdout sys.stdout = StringIO() try: display_event("Test Message") output = sys.stdout.getvalue().strip() assert "Test Messa...
[ { "docstring": "This function prints the current time and the provided message.\n\nArgs:\n message (str): Message to be displayed.", "function_declaration": "def display_event(message):", "function_name": "display_event", "parameter_list": "(message)" }, { "docstring": "Schedules multiple...
[ 1, 0, 1, 1, 0, 1, 1, 0, 0 ]
5
medium
0.556
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import sched\nimport time\n\ndef display_event(message: str):\n \"\"\"\n Print the current time and the provided message.\n \n Args:\n message (str):...
trial_gpt4o_5
{ "original_instruction": "**Question: Implement a Custom Task Scheduler**\n\nYou are required to create a task scheduler using Python's `sched` module to manage a series of tasks. Implement the following functions to demonstrate your understanding of the `sched` module:\n\n1. **Function: `display_event()`**\n ```p...
0.615946
Docs: Python310_41996
C
[ "display_event", "schedule_tasks" ]
2
[ [ "schedule_tasks", "display_event" ] ]
1
[]
false
[]
false
pytest
true
[]
true
27da701144d778733c27c036444a6e5841aafa4c
84b4b0db993d500c06ddbfa6c8c0abb61ba2cc40
v1.0
complete
Docs
Docs: Scikit_42390_C
import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.metrics import accuracy_score from sklearn.metrics.pairwise import polynomial_kernel, rbf_kernel def custom_kernel(X, Y, gamma1=0.1, gamma2=0.1, c0=1, d=3): ...
import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.metrics import accuracy_score from sklearn.metrics.pairwise import polynomial_kernel, rbf_kernel def custom_kernel(X, Y, gamma1=0.1, gamma2=0.1, c0=1, d=3): ...
from solution import custom_kernel, evaluate_kernels import numpy as np from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split def test_custom_kernel(): X, y = make_classification(n_samples=100, n_features=20, random_state=42) # Basic test to check the shape ...
[ { "docstring": "Custom kernel combining polynomial and RBF kernels.\n\nParameters:\nX, Y : array-like of shape (n_samples_X, n_features), (n_samples_Y, n_features)\ngamma1 : float, default=0.1\ngamma2 : float, default=0.1\nc0 : float, default=1\nd : int, default=3\n\nReturns:\nK : array-like of shape (n_samples...
[ 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 ]
8
easy
0.8
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import numpy as np\nfrom sklearn.datasets import make_classification\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.me...
trial_gpt4o_9
{ "original_instruction": "### Question: Implement Custom Kernel Function and Compare with Predefined Kernels\n\n#### Objective:\nWrite a Python function to implement a custom kernel function and compare its performance on a sample dataset with predefined kernels provided by scikit-learn. Demonstrate your understandi...
0.613043
Docs: Scikit_42390
C
[ "custom_kernel", "evaluate_kernels" ]
2
[ [ "evaluate_kernels", "custom_kernel" ] ]
1
[]
false
[]
false
pytest
true
[ "numpy", "sklearn" ]
false
8ea8b34b7315e5665a25a0054c7d2942cc196f9b
cf9d89d0f407eed06c28bb2b151a561b7802ee3a
v1.0
complete
Docs
Docs: Python310_42752_C
import asyncio async def async_server(host: str, port: int, runtime: int) -> None: """ Simulates a server that processes client requests using the asyncio event loop in Python. Args: - host (str): The host address on which the server listens. - port (int): The port number on which the server listens. ...
import asyncio async def handle_client(reader, writer): try: data = await reader.read(100) message = data.decode().strip() numbers = list(map(int, message.split(','))) result = sum(numbers) response = str(result) writer.write(response.encode()) await...
import asyncio import socket import pytest from solution import async_server @pytest.fixture def event_loop(): loop = asyncio.new_event_loop() yield loop loop.close() async def send_data(host, port, data): reader, writer = await asyncio.open_connection(host, port) writer.write(data.encode()) a...
[]
[ 0, 1, 0, 1, 1, 1, 1, 1, 1, 0 ]
7
easy
0.7
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\n\nasync def handle_client(reader, writer):\n try:\n data = await reader.read(100)\n message = data.decode()\n numbers = list(map...
trial_gpt4o_6
{ "original_instruction": "**Objective**: Implement a function to simulate a server that processes client requests using the `asyncio` event loop in Python.\n\n### Problem Statement\n\nYou are tasked with creating a server that can handle multiple client requests asynchronously using the `asyncio` package. Your serve...
0.608165
Docs: Python310_42752
C
[ "handle_client", "async_server" ]
2
[ [ "async_server", "handle_client" ] ]
1
[]
false
[]
false
pytest
true
[]
true
c1b115ba4cda8bb642957bba3e770bd1f747d9a7
bd3488f584cdcf9ac5df0f7e59eb98261ac52ce4
v1.0
complete
Docs
Docs: Python310_42577_C
import concurrent.futures from typing import List, Dict, Any def download_and_process_data(urls: List[str], timeout: int, max_workers: int) -> Dict[str, Any]: """ Fetch data from multiple URLs and process it using parallel tasks. The function downloads data from the given list of URLs using the specified ...
import concurrent.futures import requests from typing import List, Dict, Any def fetch_url(url: str, timeout: int) -> Any: try: response = requests.get(url, timeout=timeout) response.raise_for_status() return response.content except Exception as e: return str(e) def download_an...
from solution import download_and_process_data def test_download_and_process_data_success_case(): urls = [ 'http://httpbin.org/get', 'http://httpbin.org/delay/1', 'http://httpbin.org/uuid' ] result = download_and_process_data(urls, timeout=5, max_workers=3) for url in urls: ...
[ { "docstring": null, "function_declaration": "def fetch_url(url, timeout):", "function_name": "fetch_url", "parameter_list": "(url, timeout)" }, { "docstring": null, "function_declaration": "def download_and_process_data(urls, timeout, max_workers):", "function_name": "download_and_p...
[ 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 concurrent.futures\nimport requests\nfrom typing import List, Dict, Any\n\ndef fetch_url(url: str, timeout: int) -> Any:\n try:\n response = requests.g...
trial_gpt4o_7
{ "original_instruction": "**Coding Assessment Question:**\n\nYou are required to implement a Python function `download_and_process_data(urls: List[str], timeout: int, max_workers: int) -> Dict[str, Any]` using the `concurrent.futures` module. This function should fetch data from multiple URLs using parallel tasks an...
0.555969
Docs: Python310_42577
C
[ "fetch_url", "download_and_process_data" ]
2
[ [ "download_and_process_data", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "requests" ]
false
5f16a492b2d85c2a51555c38ea64070cbdb58bf0
dcf273a30b77c26212fb0b27d82fc332596c92f3
v1.0
complete
Docs
Docs: Python310_42420_C
from typing import List import concurrent.futures def parallel_sum_of_squares(numbers: List[int], num_workers: int) -> int: """ Compute the sum of squares of a list of integers in parallel using the specified number of worker threads. >>> parallel_sum_of_squares([1, 2, 3, 4], 2) 30 >>> parallel_sum_of_...
from typing import List import concurrent.futures def sum_of_squares(numbers: List[int]) -> int: return sum(x ** 2 for x in numbers) def parallel_sum_of_squares(numbers: List[int], num_workers: int) -> int: chunk_size = (len(numbers) + num_workers - 1) // num_workers sublists = [numbers[i:i + chunk_size] ...
from solution import parallel_sum_of_squares def test_parallel_sum_of_squares_basic(): assert parallel_sum_of_squares([1, 2, 3, 4], 2) == 30 def test_parallel_sum_of_squares_one_worker(): assert parallel_sum_of_squares([1, 2, 3, 4], 1) == 30 def test_parallel_sum_of_squares_large_input(): assert parallel...
[ { "docstring": null, "function_declaration": "def sum_of_squares(numbers):", "function_name": "sum_of_squares", "parameter_list": "(numbers)" }, { "docstring": null, "function_declaration": "def parallel_sum_of_squares(numbers, num_workers):", "function_name": "parallel_sum_of_square...
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ThreadPoolExecutor\nfrom typing import List\n\ndef parallel_sum_of_squares(numbers: List[int], num_workers: int) -> int:\n def sum_of_...
trial_gpt4o_7
{ "original_instruction": "### Question: Parallel Sum Calculation using `concurrent.futures`\n\n**Objective:** Write a function that uses the `concurrent.futures` module to compute the sum of squares of a list of integers in parallel.\n\n#### Function Signature\n```python\ndef parallel_sum_of_squares(numbers: List[in...
0.604624
Docs: Python310_42420
C
[ "sum_of_squares", "parallel_sum_of_squares" ]
2
[ [ "parallel_sum_of_squares", "sum_of_squares" ] ]
1
[]
false
[]
false
pytest
true
[]
true
2f72cbdf03134519599386a6012b09ace7f55180
7c645990f4c03d23f8bbc47c5d35b95ed2e1157f
v1.0
complete
Docs
Docs: Scikit_42256_C
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.neighbors import KDTree, BallTree from sklearn.metrics import accuracy_score import time def load_and_preprocess_data(filepath): """ Load and preprocess the dataset from the given filepath. Args: filepath (str): Path ...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.neighbors import KDTree, BallTree from sklearn.metrics import accuracy_score import time def load_and_preprocess_data(filepath): data = pd.read_csv(filepath) X = data[['x1', 'x2']].values y = data['label'].values retu...
import pytest from solution import evaluate_knn def mock_read_csv(filepath): data_content = { 'x1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'x2': [1, 2, 1, 2, 1, 2, 1, 2, 1, 2], 'label': [1, 0, 1, 0, 1, 0, 1, 0, 1, 0] } return pd.DataFrame.from_dict(data_content) @pytest.fixture def patch...
[ { "docstring": null, "function_declaration": "def load_and_preprocess_data(filepath):", "function_name": "load_and_preprocess_data", "parameter_list": "(filepath)" }, { "docstring": null, "function_declaration": "def knn_kdtree(X_train, y_train, X_test, k=3):", "function_name": "knn_...
[ 0, 0, 1, 1, 0, 1, 1, 0, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_scor...
trial_gpt4o_6
{ "original_instruction": "**Objective**: Implement a classification task using `sklearn.neighbors` and compare the performance of different nearest neighbor algorithms.\n\n**Problem Statement**:\n\nYou are provided with a dataset that contains labeled points in a 2D space. Your task is to implement a nearest neighbo...
0.660937
Docs: Scikit_42256
C
[ "load_and_preprocess_data", "knn_kdtree", "knn_balltree", "evaluate_knn" ]
4
[ [ "evaluate_knn", "knn_balltree" ], [ "evaluate_knn", "knn_kdtree" ], [ "evaluate_knn", "load_and_preprocess_data" ] ]
3
[]
false
[]
false
pytest
true
[ "pandas", "sklearn" ]
false
d956844d544556a794c74f900344596654dcbfa6
00a87ff52dc0b3746752b4d38d8d1a7d0c1266b7
v1.0
complete
Docs
Docs: Python310_42138_C
import urllib.request import urllib.error from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List, Dict, Union def fetch_url(url: str, timeout: int) -> Dict[str, Union[str, int]]: """ Fetches the contents of the URL and returns a dictionary containing status and content length. ...
import urllib.request import urllib.error from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List, Dict, Union def fetch_url(url: str, timeout: int) -> Dict[str, Union[str, int]]: """ Fetches the contents of the URL and returns a dictionary containing status and content length. ...
import pytest from solution import fetch_urls def test_fetch_urls_success(): urls = ["http://www.example.com"] result = fetch_urls(urls, timeout=10) assert "http://www.example.com" in result assert result["http://www.example.com"]["status"] == 200 assert isinstance(result["http://www.example.com"][...
[ { "docstring": "Fetches the contents of the URL and returns a dictionary containing status and content length.\n\nArgs:\nurl: str - The URL to fetch.\ntimeout: int - The timeout value for each URL fetch operation.\n\nReturns:\nDict[str, Union[str, int]] - A dictionary with 'status' and 'content_length' keys.", ...
[ 0, 1, 1, 1, 0, 1, 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": "from typing import List, Dict, Union\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nimport urllib.request\nimport urllib.error\n\ndef fetch_url(url: ...
trial_gpt4o_7
{ "original_instruction": "### Question: Concurrent Web Scraper\n\nYou are tasked with implementing a concurrent web scraper using Python's `concurrent.futures` module. The goal is to fetch the contents of multiple web pages concurrently and process the data efficiently. Here is the detailed specification:\n\n#### Fu...
0.638295
Docs: Python310_42138
C
[ "fetch_url", "fetch_urls" ]
2
[ [ "fetch_urls", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6146517a95d96493d293845cb4f53469598effd3
84d8ac55271ac64b77b9042133426fe1158b60ac
v1.0
complete
Docs
Docs: Python310_42845_C
class Cell: """ Mock implementation of Python cell objects. """ def __init__(self, value): self._value = value def get(self): """ Returns the value contained in the cell. """ pass # Implement this method def set(self, value): """ Sets a ...
class Cell: """ Mock implementation of Python cell objects. """ def __init__(self, value): self._value = value def get(self): """ Returns the value contained in the cell. """ return self._value def set(self, value): """ Sets a new value t...
from solution import Cell, cell_check, cell_new, cell_get, cell_set def test_cell_creation(): c = cell_new(10) assert cell_get(c) == 10 def test_cell_set(): c = cell_new(10) cell_set(c, 20) assert cell_get(c) == 20 def test_cell_check(): c = cell_new(10) assert cell_check(c) is True a...
[]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
10
easy
1
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "class Cell:\n def __init__(self, value):\n self.value = value\n \n def get(self):\n return self.value\n \n def set(self, value):\n ...
trial_gpt4o_9
{ "original_instruction": "**Question: Implementing a Mock of Python Cell Objects**\n\nIn Python, cell objects are a crucial part of closures, allowing variables to be referenced by multiple scopes. Your task is to implement a mock version of these cell objects in pure Python. This will help you understand the underl...
0.413369
Docs: Python310_42845
C
[ "cell_check", "cell_new", "cell_get", "cell_set" ]
4
[ [ "cell_get", "cell_check" ], [ "cell_set", "cell_check" ] ]
2
[]
false
[ "Cell" ]
true
pytest
true
[]
true
71f27670db9e277b19cceab76591df84cfdb08e6
cae3c533ce03aa3a7d153fb2fb6efe2e8329e913
v1.0
complete
Docs
Docs: Python310_42768_C
from concurrent.futures import ThreadPoolExecutor from typing import List def parallel_matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]: """ Parallelize the computation of matrix multiplication using ThreadPoolExecutor. Given two matrices A and B, compute their product matrix C i...
from concurrent.futures import ThreadPoolExecutor from typing import List def compute_element(A: List[List[int]], B: List[List[int]], row: int, col: int) -> int: # Helper function to compute the value of a single element in the result matrix (row, col) return sum(A[row][k] * B[k][col] for k in range(len(B))) ...
from solution import parallel_matrix_multiply def test_small_matrix_multiplication(): A = [ [1, 2, 3], [4, 5, 6] ] B = [ [7, 8], [9, 10], [11, 12] ] expected = [ [58, 64], [139, 154] ] assert parallel_matrix_multiply(A, B) == expected ...
[ { "docstring": null, "function_declaration": "def compute_element(A, B, row, col):", "function_name": "compute_element", "parameter_list": "(A, B, row, col)" }, { "docstring": "Multiplies two matrices A and B using parallel computation.", "function_declaration": "def parallel_matrix_mult...
[ 0, 1, 0, 0, 1, 1, 1, 1, 1, 0 ]
6
medium
0.6
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from concurrent.futures import ThreadPoolExecutor, as_completed\nfrom typing import List\n\ndef compute_element(A: List[List[int]], B: List[List[int]], i: int, j: int) ...
trial_gpt4o_6
{ "original_instruction": "#### Title: Parallel Matrix Multiplication using `concurrent.futures`\n\n**Objective**: Demonstrate comprehension of asynchronous execution, thread management, and exception handling using the `concurrent.futures` module in Python.\n\n**Problem Statement**:\n\nParallelize the computation of...
0.56814
Docs: Python310_42768
C
[ "compute_element", "parallel_matrix_multiply" ]
2
[ [ "parallel_matrix_multiply", "compute_element" ] ]
1
[]
false
[]
false
pytest
true
[]
true
3a7fc295ad44cbf2cad97243b0aa1b2a7b590b42
47ebe9bd15d8031e7567665bc0b922c9ac70de21
v1.0
complete
Docs
Docs: Python310_43027_C
from contextvars import ContextVar import asyncio # Define the context variable client_addr_var = ContextVar('client_addr') def log_client_info(): """ Log the client address using the context variable. """ async def handle_request(client_addr: tuple): """ Simulate handling a client request and lo...
from contextvars import ContextVar import asyncio # Define the context variable client_addr_var = ContextVar('client_addr') def log_client_info(): """ Log the client address using the context variable. """ client_addr = client_addr_var.get() print(f"Client Address: {client_addr[0]}:{client_addr[1]...
import pytest from contextvars import ContextVar import asyncio from unittest.mock import patch # Redefine the context variable locally for test isolation client_addr_var = ContextVar('client_addr') # Re-implement the functions in local scope for testing def log_client_info(): client_addr = client_addr_var.get() ...
[ { "docstring": "Log the client address using the context variable.", "function_declaration": "def log_client_info():", "function_name": "log_client_info", "parameter_list": "()" } ]
[ 0, 0, 0, 1, 1, 1, 0, 0, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from contextvars import ContextVar\nimport asyncio\n\n# Define the context variable\nclient_addr_var = ContextVar('client_addr', default=None)\n\ndef log_client_info():...
trial_gpt4o_3
{ "original_instruction": "**Objective**: Demonstrate the effective use of the `contextvars` module, especially in the context of asynchronous programming.\n\n#### Problem Statement\n\nYou are tasked with developing a logging system for an asynchronous web server. The logging system should record the IP address and p...
0.583034
Docs: Python310_43027
C
[ "log_client_info", "handle_request", "main" ]
3
[ [ "handle_request", "log_client_info" ] ]
1
[]
false
[]
false
pytest
false
[]
true
44c3c0e89c62287eaee943b0211388efee945661
f7ce9b40c063202053d94b59de1ddde0ff47b961
v1.0
complete
Docs
Docs: Python310_42627_C
import readline import os import atexit # Define available commands for the custom completer COMMANDS = ['help', 'exit', 'load', 'save', 'list'] def completer(text, state): """Autocomplete commands starting with the typed prefix.""" options = [cmd for cmd in COMMANDS if cmd.startswith(text)] if state < le...
import readline import os import atexit # Define available commands for the custom completer COMMANDS = ['help', 'exit', 'load', 'save', 'list'] def completer(text, state): options = [cmd for cmd in COMMANDS if cmd.startswith(text)] if state < len(options): return options[state] else: retu...
import os import readline from pytest import fixture; @fixture(autouse=True) def prepare_history_file(): histfile = os.path.join(os.path.expanduser("~"), ".cli_history") if os.path.exists(histfile): os.remove(histfile) yield if os.path.exists(histfile): os.remove(histfile) def test_his...
[ { "docstring": null, "function_declaration": "def completer(text, state):", "function_name": "completer", "parameter_list": "(text, state)" }, { "docstring": null, "function_declaration": "def load_history():", "function_name": "load_history", "parameter_list": "()" }, { ...
[ 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 os\nimport readline\n\nHISTORY_FILE = os.path.expanduser(\"~/.cli_history\")\nCOMMANDS = ['help', 'exit', 'load', 'save', 'list']\nHISTORY_LENGTH = 500\n\ndef co...
trial_gpt4o_6
{ "original_instruction": "### Advanced Python Programming Assignment\n\nYou are tasked with enhancing a command-line interface (CLI) Python application by incorporating features from the `readline` module. Your solution should demonstrate the use of various functionalities of the `readline` module to improve the exp...
0.392701
Docs: Python310_42627
C
[ "completer", "load_history", "save_history", "run_cli" ]
4
[ [ "run_cli", "completer" ], [ "run_cli", "load_history" ], [ "run_cli", "save_history" ] ]
3
[]
false
[]
false
pytest
true
[]
true
742bd7e75124d54801e32695eb8c092f23a9b114
997e82c801b00122d54b4ad30da99aeb87bc1380
v1.0
complete
Docs
Docs: Python310_42997_C
import random import _thread import time def log_temperature(sensor_id, log_file, lock): """Simulate a sensor reading and log it to the log file in a thread-safe manner.""" pass def start_logging(sensor_count, log_filename): """Start multiple sensor threads to log temperatures concurrently. Args:...
import random import _thread import time def log_temperature(sensor_id, log_file, lock): """ Simulate a sensor reading and log it to the log file in a thread-safe manner. """ temperature = round(random.uniform(-30.0, 50.0), 2) with lock: log_file.write(f"Sensor {sensor_id}: {temperature}\n"...
import os import time from solution import start_logging def test_logging_creates_file(): log_filename = 'test_temperature_log.txt' sensor_count = 5 if os.path.exists(log_filename): os.remove(log_filename) start_logging(sensor_count, log_filename) time.sleep(1.5) # Wait for...
[ { "docstring": "Simulate a sensor reading and log it to the log file in a thread-safe manner.", "function_declaration": "def log_temperature(sensor_id, log_file, lock):", "function_name": "log_temperature", "parameter_list": "(sensor_id, log_file, lock)" }, { "docstring": "Start multiple sen...
[ 1, 0, 0, 1, 0, 1, 0, 1, 0, 0 ]
4
medium
0.4
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import random\nimport _thread\nimport time\n\ndef log_temperature(sensor_id, log_file, lock):\n \"\"\"\n Logs the temperature reading from a sensor to a log file ...
trial_gpt4o_7
{ "original_instruction": "### Multi-threaded Temperature Logger\n\nAs part of a climate monitoring system, you need to implement a temperature logger that records temperature readings from different sensors concurrently. Each sensor runs in its own thread and writes temperature data to a shared log file. To ensure t...
0.589232
Docs: Python310_42997
C
[ "log_temperature", "start_logging" ]
2
[ [ "start_logging", "log_temperature" ] ]
1
[]
false
[]
false
pytest
true
[]
true
6480600f2027f1188dac2e61de4e9e4810dc63f9
9dad075c36d3d5d2059c83ac33a09b000732804c
v1.0
complete
Docs
Docs: Python310_42499_C
from typing import List import concurrent.futures def count_keyword_in_file(file_path: str, keyword: str) -> int: """ Counts the number of occurrences of the keyword in the file specified by file_path. Parameters: file_path (str): The path to the file where the keyword will be counted. keyword (st...
from typing import List import concurrent.futures def count_keyword_in_file(file_path: str, keyword: str) -> int: """ Counts the number of occurrences of the keyword in the file specified by file_path. Parameters: file_path (str): The path to the file where the keyword will be counted. keyword...
import pytest from solution import keyword_occurrence_counter def test_keyword_occurrence_counter(): # Setup file_list = ['file1.txt', 'file2.txt', 'file3.txt'] keyword = 'test' # Creating temporary files for testing with open('file1.txt', 'w', encoding='utf-8') as f: f.write('This is ...
[ { "docstring": "Counts the number of occurrences of the keyword in the file specified by file_path.\n\nParameters:\nfile_path (str): The path to the file where the keyword will be counted.\nkeyword (str): The keyword to count in the file.\n\nReturns:\nint: The number of occurrences of the keyword in the file.",...
[ 1, 0, 0, 0, 0, 0, 1, 1, 0, 0 ]
3
hard
0.3
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "from typing import List\nimport concurrent.futures\n\ndef count_keyword_in_file(file_path: str, keyword: str) -> int:\n \"\"\"\n This helper function counts the k...
trial_gpt4o_7
{ "original_instruction": "#### Task:\nYou are tasked with processing a large list of text files to count the occurrences of a specific keyword in each file, and then aggregate the results. To achieve efficient processing and leverage multi-core CPUs, you will use the `concurrent.futures` module with `ThreadPoolExecu...
0.651436
Docs: Python310_42499
C
[ "count_keyword_in_file", "keyword_occurrence_counter" ]
2
[ [ "keyword_occurrence_counter", "count_keyword_in_file" ] ]
1
[]
false
[]
false
pytest
true
[]
true
ff08d29aea2a6797646a24fe56ffd1fdbff352cd
63261d4f0cefcd4dc57ad5a9d861a1dc2b158d2e
v1.0
complete
Docs
Docs: Pytorch_42419_C
import torch.nn as nn from torch.__future__ import set_overwrite_module_params_on_conversion, set_swap_module_params_on_conversion def toggle_overwrite_module_parameters(value: bool): """Sets the overwrite_module_params_on_conversion flag using the provided value. Args: value (bool): Flag to overwrite ...
import torch.nn as nn from torch.__future__ import set_overwrite_module_params_on_conversion, set_swap_module_params_on_conversion def toggle_overwrite_module_parameters(value: bool): set_overwrite_module_params_on_conversion(value) def toggle_swap_module_parameters(value: bool): set_swap_module_params_on_con...
from solution import ( toggle_overwrite_module_parameters, toggle_swap_module_parameters, apply_conversion_flags_and_convert, convert_model ) import torch.nn as nn class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.fc = nn.Linear(10, 10) ...
[ { "docstring": null, "function_declaration": "def toggle_overwrite_module_parameters(value):", "function_name": "toggle_overwrite_module_parameters", "parameter_list": "(value)" }, { "docstring": null, "function_declaration": "def toggle_swap_module_parameters(value):", "function_nam...
[ 1, 0, 0, 1, 1, 0, 1, 0, 0, 1 ]
5
medium
0.5
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import torch.nn as nn\nfrom torch.__future__ import set_overwrite_module_params_on_conversion, \\\n set_swap_module_params_on_conversion\n\nde...
trial_gpt4o_6
{ "original_instruction": "### PyTorch Coding Assessment Question\n\n**Objective**: This task is focused on your ability to manipulate module parameters in PyTorch, particularly during the conversion process. You will be required to implement PyTorch functions and demonstrate an understanding of module parameter mana...
0.432548
Docs: Pytorch_42419
C
[ "toggle_overwrite_module_parameters", "toggle_swap_module_parameters", "apply_conversion_flags_and_convert", "convert_model" ]
4
[ [ "convert_model", "apply_conversion_flags_and_convert" ], [ "convert_model", "toggle_overwrite_module_parameters" ], [ "convert_model", "toggle_swap_module_parameters" ] ]
3
[]
false
[]
false
pytest
true
[ "torch" ]
false
6a6502d15bbf22faca36c88c33593959a00073c2
5e3587693462b68c9c3fc3f08d92407133ca3740
v1.0
complete
Docs
Docs: Pytorch_42061_C
import torch import torch.nn.functional as F def create_block_mask(tensor, block_shape): """ Function to create a dynamic block mask for the attention mechanism. Params: - tensor (torch.Tensor): Tensor to create a block mask for. - block_shape (tuple): Shape of the block (block_height, block_width...
import torch import torch.nn.functional as F def create_block_mask(tensor, block_shape): """ Function to create a dynamic block mask for the attention mechanism. Params: - tensor (torch.Tensor): Tensor to create a block mask for. - block_shape (tuple): Shape of the block (block_height, block_width...
import torch from solution import custom_flexible_attention def test_custom_flexible_attention_output_shape(): batch_size = 2 seq_len = 10 dim = 4 block_shape = (2, 2) query = torch.randn(batch_size, seq_len, dim) key = torch.randn(batch_size, seq_len, dim) value = torch.randn(batch_size, ...
[ { "docstring": "Function to create a dynamic block mask for the attention mechanism.\n\nParams:\n- tensor (torch.Tensor): Tensor to create a block mask for.\n- block_shape (tuple): Shape of the block (block_height, block_width).\n\nReturns:\n- mask (torch.Tensor): Block mask.", "function_declaration": "def ...
[ 0, 0, 1, 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 torch\nimport torch.nn.functional as F\n\ndef create_block_mask(seq_len, block_shape):\n \"\"\"\n Creates a block mask for attention mechanism.\n \n ...
trial_gpt4o_2
{ "original_instruction": "**Question: Implement a Custom Flexible Attention Mechanism with Dynamic Blocks**\n\nIn this task, you are required to implement a custom attention mechanism using PyTorch. Your task is to create a flexible attention mechanism that leverages dynamic blocks and mask utility functions provide...
0.443067
Docs: Pytorch_42061
C
[ "create_block_mask", "custom_flexible_attention" ]
2
[ [ "custom_flexible_attention", "create_block_mask" ] ]
1
[]
false
[]
false
pytest
true
[ "torch" ]
false
7e9320d308863240425a423eb69e900780a055e1
d052e4f4510c8c1a3e1cb6927117c9cf56e4f1c5
v1.0
complete
Docs
Docs: Python310_42441_C
import asyncio import contextlib # Part 1: Synchronous Resource Management @contextlib.contextmanager def sync_resource_manager(): """ Context manager to handle acquiring and releasing a synchronous resource. Example: >>> with sync_resource_manager() as resource: ... print("Using resource") ...
import asyncio import contextlib # Part 1: Synchronous Resource Management @contextlib.contextmanager def sync_resource_manager(): print("Resource acquired") try: yield "resource" finally: print("Resource released") def use_synchronous_resource(): with sync_resource_manager() as resour...
from solution import use_synchronous_resource, use_asynchronous_resource, manage_multiple_resources, manage_multiple_async_resources def test_use_synchronous_resource(capfd): use_synchronous_resource() captured = capfd.readouterr() assert captured.out == "Resource acquired\nUsing resource\nResource release...
[ { "docstring": null, "function_declaration": "def sync_resource_manager():", "function_name": "sync_resource_manager", "parameter_list": "()" }, { "docstring": null, "function_declaration": "def use_synchronous_resource():", "function_name": "use_synchronous_resource", "parameter...
[ 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": "import asyncio\nimport contextlib\n\n# Part 1: Synchronous Resource Management\n@contextlib.contextmanager\ndef sync_resource_manager():\n print(\"Resource acquired\...
trial_gpt4o_4
{ "original_instruction": "You are tasked with developing a resource management system for handling both synchronous and asynchronous resources using the `contextlib` module. Your goal is to ensure that resources are properly managed and cleaned up at the end of their usage, even when errors occur during processing.\...
0.400834
Docs: Python310_42441
C
[ "sync_resource_manager", "use_synchronous_resource", "async_resource_manager", "use_asynchronous_resource", "manage_multiple_resources", "manage_multiple_async_resources" ]
6
[ [ "manage_multiple_async_resources", "async_resource_manager" ], [ "manage_multiple_resources", "sync_resource_manager" ], [ "use_asynchronous_resource", "async_resource_manager" ], [ "use_synchronous_resource", "sync_resource_manager" ] ]
4
[]
false
[]
false
pytest
true
[]
true
ec7f3d65bcb34a254584445746100619ef278ca1
843ca3e0953efe2fc0fb084a2dc6a669b2d18757
v1.0
complete
Docs
Docs: Python310_42706_C
import resource from typing import Callable, Union def limit_cpu_time(seconds: int) -> None: """ Limits the CPU time for the current process to `seconds` seconds. Prints an error message if exception occurs. """ pass def get_process_usage(detail: bool) -> Union[dict, tuple]: """ Retrieve...
import resource def limit_cpu_time(seconds): """Limits the CPU time for the current process to `seconds` seconds.""" try: resource.setrlimit(resource.RLIMIT_CPU, (seconds, seconds)) except resource.error as e: print(f"Error setting CPU limit: {str(e)}") def get_process_usage(detail=False):...
import pytest import time from solution import limit_cpu_time, get_process_usage, monitor_cpu_limited_task def test_limit_cpu_time(): try: limit_cpu_time(1) assert True # If no exception, test passes except Exception: assert False # If there is an exception, test fails def test_get_p...
[ { "docstring": "Limits the CPU time for the current process to `seconds` seconds.", "function_declaration": "def limit_cpu_time(seconds):", "function_name": "limit_cpu_time", "parameter_list": "(seconds)" }, { "docstring": "Retrieves the resource usage statistics for the current process.\n\n...
[ 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 resource\n\ndef limit_cpu_time(seconds):\n \"\"\"Limits the CPU time for the current process to `seconds` seconds.\"\"\"\n try:\n resource.setrlimit...
trial_gpt4o_0
{ "original_instruction": "### Resource Management and Usage Monitoring\n\nYou are required to manage and monitor system resources using Python's `resource` module. This will involve limiting resource usage by processes and retrieving detailed resource consumption data.\n\n#### Problem Statement\n\n1. **Resource Limi...
0.614894
Docs: Python310_42706
C
[ "limit_cpu_time", "get_process_usage", "monitor_cpu_limited_task" ]
3
[ [ "monitor_cpu_limited_task", "get_process_usage" ], [ "monitor_cpu_limited_task", "limit_cpu_time" ] ]
2
[]
false
[]
false
pytest
true
[]
true
a5bd3f7c4dbb405b0cfdd6f505afffa2379d6acc
46772a152d36a88bc47328fe037cd01871004231
v1.0
complete
Docs
Docs: Python310_43148_C
import asyncio import aiohttp async def fetch_all_urls(url_list: list, max_concurrent_requests: int) -> dict: """ Fetches content from multiple URLs concurrently. Parameters: url_list (list): A list of URLs to fetch. max_concurrent_requests (int): The maximum number of concurrent requests. Re...
import asyncio import aiohttp async def fetch_url(session, url): try: async with session.get(url) as response: response.raise_for_status() return url, await response.text() except Exception as e: return url, str(e) async def fetch_all_urls(url_list: list, max_concurrent...
import asyncio import pytest from solution import fetch_all_urls async def mock_server(request): return web.Response(text="Test response") def test_fetch_all_urls_with_valid_urls(): url_list = [ 'https://httpbin.org/get', 'https://jsonplaceholder.typicode.com/posts/1' ] max_concurrent_...
[]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
9
easy
0.9
{ "trial_gpt4o_0": { "file_source": "CodeGen_instruction_docs_50000_1740127252_sanitized_prepared0_results_combined.jsonl", "solution_code": "import asyncio\nimport aiohttp\n\nasync def fetch_url(session, url):\n try:\n async with session.get(url) as response:\n response.raise_for_status(...
trial_gpt4o_7
{ "original_instruction": "### Advanced Programming Question: Concurrent URL Fetcher with asyncio\n\nUsing the information provided in the documentation about asyncio, design and implement a Python function called `fetch_all_urls` that concurrently fetches content from multiple URLs.\n\n#### Function Signature\n```py...
0.58378
Docs: Python310_43148
C
[ "fetch_url", "fetch_all_urls" ]
2
[ [ "fetch_all_urls", "fetch_url" ] ]
1
[]
false
[]
false
pytest
true
[ "aiohttp" ]
false
f0d308b69f73b6bd873e54dd787c65d97d7353aa
e85128f4ea2e36d670aa2eaac183e579b8b55e7f